我是Symfony的新手。我决定使用Symfony版本2移动轮子。

在我的用户表格中:

  • 我想在数据库中验证电子邮件的唯一性。
  • 我还想使用确认密码字段验证密码。
  • 我可以在Symfony2文档中找到任何帮助。
有帮助吗?

解决方案

这些东西也花了我一段时间来追踪,所以这就是我想到的。老实说,我不确定用户实体的Getroles()方法,但这只是我的测试设置。诸如此类的上下文项目仅是为了清晰的。

以下是一些有用的链接以进行进一步阅读:

我将所有这些设置为确保它作为安全性的用户提供工作,因为我认为您可能正在这样做。我还认为您将电子邮件用作用户名,但您不必这样做。您可以创建一个单独的用户名字段并使用它。看 安全 了解更多信息。

实体(仅重要的部分;可自动化的getters/setters):

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;
    }
}
?>

表格类:

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',
        );
    }
}
?>

控制器:

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");
    }

安全性部分.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: ~

其他提示

查看 http://github.com/friendsofsymfony 有一个具有该功能的UserBundle。您也可以检查 http://blog.bearwoods.com 有关于添加自定义字段,约束和验证器的博客文章。

如果您仍在遇到麻烦的情况下,人们通常会在FreeNode Network上的#Symfony-Dev上对IRC有帮助和友好,那么Thoose Resources应该让您开始正确的道路。在FreeNoce上,还有一个通用频道#symfony,您可以在其中询问有关如何使用#Symfony-Dev在Symfony2 Core开发的地方的问题。

希望这将有助于您继续进行项目。

我认为创建自定义验证器时需要注意的主要内容是在getTargets()方法中指定的常数。

如果您更改

self::PROPERTY_CONSTRAINT

至:

self::CLASS_CONSTRAINT

您应该能够访问实体的所有属性,而不仅仅是一个属性。


注意:如果您使用注释来定义约束,现在需要移动注释,该注释将您的验证器定义到类的顶部,因为它现在适用于整个实体,而不仅仅是单个属性。

您应该能够从中获得所需的一切 文档. 。特别是 约束 其中包含有关电子邮件检查的信息。还有关于写作的文档 自定义验证器.

我已经完成了 http://symfony.com/doc/2.0/book/validation.html

我的配置:

validator.debit_card:
        class: My\Validator\Constraints\DebitCardValidator
        tags:
            - { name: validator.constraint_validator, alias: debit_card }

试图与它一起使用

@assert:DebitCard
@assert:debitCard
@assert:debit_card

但是它没有触发吗?

来自数据库的唯一电子邮件

验证

DashboardArticleBundleEntityArticle: constraints: #- SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity: senderEmail - SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity: { fields: senderEmail, message: This email already exist }

使用确认密码的密码

    $builder->add('password', 'repeated', array(
       'first_name' => 'password',
       'second_name' => 'confirm',
       'type' => 'password',
       'required' => false,
    ));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top