I'm trying to modify a custom block form with hook_form_alter
.In its validate function I have a case where one of the field value needs to be unset. For modifying its value I tried with
$form_state->setValue('field_name', '')
/
$form['field_name']['#default_value'] = ''
/
$form['field_name']['#value'] = ''
But none of these approach seems to work. Below is my code -
function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
//create or edit form
if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
$form['#validate'][] = 'coolblockvalidate';
}
}
function coolblockvalidate(array &$form, FormStateInterface &$form_state) {
//trying to unset the field value here, which is not working.
$form_state->setValue('field_mycoolfield', '');
//tried these approach too with no luck.
//$form['field_mycoolfield']['#default_value'] = '';
//$form['field_mycoolfield']['#default_value'] = '';
}
I'm very interested in knowing why the field value can't be changed. I tried the same with a custom form alter and it works.
Any ideas/ suggestions would save me. Thanks.