簡體   English   中英

Symfony 3約束驗證日期或日期時間

[英]Symfony 3 Constraint validation Date or Datetime

我嘗試通過驗證表單來驗證日期(或日期時間)到Symfony(3.2)。

我正在使用FOSRestBundle來從請求中使用json(因為我嘗試開發我的個人API)

但我嘗試了很多格式:

  • 2017年4月9日
  • 17-04-09
  • 對於日期時間:
    • 2017-04-09 21:12:12
    • 2017-04-09T21:12:12
    • 2017-04-09T21:12:12 + 01:00
  • ...

但表單無效,我總是得到這個錯誤:此值無效

我的控制器的功能

public function postPlacesAction(Request $request) {
    $place = new Place();
    $form = $this->createForm(PlaceType::class, $place);

    $form->handleRequest($request);

    if ($form->isValid()) {
        return $this->handleView($this->view(null, Response::HTTP_CREATED));
    } else {
        return $this->handleView($this->view($form->getErrors(), Response::HTTP_BAD_REQUEST));
    }
}

我的實體

class Place
{
    /**
     * @var string
     *
     * @Assert\NotBlank(message = "The name should not be blank.")
     */
    protected $name;

    /**
     * @var string
     *
     * @Assert\NotBlank(message = "The address should not be blank.")
     */
    protected $address;

    /**
     * @var date
     *
     * @Assert\Date()
     */
    protected $created;

    // ....
    // Getter and setter of all var

我的實體類型

class PlaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
        $builder->add('address');
        $builder->add('created');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'MyBundle\Entity\Place',
            'csrf_protection' => false
        ]);
    }
}

請求的一個例子(我正在使用Postman)

  • 方法:POST
  • 標題:application / json
  • 身體(原始):

     {"place":{"name":"name","address":"an address","created":"1997-12-12"}} 

我不確定我是否使用了正確的格式,或者如果我在文件中遺漏了任何內容:/

請你在我腦海里打開燈!?! :)

非常感謝你的幫助。 法布里斯

表單類型中已created字段的問題。 使用$builder->add('created');添加created字段時$builder->add('created'); 語法,將應用默認類型Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType1997-12-12輸入數據是一個字符串,而不是DateTime實例。

要解決此問題,您應該在第二個參數中傳遞DateType$builder->add('created', 'Symfony\\Component\\Form\\Extension\\Core\\Type\\DateType'); DateType $builder->add('created', 'Symfony\\Component\\Form\\Extension\\Core\\Type\\DateType'); 此表單類型有一個轉換器,它將輸入數據1997-12-12轉換為DateTime實例。

有關Symfony表單類型的更多信息,請查看表單類型參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM