POST后我有通常的表格:
$entity = new SomeEntity();
$form = $this->createForm(new SomeType(), $entity);
$form->handleRequest($request);
而不是做
if($form->isValid()) {
$session = new Session();
$session->start();
$session->set('name', $entity->name())
...
}
如果验证通过,表单是否有办法检测验证并在会话中设置值?
这是太多的逻辑我不想泄露到控制器中它会使我的表单更可重用。
答案 0 :(得分:1)
Symfony2中没有内置方法来检测验证。
使用表单事件来检测何时提交数据,然后执行验证和其余逻辑。
form.post_set_data
(POST_SET_DATA
)或form.post_submit
(POST_SUBMIT
)是最佳选择。在Symfony v2.3之前form.post_submit
是form.post_bind
。
另请查看this cookbook article以获取有关Symfony中表单事件的更多信息。
例如:
表格
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Acme\DemoBundle\Service\SomeService;
class SomeType extends AbstractType
{
private $someService;
public function __construct(SomeService $someService)
{
$this->someService = $someService;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// your form field declarations go here...
$builder->addEventListener(
FormEvents::POST_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
if ($form->isValid()) {
$entity = $form->getData();
$this->someService->doSomething($entity);
}
}
);
}
}
服务
namespace Acme\DemoBundle\Service;
use Symfony\Component\HttpFoundation\RequestStack;
class SomeService
{
private $request;
public function __construct(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
}
public function doSomething($entity)
{
$session = $this->request->getSession();
$session->getFlashBag()->add('name', $entity->name());
}
}
注册服务
acme.demo.service.some:
class: Acme\DemoBundle\Service\SomeService
arguments: ['@request_stack']