2013-11-14 35 views
1

我有一個Assert回調方法「processSignup」的實體帳戶。我只想在登錄約束和密碼約束成功的情況下調用「processSignup」。我如何在我的processSignup方法中檢查這個?如何滿足所有約束條件才調用Assert回調方法?

<?php 
namespace MyProject\Bundle\FrontBundle\Entity; 

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Validator\ExecutionContext; 
use Symfony\Component\Validator\Constraints as Assert; 

/** 
* @Assert\Callback(methods={"processSignup"}) 
*/ 
class Account 
{ 

    /** 
    * @Assert\NotBlank() 
    * @Assert\Type(type="string") 
    * @Assert\Length(min = 6, max = 16) 
    */ 
    protected $login; 

    /** 
    * @Assert\NotBlank() 
    * @Assert\Type(type="string") 
    * @Assert\Length(min = 8, max = 12) 
    */ 
    protected $password; 

    /** 
    * @param ExecutionContext $context 
    */ 
    public function processSignup(ExecutionContext $context) 
    { 
     // if login and password constraints success, do something 
    } 

    public function getLogin() 
    { 
     return $this->login; 
    } 

    public function setLogin($login) 
    { 
     $this->login = $login; 
    } 

    public function getPassword() 
    { 
     return $this->password; 
    } 

    public function setPassword($password) 
    { 
     $this->password = $password; 
    } 
} 
+0

用'$ context-> getViolations()'試試它。它返回到目前爲止的所有違規 –

+0

我試過了,但是當約束不滿足時,它返回一個空數組。 – user777897

+0

你是對的,但我認爲這是檢查約束是否成功的唯一方法。嘗試觸發用戶名和密碼約束,並檢查數組是否爲空。你可以用vardev的Xdebug來做到這一點,並死:) –

回答

1

在相同情況下,我已經使用驗證組:

/** @Assert\Callback(methods={"processSignup"}, groups={"LastValidation"}) */ 
class Account { 
    /** 
    * @Assert\NotBlank() 
    * @Assert\Type(type="string") 
    * @Assert\Length(min = 6, max = 16) 
    */ 
    protected $login; 
.... 
} 

和FormType:

class AccountType extends AbstractType { 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     .... 
    } 

public function setDefaultOptions(OptionsResolverInterface $resolver) 
{ 
    parent::setDefaultOptions($resolver); 
    $resolver->setDefaults(
      [ 
      .... 
      'validation_groups' => function (FormInterface $form) 
        { 
         return ['Account', 'LastValidation']; 
         // The first element's value must be the same as data-class name 
        } 
      ] 
    ); 

} 

然後在processSignup方法可以檢查

if(0 !== $context->getViolations()->count()) 
    { 
     return; 
    } 
相關問題