Php 在symfony2中保存到数据库之前,如何操作日期数据
我有一个Php 在symfony2中保存到数据库之前,如何操作日期数据,php,symfony,Php,Symfony,我有一个离合器实体,如下所示: <?php namespace Breedr\ClutchBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Clutch * * @ORM\Table() * @ORM\Entity */ class Clutch { /** * @var integer * * @ORM\Column(name="id", type="integer")
离合器
实体,如下所示:
<?php
namespace Breedr\ClutchBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Clutch
*
* @ORM\Table()
* @ORM\Entity
*/
class Clutch
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Breedr\BreedingPairsBundle\Entity\Pairs
*
* @ORM\ManyToOne(targetEntity="Breedr\BreedingPairsBundle\Entity\Pairs")
* @ORM\JoinColumn(name="breeding_pair", referencedColumnName="id")
*/
private $breedingPair;
/**
* @var \DateTime
*
* @ORM\Column(name="laid_date", type="date")
*/
private $laidDate;
/**
* @var \DateTime
*
* @ORM\Column(name="estimated_hatch_start", type="date")
*/
private $estimatedHatchStart;
/**
* @var \DateTime
*
* @ORM\Column(name="estimated_hatch_end", type="date")
*/
private $estimatedHatchEnd;
/**
* @var \DateTime
*
* @ORM\Column(name="hatch_date", type="date")
*/
private $hatchDate;
/**
* @var integer
*
* @ORM\Column(name="egg_amount", type="integer")
*/
private $eggAmount;
/**
* @var Breedr\UserBundle\Entity\User
*
* @ORM\ManyToOne(targetEntity="Breedr\UserBundle\Entity\User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set breedingPair
*
* @param integer $breedingPair
* @return Clutch
*/
public function setBreedingPair($breedingPair)
{
$this->breedingPair = $breedingPair;
return $this;
}
/**
* Get breedingPair
*
* @return integer
*/
public function getBreedingPair()
{
return $this->breedingPair;
}
/**
* Set laidDate
*
* @param \DateTime $laidDate
* @return Clutch
*/
public function setLaidDate($laidDate)
{
$this->laidDate = $laidDate;
return $this;
}
/**
* Get laidDate
*
* @return \DateTime
*/
public function getLaidDate()
{
return $this->laidDate;
}
/**
* Set estimatedHatchStart
*
* @param \DateTime $estimatedHatchStart
* @return Clutch
*/
public function setEstimatedHatchStart($estimatedHatchStart)
{
$this->estimatedHatchStart = $estimatedHatchStart;
return $this;
}
/**
* Get estimatedHatchStart
*
* @return \DateTime
*/
public function getEstimatedHatchStart()
{
return $this->estimatedHatchStart;
}
/**
* Set estimatedHatchEnd
*
* @param \DateTime $estimatedHatchEnd
* @return Clutch
*/
public function setEstimatedHatchEnd($estimatedHatchEnd)
{
$this->estimatedHatchEnd = $estimatedHatchEnd;
return $this;
}
/**
* Get estimatedHatchEnd
*
* @return \DateTime
*/
public function getEstimatedHatchEnd()
{
return $this->estimatedHatchEnd;
}
/**
* Set hatchDate
*
* @param \DateTime $hatchDate
* @return Clutch
*/
public function setHatchDate($hatchDate)
{
$this->hatchDate = $hatchDate;
return $this;
}
/**
* Get hatchDate
*
* @return \DateTime
*/
public function getHatchDate()
{
return $this->hatchDate;
}
/**
* Set eggAmount
*
* @param integer $eggAmount
* @return Clutch
*/
public function setEggAmount($eggAmount)
{
$this->eggAmount = $eggAmount;
return $this;
}
/**
* Get eggAmount
*
* @return integer
*/
public function getEggAmount()
{
return $this->eggAmount;
}
/**
* Set user
*
* @param \Breedr\UserBundle\Entity\User $user
* @return Clutch
*/
public function setUser(\Breedr\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \Breedr\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
现在,我想做的不是在前端显示estimatedHatchStart
或estimatedHatchEnd
,而是使用laidDate
中的数据分别添加30天和40天,以给出开始和结束填充日期,然后将其保存到数据库中
#services.yml
services:
my_custom_manager:
class: AppBundle\Entity\MyEntityManager
arguments: [ "@doctrine.orm.entity_manager" , 'AppBundle\Entity\MyEntity']
这样做的最佳实践是什么?我刚刚读到了FormEvents::PRE_SUBMIT
事件,但我不确定这是否是正确的方式
编辑:
setLaidDate
功能:
/**
* Set laidDate
*
* @param \DateTime $laidDate
* @return Clutch
*/
public function setLaidDate($laidDate)
{
$this->laidDate = $laidDate;
$estimatedHatchStart = $laidDate->modify('+30days');
$estimatedHatchEnd = $laidDate->modify('+40days');
$this->setEstimatedHatchStart($estimatedHatchStart);
$this->setEstimatedHatchEnd($estimatedHatchEnd);
return $this;
}
离合器控制器:
<?php
namespace Breedr\ClutchBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Breedr\ClutchBundle\Entity\Clutch;
use Breedr\ClutchBundle\Form\ClutchType;
/**
* Clutch controller.
*
*/
class ClutchController extends Controller
{
/**
* Lists all Clutch entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$entities = $em
->getRepository('BreedrClutchBundle:Clutch')
->findBy(array('user' => $user), array()
);
return $this->render('BreedrClutchBundle:Clutch:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Clutch entity.
*
*/
public function createAction(Request $request)
{
$entity = new Clutch();
$entity->setUser($this->getUser());
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('clutch_show', array('id' => $entity->getId())));
}
return $this->render('BreedrClutchBundle:Clutch:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Clutch entity.
*
* @param Clutch $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Clutch $entity)
{
$currentUser = $this->getUser()->getId();
$form = $this->createForm(new ClutchType($currentUser), $entity, array(
'action' => $this->generateUrl('clutch_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Clutch entity.
*
*/
public function newAction()
{
$entity = new Clutch();
$form = $this->createCreateForm($entity);
return $this->render('BreedrClutchBundle:Clutch:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Clutch entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Clutch entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('BreedrClutchBundle:Clutch:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Clutch entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Clutch entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('BreedrClutchBundle:Clutch:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Clutch entity.
*
* @param Clutch $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Clutch $entity)
{
$currentUser = $this->getUser()->getId();
$form = $this->createForm(new ClutchType($currentUser), $entity, array(
'action' => $this->generateUrl('clutch_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Clutch entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Clutch entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('clutch_edit', array('id' => $id)));
}
return $this->render('BreedrClutchBundle:Clutch:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Clutch entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Clutch entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('clutch'));
}
/**
* Creates a form to delete a Clutch entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('clutch_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
在实体中直接执行没有什么错。比如说
public function setLaidDate($date)
{
$this->laidDate = $laidDate;
$hatchDate = date('Y-m-d', strtotime($date . "+30 days"));
$hatchDateEnd = date('Y-m-d', strtotime($date . "+40 days"));
$this->setEstimatedHatchStart($hatchDate);
$this->setEstimatedHatchEnd($hatchDateEnd);
return $this;
}
这只意味着只要调用$this->setLaidDate()
,其他两个字段也将被更新。在处理表单提交时以及在实际将实体持久化到数据库之前,也可以在控制器中手动执行此操作
#services.yml
services:
my_custom_manager:
class: AppBundle\Entity\MyEntityManager
arguments: [ "@doctrine.orm.entity_manager" , 'AppBundle\Entity\MyEntity']
或者我最喜欢的方法是制作实体管理器。用于帮助您创建新的空实体并将现有实体保留回数据库的服务
#services.yml
services:
my_custom_manager:
class: AppBundle\Entity\MyEntityManager
arguments: [ "@doctrine.orm.entity_manager" , 'AppBundle\Entity\MyEntity']
AppBundle/Entity/MyEntityManager
namespace AppBundle\Entity;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\MyEntity;
class MyEntityManager
{
protected $class;
protected $orm;
protected $repo;
public function __construct(ObjectManager $orm , $class)
{
$this->orm = $orm;
$this->repo = $orm->getRepository($class);
$metaData = $orm->getClassMetadata($class);
$this->class = $metaData->getName();
}
public function create()
{
$class = $this->getClass();
$myEntity = new $class;
return $myEntity;
}
public function updateMyEntity(MyEntity $entity, $flush = true)
{
$date = $entity->getLaidDate();
$hatchStart = date('Y-m-d', strtotime($date . "+30 days"));
$hatchEnd = date('Y-m-d', strtotime($date . "+40 days"));
$entity->setHatchStart($hatchStart);
$entity->setHatchEnd($hatchEnd)
$this->orm->persist($entity);
if($flush)
{
$this->orm->flush();
}
}
public function getClass()
{
return $this->class;
}
}
然后在控制器中
<?php
public function createAction(Request $request)
{
$manager = $this->get('my_custom_manager');
$newEntity = $manager->create();
$form = $this->createForm(new MyType() , $newEntity);
$form->handleRequest($request);
if($form->isValid())
{
$manager->updateMyEntity($newEntity);
}
//The rest of the code
}
那么,当表单在后台提交时会发生什么呢$this->setLaidDate($date)
运行,并且设置了估计的图案填充。但是,$this->setEstimatedHatchStart($date)
和$this->estimatedHatchEnd($date)
会被调用,如果您将表单中的这些字段留空,则可能会被设置为NULL
。至少这是我的猜测。尝试从表单中删除字段,看看是否有效。这是一个很好的答案。如果我做了第一个想法,我得到了这个错误可捕获的致命错误:类DateTime的对象无法转换为字符串(我还必须将公共函数setLaidDate($date)
更改为公共函数setLaidDate($laidDate)
)-有什么想法吗?Sry必须开车回家。如果它已经是一个datetime对象,那么您只需$date->modify(“+30天”)
基本上$hatchDateStart=$date->modify(“+30天”)$此->设置HatchStart($hatchStartDate)代码>等等。哈哈,没关系。好的,我已经按照您的建议做了,并更改了几个变量,因为$date
需要$laidDate
。问题是,在提交表单时,数据库中没有设置日期?@andy您能用控制器中使用的代码和新的实体代码更新您的问题吗?对不起,我的懒虫代码。我很懒,讨厌输入长的变量名。哈哈,没问题,2秒钟:)