代码之家  ›  专栏  ›  技术社区  ›  Benjamin Kozlowski

添加新的集合元素(symfony 3.4)时无法获取嵌套集合的类内父验证器

  •  0
  • Benjamin Kozlowski  · 技术社区  · 7 年前

    我想做什么

    在一个表单中,我有一个嵌套的onetomany集合 ProspektDates 在嵌套的OneToMany集合中使用DateField Prospektlaendervarianten 实体的 Prospekt ,我要用类验证器针对实体的属性进行验证。 普鲁斯克 父集合中属性的依赖项 Prospektaendervarianten 。

    问题

    编辑现有属性时 date 属于 ProspektDate ,一切都很好。问题是,当调用类验证器时,我添加了一个新的 日期 在形式上,财产 laendervarianten 收藏中 散文日期 未设置,并且我没有访问父级的权限,无法根据其属性进行验证。

    在中添加日期 提出日期 很像这里描述的: https://symfony.com/doc/current/form/form_collections.html

    我想的解决方案

    我可能可以将一个隐藏的实体字段添加到 散文日期 ,但对我来说,这听起来像是一种权宜之计,因为条令确实在某一点上设置了属性 拉恩德瓦里安滕 ,但对我来说太晚了,我想如果不在表单中添加字段是否有更好的可能性。

    我还考虑了一个类验证器 ProspektLaendervarianten 我可以接触到所有的东西,但这听起来也像是我错过的东西的解决办法。另外,我总是要验证整个集合,我希望能够验证单个 日期 属于 散文日期 。

    安装程序

    实体prospekt

    /**
     * Prospekt
     *
     * @ORM\Table(name="prospekt")
     * @ORM\Entity()
     */
    class Prospekt
    {
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="du", type="datetime", nullable=true)
         */
        private $du;
    
    
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="uebersetzung_an_druckerei_date", type="datetime", nullable=true)
         */
        private $uebersetzungAnDruckereiDate;
    
    
        /**
         *
         * @Assert\Valid
         * @ORM\OneToMany(targetEntity="ProspektLaendervarianten", mappedBy="prospekt", orphanRemoval=true, cascade={"all"}, fetch="EAGER")
         */
        private $laendervarianten;
    
    }
    

    Prospektlaendervarianten实体

    /**
     * ProspektLaendervarianten
     *
     * @ORM\Table(name="prospekt_laendervarianten")
     * @ORM\Entity()
    
     */
    class ProspektLaendervarianten
    {
        /**
         * @ORM\ManyToOne(targetEntity="Prospekt", inversedBy="laendervarianten")
         * @ORM\JoinColumn(name="prospekt_id", referencedColumnName="id", nullable=true)
         */
        private $prospekt;
    
        /**
         * @ORM\ManyToOne(targetEntity="BaseCountries")
         * @ORM\JoinColumn(name="base_country_id", referencedColumnName="id", nullable=true)
         */
        private $baseCountry;
    
        /**
         *
         * @Assert\Valid()
         * @ORM\OneToMany(targetEntity="ProspektDates", mappedBy="laendervarianten", orphanRemoval=true, cascade={"all"}, fetch="EAGER")
         * @ORM\OrderBy({"date" = "ASC"})
         */
        protected $prospektDates;
    }
    

    实体程序日期

    /**
     * ProspektDates
     *
     * @CustomAssert\EtGermany
     *
     * @ORM\Table(name="prospekt_date)
     * @ORM\Entity()
     */
    
    
    class ProspektDates
    {
        /**
         * @var \DateTime|null
         * @Assert\Valid()
         * @ORM\Column(name="date", type="datetime", nullable=true)
         */
        private $date;
    
        /**
         * @var ProspektLaendervarianten
         *
         * @ORM\ManytoOne(targetEntity="ProspektLaendervarianten", inversedBy="prospektDates")
         * @ORM\JoinColumn(name="prospekt_laender_varianten_id", referencedColumnName="id", nullable=false)
         */
        private $laendervarianten;
    }
    

    表格的一部分

    {% for land in form.laendervarianten %}
    
        <div class="row">
            <div class="col-md-4">
                <div class="row">
                    <div class="col-md-6 aktiv">
                            {{ land.vars.data.baseCountry.title }}
                    </div>
                </div>
            </div>
            <div class="col-md-8 without-padding">
                <div class="row">
    
                    <div class="col-md-4">
                        <div class="row prospekt-dates"
                             data-prototype="{{ form_widget(land.prospektDates.vars.prototype)|e('html_attr') }}"
                             data-index="{{ land.prospektDates|length }}">
    
                            {{ form_widget(land.prospektDates) }}
    
    
                            <div class="form-group">
                                <a href="#" class="prospekt-date-add">
                                    <span class="fa fa-plus-circle"></span>
                                </a>
                            </div>
    
    
                        </div>
                    </div>
                </div>
            </div>
        </div>
    {% endfor %}
    

    实体prospektdates的类验证器

        class EtGermanyValidator extends ConstraintValidator
        {
            public function validate($protocol, Constraint $constraint)
            {
    
                /* @var $protocol ProspektDates */
                if (!$constraint instanceof EtGermany) {
                    throw new UnexpectedTypeException($constraint, EtGermany::class);
                }
    
    
                if (null === $protocol->getDate() || '' === $protocol->getDate()) {
                    return;
                }
                //when saving new date laendervarianten is null. Here's my problem!
                if (empty($protocol->getLaendervarianten())) {
                    return;
                }
    
                // only validate if BaseCountry of parent Collection is Germany
                if (BaseCountries::DE !== $protocol->getLaendervarianten()->getBaseCountry()->getId()) {
                    return;
                }
    
                // check if property Date (DateTime) of ProspektDates is later than property Du (DateTime) of Entity Prospekt
                $du = $protocol->getLaendervarianten()->getProspekt()->getDu();
                $et = $protocol->getDate();
                if ($et < $du) {
                    $this->context->buildViolation($constraint->message)
                        ->atPath('date')
                        ->addViolation();
                }
        /*
                if (!is_string($value)) {
                    throw new UnexpectedTypeException($value, 'string');
                }
        */
    
            }
        } 
    

    集合prospektates的formtype

    class ProspektDateType extends AbstractType
    {
    
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('date',
                    DateType::class,
                    array(
    
                        'attr' => [
                            'class' => 'form-control input-inline date_custom input-sm date_et',
                            'html5' => false,
                            'readonly' => true
    
                        ],
                        'required' => false,
                        'widget'        => 'single_text',
                        'format'        => 'ccc, dd.MM.y',
                        'label' => 'ET',
                        'model_timezone' => 'Europe/Berlin',
    
                    )
                );
        }
    
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => ProspektDates::class,
                'error_bubbling'=>false
            ));
        }
    
        /**
         * {@inheritdoc}
         */
        public function getBlockPrefix()
        {
            return 'prospektDates';
        }
    }
    

    收集prospektlaendervarianten的模板类型

    class ProspektLaendervariantenType extends AbstractType
    
    {
        /**
         * {@inheritdoc}
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('prospektDates', CollectionType::class, [
                'label'         => 'ETs',
                'entry_type'    => ProspektDateType::class,
                'entry_options' => [
                    'label' => false,
                    'attr' => [
                        'class' => 'date-item', 
                    ],
                ],
                'allow_add'     => true,
                'allow_delete'  => true,
                'prototype'     => true,
                'required'      => false,
               'by_reference'  => false,
                'delete_empty'  => true,
               'prototype_name' => '__prospektDates-collection__',
    
               'attr'          => [
                    'class' => 'prospektDates-collection',
                ],
               'block_name' => 'prospektDates',
    
           ]);
    
        }
    
    
    
        /**
         * {@inheritdoc}
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'ProspektLaendervarianten::class',
            ));
        }
    
        /**
         * {@inheritdoc}
         */
        public function getBlockPrefix()
        {
            return 'laendervarianten';
        }
    }
    
    0 回复  |  直到 7 年前
    推荐文章