1

I've got some form input fields in a paragraph whose visibility need to be dynamically toggled by the value of a another field. This can be done with the states API and the HOOK_field_widget_WIDGETTYPE_form_alter hook.

My problem is that the paragraph is nested inside another paragraph, and I don't know how to get the delta of the parent widget, in order to build my selector name for the states API.

My node has a paragraph field_pagebuilder, which contains another paragraph field_row. All toggleable/dependant fields are inside the same sub-paragraph. This is the code I've got so far:

function wt_pricetable_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($element['#paragraph_type'] == 'pricetable_frontend') {

    $deltaSelf = $context['delta'];
    //////////////////////////////
    $deltaParent = 0; // FIXME: how to I get this?
    //////////////////////////////
    $element['subform']['field_pt_showroom']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'single_room'],
        ],
      ],
    ];
    $element['subform']['field_pt_hiderooms']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
    $element['subform']['field_bem_modifier']['#states'] = [
      'visible' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
      'required' => [
        [
          'select[name="field_pagebuilder['.$deltaParent.'][subform][field_row]['.$deltaSelf.'][subform][field_pt_tablemode]"' => ['value' => 'multi_room'],
        ],
      ],
    ];
  }
}

My problem is the $deltaParent - how can I retrive it?

1

Found it in $context['form']['#parents']. This is an array that contains the keys of the parent widget. In my case it looked like

[ 0 => 'field_pagebuilder',
  1 => ___PARENT_INDEX___,
  2 => 'subform',
]

which allowed me to generate my CSS selector for the states API:

$deltaParent = $context['form']['#parents'][1];

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.