drupalformsactiondrupal-fapidrupal-alter

How to override form action in Drupal?


I originally started this question in another thread, but that thread was sorta, kinda answered, and now I primarily want to know how to specify another form action... I tried using the code below, but the form action, when output, remains unchanged, although looking at the print_r($form), it's correctly changed... Why isn't it picking up?

function mytheme_user_profile_form($form) {
        global $user;
        $uid = $user->uid;
        //print '<pre>'; print_r($form); print '</pre>';
    $category = $form['_category']['#value'];

    switch($category) {
            case 'account':
                $form['#action'] = '/user/'.$uid.'/edit?destination=user/'.$uid;
                        break;
        case 'education':
                        $form['#action'] = '/user/'.$uid.'/edit/education?destination=user/'.$uid;
                        break;
        case 'experience':
                        $form['#action'] = '/user/'.$uid.'/edit/experience?destination=user/'.$uid;
                        break;
            case 'publications':
                        $form['#action'] = '/user/'.$uid.'/edit/publications?destination=user/'.$uid;
                        break;
        case 'conflicts':
                        $form['#action'] = '/user/'.$uid.'/edit/conflicts?destination=user/'.$uid;
                        break;
    }

        //print '<pre>'; print_r($form); print '</pre>';
        //print $form['#action'];
        $output .= drupal_render($form);
        return $output;

Solution

  • hook_form_alter() is likely the way to go. Here are some hopefully helpful links:

    Form Theming: How do I set $form['action']?

    Modifying Forms in Drupal 5 and 6

    hook_form_alter

    EDIT: reply to comment #1 below:

    How to implement hook_form_alter():

    You must create a module (you cannot use template.php). It's easier than it looks.

    For a module named "formstuff", you would create formstuff.info and formstuff.module and put them in either sites/all/modules or sites/yoursitename/modules. Set up the .info and .module files per the instructions, then just create the following function in your .module file:

    function formstuff_form_alter(&$form, $form_state, $form_id) {
      // do stuff
    }
    

    This function is a hook because it is named properly (i.e. replace the word 'hook' with the name of your module), and it matches hook_form_alter's function signature (i.e. it takes the same parameters).

    Then just enable your module in your site's admin and the hook should do it's magic.

    Note that hook_form_alter takes a reference to the form; this allows you to modify it in-place.