質問

私はSymfonyが初めてです。 Symfonyバージョン2でホイールを動かすことにしました。

私のユーザーフォーム:

  • データベース内の電子メールの独自性を検証したいと思います。
  • また、パスワードの確認フィールドを使用してパスワードを検証したいと思います。
  • Symfony2ドキュメントで助けが見つかりました。
役に立ちましたか?

解決

このようなものは私にも追跡するのに時間がかかったので、ここに私が思いついたものがあります。正直に言うと、ユーザーエンティティのgetRoles()メソッドについてはよくわかりませんが、これは私にとってのテストセットアップです。そのようなコンテキスト項目は、明確にのみ提供されます。

さらに読むためのいくつかの役立つリンクは次のとおりです。

私はあなたがおそらくそれをしていると思ったので、それがセキュリティのユーザープロバイダーとしても機能することを確認するためにこれをすべて設定しました。また、電子メールをユーザー名として使用していると思いましたが、そうする必要はありません。個別のユーザー名フィールドを作成して、それを使用できます。見る 安全 詳細については。

エンティティ(重要な部分のみ、自動発電機のゲッター/セッターは省略されています):

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

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: ~

他のヒント

チェックアウト http://github.com/friendsofsymfony その機能を備えたユーザーバンドルがあります。確認することもできます http://blog.bearwoods.com Recaptchaのカスタムフィールド、Constraint、およびValidatorの追加に関するブログ投稿があります。

Thoose Resourcesは、トラブルに遭遇している場合、正しい道を開始する必要があります。 FreeNoceには、#Symfony-DevがSymfony2 Coreの開発のためのものを使用する方法について質問することができる一般的なチャンネル#Symfonyもあります。

うまくいけば、これがあなたがあなたのプロジェクトを前進させるのに役立つでしょう。

カスタムバリーターを作成するときに注意する必要がある主なものは、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

しかし、それはトリガーされていませんか?

データベースからの一意の電子メール

validation.yml

Dashboard articlebundle entity article:constraints:# -symfony bridge doctrine validator constraints constraints uniquentity:senderemail -symfony bridge doctrine 制約 constraints inquireentity:{fields:senderemail、senderemail:cenderemail}

パスワードを確認したパスワード

    $builder->add('password', 'repeated', array(
       'first_name' => 'password',
       'second_name' => 'confirm',
       'type' => 'password',
       'required' => false,
    ));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top