【问题标题】:Custom Drupal Module, how to post query results to a Form自定义 Drupal 模块,如何将查询结果发布到表单
【发布时间】:2020-04-29 20:51:52
【问题描述】:

我有一个自定义模块,当用户导航到特定页面时,它可以通过执行获取 50 条记录的查询来成功显示查询结果。我想使用表单来收集用户输入以创建更具体的查询。

我的表单正在工作,它确实收集数据,它运行查询,但我无法让结果显示在同一个表单上。我已经在 Google 上搜索了很多小时,但找不到明确的答案。表格如下:

public function buildForm(array $form, FormStateInterface $form_state){
   $form['employee_last_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Last Name:'),
            '#default_value' => (isset($record['LAST_NAME'])) ? $record['LAST_NAME']:'',
            '#attributes' => array('class' => array('test')
            )
    );

当表单返回结果时,我正在尝试写入表单,但它似乎不起作用。我需要重建表格显示表格吗?我希望将结果显示在与表单字段相同的页面上。我正在迭代结果并将其放入表声明中使用的 $rows 变量中

表格:

       $form['table'] = [
                '#type' => 'table',
                '#header' => $header_table,
                '#rows' => $rows,
                '#empty' => t('No users found'),
        ];

谢谢

【问题讨论】:

  • 你想使用ajax提交表单吗?显示您的提交功能。
  • 不,我只是想将结果发布回表单本身。提交函数是查询发生的地方:
  • 我在提交中这样做:$form_state = new FormState(); $form_state->setRebuild(); $form_state->set('result', 'test'); $form_state->set('result_table', $form['results_table']); $searchForm = \Drupal::formBuilder()->buildForm('Drupal\workforce_data\Form\SearchForm', $form_state); return [ 'form' => $searchForm, ];

标签: drupal drupal-8 drupal-forms form-api


【解决方案1】:

我刚刚完成了以下操作,它在表单上方显示了一个结果表。 我的 buildForm 函数的顶部如下所示:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['results'] = $form_state->getValue("results_table");

第一次访问页面$form_state->getValue("results_table") 没有任何值,所以什么也没有显示。 在我的 submitForm 函数中,我对表单输入进行了一些处理,然后将结果打包到 $form_state 中,如下所示:

public function submitForm(array &$form, FormStateInterface $form_state) {

  // do stuff with form values and put results into table rows.

  $table = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty'  => "no values"
  ];

  $form_state->setValue("results_table", $table);

  $form_state->setRebuild(TRUE);
}

当我提交填写的表单时,我会返回到表单视图,并在表单上方显示一个结果表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多