1

I have a basic form like this, that is literally just a submit button:

function mymodule_form($form, &$form_state) {
    $form = array();

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'callback' => 'mymodule_form',
        ),
    );

    return $form;
}

The form uses Drupal's built in #ajax feature, and calls back to itself because nothing is supposed to change after the submit button is clicked.

I also have this form submit function that submits that form:

function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load(arg(1));

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

This form submit should, in theory, add the current nodes ID to the 'nid' column of mydatabase, and 'value1' to the 'column1' column. The form submit correctly adds 'value1' to my 'column1', however it adds NULL to my 'nid' column every time. But ONLY when ajax is enabled on the form. When ajax is disabled, it correctly submits the node ID. Which leads me to believe there is either an issue with using node_load in an ajax form submit, or using arg(1) in an ajax form submit.

Any advice would be appreciated.

1

I ended up finding a solution to this. Essentially, instead of trying to load the arg(1) inside the mymodule_form_submit (because apparently you can't do that when the submit is triggered via ajax), I instead passed the node ID to the form submit through a hidden form field. See below:

function mymodule_form($form, &$form_state) {
    $form = array();

    $form['node'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'callback' => 'mymodule_form',
        ),
    );

    return $form;
}


function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load($form['node']['#value']);

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

And now it works just fine.

0

I had the same problem. You can pull entity_id from $form_state:

Something like this:

// arg(1) returns 'ajax' on ajax request instead node id
$node_id = arg(1) == 'ajax' ? $form_state['build_info']['args']['0']->entity_id : arg(1);
$node = node_load($node_id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.