Symfony2 (бета5) 1: M / M: 1 в формах - PullRequest
1 голос
/ 23 июня 2011

У меня есть сущность "Creative" и сущность "Question" ... Когда у меня было отношение ManyToMany от Creative до Question, я мог легко сделать $ builder-> add ('questions'), и он бы захватил все вопросыи поместите их в мультиселектор и вставьте в creative_question.Ну, мне нужно новое поле (позиция) для creative_question, поэтому мне пришлось создать отношение OneToMany / ManyToOne.Но когда я добавляю поле ($ builder-> add ('creativeQuestions')), множественный выбор становится пустым, и кажется, что он пытается запросить creative_question, чтобы заполнить его ... что неправильно.Мне нужно заполнить Вопросы и вставить их в creative_question.

В любом случае, вот мой код:

## Creative.php

[...]

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

/**
 * @ORM\ManyToOne(targetEntity="Offer", cascade={"persist"})
 */
protected $offer;

/**
 * @ORM\OneToMany(targetEntity="CreativeQuestion", mappedBy="creative", cascade={"persist"})
 */
protected $creativeQuestions;

[...]

## CreativeQuestion.php

[...]

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

/**
 * @ORM\ManyToOne(targetEntity="Creative", cascade={"persist"})
 */
protected $creative;

/**
 * @ORM\ManyToOne(targetEntity="Question", cascade={"persist"})
 */
protected $question;

/**
 * @ORM\Column(type="integer")
 */
protected $pos;

[...]

## CreativeType.php

[...]

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('name')
        ->add('title')
        ->add('description')
        ->add('body')
        ->add('script')
        ->add('creativeQuestions') // how do i populate list with "Questions" then insert into creative_question?
        ->add('active');
}

public function getDefaultOptions(array $options)
{
    return array(
        'data_class' => 'JStout\MainBundle\Entity\Creative'
    );
}

[...]

## In My Controller:

 /**
 * @Extra\Route("/offer/{offerId}/creative", name="admin_offer_creative")
 * @Extra\Route("/offer/{offerId}/creative/{creativeId}", name="admin_offer_creative_edit")
 * @Extra\Template()
 */
public function creativeAction($offerId = null, $creativeId = null)
{
    // Get Offer
    $offer = $this->_getObject('Offer', $offerId);

    if (null === $offer->getId()) throw new NotFoundHttpException('The page you requested does not exist!');

    // Get Creative
    $creative = $this->_getObject('Creative', $creativeId);

    // Set offer to creative
    $creative->setOffer($offer);

    // Get form and handler
    $form = $this->get('form.factory')->create(new Form\CreativeType(), $creative);
    $formHandler = $this->get('form.handler')->create(new Form\CreativeHandler(), $form);

    [...]
}

protected function _getObject($entityName, $id = null)
{
    // Find object
    if (null !== $id) {
        if (!$object = $this->get('doctrine')->getEntityManager()->find('ZGOffersMainBundle:' . $entityName, $id)) {
            throw new NotFoundHttpException('The page you requested does not exist!');
        }

        return $object;
    }

    // Initialize new object
    $entityName = 'JStout\MainBundle\Entity\\' . $entityName;
    if (class_exists($entityName)) {
        return new $entityName();
    }

    throw new NotFoundHttpException('The page you requested does not exist!');
}

[...]

Опять же, то, что мне нужно, работает, когда я удаляю CreativeQuestion и просто делаю Вопрос с отношением ManyToMany:

working

Но, в идеале, я хотел бы иметь возможность (с помощью jquery) добавьте вопросы, выбрав их из выпадающего списка, затем перетащите для размещения вопросов.Позиционирование с помощью jquery легко, я просто не знаю, как добавить вопросы так, как я хочу.Если мне удастся хотя бы заставить работать мультиселектор, то я смогу двигаться вперед, но я как бы застрял прямо сейчас!

Кто-нибудь еще может зайти так далеко с Symfony2 (бета5)?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...