I have 2 fields in a form. One select list and another entity reference field referring to a Paragraph type (multivalued). The on-change event should trigger an ajax callback which will disable some of the fields in the paragraph type. I managed to achieve this on ajax callback. Now, the problem is when I add more values to the paragraph the previous disabled field goes back to the default state. Any suggestions /examples will be helpful. Below is my code. Thanks.
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
//Ajax callback on change event
if (isset($form['field_link_type'])) {
$form['field_select_sample']['widget']['#ajax'] = array(
'callback' => '_my_ajaxcallback',
'event' => 'change',
);
}
}
function _my_ajaxcallback(array $form, FormStateInterface $form_state) {
$response = new \Drupal\Core\Ajax\AjaxResponse();
//disable field_htext of paragraph field
$response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));
return $response;
}
Updated code - In my callback -
echo 'disabled - ' . $form_state->get('field_header_disabled');`
$form_state->set('field_header_disabled', TRUE);`
echo $form_state->get('field_header_disabled');
return $response;
The output is something like - disabled - 1 on both first and second callbacks. On second callback I'm expecting the output to be something like disabled - 11
$form_state
, that the fields are disabled/enabled and in yourhook_form_alter()
read that flag from$form_state
and set the field attributes accordingly.disabled - 11
? - You echo the value only once...disabled -
.I am ok with that coz this is the first callback and thefield_header_disabled
is not yet set. On the next line I'm setting thefield_header_disabled
and again echoed as1
. Till here I concur with you. Now, when I trigger the callback function for the second time it should give medisabled - 1
in the first line and once again output1
in the third line. So altogether it should output something asdisabled - 11
. Right?