Custom Ajax forms with managed_file form element

We have a form with three fields – where depending on the value of the first select field, we will show the other two form elements – one select field (the options depends on the value of the first select field) and one file upload field.

The issue is that when I upload a file the second select list value is resetting. Because managed_file form element is again calling an ajax function which overrides the value of my first ajax call

Code is below:

public function buildForm(array $form, FormStateInterface $form_state) {     $texts = array();     $text_values = db_query("SELECT text_id, title FROM `heritage_text_structure`")->fetchAll();     foreach($text_values AS $key => $value){         $texts[$value->text_id] = $value->title;     }     $form['text'] = array(         '#type' => 'select',         '#title' => $this->t('Select the heritage text'),         '#required' => TRUE,         '#options' => $texts,         '#default_value' => isset($form['text']['#default_value'])?$form['text']['#default_value']:null,         '#ajax' => array(             'event' => 'change',             'wrapper' => 'text-info',             'callback' => '::_ajax_text_callback',         ),     );     if(!empty($form_state->getTriggeringElement())) {         $description = '';         $text_id = $form_state->getTriggeringElement()['#value'];         $labels = db_query("SELECT level_labels FROM `heritage_text_structure` WHERE text_id = :text_id", array(':text_id' => $text_id))->fetchField();         $labels_array = explode(',', $labels);         $label_count = count($labels_array);         for($i=0; $i<count($labels_array); $i++){             if($i < $label_count-1)                 $description = $description.$labels_array[$i].', ';             else $description = $description.$labels_array[$i];         }         $description = $description.', Content, Language';         $csvCount = $label_count + 2;     }     $form['text_info'] = array(         '#type' => 'container',         '#prefix' => '<div id="text-info">',         '#suffix' => '</div>'     );     if(isset($text_id) && $text_id > 0){         $validators = array(             'file_validate_extensions' => array('csv '),         );         $form['text_info']['fieldset'] = array(             '#type' => 'fieldset',             '#title' => $this->t('Select the Target Source'),             '#description' => $this->t('Choose the source into which you are importing content'),          );         $sources = array();         $source_values = db_query("SELECT id, title FROM `heritage_source_nodes` WHERE text_id = :text_id", array('text_id' => $text_id))->fetchAll();         foreach($source_values AS $key => $value){             $sources[$value->id] = $value->title;         }         $form['text_info']['fieldset']['sources'] = array(             '#type' => 'select',             '#title' => $this->t('Select the Source to which content is imported'),             '#required' => TRUE,             '#options' => $sources,             '#default_value' => isset($form['text_info']['fieldset']['sources']['widget']['#default_value'])?$form['text_info']['fieldset']['sources']['widget']['#default_value']:null,         );         $form['text_info']['fieldset']['file'] = array(             '#type' => 'managed_file',             '#title' => t('Upload the Content in CSV format'),             '#size' => 20,             '#description' => t('CSV file (eg: '.$description.'). Please maintain the order of the fields.'),             '#upload_location' => 'public://file_uploads/',             '#upload_validators' => $validators,         );         $form['text_info']['fieldset']['csv_count'] = array(             '#type' => 'hidden',             '#value' => $csvCount,         );     }     $form['actions']['submit'] = array(         '#type' => 'submit',         '#value' => $this->t('Import Content'),     );     return $form; } /** * {@inheritdoc} Map content to the corresponding fields. */ public function submitForm(array &$form, FormStateInterface $form_state) {     $text = $form_state->getValue('text');     print("<pre>");print_r($form_state->getValue());exit; }  /** * Ajax callback function */ public function _ajax_text_callback(array $form, FormStateInterface $form_state) {     return $form['text_info']; } 
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Custom Ajax forms with managed_file form element

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.