所有视图中的Symfony访问表单

时间:2016-11-04 11:46:24

标签: forms symfony

我在应用程序中有一个登录/注册表单。

namespace UserBundle\Form;

use Symfony\Component\Form\AbstractType;

class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('username', 'text', ['label' => 'Username']);
        $builder->add('email', 'hidden', ['label' => 'Email']);
        $builder->add('password', 'password',['label' => 'Password']);

        $builder->add('cancel', SubmitType::class, [
            'label' => 'CANCEL'
        ]);

        $builder->add('register', SubmitType::class, [
            'label' => 'CREATE ACCOUNT'
        ]);
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'UserBundle\Entity\User',
        ]);
    }
}

我希望所有页面都提供此功能,因此我希望将表单标记放在base.html.twig

我的问题是,Symfony推荐的做法是什么?我不想继续在控制器的每个动作中传递表单。

我如何得到它?通过定义服务?任何例子或指针都表示赞赏。

感谢。

2 个答案:

答案 0 :(得分:3)

我会有一个处理表格的专用控制器 然后,您可以直接从twig调用此控制器操作,将控制器调用添加到主layout.html.twig中。

E.g。

{% render controller('AppBundle:Login:form') %}

和控制器类似;

class LoginController extends Controller 
{
  public function form(Request $request)
  {
    // create your form

    // return html of form
  }
}

参考:How to load a controller function and render it in a twig tag using Symfony2? - 看看@Blowski的回答

注册示例;

<?php
namespace AppBundle\Controller\Security;

use AppBundle\Entity\User,
    AppBundle\Form\Entity\UserType;
use \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
    Symfony\Component\HttpFoundation\Request;

class RegistrationController extends Controller
{
    /**
     * @Route("/register", name="user_registration")
     */
    public function registerAction(Request $request)
    {
        // 1) build the form
        $user = new User();
        $form = $this->createForm(UserType::class, $user);

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // 4) save the User!
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            // ... do any other work - like sending them an email, etc
            // maybe set a "flash" success message for the user

            return $this->redirectToRoute('replace_with_some_route');
        }

        return $this->render(
            'AppBundle:security:register.html.twig',
            array('form' => $form->createView())
        );
    }
}

答案 1 :(得分:2)

您的意思是传递FormView的{​​{1}}实例?

我认为最容易创建的Twig扩展名将RegisterType作为其依赖项注册,并将使用表单视图公开函数(或者甚至是全局变量)。然后,您也可以只使用一个表单视图实例,并根据需要多次使用它。

请参阅http://symfony.com/doc/current/templating/twig_extension.html