私はsymfonyに不慣れです。Symfonyバージョン2でホイールを動かすことにしました。
私のユーザーフォーム:
- データベース内の電子メールの一意性を検証したいと思います。
- また、パスワードの確認フィールドでパスワードを検証したいと思います。
- symfony2のドキュメントで助けを見つけることができました。
私はsymfonyに不慣れです。Symfonyバージョン2でホイールを動かすことにしました。
私のユーザーフォーム:
このようなものも追跡するのに時間がかかったので、これが私が思いついたものです。正直なところ、UserエンティティのgetRoles()メソッドについてはよくわかりませんが、これは私にとっては単なるテスト設定です。このようなコンテキストアイテムは、わかりやすくするためにのみ提供されています。
さらに読むためのいくつかの役立つリンクは次のとおりです。
おそらくそうしていると思ったので、セキュリティのUserProviderとしても機能するようにこれをすべて設定しました。また、ユーザー名として電子メールを使用していると仮定しましたが、その必要はありません。別のユーザー名フィールドを作成して使用することができます。詳細については、セキュリティを参照してください。
エンティティ(重要な部分のみ。自動生成可能なゲッター/セッターは省略されます):
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: ~
カスタムバリデーターを作成するときに注意する必要がある主なことは、getTargets()メソッドで指定された定数だと思います。
変更した場合
self::PROPERTY_CONSTRAINT
に:
self::CLASS_CONSTRAINT
単一のプロパティだけでなく、エンティティのすべてのプロパティにアクセスできる必要があります。
注:アノテーションを使用して制約を定義している場合は、バリデーターを定義するアノテーションをクラスの最上位に移動する必要があります。これは、単一のプロパティだけでなく、エンティティ全体に適用できるようになったためです。
http://github.com/friendsofsymfonyをチェックしてください。その機能を備えたUserBundleがあります。Recaptchaのカスタムフィールド、制約、バリデーターの追加に関するブログ投稿があるhttp://blog.bearwoods.comを確認することもできます。
それでも問題が発生する場合は、リソースを選択することで正しい道を歩み始めることができます。Freenodeネットワークの#symfony-devにあるircの人々は、一般的に親切でフレンドリーです。Freenoceには一般的なチャンネル#symfonyもあり、#symfony-devがSymfony2Coreの開発用であるものの使用方法について質問することができます。
うまくいけば、これはあなたがあなたのプロジェクトを進めるのを助けるでしょう。
ドキュメントから必要なものをすべて入手できるはずです。具体的には、電子メールチェックに関する情報を持つ制約。カスタムバリデーターの作成に関するドキュメントもあります。
私は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
しかし、それはトリガーされませんか?
データベースからの一意の電子メール
検証.yml
Dashboard \ ArticleBundle \ Entity \ Article:制約:#-Symfony \ Bridge \ Doctrine \ Validator \ Constraints \ UniqueEntity:senderEmail-Symfony \ Bridge \ Doctrine \ Validator \ Constraints \ UniqueEntity:{フィールド:senderEmail、メッセージ:このメールは既に存在します}
確認パスワード付きのパスワード
$builder->add('password', 'repeated', array(
'first_name' => 'password',
'second_name' => 'confirm',
'type' => 'password',
'required' => false,
));