gpt4 book ai didi

symfony - symfony2中的自定义验证

转载 作者:行者123 更新时间:2023-12-04 04:54:08 24 4
gpt4 key购买 nike

我是symfony的新手。我决定使用Symfony版本2来移动我的方向盘。

在我的用户表单中:

  • 我想验证数据库中电子邮件的唯一性。
  • 我也想通过确认密码字段来验证密码。
  • 我可以在symfony2文档中找到任何帮助。
  • 最佳答案

    这些东西也花了我一段时间来追踪,所以这就是我想出的。老实说,我不太确定User实体的getRoles()方法,但这只是我的测试设置。此类上下文项仅为了清楚起见而提供。

    以下是一些有用的链接,供您进一步阅读:

  • A validation constraint that forces uniqueness
  • A field type for repeated (double-entry-verified) fields

  • 我进行了所有设置,以确保它也可以用作UserProvider以确保安全性,因为我认为您可能正在这样做。我还假设您使用电子邮件作为用户名,但是您不必这样做。您可以创建一个单独的用户名字段并使用它。有关更多信息,请参见 Security

    实体(仅重要部分;省略了可自动生成的 getter / setter ):

    namespace Acme\UserBundle\Entity;

    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
    use Doctrine\ORM\Mapping as ORM;

    /**
    * @ORM\Entity()
    * @ORM\HasLifecycleCallbacks()
    *
    * list any fields here that must be unique
    * @DoctrineAssert\UniqueEntity(
    * fields = { "email" }
    * )
    */
    class User implements UserInterface
    {
    /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @ORM\Column(type="string", length="255", unique="true")
    */
    protected $email;

    /**
    * @ORM\Column(type="string", length="128")
    */
    protected $password;

    /**
    * @ORM\Column(type="string", length="5")
    */
    protected $salt;

    /**
    * Create a new User object
    */
    public function __construct() {
    $this->initSalt();
    }

    /**
    * Generate a new salt - can't be done as prepersist because we need it before then
    */
    public function initSalt() {
    $this->salt = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);
    }

    /**
    * Is the provided user the same as "this"?
    *
    * @return bool
    */
    public function equals(UserInterface $user) {
    if($user->email !== $this->email) {
    return false;
    }

    return true;
    }

    /**
    * Remove sensitive information from the user object
    */
    public function eraseCredentials() {
    $this->password = "";
    $this->salt = "";
    }


    /**
    * Get the list of roles for the user
    *
    * @return string array
    */
    public function getRoles() {
    return array("ROLE_USER");
    }

    /**
    * Get the user's password
    *
    * @return string
    */
    public function getPassword() {
    return $this->password;
    }

    /**
    * Get the user's username
    *
    * We MUST have this to fulfill the requirements of UserInterface
    *
    * @return string
    */
    public function getUsername() {
    return $this->email;
    }

    /**
    * Get the user's "email"
    *
    * @return string
    */
    public function getEmail() {
    return $this->email;
    }

    /**
    * Get the user's salt
    *
    * @return string
    */
    public function getSalt() {
    return $this->salt;
    }

    /**
    * Convert this user to a string representation
    *
    * @return string
    */

    public function __toString() {
    return $this->email;
    }
    }
    ?>

    Form类:

    namespace Acme\UserBundle\Form\Type;

    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;

    class UserType extends AbstractType {
    public function buildForm(FormBuilder $builder, array $options) {
    $builder->add('email');
    /* this field type lets you show two fields that represent just
    one field in the model and they both must match */
    $builder->add('password', 'repeated', array (
    'type' => 'password',
    'first_name' => "Password",
    'second_name' => "Re-enter Password",
    'invalid_message' => "The passwords don't match!"
    ));
    }

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

    public function getDefaultOptions(array $options) {
    return array(
    'data_class' => 'Acme\UserBundle\Entity\User',
    );
    }
    }
    ?>

    Controller :

    namespace Acme\UserBundle\Controller;

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Acme\UserBundle\Entity\User;
    use Acme\UserBundle\Form\Type\UserType;


    class userController extends Controller
    {
    public function newAction(Request $request) {
    $user = new User();
    $form = $this->createForm(new UserType(), $user);

    if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if ($form->isValid()) {
    // encode the password
    $factory = $this->get('security.encoder_factory');
    $encoder = $factory->getEncoder($user);
    $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
    $user->setPassword($password);

    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($user);
    $em->flush();

    return $this->redirect($this->generateUrl('AcmeUserBundle_submitNewSuccess'));
    }
    }

    return $this->render('AcmeUserBundle:User:new.html.twig', array (
    'form' => $form->createView()
    ));
    }

    public function submitNewSuccessAction() {
    return $this->render("AcmeUserBundle:User:submitNewSuccess.html.twig");
    }

    security.yml的相关部分:
    security:
    encoders:
    Acme\UserBundle\Entity\User:
    algorithm: sha512
    iterations: 1
    encode_as_base64: true

    role_hierarchy:
    ROLE_ADMIN: ROLE_USER
    ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
    main:
    entity: { class: Acme\UserBundle\Entity\User, property: email }

    firewalls:
    secured_area:
    pattern: ^/
    form_login:
    check_path: /login_check
    login_path: /login
    logout:
    path: /logout
    target: /demo/
    anonymous: ~

    关于symfony - symfony2中的自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5311308/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com