gpt4 book ai didi

symfony - 两个表单字段合并为一个实体值

转载 作者:行者123 更新时间:2023-12-04 08:50:33 26 4
gpt4 key购买 nike

如何以一种形式(例如日期和时间)将两个单独的字段(必须分开)连接到一个实体属性 datetime 以在表单发布后保留?

什么是更好的方法?数据转换器 ?表单事件 ?表格模型 ?在持久化之前手动设置所有实体属性?

实体:

<?php namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="event")
*/
class EventEntity
{

/**
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;

// ...

/**
* @ORM\Column(name="date_time", type="datetime", nullable=false)
*/
protected $datetime;

public function getId()
{
return $this->id;
}

// ...

public function getDateTime()
{
return $this->datetime;
}

public function setDateTime(\DateTime $datetime)
{
$this->datetime = $datetime;
}

}

表格类型:
<?php namespace Acme\DemoBundle\Form\Type;

use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EventType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('date', 'date', [
'required' => true,
'widget' => 'single_text',
'format' => 'dd.MM.yyyy'
]
)
->add('time', 'time', [
'required' => false,
'widget' => 'single_text'
]
);
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\EventEntity' //Acme\DemoBundle\Form\Model\EventModel ?
));
}

public function getName()
{
return 'event';
}

}

最佳答案

如果您在 datetime 类型中单独设置日期和时间小部件,则它们将单独呈现,但作为一个字段进行验证。

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('datetime', 'datetime', array(
'date_widget' => 'single_text',
'time_widget' => 'single_text',
'date_format' => 'dd.MM.yyyy',
));
}

关于symfony - 两个表单字段合并为一个实体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17412965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com