0

我在 Drupal 8 中有一个自定义表单。表单的 managed_file 字段具有多个 true。我面临着关于上传到该字段的文件数量限制的挑战。

我必须让这个 managed_file 字段只上传 3 张图片。

有人可以帮我解决这个问题吗?我试过下面的代码。

    public function buildForm(array $form, FormStateInterface $form_state) {

    $form['upload_doc'] = array(
          '#type' => 'managed_file',
          '#title' => 'File Upload',
          '#upload_location' => 'public://upload_document/',
          '#required' => TRUE,
          '#multiple' => TRUE,
          '#upload_validators' => array(
            'file_validate_extensions' => array('jpg jpeg png'),
            'file_validate_size' => 2000,
          ),
        );

    // Add a submit button that handles the submission of the form.
        $form['actions']['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Submit'),
        ];

        return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {      
      $fileObj = $form_state->getValue('upload_doc');
      if (count($fileObj) > 3) {
        drupal_set_message('File limit exceed'.count($fileObj), 'error');
        return false;
      } else {
          return true;
      }
  }

问题是,我无法验证文件上传限制。它允许上传超过限制。请帮帮我谢谢

4

1 回答 1

0
public function validateForm(array &$form, FormStateInterface $form_state) {
$fileObj = $form_state->getValue('upload_doc');
if (count($fileObj) >= 4) {
  $form_state->setErrorByName('upload_doc', $this->t("<em>Only 3 images are allowed per run</em>."));}}
于 2019-11-22T10:50:32.113 回答