以嵌入形式保留 OneToOne 关系时出错

Error when persisting OneToOne relation in embed form

我的 symfony EntityBundle 中有这些实体: 拳头Organization.php:

    class Organization
    {
    /**
         * @var integer
         *
         * @ORM\Column(name="organization_id", type="integer", nullable=false)
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        protected $id;

        /**
         * @Assert\Type(
         *     type="string",
         *     message="The value {{ value }} is not a valid {{ type }}."
         * )
         * @Assert\NotNull()
         * @Assert\NotBlank()
         * @ORM\Column(name="organization_name", length=255)
         */
        protected $name;
    /**
         * @var Address
         *
         * @ORM\OneToOne(targetEntity="Address", inversedBy="organization", cascade={"persist"})
         * @ORM\JoinColumn(name="address_id", referencedColumnName="address_id")
         */
        protected $address;
    /**
         * Set address
         *
         * @param \MyNamespace\EntityBundle\Entity\Address $address
         *
         * @return Organization
         */
        public function setAddress(\MyNamespace\EntityBundle\Entity\Address $address = null)
        {
            $this->address = $address;
            $address->setOrganization($this);

        }


        /**
         * Get address
         *
         * @return \MyNamespace\EntityBundle\Entity\Address
         */
        public function getAddress()
        {
            return $this->address;
        }
    }

其次,Address.php

class Address
{
/**
     * @var integer
     *
     * @ORM\Column(name="address_id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @Assert\Length(
     *      max = 5,
     *      maxMessage = "Votre numéro de rue doit avoir maximum {{ limit }} chiffres"
     * )
     * @Assert\NotNull()
     * @Assert\NotBlank()
     * @ORM\Column(name="street_number", type="integer")
     */
    protected $streetNumber;
/**
     * @Assert\Type(
     *     type="string",
     *     message="The value {{ value }} is not a valid {{ type }}."
     * )
     * @Assert\NotNull()
     * @Assert\NotBlank()
     * @ORM\Column(name="street_name", length=255)
     */
    protected $streetName;
/**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\OneToOne(targetEntity="Organization", mappedBy="address")
     */
    protected $organization;
/**
     * Set organization
     *
     * @param \MyNamespace\EntityBundle\Entity\Organization $organization
     *
     * @return Address
     */
    public function setOrganization(\MyNamespace\EntityBundle\Entity\Organization $organization = null)
    {
        $this->organization = $organization;

        return $this;
    }

    /**
     * Get organization
     *
     * @return \MyNamespace\EntityBundle\Entity\Organization
     */
    public function getOrganization()
    {
        return $this->organization;
    }

    /**
     * Add organization
     *
     * @param \MyNamespace\EntityBundle\Entity\Organization $organization
     * @return Address
     */
    public function addOrganization(\MyNamespace\EntityBundle\Entity\Organization $organization)
    {
        $this->organization[] = $organization;

        $organization->setOrganization($this);

        return $this;
    }
}

这是 y 控制器,用于以嵌入形式保存数据:

public function RegistrationAction()
    {

      $organization = new Organization();

      $form = $this->createForm(new OrganizationType(), $organization)
                   ->add('save', 'submit', array('label' => 'Create'));

      $request = $this->getRequest();

      if( $request->isMethod('POST') ) {

        $form->bind($request);

        if( $form->isValid() ) {

          $em = $this->getDoctrine()->getManager();
          $em->persist($organization);
          $em->flush();

           return $this->redirectToRoute('homepage');

        }
      }

      return $this->render('MyBundle:MyFolder:Registration.html.twig', array(
        'form' => $form->createView(),
      ));
    }

这是我的表单类型 OrganizationType.php :

$builder
->add('name')
/* ... the other fields ... */
->add('address', 'collection', array(
                                     'type' => new AddressType(),
                                     'allow_add' => true,
                                     'allow_delete' => false,
                                     'by_reference' => false,
                                     'mapped' => true,
                                     ));
}

最后是我的 twig 视图来呈现表单:

<div>
  {{ form_start(form, {'action': path('path_action'), 'method': 'POST'}) }}
    {{ form_errors(form) }}
    {{ form_row(form.name) }}
    {# .. the other fields ...#}
    {{ form_row(form.address.vars.prototype) }}
  {{ form_end(form) }}
</div>

除提交表单外,一切正常。 发生此错误:

Catchable Fatal Error: Argument 1 passed to MyNamespace\EntityBundle\Entity\Organization::setAddress() must be an instance of MyNamespace\EntityBundle\Entity\Address, array given, called in C:\wamp\www\myApp\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php on line 502 and defined, 'C:\wamp\www\myApp\src\MyNamespace\EntityBundle\Entity\Organization.php', '336', array('this' => object(Organization))) in src\MyNamespace\EntityBundle\Entity\Organization.php at line 336

我该如何解决?

问题就在这里

->add('address', 'collection', array(
                                 'type' => new AddressType(),
                                 'allow_add' => true,
                                 'allow_delete' => false,
                                 'by_reference' => false,
                                 'mapped' => true,
                                 ));

即使是一对一关系,您也已将表单属性类型设置为集合,因此当 symfony 解析表单数据时,它会将地址包装在一个数组中,您可以通过以下方式解决此问题:

->add('address', new AddressType());