zend framework2 - Check for unique constraint violation -
i have 2 fields on entity form unique constraint: fielda
, fieldb
, mapped database columns field_a
, field_b
, respectively.
my input filter requires both of fields:
public function init() { parent::init(); $this->add([ 'name' => 'field_a', 'required' => true, 'allow_empty' => false, ]); $this->add([ 'name' => 'field_b', 'required' => true, 'allow_empty' => false, ]); }
i trying figure out best way validate 2 fields unique in database table. input filter fail validation if there different entity same field values.
i thinking override isvalid
function , put custom logic in there.
i suggest use callback validator ( zend\validator\callback ) on both fields , put custom logic in callback function.
i use inputfilter add filters , validators form fields can implement inputfilterproviderinterface directly in form/fieldset class.
use zend\inputfilter\inputfilter; class formfilter extends inputfilter { public function __construct() { $this->add( array( 'name' => 'field_a', 'filters' => array(), 'validators' => array ( array( 'name' => 'zend\validator\callback', 'options' => array( 'messages' => array( \zend\validator\callback::invalid_value => 'custom message', ), 'callback' => array($this,'validatefielda'), ), ), ) ) ); $this->add( array( 'name' => 'field_b', 'filters' => array(), 'validators' => array ( array( 'name' => 'zend\validator\callback', 'options' => array( 'messages' => array( \zend\validator\callback::invalid_value => 'custom message', ), 'callback' => array($this,'validatefieldb'), ), ), ) ) ); } public function validatefielda($value, $context) { // $value contains field_a value // $context['field_b'] contains field_b value // put custom logic here // return true if fields unique // return false if fields not unique } public function validatefieldb($value, $context) { .... } }
Comments
Post a Comment