How to make a form self referencing in Drupal? Or

2019-08-15 17:53发布

问题:

I would like to make a form I have in my website self referencing. Or if that's not an option, how would I go for, for example, showing the results of a search I make in my site?

I have a site in which you search for places and it returns a list of places for your preferences. At the moment my script creates a new node every time a user searches but this isn't convenient anymore. How do I change it so that the page content is changed and I see the results instead of the search form?

Thanks,

回答1:

You should redirect your form to a page passing a query string with the string of what the user searched and then use $_GET['search_param'] in your search/restuls page to handle what will be displayed to the user.

function yourform_form($form_state) {
    $form = array();
    //$form['your_search_field']
    $form['#submit'][] = 'yourform_form_submit';
    return $form;
}

function yourform_form_submit(&$form, $form_state) {
    $query = 'search_param='. $form_state['values']['your_search_field'];
    drupal_goto('search/results', query);
}

If you're using Drupal 7 your submit function should look like:

 function yourform_form_submit(&$form, $form_state) {
        $options['query']['search_param'] = $form_state['values']['your_search_field'];
        drupal_goto('search/results', $options);
    }

After you submit you should be redirected to http://yoursite.com/search/results?search_param=my_search_value

Note that this technique is used by popular search engines:

https://www.google.com/search?q=my_search_value



回答2:

Your form should include $form['#action'] to lead you to specific page after submit:

function example_form($form_state) {
    $form = array();
    //your form code
    //...
    $form['#action'] = url('search/results');
    return $form;
}

On submitting form (example_form_submit) you should take all your values and save them to cookies using user_cookie_save function and on your page you can use this cookies. You also could serialize your values to deal only with one cookie if you want, and then unserialize them on your page. You can delete cookie using user_cookie_delete function.

You should define path search/results where you could take those cookies data and manipulate with it.



标签: php forms drupal