奏鸣曲管理员一对多的关系

时间:2016-01-19 21:19:59

标签: symfony sonata-admin

我今天开始使用SonataAdmin Bundle,但我无法弄清楚OneToMany的关系。我的用户可以关注(观察)offerts

实体:

class Obserwowane {

  /**
   * @ORM\Id
   * @ORM\Column(type="integer")
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  protected $id;

  /**
   * @ORM\ManyToOne(targetEntity="Oferty",inversedBy="obserwowane")
   * @ORM\JoinColumn(name="oferta", referencedColumnName="id_oferty", onDelete="CASCADE")
   */
  protected $oferta;

  /**
   *
   * @ORM\ManyToOne(targetEntity="User", inversedBy="obserwowane")
   * @ORM\JoinColumn(name="user", referencedColumnName="id")
   */
  protected $user;
}  

class User {

  /**
   * @ORM\OneToMany(targetEntity="Obserwowane", mappedBy="user")
   */
  public $obserwowane;
}

class Oferty {

  /**
   * @ORM\OneToMany(targetEntity="Obserwowane", mappedBy="oferta")
   */
  protected $obserwowane;
}

我的servies.yml - > http://pastebin.com/biNCLhNt

我想在SonataAdminBundle的用户表单中显示以下优惠。我也希望它可以编辑。

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('id', 'integer', array('label' => 'id'))
        ->add('username', 'text', array('label' => 'Username'))
        ->add('email', 'text', array('label' => 'e-mail'))
        ->add('password', 'text', array('label' => 'Password'))
    ;
}

1 个答案:

答案 0 :(得分:1)

将obserwowane定义为ArrayCollection并添加getter和setter方法,以便sonata使用它们与Obserwowane实体数组一起操作。

use Doctrine\Common\Collections\ArrayCollection;

class user{

// ...

    public function __construct()
    {
        $this->obserwowane = new ArrayCollection;
    }

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


      public function setObserwowane (ArrayCollection $obserwowane )
      {
          $this->obserwowane  = $obserwowane ;

          return $this;
      }

      /**
       * Add Obserwowane
       *
       * @param Obserwowane $obserwowane
       * @return Obserwowane
       */
      public function addObserwowane (Obserwowane $obserwowane )
      {
          $this->obserwowane[] = $obserwowane;

          return $this;
      }

      /**
       * Remove Obserwowane
       *
       * @param Obserwowane $obserwowane
       */
      public function removeObserwowane(Obserwowane $obserwowane)
      {
          $this->obserwowane->removeElement($obserwowane);
      }

}

最后在formMapper

中添加obserwowane字段
$formMapper
 ->add('obserwowane')

<强>更新

要为Obserwowane实体添加或删除用户,请将这些功能添加到Obserwowaneclass

class Obserwowane{

    // ..

    /**
     * Set User
     *
     * @param User $user
     * @return User
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get User
     *
     * @return User
     */
    public function getUser()
    {
        return $this->user;
    }
}

在奏鸣曲

$formMapper
 ->add(user) 
相关问题