Doctrine2一对多关系未以管理形式显示

时间:2015-03-14 00:28:32

标签: symfony orm doctrine-orm sonata-admin

所以我(我认为我已经正确完成)映射了两个表之间的一对多关系。

生成了用于创建外键的SQL但是有能力。我的管理类显示表单字段方法中的字段不输出另一个表中的字段。

我的主要实体

/**
 * Suppliers
 *
 * @ORM\Table(
 *      name="suppliers",
 *      indexes={
 *          @Index(
 *              name="supplier_name", columns={"name"}
 *          )
 *      })
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Suppliers
{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned":true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @Assert\NotNull()
     * @ORM\Column(name="type", type="string", nullable=false)
     */
    private $type;

    /**
     * @var string
     *
     * @Assert\NotNull()
     * @ORM\Column(name="name", type="string", nullable=false, nullable=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    /**
     * @var string
     *
     * @ORM\Column(name="updated", nullable=true, type="datetime")
     */
    private $updated;

    /**
     * @var string
     *
     * @ORM\Column(name="deleted", type="boolean", options={"default":0})
     */
    private $deleted;

    /**
     * @var
     *
     * @ORM\OneToMany(targetEntity="AppNamespace\Bundle\SupplierBundle\Entity\Region\Region", mappedBy="supplies")
     */
    private $regions;

    /**
     * @var string
     */
    private $entityName;

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

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

    /**
     * Set type
     *
     * @param string $type
     * @return User
     */
    public function setType($type)
    {
        $this->type = strtolower($type);

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return strtoupper($this->type);
    }

    /**
     * Set name
     *
     * @param string $name
     * @return User
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set created
     *
     * @param string $created
     * @return $this
     */
    public function setCreated($created)
    {
        if (!empty($created)) {
            $this->created = $created;
        } else {
            $this->created = new \DateTime("now");
        }

        return $this;
    }

    /**
     * Get created
     *
     * @return string
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param string $updated
     * @return User
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return string
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set deleted
     *
     * @param boolean $deleted
     * @return User
     */
    public function setDeleted($deleted)
    {
        $this->deleted = $deleted;

        return $this;
    }

    /**
     * Get deleted
     *
     * @return boolean
     */
    public function getDeleted()
    {
        return $this->deleted;
    }

    /**
     * @ORM\PrePersist()
     */
    public function onPrePersist()
    {
        $this->created = new \DateTime();
        $this->updated = new \DateTime();
        if ($this->deleted === null) {
            $this->deleted = 0;
        }
    }

    /**
     * @ORM\PreUpdate()
     */
    public function onPreUpdate()
    {
        $this->created = new \DateTime();
        $this->updated = new \DateTime();
        if ($this->deleted === null) {
            $this->deleted = 0;
        }
    }

    /**
     * @return array
     */
    public static function getTypes()
    {
        return array(
            'internal' => 'Internal',
            'external' => 'External',
            'lpe' => 'LPE'
        );
    }

    /**
     * Set entityName
     *
     * @param string $name
     * @return User
     */
    public function setEntityName($name)
    {
        $this->entityName = $name;

        return $this;
    }

    public function __toString()
    {
        if (!empty($this->entityName) && !empty($this->id)) {
            return $this->entityName;
        } else if (!empty($this->id)) {
            return 'Supplier #'. $this->getId();
        }
        return 'Supplier';
    }
}

模式

CREATE TABLE `suppliers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `type` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `updated` datetime DEFAULT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `supplier_name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

供应商地区加入表

/**
 * Region
 *
 * @ORM\Table(
 *      name="supplier_regions",
 *      indexes={
 *          @Index(
 *              name="supplier_regions_postcode", columns={"postcode"}
 *          )
 *      })
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Region
{
    /**
     * @var integer
     *
     * @ORM\Column(name="supplier_id", type="integer", nullable=false, options={"unsigned":true})
     * @ORM\Id
     */
    private $supplierId;

    /**
     * @var integer
     *
     * @ORM\Column(name="postcode", type="string", nullable=false)
     * @ORM\Id
     */
    private $postcode;

    /**
     * @var string
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    /**
     * @var
     *
     * @ORM\ManyToOne(targetEntity="AppNamespace\Bundle\SupplierBundle\Entity\Suppliers", inversedBy="regions")
     * @ORM\JoinColumn(name="supplier_id", referencedColumnName="id")
     */
    private $supplies;


    /**
     * Get supplierId
     *
     * @return integer 
     */
    public function getSupplierId()
    {
        return $this->supplierId;
    }

    /**
     * Set supplierId
     *
     * @param integer $supplierId
     * @return $this
     */
    public function setSupplierId($supplierId)
    {
        $this->supplierId = $supplierId;
        return $this;
    }

    /**
     * Get postcode
     *
     * @return integer
     */
    public function getPostcode()
    {
        return $this->postcode;
    }

    /**
     * Set postcode
     *
     * @param integer $postcode
     * @return $this
     */
    public function setPostcode($postcode)
    {
        $this->postcode = $postcode;
        return $this;
    }

    /**
     * Set created
     *
     * @param string $created
     * @return $this
     */
    public function setCreated($created)
    {
        if (!empty($created)) {
            $this->created = $created;
        } else {
            $this->created = new \DateTime("now");
        }

        return $this;
    }

    /**
     * Get created
     *
     * @return string
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * @param Supplier $supplies
     * @return $this
     */
    public function setSupplied(Supplier $supplies = null)
    {
        $this->supplies = $supplies;
        return $this;
    }

    /**
     * Get supplies
     *
     * @return Supplier
     */
    public function getSupplied()
    {
        return $this->supplies;
    }
}

模式

CREATE TABLE `supplier_regions` (
  `supplier_id` int(10) unsigned NOT NULL,
  `postcode` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`supplier_id`,`postcode`),
  KEY `supplier_regions_postcode` (`postcode`),
  KEY `IDX_23020DEC2ADD6D8C` (`supplier_id`),
  CONSTRAINT `FK_23020DEC2ADD6D8C` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

因此,当Sonata进入表格形式时,我希望它在幕后运行以下查询:

SELECT
    *
FROM
    supplier_regions sr
JOIN suppliers s ON s.id = sr.supplier_id

这是我的供应商管理类:

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Form\Type;
use Sonata\AdminBundle\Validator\ErrorElement;
use Housesimple\Bundle\CoreBundle\Util\Request as RequestHelper;
use Housesimple\Bundle\SupplierBundle\Entity\Suppliers as Suppliers;

use Knp\Menu\ItemInterface as MenuItemInterface;

class SupplierAdmin extends Admin
{

    protected $parentAssociationMapping = 'admin';

    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;


    public function setContainer (\Symfony\Component\DependencyInjection\ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param \Sonata\AdminBundle\Show\ShowMapper $showMapper
     *
     * @return void
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        dump($this->getSubject());
        $showMapper
            ->add('id')
            ->add('type')
            ->add('name')
            ->add('created')
            ->add('updated')
            ->end()
            ->with('Regions')
            ->add('region', 'sonata_type_collection', array(
                'by_reference' => false // true doesn't work neither
            ))
            ->end();
    }

    /**
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     *
     * @return void
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $actionName = RequestHelper::getActionName($this->getRequest());

        switch ($actionName) {
            case 'create':
                $em = $this->container->get('doctrine.orm.entity_manager');
                $lastId = $em->getConnection()->lastInsertId();
                $nextId = (empty($lastId) ? '' : ' #'. $lastId + 1);
                $this->getSubject()->setEntityName('New supplier #' . $nextId);
                $formMapper->with('New supplier'. $nextId);
                break;
            case 'edit':
                $this->supportsPreviewMode = true;
                $formMapper->with('Edit Supplier #'. $this->getSubject()->getId());
                break;
        }
        $formMapper
                ->add('type', 'choice', array(
                    'choices' =>  Suppliers::getTypes(),
                    'empty_value' => 'Choose an option',
                    'required' => true
                ))
            ->add('name')
            ->end();
    }

    /**
     * {@inheritdoc}
     */
    protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
    {
        /*$admin = $this->isChild() ? $this->getParent() : $this;
        $menuItems = array('list', 'create');
        $menu->addChild('action', array('attributes' => array('dropdown' => true)));
        foreach ($menuItems as $item) {
            if ($item == $action) {
                continue;
            }
            $menu['action']->addChild(
                ucwords($item),
                array('uri' => $admin->generateUrl(strtolower($item)))
            );
        }
        return $menu;*/
    }

    /**
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
     *
     * @return void
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        //unset($this->listModes['mosaic']);
        $listMapper
            ->add('id')
            ->add('type')
            ->addIdentifier('name')
            ->add('created', 'date', array(
                'pattern' => 'dd/MM/Y @ H:m',
                'locale' => 'en_GB',
                'timezone' => 'Europe/London',
            ))

            // add custom action links
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array()
                )
            ));
    }

    /**
     * @param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
     *
     * @return void
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('type')
            ->add('name')
            ->add('created')
            ->add('updated');
    }

    public function preUpdate($supplier)
    {
        $supplier->setDeleted(0);
        return $supplier;
    }

    public function preCreate($supplier)
    {
        $supplier->setDeleted(0);
        return $supplier;
    }
}

我希望我的展示表单能够显示特定供应商的所有邮政编码条目,但目前它是空白的......

enter image description here

有人能发现我需要做什么吗?

提前致谢:)

0 个答案:

没有答案