【问题标题】:Fatal error: Call to undefined method, in Drupal 8 database insert致命错误:调用未定义的方法,在 Drupal 8 数据库中插入
【发布时间】:2016-04-18 06:21:42
【问题描述】:
<?php
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Driver\mysql\Connection;

class <classname> extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $data = get_data(); // this just summarises getting all the data from $form_state
    $result = Connection::insert('<database-name>')
      ->fields($data)
      ->execute();

当通过尝试提交表单运行上述操作时(为简洁起见,我将 buildForm 方法排除在外),我得到

Fatal error: Call to undefined method Drupal\<module>\Form\<form-name>::getDriverClass() in <drupal-root>/core/lib/Drupal/Core/Database/Connection.php on line 812

812的方法是insert

/**
 * Prepares and returns an INSERT query object.
 *
 * @param string $table
 *   The table to use for the insert statement.
 * @param array $options
 *   (optional) An array of options on the query.
 *
 * @return \Drupal\Core\Database\Query\Insert
 *   A new Insert query object.
 *
 * @see \Drupal\Core\Database\Query\Insert
 */
public function insert($table, array $options = array()) {
  $class = $this->getDriverClass('Insert');
  return new $class($this, $table, $options);
}

我不是特别熟悉如何在 PHP 中使用面向对象的技术,所以我不知道我的问题是我使用命名空间/use 关键字,还是我尝试过的方式调用insert 方法,与使用外部静态对象相关的其他事情,或者如果完全缺少其他事情。

谁能帮我定位并修复错误?

谢谢。

【问题讨论】:

    标签: php oop drupal namespaces drupal-8


    【解决方案1】:
    1. 你“使用”了错误的类。替换为:

      use Drupal\Core\Database\Connection;
      
    2. 定义一个变量

      /**
      * @var Connection
      */
      protected $db;
      
    3. 填充构造函数

      public function __construct(/* other stuff*/, Connection $db) {
        //stuff
        $this->db = $db;
      }
      
    4. 扩展创建函数

      public static function create(ContainerInterface $container) {
        return new static(
          //stuff
          $container->get('database')
        );
      }
      
    5. 使用它:)

      $this->db->insert()
      

    【讨论】:

      猜你喜欢
      • 2014-02-21
      • 2015-01-28
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 2012-01-06
      相关资源
      最近更新 更多