How to use states for inline entities?

Created on 20 August 2016, about 8 years ago
Updated 23 October 2023, about 1 year ago

I would like to use Drupal states together with inline entity form. However, this doesn't seem to work.

Using hook_form_alter to add states I confirm that the child entity can react to field changes in its own form.

Example

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['my_field_a']['#states'] = array(
    'invisible' => array(
      ':input[name="my_field_b"]' => array('value' => 'some_value'),
    ),
  );
}

I expected using hook_inline_entity_form_entity_form_alter() would allow me to add states through the parent entity. But this doesn't seem to work.

function my_module_inline_entity_form_entity_form_alter(&$entity_form, FormStateInterface $form_state) {
  $entity_form['my_field_a']['#states'] = array(
    'invisible' => array(
      ':input[name="my_field_b"]' => array('value' => 'some_value'),
    ),
  );
}

Any suggestions?

πŸ’¬ Support request
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡©πŸ‡°Denmark Roensby

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States ndewhurst USA

    @stijndmd yes, this is possible. Here's an example where a field within a paragraph IEF is displayed based on the value of a field from the parent form. Your specific form structure will vary, so have a look at the parents array and the name of the controlling field.

    function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
      if ($entity_form['#entity_type'] === 'paragraph' && $entity_form['#bundle'] === 'my_paragraph_type') {
        if ($entity_form['#array_parents'][0] === 'field_my_parent_field' && is_numeric($entity_form['#array_parents'][2])) {
          $parent_field_delta = $entity_form['#array_parents'][2];
          $entity_form['my_conditional_field']['widget']['value']['#states'] = [
            'visible' => [
              ":input[name=\"field_my_parent_field[$parent_field_delta][subform][my_controlling_field][value]\"]" => ['checked' => TRUE]
            ],
          ];
        }
      }
    }
    
Production build 0.71.5 2024