Symfony的2 - 布局嵌入“没有实体/班形式”验证不工作(Symfony 2 - Layou

2019-10-21 07:00发布

我正在开发symfony的一个博客,我又立刻陷入与被里面的布置形式嵌入。 在我的情况下,简单的搜索。

<div class="b-header-block m-search">
    {{ render(controller('YagoQuinoySimpleBlogBundle:Blog:searchArticles')) }}
</div>

来渲染表单我使用的布局树枝文件内的嵌入控制器。

public function searchArticlesAction(Request $request)
{
    $form = $this->createForm(new SearchArticlesType());

    $form->handleRequest($request);
    if ($form->isValid()) {
        // Do stuff here
    }

    return $this->render('YagoQuinoySimpleBlogBundle:Blog:searchArticles.html.twig', array(
                'form' => $form->createView()
    ));
}

该的indexAction是获取表单数据和过滤器的文章列表中的一个。

public function indexAction(Request $request)
{
    $form = $this->createForm(new SearchArticlesType());
    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        $criteria = array(
            'title' => $data['search']
        );
    } else {
        $criteria = array();
    }

    $articles = $this->getDoctrine()->getRepository('YagoQuinoySimpleBlogBundle:Article')->findBy($criteria, array(
        'createDateTime' => 'DESC'
            ), 5);

    return $this->render('YagoQuinoySimpleBlogBundle:Blog:index.html.twig', array('articles' => $articles));
}

SearchArticlesType是一个窗体类

class SearchArticlesType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('search', 'text', array(
            'constraints' => new NotBlank()
        ))
                ->add('submit', 'submit', array(
                    'label' => 'Buscar'
        ));
    }

    public function getName()
    {
        return 'searchArticles';
    }
}

问题是当我提交此表。 该做的indexAction他的一部分,验证表单和过滤的文章,但是当嵌入控制器尝试验证数据(只用于显示信息或其他)

$form->handleRequest($request);
if ($form->isValid()) {
    // Do stuff here
}

我觉得我失去了一些东西。

谢谢您的帮助!

Answer 1:

当你调用render(controller('your_route'))你实际上是在做一个子请求,这意味着包装袋被清空所以你的请求不被“处理”的表格中的参数。

如果使用的是2.4及以上的,你可以得到使用请求栈的主机请求..

/** @var \Symfony\Component\HttpFoundation\RequestStack $requestStack */
$requestStack = $this->get('request_stack');

$masterRequest = $requestStack->getMasterRequest();

然后,你可以处理该请求在您的渲染器,而不是像现在的(子)的要求..

$form->handleRequest($masterRequest);


Answer 2:

在你的: public function searchArticlesAction(Request $request)你错过了上创建表格的第二个参数

$searchArticle = new SearchArticle(); // I assume this is how you named the Entity, if not just change the entity name
$form = $this->createForm(new SearchArticlesType(), $article);


文章来源: Symfony 2 - Layout embed “no entity/class form” validation isn't working