我最近开始学习 ZF2,希望有人可以帮助我。
我正在学习 Rob Allen 的 Zend Framework 2 教程(非常感谢@rob-allen)。
我还使用了@AlloVince 和@Maciej How to set db adapter to Validator RecordExists in Zend Framework 2的解决方案(非常感谢两位作者),我很困惑,因为没有在editAction中使用这个解决方案。
我Fatal error: Call to a member function get() on a non-object
在'adapter' => $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
.
1)在Module.php中添加
public function getServiceConfig() { return array( 'invokables' => array( 'RegionModel' => 'FcLibraries\Model\Region', //<-- added it ), 'factories' => array( 'FcLibraries\Model\RegionTable' => function ($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $table = new RegionTable($dbAdapter); return $table; }, ), ); }
2)在Region.php中添加
/** * @var */ protected $serviceLocator; /** * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator * @return Library */ public function setServiceLocator(ServiceLocatorInterface $serviceLocator) { $this->serviceLocator = $serviceLocator; return $this; } /** * @return \Zend\ServiceManager\ServiceLocatorInterface */ public function getServiceLocator() { return $this->serviceLocator; }
和
$inputFilter->add($factory->createInput(array( 'name' => 'name', 'required' => true, 'filters' => $this->_filters, 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 1, 'max' => 30, ), ), array( 'name' => 'Db\NoRecordExists', 'options' => array( 'table' => $this->table, 'field' => 'name', //'exclude' => array( // 'field' => 'id', // 'value' => $this->id //), 'adapter' => $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), ), ), ), )));
3)在 addAction 中的 RegionController.php 中使用
$model = $this->getServiceLocator()->get('RegionModel');
而不是$model = new Region();
.
这适用于 addAction,但我不明白应该如何在 editAction 中使用它。
我的
public function editAction() { $id = (int)$this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('zfcadmin/region', array( 'action' => 'add' )); } $data = $this->getRegionTable()->get($id); $form = new RegionForm(); $form->bind($data); $form->get('submitBtn')->setAttribute('value', 'Save'); $request = $this->getRequest(); if ($request->isPost()) { $form->setInputFilter($data->getInputFilter()); $form->setData($request->getPost()); if ($form->isValid()) { $this->getRegionTable()->save($form->getData()); return $this->redirect()->toRoute('zfcadmin/regions'); } } return array( 'id' => $id, 'form' => $form, ); }
我的 RegionTable 有以下代码:
/** * @param \Zend\Db\Adapter\Adapter $adapter */ public function __construct(Adapter $adapter) { $this->adapter = $adapter; $this->resultSetPrototype = new ResultSet(); $this->resultSetPrototype->setArrayObjectPrototype(new Region()); $this->initialize(); } public function get($id) { $id = (int)$id; $rowSet = $this->select(array('id' => $id)); $row = $rowSet->current(); if (!$row) { throw new \Exception("Could not find row $id"); } return $row; }
非常感谢所有回答我问题的人。
最好的问候,鲁斯兰。