I followed this tutorial: https://rapiddg.com/blog/creating-ajax-callback-user-reference-fields
to create a button to fill some field in a form with the values of the current user.
Here the cose I added to my hoo_form_alter:
if ($form_id == 'datore_node_form')
{
global $user;
$form['title']['#type'] = 'hidden';
$form['title']['#value'] = 'test';
$form['user_replace'] = array(
'#title' => t("User Information"),
'#prefix' => '<div id="datore_node_form_group_cs">',
//name of the node form (already existing, if you're modifying an existing node form)
'#suffix' =>'</div>',
$form['user_replace']['user_copy'] = array(
'#type' => 'button',
'#value' => 'Sono io il datore!',
'#ajax' => array(
'event'=>'click',
'callback' =>'user_replace_ajax_callback',
'wrapper' => 'datore_node_form_group_cs',
),
),
);
$form['user_replace']['field_cognome'] = $form['field_cognome'];
unset($form['field_cognome']);
$user = user_load($user->uid);
dpm($user);
dpm($user->field_cognome['und'][0]['value']);
dpm($form);
dpm($form_state);
if (!empty($form_state['values']['field_cognome']))
{
unset($form_state['input']['field_cognome']['und'][0]['value']);
$form_state['input']['field_cognome']['und'][0]['value'] = $user->field_cognome['und'][0]['value'];
return $form;
}
function user_replace_ajax_callback($form, &$form_state)
{
ajax_command_alert("hello"); // doesn't work
return $form['user_replace'];
}
but if I click the button nothing happen. Any advise?
type => '#ajax'
dpm()
calls. It will make debugging tougher for AJAX calls. Look into using xdebug. But in order to use ajax commands, your callback has to return an array of commands as an#ajax
response type. See the callback function in this example: redcrackle.com/blog/… or the ajax callback here jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7