Home > OS >  Optional date in form
Optional date in form

Time:12-15

want to add optional DateType class in symfony form. It kinda works because I can submit form without setting the date but it auto sets todays date.

TodoType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name')
            ->add('Deadline', DateType::class, [
                'widget' => 'single_text',
                'required' => false,
                'empty_data' => ''
            ])
            ->add('Submit', SubmitType::class)
        ;
    }

deadline entities

/**
* @ORM\Column(type="date", nullable=true)
*/
private $deadline;

...

public function getDeadline(): ?\DateTimeInterface
    {
        return $this->deadline;
    }

public function setDeadline(\DateTimeInterface $deadline = null): self
    {
        $this->deadline = $deadline;

        return $this;
    }

TodoController.php

    /**
     * @Route("/todos", methods={"GET", "POST"}, name="todos")
     * 
     */
    public function todos(EntityManagerInterface $entityManager, Request $request): Response
    {
        
        // Rendering todos
        $todos = $entityManager->getRepository(Todo::class)
            ->findBy(
                ['owner' => $this->getUser()]
            );
        

        // Creating new TODO
        $todo = new Todo();
        
        $todo
            ->setOwner($this->getUser())
            ->setCreationDate(new \DateTime());
        $form = $this->createForm(TodoType::class, $todo);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid())
        {
            $entityManager->persist($todo);
            $entityManager->flush();
            
            return $this->redirectToRoute('todos');
        } 


        return $this->render('todo/todos.html.twig', [
            'todos' => $todos,
            'form' => $form->createView(),
        ]);
    }

To render in .twig I used just {{ form(form) }} haven't customized it yet.

Edit: code missing

CodePudding user response:

Every thing looks good.

I tried on my side and it worked fine (in database, i got null): Form:

$builder->add(
            'dateTime', DateType::class, [
                          'required' => false,
                          'widget'   => 'single_text',
                          'empty_data' => ''
                      ]
        );

Entity


    public function __construct() {
        // empty
    }

    /**
     * @var DateTime|null
     * @ORM\Column(name="date_time", type="datetime", nullable=true)
     */
    private ?DateTime $dateTime;

    /**
     * @return DateTime|null
     */
    public function getDateTime(): ?DateTime
    {
        return $this->dateTime;
    }

    /**
     * @param DateTime|null $dateTime
     *
     * @return SupportTimeSlot
     */
    public function setDateTime(?DateTime $dateTime): SupportTimeSlot
    {
        $this->dateTime = $dateTime;
        return $this;
    }

Controller



    /**
     * @Route("/time-slot-detail/{id}", name="time_slot_detail", methods={"GET", "POST"})
     * @param SupportTimeSlot        $supportTimeSlot
     * @param Request                $request
     * @param SupportTimeSlotManager $supportTimeSlotManager
     *
     * @return Response
     */
    public function timeSlotDetail(
        SupportTimeSlot $supportTimeSlot,
        Request $request,
        SupportTimeSlotManager $supportTimeSlotManager
    ): Response
    {
        $form = $this->createForm(TimeSlotEditType::class, $supportTimeSlot);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $supportTimeSlotManager->save($supportTimeSlot);
            return $this->redirectToRoute('boa_support_time_slot_detail', ['id' => $supportTimeSlot->getId()]);
        }
        return $this->render(
            'boa/support/detail.twig', [
                                         'timeSlot' => $supportTimeSlot,
                                         'form'     => $form->createView(),
                                     ]
        );
    }

Twig

    <div >
        <div >
            {{ form_start(form) }}
            {{ form_row(form.dateTime) }}
            <button type="submit" >
                 {% trans %}Save{% endtrans %}
            </button>
            {{ form_end(form) }}
        </div>
    </div>

My project contain some datepicker and datetimepicker js, maybe try to instanciate js to check if it come from this.

Otherwise try to debug your $request in your controller. If it provide some date for your deadline attribute, your problem come from twig/js If $request is null but your entity is populated with data for deadline, your problem come from your construct If you save your entity with enpty deadline but you gotr one in database, your problem come from your database

  • Related