php - Form element validation based on other form element -
i'm rendering form add class (course) database. class has starttime , endttime. both time of day fields. created fieldset class:
<?php namespace admin\form; use zend\form\fieldset; use zend\inputfilter\inputfilterinterface; use zend\inputfilter\inputfilterproviderinterface; class artclassfieldset extends fieldset implements inputfilterproviderinterface { public function __construct() { parent::__construct('artclass'); $this->add(array( 'name' => 'dayofweek', 'type' => 'zend\form\element\select', 'options' => array( 'label' => 'day of week:', 'value_options' => array( 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday', ), ), )); $this->add(array( 'name' => 'starttime', 'type' => 'zend\form\element\time', 'options' => array( 'label' => 'start time:', 'format' => 'h:ia', ), ) ); $this->add(array( 'name' => 'endtime', 'type' => 'zend\form\element\time', 'options' => array( 'label' => 'end time:', 'format' => 'h:ia', ), ) ); $this->add(array( 'name' => 'teacher', 'type' => 'admin\form\teacherselectorfieldset', 'options' => array( 'label' => 'teacher:', ) ) ); } public function getinputfilterspecification() { return array( 'dayofweek' => array( 'required' => true, 'filters' => array( array('name' => 'int'), ), 'validators' => array( array( 'name' => 'between', 'break_chain_on_failure' => true, 'options' => array( 'min' => 1, 'max' => 6, ), ), ), ), 'starttime' => array( 'required' => true, ), 'endtime' => array( 'required' => true, ), 'teacher' => array( ), ); } }
in form class add fieldset form:
<?php namespace admin\form; use zend\form\form; class artclassadd extends form { public function __construct() { parent::__construct("artclass-add"); $this->setattribute('action', '/admin/artclass/add'); $this->setattribute('method', 'post'); $this->add(array( 'type' => 'admin\form\artclassfieldset', 'options' => array('use_as_base_fieldset' => true) ) ); $this->add(array( 'name' => 'submit', 'attributes' => array( 'type' => 'submit', 'value' => 'save' ) ) ); } }
the format of 2 time fields 'h:ia' means '11:00am'. validate starttime before endtime. question how do that? i'm thinking should use zend\validator\callback, not sure.
you're on right track. have use callback
validator. use endtime
input spec:
return array( 'endtime' => array( 'required' => true, 'validators' => array( array( 'name' => 'callback', 'options' => array( 'callback' => function($value, $context) { $endtime = datetime::createfromformat'h:ia', $value); $starttime = datetime::createfromformat('h:ia', $context['starttime']); return $endtime > $starttime; } ), ), ), ), );
Comments
Post a Comment