0

I'm triggering an ajax callback on change event of a dropdown, this method returns additional form elements like text fields, number and checkboxes, but for checkboxes the options are not appearing at all.

---------
Container for additional elements

  $form['dynamic_field_container'] = [
                '#type' => 'container',  
                '#attributes' => ['id' => 'dynamic-field-wrapper'],
              ];

----------

   public function ProjectOptions($data, $ProjectOptions)
    {
        return [
            '#type' => 'select',
            '#options' => $data,
            '#title' => t('Options Name'),
            '#required' => TRUE,
            '#default_value' => $ProjectOptions,
     
            '#ajax' => [
              'callback' => [$this,'dynamicFieldCallback'],
              'wrapper' => 'dynamic-field-wrapper',
              'event' => 'change',
              'progress' => [
                'type' => 'throbber',
                'message' => t('Loading...'),
              ],
            ],
        ];
    }

    public function dynamicFieldCallback(array &$form, FormStateInterface $form_state) {
            $form['dynamic_field_container']['number_field'] = [
                    '#type' => 'number',
                    '#title' => t('Number field titile'),
                    '#description' => t('This field changes based on dropdown selection.'),
                    '#required' => TRUE,
                    '#value' =>'555'
                  ];
            $options = [
                        'option1' => 'Option 1',
                        'option2' => 'Option 2',
                        'option3' => 'Option 3',
                ];
            $form['dynamic_field_container']['dynamic_field_checkbox' ] = [
                    '#type' => 'checkboxes',
                    '#title' => t('Titile of the Check box field'),
                    '#description' => t('This field changes based on dropdown selection.'),
                    '#required' => TRUE,
                    '#options' => $options,
                    '#value' => true
                ];
        return $form['dynamic_field_container'];
    } 

In the output, only the title of checkboxes are visible

2
  • See drupal.stackexchange.com/questions/314435/…
    – 4uk4
    Commented Jun 28, 2023 at 18:22
  • Thanks! By calling the processCheckboxes, processAjaxForm i was able to render the options but I'm still unable to set either the '#value' or '#default_value' to the checkboxes element. Commented Jul 5, 2023 at 10:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.