我试图使用Classmethod()水分器将实体Contact与默认值(使用getter)绑定到ContactForm形式。
问题是当我用一组值调用setData时,Hydrator无法合并默认值和值集,而是仅返回值集。请在下面找到我的代码的摘录。
<?php
// My contact form
namespace Application\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
class Contact extends Form
{
public function __construct($name = 'contact')
{
parent::__construct($name);
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Your name',
),
'type' => 'Text',
));
$this->add(array(
'name' => 'subject',
'options' => array(
'label' => 'Subject',
),
'type' => 'Text',
));
$this->add(new \Zend\Form\Element\Csrf('security'));
$this->add(array(
'name' => 'send',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
),
));
// We could also define the input filter here, or
// lazy-create it in the getInputFilter() method.
}
public function getInputFilter()
{
if (!$this->filter) {
$inputFilter = new InputFilter();
$inputFilter->add(array('name' => 'name', 'required' => false));
$inputFilter->add(array('name' => 'subject', 'required' => false));
$this->filter = $inputFilter;
}
return $this->filter;
}
}
这是我的实体
class Contact
{
protected $name;
protected $subject;
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $subject
*/
public function setSubject($subject)
{
$this->subject = $subject;
}
/**
* @return mixed
*/
public function getSubject()
{
// Trying to set a default value
if (null == $this->subject) {
return 'default subject';
}
return $this->subject;
}
}
这里我在控制器动作中测试它
class TestController extends AbstractActionController
{
public function indexAction()
{
$data = array(
'name' => 'myName'
);
$class = '\Application\Entity\Contact';
$contact = new $class;
$form = new \Application\Form\Contact();
$form->setHydrator(new ClassMethods(false));
$form->bind($contact);
$form->setData($data);
if ($form->isValid()) {
var_dump($form->getData());
}
die("end");
}
}
我想得到
object(Application\Entity\Contact)[---]
protected 'name' => string 'myName' (length=6)
protected 'subject' => string 'default subject' ...
但我得到了这个结果
object(Application\Entity\Contact)[---]
protected 'name' => string 'myName' (length=6)
protected 'subject' => null
任何想法如何使Classmethod()从绑定中提取getter值并合并setData()上的剩余数据?
答案 0 :(得分:2)
实际上很容易设置默认值。 在实体中定义默认值:
class Contact
{
protected $subject = 'Default Subject';
// other properties and methods
}
此外,您还可以在表单中定义默认值:
$this->add(array(
'name' => 'subject',
'options' => array(
'label' => 'Subject',
),
'attributes' => array(
'value' => 'Default Subject'
),
'type' => 'Text',
));