Drupal 7 - Change field widget type based on form status (add/edit)

2k Views Asked by At

I have an entity reference field using Autocomplete widget type. I´d like to change the widget type to 'select list' for adding new node, and keep autocomplete when editing.

Have been two days I´m working on this. I didn´t found any solution.

1

There are 1 best solutions below

1
On

One way I've done this is using hook_form_alter. Create a custom module (if you don't have one already (let's call it mymodule for now) and add the function:

function mymodule_form_alter(&$form, &$form_state, $form_id)

In there you can check the id to see which form is being processed, it should be something along the lines of mytype_node_form but you can also inspect it fairly easily by executing something like drupal_set_message(print_r($form_id, true)); in the function.

You can check to see if you're adding or updating by checking $form_state['node']->nid. After that you can modify the form by doing something like the following:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    // check to see if this is our form and it is a new node form (doesn't have an id yet)
    if ($form_id == 'mytype_node_form' && !isset($form_state['node']->nid)) {
        $form['field_coordinators']['und']['#type'] = 'select';
    }
}

That's just a start mind you, you'll likely have to change or even remove other properties but you can look into these settings by setting the field to use a select list and inspecting the structure of $form, again.