0
votes

I have a custom form in Drupal 8. Form has managed_file field with multiple true. I am facing challenge regarding the limit of number of files upload to this field.

I have to make this managed_file field to upload only 3 images.

Can someone help me regarding this? I have tried below code.

    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;
      }
  }

The problem is, i am not able to validate file upload limit. It's allow to upload more than limit. Please help me Thank you

1
can you share what you've got $form_state->getValue('upload_doc'), is it array? object ? - Yuseferi
@Yusef: I am able to get file object with all file properties like size,name etc.. - Dipti
is it an array of file objects or just one file? - Yuseferi
array of file Objects. able to get count($fileObj). Array of file - Dipti
do you mean count($fileObj) return the number of files you have uploaded? would you please add a dump (var_dump or print_r, or kint, or dpm, what you are feel free with) of the $fileObj to question? - Yuseferi

1 Answers

0
votes
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>."));}}