There are some fields (some required, some not) I need to (conditionally) hide in the user creation form:
function hook_form_alter(&$form, &$form_state, $form_id){
switch($form_id) {
case 'user_register_form':
//variable_name is sent using hook_menu_output_alter()
if ($_REQUEST['variable_name'] == 'variable_value') {
$form['field_id'][LANGUAGE_NONE]['#required'] = FALSE;
$form['field_id']['#access'] = FALSE;
}
}
This generally works but not when I override a (required) entity reference field in the form to change its autocomplete path:
//in another module:
function hook_alter(&$form, &$form_state, $form_id){
$form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#autocomplete_path']= 'custom_autocomplete';
$form['entity_ref_field'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
'callback' => 'custom_callback',
'wrapper' => 'custom_wrapper',
'method' => 'html',
'effect' => 'fade',
);
}
function hook_menu(){
$items = array();
$items['custom_autocomplete'] = array(
'title' => '',
'page callback' => 'custom_page_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_page_autocomplete($string) {
$string = array(':s' => $string . '%');
if ($string) {
$results = db_query("SELECT title, nid FROM {node} as n WHERE type = 'custom_type' and title LIKE :s", $string);
$items = array();
foreach ($results as $result) {
$items[$result->title.' ('.$result->nid.')'] = $result->title;
}
print drupal_json_encode($items);
}
}
function custom_callback(&$form, &$form_state) {
//if an entity reference field value is set, then find & assign values to some other fields, based on that entity:
$entity_id = $form_state['values']['field_id']['und'][0]['target_id'];
if ($selected_entity = node_load($entity_id)) {
$form['field_somefield1'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield1['und'][0]['value'];
$form['field_somefield2'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield2['und'][0]['value'];
$form['field_somefield3'][LANGUAGE_NONE][0]['value']['#value'] = $selected_entity->field_someotherfield3['und'][0]['value'];
}
$commands = array();
$commands[] = ajax_command_replace("#edit-field-user-somefield1", render($form['field_user_somefield1']));
$commands[] = ajax_command_replace("#edit-field-user-somefield2", render($form['field_user_somefield2']));
$commands[] = ajax_command_replace("#edit-field-user-somefield3", render($form['field_user_somefield3']));
return array('#type' => 'ajax', '#commands' => $commands);
}
So, whenever an AJAX call is made by the overridden field and I then submit the form, all the (previously hidden) fields are visible again and the required fields become required again.
Any ideas why this is happening?