在symfony2中显示错误消息

时间:2014-05-25 10:18:45

标签: symfony flush

我是symfony的新手,我做了一个表单来注册新用户,表单很简单;电子邮件,名称和密码。我想根据异常显示错误消息。示例(用户名存在)。我的代码工作正常,但如何捕获异常并显示错误???

public function signupAction(Request $request) {
    if ($request->getMethod() == 'POST') {
        $username = $request->get('username');
        $firstname = $request->get('firstname');
        $password = $request->get('password');

        $user = new Users();
        $user->setFirstName($firstname);
        $user->setPassword(sha1($password));
        $user->setUserName($username);
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($user);
        $em->flush();
    }

    return $this->render('LoginLoginBundle:Default:signup.html.twig');
}

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用自己的FormType类执行此操作,如下所示:

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('username')
            ->add('password')
        ;
    }

    ...
}

在你的控制器中,你会写这样的东西:

/**
 * Displays a form to create a new User entity.
 *
 * @Method("GET")
 * @Template()
 */
public function newAction()
{
    $entity = new User();
    $form   = $this->createCreateForm($entity);

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

/**
 * @Method("POST")
 * @Template("CoreBundle:User:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity     = new User();
    $form       = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('user_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

/**
 * Creates a form to create a User entity.
 *
 * @param User $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(User $entity)
{
    $form = $this->createForm(new UserType(), $entity, array(
        'action' => $this->generateUrl('user_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

在您的实体用户中,您需要添加约束以确保您的用户名是唯一的:

use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity("username")
 */
class Author{
    ...
}

这样,如果表单无效或使用了用户名字段,您将使用错误呈现User表单。

您可以在http://symfony.com/doc/current/reference/constraints.html

中详细了解约束

如果您想管理自己的用户帐户,我建议您查看FOSUserBundle。 https://github.com/FriendsOfSymfony/FOSUserBundle