Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Symfony 3-CollectionType仅保存第一个元素_Php_Symfony_Many To One_Persist_Symfony 3.2 - Fatal编程技术网

Php Symfony 3-CollectionType仅保存第一个元素

Php Symfony 3-CollectionType仅保存第一个元素,php,symfony,many-to-one,persist,symfony-3.2,Php,Symfony,Many To One,Persist,Symfony 3.2,我有一个很奇怪的问题。我有一个实体:财产 它与图片有着多方面的联系 当我为表单添加更多图片时,当我只保存第一张已保存的图片时,其余的则不保存。 但是,我可以在每次保存后添加新图片,但一次只能添加一张 代码: 财产实体 namespace Ciber\PropertyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\

我有一个很奇怪的问题。我有一个实体:财产 它与图片有着多方面的联系

当我为表单添加更多图片时,当我只保存第一张已保存的图片时,其余的则不保存。 但是,我可以在每次保存后添加新图片,但一次只能添加一张

代码: 财产实体

namespace Ciber\PropertyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use \Ciber\UtilBundle\Entity\Traits as CiberTraits;

/**
 * Property
 *
 * @ORM\Table(name="property")
 * @ORM\Entity(repositoryClass="Ciber\PropertyBundle\Repository\PropertyRepository")
 */
class Property
{
    use ORMBehaviors\Timestampable\Timestampable;
    use CiberTraits\AddressTrait;
    use CiberTraits\PriceTrait;
    use ORMBehaviors\Translatable\Translatable;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;


    /**
     *
     * @ORM\OneToMany(targetEntity="Ciber\PropertyBundle\Entity\PropertyImage", mappedBy="property", orphanRemoval=true, cascade={"persist"})
     */
    private $propertyImages;

    /**
     *
     * @ORM\OneToMany(targetEntity="Ciber\PropertyBundle\Entity\PropertyPlan", mappedBy="property", orphanRemoval=true, cascade={"persist"})
     */
    private $propertyPlans;


    /**
     * @ORM\ManyToOne(targetEntity="Ciber\UserBundle\Entity\User", inversedBy="properties", cascade={"persist"})
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;


    /**
     * Constructor
     */
    public function __construct()
    {
        $this->propertyImages = new ArrayCollection();
        $this->propertyPlans = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }


    /**
     * Add PropertyImage
     *
     * @param \Ciber\PropertyBundle\Entity\PropertyImage $propertyImage
     * @return Property
     */
    public function addPropertyImage(\Ciber\PropertyBundle\Entity\PropertyImage $propertyImage)
    {

        //$this->propertyImages[] = $propertyImage;
        $this->propertyImages->add($propertyImage);
        $propertyImage->setProperty($this);

        return $this;
    }

    /**
     * Remove propertyImage
     *
     * @param \Ciber\PropertyBundle\Entity\PropertyImage $propertyImage
     */
    public function removePropertyImage(\Ciber\PropertyBundle\Entity\PropertyImage $propertyImage)
    {
        $this->propertyImages->removeElement($propertyImage);
    }

    /**
     * Add propertyPlans
     *
     * @param \Ciber\PropertyBundle\Entity\PropertyPlan $propertyPlans
     * @return Property
     */
    public function addPropertyPlan(\Ciber\PropertyBundle\Entity\PropertyPlan $propertyPlans)
    {
        $this->propertyPlans[] = $propertyPlans;
        $propertyPlans->setProperty($this);

        return $this;
    }

    /**
     * Remove propertyPlans
     *
     * @param \Ciber\PropertyBundle\Entity\PropertyPlan $propertyPlan
     */
    public function removePropertyPlan(\Ciber\PropertyBundle\Entity\PropertyPlan $propertyPlan)
    {
        $this->propertyPlans->removeElement($propertyPlan);
    }

    /**
     * Get propertyImages
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPropertyImages()
    {
        return $this->propertyImages;
    }


    /**
     * Get propertyPlans
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPropertyPlans()
    {
        return $this->propertyPlans;
    }

    /**
     * Gets triggered only on insert

     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->createdAt = new \DateTime("now");
    }

    public function __call($method, $arguments)
    {
        return $this->proxyCurrentLocaleTranslation($method, $arguments);
    }
}
图片实体

    namespace Ciber\PropertyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File as File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * PropertyImage
 *
 * @ORM\Table(name="property_image")
 * @ORM\Entity
 * @Vich\Uploadable
 */
class PropertyImage
{
    use ORMBehaviors\Timestampable\Timestampable;
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Ciber\PropertyBundle\Entity\Property", inversedBy="propertyImages")
     * @ORM\JoinColumn(name="property_id", referencedColumnName="id")
     */
    private $property;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="property_images", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }


    /**
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return PropertyImage
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return PropertyImage
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * Set property
     *
     * @param \AppBundle\Entity\Property $property
     *
     * @return PropertyImage
     */
    public function setProperty( \Ciber\PropertyBundle\Entity\Property $property = null ) {
        $this->property = $property;

        return $this;
    }

    /**
     * Get property
     *
     * @return \Ciber\PropertyBundle\Entity\Property
     */
    public function getProperty() {
        return $this->property;
    }

    public function __toString()
    {
        return $this->imageName;
    }
}
表格:

class FlatType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ...

            // Pictures
            ->add('propertyImages', CollectionType::class, array(
                'by_reference' => false,
                'entry_type' => PropertyImageType::class,
                'allow_add'    => true,
                'allow_delete' => true,
            ))
            ->add('propertyPlans', CollectionType::class, array(
                'by_reference' => false,
                'entry_type' => PropertyPlanType::class,
                'allow_add'    => true,
                'allow_delete' => true,
            ))

            ...
        ;
        $builder->add('save', ButtonType::class, array(
            'label' => 'property.form.save'
        ));
    }



    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ciber\PropertyBundle\Entity\Property',
        ));
    }
}
有趣的事实:

if ($request->isMethod('POST')) {
        $form->handleRequest($request);
        $property = $form->getData();
        dump($property); exit();
...
当我转储$property时-在同时提交两张图片之后-我得到了以下结果:

elements: array:2 [▼
0 => PropertyImage {#3937 ▼
  -id: 10
  -isDefault: false
  -title: null
  -property: Property {#2799}
  -imageFile: null
  -imageName: "5939c65692d47.jpg"
  #createdAt: DateTime {#3933 ▶}
  #updatedAt: DateTime {#2605 ▶}
}
1 => PropertyImage {#4225 ▼
  -id: null
  -isDefault: false
  -title: null
  -property: Property {#2799}
  -imageFile: UploadedFile {#14 ▶}
  -imageName: null
  #createdAt: null
  #updatedAt: DateTime {#4224 ▶}
}
]
我真的不知道这里发生了什么 (当然,我有更多的字段,比如title,我认为这与问题无关。但是,正如您所看到的,我还有一个“PropertyPlans ArrayCollection,它也有同样的问题。只有第一个字段正确地存在)

编辑。这是我的控制器:

/**
 * @Route("/properties/{property_category}/new", name="propertycreateindex")
 */
public function propertyCreateIndexAction(Request $request)
{

    $entity = new Property();
    $form = $this->createForm(Ciber\PropertyBundle\Form\FlatType, $entity);

    if ($request->isMethod('POST')) {
        $form->handleRequest($request);
        $property = $form->getData();
        $property->setUser($this->getUser());
        $property->setIsActive(1);
        $em = $this->getDoctrine()->getManager();
        $em->persist($property);
        $em->flush();
        $this->addFlash(
            'success',
            $this->get('translator')->trans('success.message.create_successfull')
        );
        return $this->redirectToRoute('dashboard');
    }

    return $this->render(view.html.twig, array(
        'form' => $form->createView(),
        'property' => $entity
    ));

}
这是PropertyImageType.php

namespace Ciber\PropertyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class PropertyImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('isDefault')
            ->add('title', TextType::class, array(
                'required' => false
            ))
            ->add('imageFile', VichImageType::class, array(
                'required' => false,
                'allow_delete' => true, // not mandatory, default is true
                'download_link' => false //  default is true
            ));

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ciber\PropertyBundle\Entity\PropertyImage',
        ));
    }
}

对不起,我的不好。我睡了几个小时后,重新测试了一下。 我发现,我错了。不是第一张,而是最后一张。 从这里,这是一个简单的方法来找出,我错过了一行从教程

newinputs.each(function(){
    $(this).attr('id', $(this).attr('id').replace(/__name__/g, $randomId));
    $(this).attr('name', $(this).attr('name').replace(/__name__/g, $randomId));
});
CollectionType默认的“property_name”是name,在从form.prototype创建新的嵌入后,必须使用javascript对其进行修改
你必须在新创建的字段中更改名称

控制器、命令或其他什么东西在哪里被持久化?在转储中很奇怪,它显示第一个实体已经存在,但第二个是一个
上传文件
。这个编辑和图像已经存在吗?我已经更新了帖子。不,两个图像都是newly uploaded。第二个在UploadedFile节点上有第二个图像数据。并且您没有使用浏览器中的其他工具预上载它们?您不认为这很奇怪,第一个保存,第二个(仅显示为UploadedFile)没有保存?我想看看为什么会这样。在这种情况下,第一个也应该显示为已上载。在任何情况下,您可能应该在上载时迭代该集合中的
属性图像
,处理文件本身,然后在保存之前保存并更新实体。我没有看到任何特定的代码lly将一个
UploadedFile
转换为可以像第一行一样持久化的内容。作为symfony文档:通过这两个更改,在提交表单时,通过调用addTag()方法将每个新标记对象添加到Task类中。在此更改之前,表单通过调用$Task->getTags()->add在内部添加它们($tag)。这很好,但是强制使用“adder”方法可以更容易地处理这些新的标记对象。