【问题标题】:Module development: hook_form(), hook_menu() and how to get $_POST模块开发:hook_form()、hook_menu()以及如何获取$_POST
【发布时间】:2011-03-18 12:50:29
【问题描述】:

我想提高我在模块开发方面的知识(离基础还很远),所以我尝试开发一个周边搜索模块。 我现在实现的是一个包含表单的块:

function perimeter_search_block_view($delta = '') {
  // Define an empty array for the block output.
  $block = array();

  switch($delta) {
    case 'perimeter_search_box':
      $block['subject'] = t('Perimeter search box');
      $block['content'] = drupal_get_form('perimeter_search_form');;
      break;
  }

  return $block;
}

/**
* Implementation of the perimeter search form
* @return array with form data
*/
function perimeter_search_form($form, &$form_state) {
  $form = array(
    '#action' => 'perimeter-search-results',
    'keyword' => array(
      '#type' => 'textfield'
    ),
    'location' => array(
      '#type' => 'textfield'
    ),
    'perimeter' => array(
      '#type' => 'select',
      '#title' => t('Perimeter'),
      '#options' => array('15 km', '30 km', '60 km', '120 km')
    ),
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Start search')
    )
  );

  return $form;
}

我还有一个输出搜索结果的功能:

/**
* Implementation of hook_menu()
* @return defined menu/page items
*/
function perimeter_search_menu() {
  $items = array();

  // Search results page
  $items['perimeter-search-results'] = array(
    'title' => t('Perimeter search results'),
    'page callback' => 'perimeter_search_results',
    'access arguments' => array('view perimeter search'),
    'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/**
* Processing job search queries
*/
function perimeter_search_results() {
  $page_content = t('Search results');
  return $page_content;
} 

我的(简单?)问题是:如何在 perimeter_search_results() 函数中获取帖子数据(关键字、位置、周长)?

【问题讨论】:

    标签: drupal-modules drupal-7


    【解决方案1】:

    很简单,你必须为你的表单创建 _submit 函数,这里是一个例子:

    function perimeter_search_form_submit($form, &$form_state) {
        /*
         * Your data handling goes here on the $form_state['values']['myfieldname']
         * variable.
         */
         drupal_set_message(t('Awesome, you managed to fill the form!'));
    }
    

    如果你需要验证..

    function perimeter_search_form_validate($form, &$form_state) {
        if($form_state['values'['myfieldname'] == '') {
          form_set_error('', t('Hey, it doesn't work like that!'));
        }
    }
    

    请记住,如果您将属性 '#required' => TRUE 添加到表单字段,该字段将自动验证为始终需要该字段,因此如果您不需要对该字段使用验证器只需要编译它。

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2019-07-15
      • 1970-01-01
      相关资源
      最近更新 更多