I am trying to alter the node form layout in a form alter hook.
I altered the node form and added a field set in which I grouped couple of existing fields into a fieldset. Then hid the existing fields so that they don't show up twice:in the fieldset and standalone.
However, after changing the structure, the field content are not being saved on submission. I thought this is due to drupal internal validation. So I thought I would use a validation hook to map the new fields structure to their existing (hidden fields). But I am facing couple of issues:
can't retrieve the values in the validation function using
$formstate->getValue()
.Changing the structure causing the fields to not be processed correctly.
// Group 2 fields: 1 date field and another text field in custom group
$form['custom_group'] = [
'#tree' => TRUE,
'#type' => 'details',
'#title' => t('Custom Group'),
'#weight' => 19,
'#collapsible' => TRUE,
'existing_field_1' => $form['existing_field_1'], // is a date field
'existing_field_2' => $form['existing_field_2'],
];
// Hide the original fields.
$form['existing_field_1']['#access'] = FALSE;
$form['existing_field_2']['#access'] = FALSE;
// Add our validation to try to force the values to be saved:
$form['#validate'][] = 'my_module_form_node_form_validate';
// make my validation first but probably unnecessary:
$form['#validate'] = array_reverse($form['#validate']);
And in the validation function:
function my_module_form_node_form_validate($form, $form_state) {
// grab the field values:
$my_values = $form_state->getValue('custom_group')
}
But I cannot access them this way.
After digging into the issue I was able to access the values:
function my_module_form_node_form_validate($form, $form_state) {
$values = $form_state->getUserInput();
$form_state->setValue('existing_field_1', $values['custom_group']['existing_field_1'];
}
However issue #2 remains.
For example, ->getUserInput();
is returning the raw value of the existing_field_1
which has type date. And the value is just a raw string instead of the normal DateTime object. So it's failing validation. To clarify ->getUserInput()
returns raw string as expected 01-01-2019
and not valid datetime. So I end up with datetime validation error.
I could do the processing myself but that would be an overkill. So, in short, is it possible to use an alter hook two group fields (date/text/esle) into a field set and let drupal process the values?