duandianwen1723 2017-09-14 00:26
浏览 20

Symfony验证

I'm working in a bundle where the user creates a "comision" using a form, and I'm trying to check that the user still have "credit". So I created a custom validator that queries past comisions and throws an error if credit is not enough.

My problem is that if the user submits a date with a wrong format in the "date" field (i.e. 32-13-20122 24:05) Symfony still tries to run my custom validation and I get all sort of errors (because $comision->getDate() is null and not a valid DateTime object).

I'm getting this error:

clone method called on non-object

I can also check if value of $comision->getDate() is a valid datetime in my custom validator, but it seems to me that it should be not necessary since I added this rules in the date property.

This is my entity (simplified)

/**
 * @MyValidation\TotalHours()
 */
class Comision
{

/**
 * @ORM\Column(type="datetime")
 * @Assert\DateTime()
 * @Assert\NotNull()
 */
protected $date;


/**
 * @ORM\Column(type="decimal", nullable=false, scale=1)
 * @Assert\NotBlank()
 */
protected $hours;

...

My form class ...

class NewComisionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder
                ->add('date', DateTimeType::class, array(
                'widget' => 'single_text',
                'label' => 'Starting date and time',
                'format' => 'dd/MM/yyyy HH:mm'
                ))
                ->add('hours', ChoiceType::class, array(
                    'label'=> 'How many hours',
                    'choices' => array(
                        '1:00' => 1,
                        '1:30' => 1.5,
                        '2:00' => 2,
                        '2:30' => 2.5,
                        '3:00' => 3
                    )
                ))
...

And my cutom validator that checks past comisions to find if user still has "credit"

public function validate($comision, Constraint $constraint)
{
$from = clone $comision->getDate();
$from->modify('first day of this month');

$to = clone $comision->getDate();
$to->modify('last day of this month');

$credit = $this->em->getRepository("ComisionsBundle:Comision")->comisionsByDate($comision,$from, $to);

...
  • 写回答

3条回答 默认 最新

  • dongyuzhu2244 2017-09-14 12:46
    关注

    IIRC data transformers run before validation, you can go with data transformer for your date:

    https://symfony.com/doc/current/form/data_transformers.html

    and then in data transformer check if the date is valid and if not throw an error.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度