在Zend Framework 2中验证字段集

问题描述

我有一个表单,其中包含WorkingHours集合,其字段为weekDay,workStart ... 对于集合字段的任何值,我在updateAction中的$ form-> isValid()方法始终为true! 我不明白如何验证这些字段

public function updateAction(ServerRequestInterface $request,DelegateInterface $delegate)
{
    if (! $this->_allowUpdate) {
        return $this->err(400,'Action forbidden');
    }
    $user = $this->getUserFromMiddleware($request);
    if (!$user) {
        return $this->err(403,'user not found');
    }

    $id = $request->getAttribute('id');

    if (! $id) {
        return $this->err(400,'ID missing');
    }

    try {
        $item = $this->_getItem(['id' => $id,'client' => $user]);
    } catch (\Exception $ex) {
        return $this->err(500,'Search error');
    }

    if (! $item) {
        return $this->err(400,'No item found');
    }

    $this->_checkAccessRights($item,$user);

    if (!$this->_form) {
        return $this->err(500,'form not defined');
    }


    $form = new $this->_form($this->getEntityManager(),$user,true);
    $this->_preUpdateItem($item,$user);
    $form->bind($item);
    $this->_preUpdateForm($form,$item,$user);

    if ($request->getmethod() == RequestMethodInterface::METHOD_POST) {
        $post = $this->getJsonBody($request);

        if ($post === null) {
            return $this->err(400,'No Post Data');
        }

        $post = $this->_preValidateForm($form,$post,$user);
        $form->setData($post);
        if ($form->isValid()) {
            $this->getEntityManager()->flush();
            $this->_postUpdateItem($item,$form,$user);
            return $this->res(['ok' => true]);
        } else {
            return $this->err(400,$form->getMessages());
        }
    }

    return $this->err(405);
}

表格

class Activity extends Form
{

use UserFields;
use GeneralFields;

protected $em = null;


/**
 * Activity constructor.
 * @param \Doctrine\ORM\EntityManager $em
 * @param Client $identity
 * @param null $submitButtonText
 */
public function __construct(\Doctrine\ORM\EntityManager $em,Client $identity,$submitButtonText = null)
{
    parent::__construct();
    $this->setAttribute('method','post');
    $this->setAttribute('enctype','multipart/form-data');
    $hydrator = new DoctrineObject($em);
    $this->setHydrator($hydrator);

    $this->em = $em;

    $textCollection = new Translation($em,$identity);
    $this->add($textCollection);

    $workingHours = new WorkingHours($em);
    $this->add($workingHours);

    $this->addGeneralFields();
    $this->addSubmit($submitButtonText);
}

public function bind($object,$flags = FormInterface::VALUES_norMALIZED)
{
    if ($object->getType() === 0) {
        $this->setInputFilter(new ActivityInputFilter($this->em));
        $this->addMapFields();
    } else {
        $this->setInputFilter(new RecommendationInputFilter($this->em));
    }



    parent::bind($object,$flags);

    if ($this->getobject()->getThumbnail()) {
        $this->getInputFilter()->get('thumb')->setrequired(false);
    }

    if ($this->getobject()->getimages() && $this->getobject()->getimages()->count() > 0) {
        $this->getInputFilter()->get('image')->setrequired(false);
    }

}

public function setData($data)
{
    if (isset($data['workingHours'])) {
        if ($data['workingHours'][0] === null) {
            foreach (\Core\Model\WorkingHours::$daysOfTheWeek as $key => $day) {
                $day = new \Core\Model\WorkingHours();
                $day->weekDay = $key;
                $data['workingHours'][$key] = (array) $day;
            }
        }
    }

    return parent::setData($data);
}
}

收藏

class WorkingHours extends \Zend\Form\Element\Collection
{
public function bindValues(array $values = [],array $validationGroup = null)
{
    $collection = [];
    foreach ($values as $name => $value) {
        $collection[] = $this->getHydrator()->hydrate($value,new \Core\Model\WorkingHours());
    }

    return $collection;
}

public function __construct($em)
{
    parent::__construct('workingHours');

    $this->setoptions([
        'count' => 7
    ]);

    $this->setAttribute('class','row');
    $this->setAttribute('id','WorkingHours');

    $activityTextFieldset = new \Api\V2\Form\Admin\Fieldset\Client\WorkingHours($em);
    $activityTextFieldset->setAttribute('class','col-lg-fit');
    $this->setHydrator(new \Core\Model\Hydrator\WorkingHours());
    $this->setTargetElement($activityTextFieldset);
}
}

字段集

class WorkingHours extends Fieldset implements InputFilterProviderInterface
{
public function __construct(EntityManager $em)
{
    parent::__construct('workingHours');
    $this->setHydrator(new \Core\Model\Hydrator\WorkingHours($em))
        ->setobject(new \Core\Model\WorkingHours());

    $this->addFields();
}

public function addFields()
{
    $hours = range(0,23,1);
    $minutes = range(0,45,15);

    $rangeHours = [];

    foreach ($hours as $hour) {
        foreach ($minutes as $minute) {
            $str = (strlen($hour) === 1 ? "0".$hour : $hour) . ':' .(strlen($minute) === 1 ? "0".$minute : $minute);
            $rangeHours[$str] = $str;
        }
    }

    $this->add([
        'name' => 'weekDay','type' => 'hidden',]);

    $this->add([
        'name' => 'workStart','type' => 'select','options' => [
            'label' => 'Start','empty_option' => 'select','value_options' => $rangeHours
        ],]);
    $this->add([
        'name' => 'workEnd','options' => [
            'label' => 'End',]);

    $this->add([
        'name' => 'launchStart','options' => [
            'label' => 'Lunch Start',]);
    $this->add([
        'name' => 'launchEnd','options' => [
            'label' => 'Lunch End',]);
    $this->add([
        'name' => 'dayoff','type' => 'checkBox','options' => [
            'label' => 'Day off',],'attributes' => [
            'class' => 'filled-in',]);
}

public function getInputFilterSpecification()
{
    return [
        'weekDay' => [
            'required' => true,'validators' => [
                new \Zend\Validator\Between(['min' => 0,'max' => 6]),]
        ],'workStart' => [
            'required' => true,'validators' => [
                new \Zend\Validator\Regex(['pattern' => '/^([0-1]\d|2[0-3]):[0-5]\d$/']),'workEnd' => [
            'required' => true,'launchStart' => [
            'required' => true,'launchEnd' => [
            'required' => true,'dayoff' => [
            'required' => false,]
    ];
}
}

水合器

class WorkingHours implements HydratorInterface
{
protected $hydrator;

public function __construct()
{
    $this->hydrator = new Client();
}

public function extract($object)
{
    $workingHourObject = [];

    if (!$object){

        foreach (\Core\Model\WorkingHours::$daysOfTheWeek as $day) {
            $dayOfWeek = new \Core\Model\WorkingHours();
            $dayOfWeek->weekDay = $day;
            $workingHourObject[$day] = $dayOfWeek;
        }

        return $workingHourObject;
    }

    foreach ($object as $key => $value) {
        $workingHourObject[$key] = $value;
    }

    return $workingHourObject;
}

public function hydrate(array $data,$object)
{
    return $data;
}
}

我不知道getInputFilterSpecification方法的工作方式,我认为问题出在此

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)