[英]How to set a form field value by using setter in Symfony2
I have a form that have an own model contains setters and getters like that: 我有一个具有自己的模型的表单,其中包含像这样的setter和getter:
class CommentAdd
{
protected $content;
protected $yandexCaptcha;
protected $isAnonymous;
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setYandexCaptcha(YandexCaptcha $yandexCaptcha) {
$this->yandexCaptcha = $yandexCaptcha;
}
public function getYandexCaptcha() {
return $this->yandexCaptcha;
}
public function setIsAnonymous($isAnonymous) {
$this->isAnonymous = $isAnonymous;
}
public function getIsAnonymous() {
return $this->isAnonymous;
}
}
So what is the way to set any field value by calling setter? 那么,通过调用setter设置任何字段值的方法是什么? I know the way to get any value by using getter ($form->getData()->getValue()) but I don't know the way to set.
我知道使用getter($ form-> getData()-> getValue())获取任何值的方法,但我不知道设置的方法。
Update: 更新:
The form object is created so: 表单对象的创建如下:
$commentAddForm = $this->createForm(new CommentAddType(), new CommentAdd(), [
'action' => $this->generateUrl('blog_comment_add', ['id' => $id]),
'is_authenticated' => $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')
]);
//That will return value by using the getter getContent from CommentAdd model
$commentAddForm->getData()->getContent();
//That will return value without using getter from the model
$commentAddForm->get('content')->getData();
//Now I want to know the way to set any data by using setter from the model
$commentAddForm-> ???
PS I'm sorry for my English. 附注:对不起,我的英语。
You set the data on the object instance from which you create the form; 您在创建表单的对象实例上设置数据; not on the form fields themselves.
不在表单字段本身上。 As per the Symfony documentation :
根据Symfony文档 :
$task = new Task();
$task->setTask('Write a blog post');
$task->setDueDate(new \DateTime('tomorrow'));
$form = $this->createFormBuilder($task)
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.