I want to conditionally change the widget of a plain text field attached to a node by using hook_form_alter in Drupal 8.7.6.
function mymodule_form_node_article_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$options=[
'test1' => 'AAA',
'test2' => 'BBB',
'test3' => 'CCC',
'test4' => 'DDD',
];
$form['field_testdrop']['widget'][0]['#type']='select';
$form['field_testdrop']['widget'][0]['#options'] = $options;
}
However, when trying to save the node, I get the following error:
Error: Cannot create references to/from string offsets in Drupal\Component\Utility\NestedArray::setValue() (line 155 of core/lib/Drupal/Component/Utility/NestedArray.php).
What can I do to prevent this?
This Works:
$form['field_priority_email_id']['widget'][0]['value']['#type'] = 'select';
$form['field_priority_email_id']['widget'][0]['value']['#options'] = $options;
$form['field_priority_email_id']['widget'][0]['value']['#size'] = NULL;
You have to set '#size' to NULL or the select widget will not render correctly.