forms - 在表单绑定(bind)之前克隆实体

标签 forms symfony entity bind

使用 Symfony2,我需要在使用 $form->bind() 之前保存一个实体,以便在刷新之前比较新旧实体。

我尝试了一些功能:

$command = $repository->findCommandProductsByCommand( $id );
$old_command = clone $command;
// OR $old_command = $command;
$form = $this->createForm(new EditCommandType(), $command);

if( $request->getMethod() == 'POST' )
{
    $form->bind($request);
    if ( $form->isValid() )
    {

我尝试保存实体的一小部分,如下所示:

$old_command = $command->getCommandProducts();

但是当我尝试使用这些方法之一访问 $old_command 的数据时,我只能从表单访问对象的较新值,而不是旧值。

$form->bind($request) 是主要问题,但我没有找到描述 bind() 确切功能的文档。

致以诚挚的问候

我的案例的解决方案(感谢zizoujab)

$command_entries = new ArrayCollection();
foreach ($command->getCommandproducts() as $entry) {
    $command_entries[] = clone $entry;
}

现在我的 ArrayCollection $command_entries 未链接到之前的实体。

最佳答案

来自克隆手册:

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's
properties. Any properties that are references to other variables, will remain references.

我假设 getCommandProducts() 返回一个 ArrayCollection,因此您将始终获得新列表。

您还必须克隆列表的元素。

这里是完整的解释和解决方案的示例: Symfony2/Doctrine: How to re-save an entity with a OneToMany as a cascading new row

关于forms - 在表单绑定(bind)之前克隆实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924437/

相关文章:

javascript - 限制答案数量复选框

session - Symfony2 Flash 消息未清除

php - 在 Mamp 中记录 symfony

java - 将转换器对象化为 JPA 属性转换器

symfony - get ('doctrine' 之间的区别);和 getDoctrine();

oop - 实体组件系统中的有限状态机实现

javascript - 来自json数据的AngularJS动态表单(不同类型)

php - 表单提交到 PHP

jquery - 在选择更改时提交 Ajax 表单

php - 命令行 Doctrine ORM with Silex : You are missing a "cli-config.php" or "config/cli-config.php" file in your project