简体   繁体   中英

Fatal error: Call to undefined method, in Drupal 8 database insert

<?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();

When the above is run by attempting to submit the form (I've left the buildForm method out for brevity), I get

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

The method at 812 is 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);
}

I'm not especially familiar with how to use object oriented techniques in PHP, so I don't know whether my problem is with my use of namespaces / the use keyword, or with the way that I've tried to call the insert method, something else relating to using external static objects, or if there's something else entirely missing.

Can anyone help me locate and fix the error?

Thanks.

  1. You "use" the wrong Class. Replace with:

     use Drupal\\Core\\Database\\Connection; 
  2. Define a variable

     /** * @var Connection */ protected $db; 
  3. Fill the constructor

     public function __construct(/* other stuff*/, Connection $db) { //stuff $this->db = $db; } 
  4. extend the create function

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

     $this->db->insert() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM