Drupal 8 Custom Form managed_file multiple upload field restrict limit number of upload files

2.7k views Asked by At

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

2

There are 2 answers

0
Aporie On

There is currently an opened issue to get this feature out of the box.

In the meanwhile, you can implement "element_validate" in your form:

$form['file_managed'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Files'),
  '#multiple' => TRUE,
  '#cardinality' => 3,
  '#element_validate' => [
    'your_module_max_files_validation',
  ],
];

Then in your_module.module:

/**
 * Custom validation handler. Validate number of files.
 */
function your_module_max_files_validation($element, FormStateInterface &$form_state, $form) {
  $is_removal = strpos($form_state->getTriggeringElement()['#name'], 'remove_button') !== FALSE ? TRUE : FALSE;
  if (!empty($element['#cardinality']) && count($element['#files']) > $element['#cardinality'] && !$is_removal) {
    $form_state->setErrorByName($element['#name'], t('Only max @limit files allowed.', [
      '@limit' => $element['#cardinality'],
    ]));
  }
}
0
Beyer On
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>."));}}