1

In entity, created a form display field using baseFieldDefinitions

$field['blood_type'] = BaseFieldDefinition::create('list_string')
                       ->setLabel('Select the blood type:')
                       ->setSettings(['allowed_values' => array(1 => 'A+ve', 2 => 'o+ve')]);

Now in some other custom module, I alter its state using hook_form_alter

$form['blood_type_fieldset']['report_fieldset'] = array(
          '#type' => 'fieldset',
          '#title' => t('<b>blood report</b>'),
          '#states' => array(
            'visible' => array(
             ':input[name="blood_type"]' => array(
                array('value' => 2),
              ),
            ),
          ),
          '#collapsible' => TRUE, 
          '#collapsed' => FALSE,
          '#weight' => 5,
        );
        $form['blood_type_fieldset']['report_fieldset']['report'] = array(
          '#type' => 'radios',
          '#options' => array('report1' => 'Report 1', 'report2' => 'Report 2'),
          '#default_value' => 1,
          '#weight' => 0,
        );

Now as shown, there are 2 radio buttons named A+ve and O+ve. When I select O+ve, my hook_form_alter gets called up and using #form_states, I get fieldset as shown in code.

Now happens what is, When I initially submit my form, only db field coming from original form gets populated. Means, radio button value O+ve get saved to db, and the report radios which I have selected doesn't get saved to db.

And when second time, I click on edit form, and re-entered values report 1 (say), then it gets saved to db.

Is the reason behind it is hook_form_alter()? Why #form_states is not allowed to be saved on first hit of submit button?

  • What is #form_states? $form_states or #states? – Jimmy Ko Nov 28 '16 at 12:02
  • How are you processing/*validating* the form element value from the additional form element you have added in your form alter? If you do not have an element validate, process or submit, then this is expected behavior because the entity form is not going to know or do anything with additional form state added by form alter that is not entity related. – mradcliffe Nov 28 '16 at 12:15
  • @Jimmy Ko It is #states. – Sugandh Khanna Nov 28 '16 at 12:43
  • @mradcliffe yes, you are right entity form is not going to know or do anything with additional form state added by form alter that is not entity related. Can you suggest any alternative for this? How can I process these additional elements added to form. – Sugandh Khanna Nov 28 '16 at 12:44
  • Because elements get saved on edit mode means on first submit only original form state values get saved to database additional elements added using form_alter get saved to database when I again visit the same form in editing mode. – Sugandh Khanna Nov 28 '16 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.