【问题标题】:Symfony 2 form with date as key but not on formSymfony 2 表单,以日期为键但不在表单上
【发布时间】:2015-12-03 16:02:41
【问题描述】:

所以我在 symfony 中有这个简单的表单,我只有 3 个字段。在这里工作的所有 id 一个不在表单上但在数据库中的实体是 df_date 列,它在数据库中输入 DATE。

这是那个实体:

 /**
 * @ORM\Column(type="date")
 * @ORM\Id
 */

 protected $df_date;

 /**
 * Set df_date
 *
 * @param \DateTime $dfDate
 * @return WeatherSpecials
 */

public function setDfDate($dfDate)
{
    $this->df_date = $dfDate;

    return $this;
}

/**
 * Get df_date
 *
 * @return \DateTime 
 */

public function getDfDate()
{
    return $this->df_date;
}

控制器:

    public function ajax_weather_specialsAction(Request $request, $main_id)
{

    $params = array();

    if (!$main_id) {
        /*
        $repository = $this->getDoctrine()
            ->getRepository('AppBundle:WeatherSpecials');
        $weather_specials = $repository->find($main_id);
        */
    } else {
        $weather_specials = new WeatherSpecials;
    }

    $form = $this->createFormBuilder($weather_specials)
        ->add('df_weather', 'choice', array(
            'choices'  => array(
                null, 'SU', 'PC', 'CL', 'RN'
            ),
            'label' => false, 'required' => true,
        ))
        ->add('df_temptur', 'number', array('label' => false, 'required' => true))
        ->add('df_specday', 'text', array('label' => false, 'required' => false))
        ->add('save', 'submit', array('attr' => array('class' => 'btn btn-primary')))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted()) {
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($weather_specials);

            // How to set df_date here???

            $em->flush();
        }
    }

    $data['status'] = 'success';
    $data['html'] = $this->render('sales_tabs/weather_specials.twig', array('form' => $form->createView()))->getContent();

    return new JsonResponse($data);
}

问题是,在我将该表单保存到数据库之前如何设置 df_date?

【问题讨论】:

  • 你想坚持什么价值?当前时间?
  • 任何日期,yyyy-mm-dd,不需要时间。
  • 该字段被定义为主键,所以如果你想防止重复键,我建议你存储一个时间戳,最好是一个简单的自动增量?在此处查看文档doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/…
  • 日期没问题,因为逻辑确保它每天运行一次。所以它不会重复。
  • 抱歉,我认为您已经尝试过使用$weather_specials->setDfDate(new \DateTime());,但没有成功。也许是在此处doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/… 的教义2 文档中定义的正确 php 类型

标签: php forms symfony


【解决方案1】:

假设WeatherSpecials 是您要设置df_date 的实体,请在您坚持之前设置它;

if ($form->isValid()) {
    $em = $this->getDoctrine()->getManager();
    $weather_specials->setDfDate(new \DateTime());
    $em->persist($weather_specials);
    $em->flush();
}

或使用doctrine HasLifecycleCallbacks

/**
 * WeatherSpecials
 *
 * @ORM\Table(name="weather_specials")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\WeatherSpecialsRepository")
 * @ORM\HasLifecycleCallbacks
 */
class WeatherSpecials
{
    // other stuff

    /**
     * @ORM\PrePersist
     */
    public function prePersist(\Doctrine\ORM\Event\LifecycleEventArgs $event)
    {
        $this->df_date = new DateTime();
    }

    /**
     * @ORM\PreUpdate
     */
    public function preUpdate(\Doctrine\ORM\Event\LifecycleEventArgs $event)
    {
        $this->df_date = new DateTime();
    }
}

【讨论】:

  • 这是我得到的错误。在第 1359 行的 vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php 中的堆栈跟踪 - public function addToIdentityMap($entity) { $classMetadata = $this->em->getClassMetadata(get_class($entity)); $idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]); if ($idHash === '') { throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity);
【解决方案2】:

您可以在持久化实体之前手动设置日期。

考虑下面这段代码

if ($form->isSubmitted()) {
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $weather_specials->setDfDate(new \DateTime());

        $em->persist($weather_specials);
        $em->flush();
    }
}

这会将日期设置为当前日期和时间。您可以根据需要更改日期时间值。

您甚至可以使用 Doctrine 的 preUpdateprePersist 回调。

更新您的实体定义不正确。您应该将$df_date 定义为\Datetime 参数。在你的代码中改变它

/**
* @var \datetime
* @ORM\Column(type="date")
* @ORM\Id
*/

protected $df_date;

//the rest of your stuff

【讨论】:

  • 当我添加 $weather_specials->setDfDate(new \DateTime());.我收到此错误可捕获的致命错误:无法将类 DateTime 的对象转换为字符串
  • 你确定你用\添加了new \DateTime()吗?
  • 查看我的编辑。您在变量 $df_date 的实体定义中遗漏了 * @var \datetime
  • 我添加了 * @var \datetime ,但我仍然得到那个错误,我在 symfony 2.8 上可能是这个原因吗?
  • 尝试删除setDfDate 中的return 语句并从方法上方删除* @return WeatherSpecials。不要简单地返回任何东西。
【解决方案3】:

我发现了问题,Doctrine 可以通过它的建议亲吻我的……。我花了 3 天时间才弄清楚这一点,仅在 PHP 中我就需要 5 分钟。 enter link description here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多