red888
red888

Reputation: 31530

Trouble injecting a Zend\Db\Adapter\Adapter instance into my form model

I'm following this tutorial which explains a few approaches to this (I'm doing the first one he lists) and I'm running into some trouble.

My form has Zend\Form\Element\Select populate with values from a DB. Following the tutorial I have this is my controller:

...
//So form can pull select list options from DB
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
var_dump($dbAdapter); //debug
$form = new UpdateForm($dbAdapter);
...

And this in my form model:

...
use Zend\Db\Adapter\AdapterInterface;

class UpdateTicketForm extends Form {
    protected $dbAdapter;

    protected function setDbAdapter(AdapterInterface $dbAdapter) {
        $this->dbAdapter = $dbAdapter;
        return $this;
    }

    protected function getDbAdapter() {
        return $this->dbAdapter;
    }

    public function __construct($name = null,AdapterInterface $dbAdapter) {
        $this->setDbAdapter($dbAdapter);
        parent::__construct('updateForm');
...

When I run it I can see $dbAdapter dumped to the screen appears to be valid, but I still get an error:

object(Zend\Db\Adapter\Adapter)#267 (5) { ["driver":protected]=> object(Zend\Db\Adapter\Driver\Pdo\Pdo)#268 (4) { [...

Catchable fatal error: Argument 2 passed to MyModule\Form\UpdateForm::__construct() must implement interface Zend\Db\Adapter\AdapterInterface, none given, called in ...Controller\MyController.php on line 73 and defined in ...\Form\UpdateForm.php on line 20

The person who wrote the tutorial also posted his source which I, after looking at, still could not determine the issue with my code (corresponding to the "form-db-adapter" approach in his code)

What could be the cause of this issue?

Upvotes: 0

Views: 1282

Answers (2)

Jay Bhatt
Jay Bhatt

Reputation: 5651

The construtoer of your UpdateForm expects two arguments $name and $adapter as shown below.

public function __construct($name = null, AdapterInterface $dbAdapter) {

}

So you should pass two arguments while creating the instance of UpdateForm() as shown below.

$form = new UpdateForm('formName', $dbAdapter);

And if you just want to pass $dbAdapter as the argument change the constructor of UpdateForm to this.

public function __construct(AdapterInterface $dbAdapter, $name = null) {

}

Upvotes: 1

Sergio Rinaudo
Sergio Rinaudo

Reputation: 2363

your form is expecting the DBAdapter as second argument, first argument is form name. Try the follow:

$form = new UpdateForm('myform', $dbAdapter);

Upvotes: 0

Related Questions