浏览分页输出时如何保留表单数据?

时间:2019-04-01 18:49:45

标签: php symfony

我有一个symfony表单,其中包含一长列带有复选框的项目。我已成功使knp分页器工作,现在将表单分为几页。但是,当我在页面之间移动时,会丢失复选框的选中/未选中状态。我相信这可能很容易,但是我似乎无法解决。我对php还不是很有经验。

这是我的控制人:

    /**
     * @Route("/addquestions/{quizid}", name="addquestions")
     */
    public function add(Request $request, PaginatorInterface $paginator, $quizid)
    {
        $repository = $this->getDoctrine()->getRepository(Quiz::class);
        $quiz = $repository->find($quizid);

        $repository = $this->getDoctrine()->getRepository(Question::class);
        $questions = $repository->findAll();

        // Paginate the results of the query
        $pagination = $paginator->paginate($questions, $request->query->getInt('page', 1), 3);

        $form = $this->createForm(AddQuizQuestionType::class, $quiz, ["pagination" => $pagination]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $questions = $form->get('question')->getData();
            foreach ($questions as $question){
                $quizquestion = new QuizQuestion();
                $quizquestion->setQuestion($question);
                $quiz->addQuizQuestion($quizquestion);
            }
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($quiz);
            $entityManager->flush();
            return $this->redirectToRoute('homepage');
        }

        return $this->render('editquiz/addquestions.html.twig', [
            'form' => $form->createView(),
            'pagination' => $pagination,
        ]);
    }

还有我的表单-它使用分页查询来显示带有复选框的项目。

class AddQuizQuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('question', EntityType::class, [
                'expanded' => true,
                'multiple' => true,
                'class' => Question::class,
                'mapped' => false,
                'choices' => $options['pagination'],
            ])
            ->add('submit', SubmitType::class, [
                'label' => 'Submit',
            ])
            ->setMethod('GET')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Quiz::class,
            'pagination'    => null,
        ]);
    }
}

和我的模板-它呈现带有数据库中图像的复选框。

{% extends 'base.html.twig' %}
{% block title %}CreatequizController{% endblock %}
{% block body %}
<h1>Create Quiz</h1>
{{ form_start(form) }}
{% for question in form.question %}
<h5>Question {{ question.vars.value }}</h5>
<div class="border mb-5">
  <img src="{{ asset(question.vars.label) }}" alt=""/>
  <div class="pl-3">
    {{ form_widget(question) }}
  </div>
</div>
{% endfor %}
<div class="navigation">{{ knp_pagination_render(pagination) }}</div>
{{ form_end(form) }}
{% endblock %}

我希望这样做,以便当我在页面之间跳转时,选中的复选框保持选中状态。

先谢谢您

Martyn

0 个答案:

没有答案