Symfony 3 ChoiceType недействителен

у меня очень простой сценарий. Он считывает ID и NAME из таблицы и добавляет их в качестве опции в мой тип выбора.

РЕШЕНО См. последний скрипт. вам нужно снова добавить все параметры в форму.

Это Действие.

/**
 * @Route("/monitor/setup/carousel", name="SetupCarousel")
 */
public function SetupCarouselManageAction(Request $request){
    $repository = $this->getDoctrine()->getRepository("AppBundle:Picture");
    $pictures = $repository->findAll();
    $p = array();
    $p['-- Bitte Bild setzen'] = -1;
    foreach($pictures as $pic){
        $p[$pic->getTitle()] = $pic->getId();
    }
    $carousel = new Carousel();
    $FormCarousel = $this->createForm(CarouselType::class, $carousel, array(
            'pictures' => $p,
            'action' => $this->generateUrl('SetupInputCarousel')
    ));

    $render = $this->render('SetupCarousel.html.twig',array(
            'form_event' => $FormCarousel->createView()

    ));
    return $render;
}

Тип формы:

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

    $builder
        ->add("bildId", ChoiceType::class, 
                array('choices' => $options['pictures']))
        ->add('submit', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
    $resolver
    ->setDefaults(array(
            'data_class' => Carousel::class,
            'pictures'=> array('array')))
    ->setAllowedTypes('pictures', array('array'))
    ;
}
}

Все идет нормально. на моей странице появится поле ChoiceType, я могу выбрать нужную запись и отправить ее. Если я хочу проверить, действительны ли данные, это не удается.

здесь моя Сущность

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

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

/**@ORM\Column(type="string") */
protected $text;

Вот так я получаю данные на данный момент.

/**
 * @Route("/monitor/setup/input/carousel",name="SetupInputCarousel")
 */
public function SetupInputCarouselAction(Request $request){
    $carousel = new Carousel();
    $form = $this->createForm(CarouselType::class,$carousel);
    $form->handleRequest($request);
    if($form->isSubmitted()){

        //pease rework this in future
        $data = $request->request->get('carousel');
        $carousel->setBildId($data['bildId']);

        $carousel->setText($data['text']);

        if($carousel->getBildId() == -1){
            return $this->redirectToRoute('SetupHome');
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($carousel);
        $em->flush();
    return $this->redirectToRoute('SetupCarousel');

}

есть ли у кого-нибудь идея, почему этот следующий скрипт не работает? Именно так я могу сделать это на всех других страницах моего проекта.

public function SetupInputEventsAction(Request $request){

    //YOU HAVE TO ADD THE ORIGINAL OPTIONS, THIS SOLVE THE PROBLEM
    $repository = $this->getDoctrine()->getRepository("AppBundle:Picture");
    $pictures = $repository->findAll();
    $p = array();
    $p['-- Bitte Bild setzen'] = -1;
    foreach($pictures as $pic){
        /** @var pic Picture */
        $p[$pic->getTitle()] = $pic->getId();
    }
    $carousel = new Carousel();
    $form = $this->createForm(CarouselType::class,$carousel, array(
            'pictures' => $p,
            'action' => $this->generateUrl('SetupInputCarousel')
            ));

    /*
     SEE WORKING ONE ABOVE
     $event = new Carousel();
    $form  = $this->createForm(CarouselType::class,$event);*/
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()){
        //handel type
        $em = $this->getDoctrine()->getManager();
        $em->persist($event);
        $em->flush();
    }
    return $this->redirectToRoute('SetupEvents');
}

С уважением,

Фабиан Хармсен


person LFS96    schedule 11.04.2017    source источник
comment
Вы визуализировали: form_widget(form._token) в шаблоне ветки?   -  person Đuro Mandinić    schedule 11.04.2017
comment
@ĐuroMandinić вот как я печатаю форму {{ form_start(form_event) }} {{ form_widget(form_event) }} {{ form_end(form_event) }}   -  person LFS96    schedule 11.04.2017
comment
Вы получаете сообщение об ошибке проверки? Как узнать, что поле недействительно?   -  person Đuro Mandinić    schedule 11.04.2017
comment
@ĐuroMandinić да, есть ошибки. dl.lfs96.de/SymfonyProfiler_2017-04-12.htm здесь вы можете смотрите профайлер. Я остановил перенаправление, чтобы вы могли игнорировать ошибку   -  person LFS96    schedule 12.04.2017
comment
@ĐuroMandinić Проблема найдена и решена   -  person LFS96    schedule 12.04.2017
comment
РЕШЕНО См. последний скрипт. вам нужно снова добавить все параметры в форму. — К чему этот вопрос?   -  person Quentin    schedule 12.04.2017
comment
Вы можете опубликовать решение как ответ и принять его, чтобы вопрос не оставался без ответа.   -  person apokryfos    schedule 12.04.2017


Ответы (1)


Решение простое: вам нужно добавить все параметры в функцию «SetupInputEventsAction».

public function SetupInputEventsAction(Request $request){

//YOU HAVE TO ADD THE ORIGINAL OPTIONS, THIS SOLVE THE PROBLEM
$repository = $this->getDoctrine()->getRepository("AppBundle:Picture");
$pictures = $repository->findAll();
$p = array();
$p['-- Bitte Bild setzen'] = -1;
foreach($pictures as $pic){
    /** @var pic Picture */
    $p[$pic->getTitle()] = $pic->getId();
}
$carousel = new Carousel();
$form = $this->createForm(CarouselType::class,$carousel, array(
        'pictures' => $p,
        'action' => $this->generateUrl('SetupInputCarousel')
        ));

/*
 SEE WORKING ONE ABOVE
 $event = new Carousel();
$form  = $this->createForm(CarouselType::class,$event);*/
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
    //handel type
    $em = $this->getDoctrine()->getManager();
    $em->persist($event);
    $em->flush();
}
return $this->redirectToRoute('SetupEvents');
}

С уважением,

Фабиан Хармсен

person LFS96    schedule 20.04.2017