如何使用drupal自定义模块获取数据库表

Posted

技术标签:

【中文标题】如何使用drupal自定义模块获取数据库表【英文标题】:how to fetch database table using drupal custom module 【发布时间】:2017-04-04 09:30:38 【问题描述】:

我尝试开发一个自定义模块,它有两个日期弹出窗口“start_date”和“end_date”,我有一个数据库表,其中包含 ID、姓名、支付日期、支付金额。我需要获取数据库并显示为点击按钮上的表格。我在drupal中编写了一些代码,如果有错误请更正,并请指导我获取特定日期范围的表格 form design

我的编码:

Uniview8PastpaymentsController.php

<?php

namespace Drupal\uniview8_pastpayments\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\uniview8_pastpayments\Uniview8PastPaymentsStorage;

class Uniview8PastpaymentsController extends ControllerBase 
  public function entryList() 
    $content = array();

    $content['message'] = array(
      '#markup' => $this->t('Pastpayment history for selected date ranges.'),
    );

    $rows = array();
    $headers = array(t('Id'), t('Name'), t('Paid Date'), t('Paid Amount'));

    foreach ($entries = Uniview8PastPaymentsStorage::load() as $entry) 
      $rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', (array) $entry);
    
    $content['table'] = array(
      '#type' => 'table',
      '#header' => $headers,
      '#rows' => $rows,
      '#empty' => t('No entries available.'),
    );
    $content['#cache']['max-age'] = 0;

    return $content;
  

表格 uniview8_pastpayments.php

<?php

namespace Drupal\uniview8_pastpayments\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class uniview8_pastpayments extends FormBase 

  public function getFormId() 
    return 'uniview8_pastpayments';
  

 public function buildForm(array $form, FormStateInterface $form_state) 

 $form['set_start_date'] = [
      '#title' => $this->t('START DATE '),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];


 $form['set_end_date'] = [
      '#title' => $this->t('END DATE'),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];


  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Fetch'),
      '#button_type' => 'primary',
    );
    return $form;





如何使用提交按钮获取数据库

**DB_select Function
Uniview8PastPaymentsStorage.php**
<?php
namespace Drupal\uniview8_pastpayments;
class Uniview8PastPaymentsStorage 

  public static function load($entry = array()) 

    $select = db_select('pastpayments', 'example');
    $select->fields('example')
    $select->condition('paiddate',$entry['set_start_date'], '>=')
    $select->condition('paiddate',$entry['set_end_date'], '>=')
    $select->execute();

    foreach ($entry as $field => $value) 
      $select->condition($field, $value);
    
    // Return the result in object format.
    return $select->execute()->fetchAll();
  

【问题讨论】:

【参考方案1】:

如果您的表单显示在您的控制器页面上,那么您必须在表单提交中使用 ajax 像这样

<?php

namespace Drupal\uniview8_pastpayments\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\htmlCommand;
use Drupal\Core\Ajax\InvokeCommand;


class uniview8_pastpayments extends FormBase 

  public function getFormId() 
    return 'uniview8_pastpayments';
  

 public function buildForm(array $form, FormStateInterface $form_state) 

 $form['set_start_date'] = [
      '#title' => $this->t('START DATE '),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];


 $form['set_end_date'] = [
      '#title' => $this->t('END DATE'),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];


  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Fetch'),
      '#ajax' => [
          //'callback' => 'Drupal\mcal_textmining\Form\CreateReportsForm::submitCreateReport',
          'callback' => array($this, 'fetchResult'),
          'event' => 'click',
          'progress' => array(
              'type' => 'throbber',
              'message' => t('Submitting...')
          )
      ]
    );
    return $form;



 /**
   * @inheritdoc
   */
  public function validateForm(array &$form, FormStateInterface $form_state) 
  

  /**
   * @inheritdoc
   */
  public function submitForm(array &$form, FormStateInterface $form_state) 

  

  /**
   * @inheritdoc
   */
  public function fetchResult(array &$form, FormStateInterface $form_state) 
     $maxDate = $form_state->getValue('set_start_date');
     $minDate = $form_state->getValue('set_end_date');
     $connection = Database::getConnection();
     $single = $connection->select('pastpayments', 'x')
        ->fields('x', array('Id','name','paiddate','paidamount'))
        ->condition('paiddate', $maxDate, "<=")
        ->condition('paiddate', $minDate, ">=");
     $executed = $single->execute();
     $results = $executed->fetchAssoc();
     foreach($results as $result)
       /*
          creat html table's tbody with result
          like
          $tbody .= "<tr><td>paidamount</td></tr>" 
      */

     
     // now append the result into the table as tbody
     // with drupal ajax 
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('tbodyID', $tbody));
     return $response;

  

但是如果您的表单在另一个页面并且在提交表单后将用户重定向到您的控制器页面,则将 startdate 和 enddate 作为参数发送给控制器,然后从您的控制器进行数据库查询

然后将结果追加到页面中 谢谢

【讨论】:

以上是关于如何使用drupal自定义模块获取数据库表的主要内容,如果未能解决你的问题,请参考以下文章

Drupal 7 - 自定义模块:在节点提交中使用自定义表单输入

如何通过样式表自定义 QTableWidget?

drupal - 如何在视图模块中为每种网格格式添加自定义 CSS?

如何仅基于用户角色 Drupal 自定义 drupal 过滤器

Django数据库如何将一个表自定义的key列还原成id列作为key

如何在 drupal 中的自定义实体上定义和执行 CRUD