0

제 양식에는 데이터베이스 테이블에서 고유해야하는 foo 필드가 있습니다. 그래서 나는 그것의 유효성 검사기 목록에 Zend\Validator\Db\NoRecordExists 추가 : 다른 필드에 종속 된 필드 유효성 검사를 만드는 방법 ZF2에서 usind array form setup을 사용 하시겠습니까?

namespace Bar\Form\Fieldset; 

use Zend\Form\Fieldset; 
use Zend\InputFilter\InputFilterProviderInterface; 
use Zend\Db\Adapter\AdapterInterface; 

class BuzFieldset extends Fieldset implements InputFilterProviderInterface 
{ 
    protected $dbAdapter; 

    public function __construct($name = null, $options = []) {...} 

    public function setDbAdapter(AdapterInterface $dbAdapter) {...} 

    public function init() 
    { 
     $this->add([ 
      'name' => 'id', 
      'type' => 'hidden' 
     ]); 
     $this->add(
      [ 
       'name' => 'foo', 
       'type' => 'text', 
       'options' => [...], 
       'attributes' => [ 
        'required' => 'required', 
        'class' => 'form-control' 
       ] 
      ]); 
     ... 
    } 

    public function getInputFilterSpecification() 
    { 
     return [ 
      'foo' => [ 
       'required' => true, 
       'validators' => [ 
        [ 
         'name' => 'Regex', 
         'options' => [ 
          'pattern' => '/.../', 
          'message' => _(...) 
         ] 
        ], 
        [ 
         'name' => 'Zend\Validator\Db\NoRecordExists', 
         'options' => [ 
          'table' => 'buz', 
          'field' => 'foo', 
          'adapter' => $this->dbAdapter 
         ] 
        ] 
       ] 
      ], 
      ... 
     ]; 
    } 
} 

가 지금은 검증 양식을 얻을 수없는 항목을 업데이트하기위한 물론 동일한 양식을 사용하고 싶습니다. 그래서 id 필드에 따라이 필드에 대한 NoRecordExists 확인을해야합니다. id이 설정되면 (즉, 업데이트가 아니라 생성 중임) 모든 유효성 검사기 (예 : 여기 Regex)가 적용되어야하지만이 것은 유효하지 않습니다. 그렇게하는 방법?

답변

3

Callback 검사기를 살펴볼 수 있습니다. 이 유효성 검사기는 양식 컨텍스트에 대한 액세스 권한을 부여하여 다른 필드의 값을 가져올 수 있습니다. Callback 유효성 검사기 안에 NoRecordExists 유효성 검사기를 사용하여 종속성을 확인하십시오. 이 같은. 나는 이것을 테스트하지 않았지만, 당신은 그 아이디어를 얻을 것이다.

'foo' => [ 
    'required' => true, 
     'validators' => [ 
      [ 
       'name' => 'Callback', 
       'options' => [ 
        'callback' => function($value, $context = []) { 
         if (empty($context['id'])) { 
          return $this->noRecordExistsValidator->isValid($value); 
         } 
         return true; 
        }, 
       ], 
     ] 
    ] 
] 

당신은 InputFilter와는 Fieldset 객체로 해당 인스턴스를 주입 완전히 설치 공장을 별도의 InputFilter를 만들고 해당하는 더 좋은 방법이 양식 클래스에 종속성으로 NoRecordExistsValidator를 주입해야하거나 것이다.

+0

정말 고마워요! – automatix