Nespony
Nespony

Reputation: 1371

Posting Dates in Symfony?

I have a symfony 3 app which I am using to post simple Json into a mysql database. The post request looks like this:

        /**
 * @Rest\Post("/LegoPieces")
 */
 public function postAction(Request $request)
 {
   $data = new LegoPieces;
   $piece = $request->get('piece');
   $type = $request->get('type');
   $startDate   = $request->get('startDate');
   $endDate   = $request->get('endDate');
 if(empty($piece) || empty($type))
 {
   return new View("NULL VALUES ARE NOT ALLOWED", Response::HTTP_NOT_ACCEPTABLE);
 }
  $data->setPiece($piece);
  $data->setType($type);
  $data->setStartDate($startDate);
  $data->setEndDate($endDate);
  $em = $this->getDoctrine()->getManager();
  $em->persist($data);
  $em->flush();
   return new View("LegoPieces Added Successfully", Response::HTTP_OK);
 }

The legoPieces entity for startDate looks like this:

     /**
 * @var DateTime
 *
 * @ORM\Column(name="startDate", type="datetime", nullable=true)
 */
private $startDate;

  /**
 * Set startDate
 *
 * @param datetime $startDate
 *
 * @return LegoPieces
 */
public function setStartDate($startDate)
{
    $this->type = $startDate;

    return $this;
}

/**
 * Get startDate
 *
 * @return datetime
 */
public function getStartDate()
{
    return $this->startDate;
}

However, every time I make the post request, only the strings (piece and type) are posted in to the database.

Upvotes: 2

Views: 396

Answers (1)

Sergei Kutanov
Sergei Kutanov

Reputation: 825

You have two options here. 1. Without form class (Type). With this case you'll have to create \DateTime objects manually from the data you get in the request. It might look something like this (http://php.net/manual/en/datetime.createfromformat.php):

$data->setStartDate(date_create_from_format("format_string", "your_data string_from_request"));

2. Second option is to use Type class, aka Form. Create that class for your entity (or generate it with console command doctrine:generate:form YourBundle:YourEntity). Then in that class specify what kind of data you expect, it might look something like this:

$builder
            ->add(
                'startDate',
                DateTimeType::class,
                [
                    'widget'   => 'single_text',
                    'format' => "MM/dd/yyyy HH:mm"
                ]
            )

Again all code above is an example, you might want to change it according to your needs, for example 'format' in the last example do not care about timezone. I'd strongly recommend using Type class, you should also use constraints to validate your data.

Upvotes: 2

Related Questions