On a node/add form I have a pair of fields that need to be able to control one another. The first field allows a user to enter a birthdate, the second field allows the user to say the birthdate is unknown.
I have attempted to work with Conditional Fields to make this work but I think for my case AJAX would be better.
If the birthdate_unkown field is not checked then the birthdate field should be required. When the birthdate_unkown field is checked then I would like to be able to make it so that the field is no longer required.
I have a working AJAX callback function I just cannot figure out how to use AJAX to change if the field is required or not.
I have tried options like:
$response->addCommand(new InvokeCommand('edit-field-birthdate-0-value-date','attr',['required', false]));
or
$response->addCommand(new InvokeCommand('edit-field-birthdate-0-value-date','removeAttr',['required']));
I have this code in a function that looks like this:
function _custom_field_unknown_birthday_logic(&$form, FormStateInterface $form_state) {
\Drupal::logger('custom')->error('Unknown Birthday Callback');
$values = $form_state->getValues();
$unknown_birthdate = $values['field_unknown_birthdate']['value'];
\Drupal::logger('custom')->error('Unknown Birthday Callback Value '. $unknown_birthdate);
$response = new AjaxResponse();
if ($unknown_birthdate == false) {
$response->addCommand(new InvokeCommand('edit-field-birthdate-0-value-date','attr',['required']));
\Drupal::logger('custom')->error('Birthdate IS required');
} else if ($unknown_birthdate == true) {
$response->addCommand(new InvokeCommand('edit-field-birthdate-0-value-date','removeAttr',['required'] ));
\Drupal::logger('custom')->error('Birthdate IS NOT required');
} else {
\Drupal::logger('custom')->error('No Change to Birthdate');
}
return $response;
}
With the extensive logging I am doing I can see that I am getting to the right places in the code to issue the AJAX commands. That said the AJAX commands do not appear to change anything. I do not see anything in the console for Dev Tools either.
Any help on figuring out how to do this with AJAX is greatly appreciated. Once I get this working with AJAX there is more that needs to be accomplished that will not work with just States API.
Thanks!