我想保存一些数据,其中部分数据来自用户通过表单提交的部分,而另一部分则是在实际控制器中生成的。如下所示:
# controller
use Acme\SomeBundle\Entity\Variant;
use Acme\SomeBundle\Form\Type\VariantType;
public function saveAction()
{
$request = $this->getRequest();
// adding the data from user submitted from
$form = $this->createForm(new VariantType());
$form->bindRequest($request);
// how do I add this data to the form object for validation etc
$foo = "Some value from the controller";
$bar = array(1,2,3,4);
/* $form-> ...something... -> setFoo($foo); ?? */
if ($form->isValid()) {
$data = $form->getData();
// my service layer that does the writing to the DB
$myService = $this->get('acme_some.service.variant');
$result = $myService->persist($data);
}
}
如何将$foo
和$bar
放入$form
对象,以便我可以对其进行验证并保留它?
答案 0 :(得分:0)
这是我正在使用的一般模式:
public function createAction(Request $request)
{
$entity = new Entity();
$form = $this->createForm(new EntityType(), $entity);
if ($request->getMethod() == 'POST') {
$foo = "Some value from the controller";
$bar = array(1, 2, 3, 4);
$entity->setFoo($foo);
$entity->setBar($bar);
$form->bindRequest($request);
if ($form->isValid()) {
$this->get('some.service')->save($entity);
// redirect
}
}
// render the template with the form
}
答案 1 :(得分:0)
阅读Form类的bind
方法的代码,我们可以阅读:
// Hook to change content of the data bound by the browser
$event = new FilterDataEvent($this, $clientData);
$this->dispatcher->dispatch(FormEvents::BIND_CLIENT_DATA, $event);
$clientData = $event->getData()
所以我猜你可以用这个钩子添加你的两个字段。