检查提交的单选按钮是否为true - symfony

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检查提交的单选按钮是否为true - symfony相关的知识,希望对你有一定的参考价值。

您好我想看(在提交之后)我如何验证其中一个'choices' => $question->buildAnswerWithValidKey()是真的。

这是来自问题的数组。

Array
(
    [Sonne] => 1
    [Mond] => 
    [Und Sterne] => 
)

我试图在提交表格后验证这一点。

这是我的'choices'function。根据具有正确密钥的问题得出答案(在这种情况下为1或0,真/假)

 public function buildAnswerWithValidKey()
    {
        $answers = [];
        $valid = [];
        $answersWithValidKey = [];

        /** @var Answer $answer */
        foreach ($this->getAnswers() as $answer) {
            $answers[] = $answer->getAnswer();
            $valid[] = $answer->getValid();
        }

        //Sets answers as item and valid as key as required by 'choices'
        $answersWithValidKey[] = array_combine($answers, $valid);

        return $answersWithValidKey;
    }

这是我的控制器。我正在努力验证单选按钮。

        /** @var Question $question */
        $question = $this->questionRepository->findById(12)[0];

        $options = ['question' => $question];

        $form = $this->createForm(ExamType::class, null, $options);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

        }

        return [
            'form' => $form->createView(),
        ];

以下是我可能有帮助的其他课程。

Answer.php - ManyToOne的映射位置。

<?php

namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositoryAnswerRepository")
 */
class Answer
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string")
     */
    private $answer;

    /**
     * @ORMManyToOne(targetEntity="AppEntityQuestion", inversedBy="answers")
     * @ORMJoinColumn(name="question_id", referencedColumnName="id")
     */
    private $question;

    /**
     * @ORMColumn(type="boolean")
     */
    private $valid;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getAnswer(): ?string
    {
        return $this->answer;
    }

    public function setAnswer(string $answer): self
    {
        $this->answer = $answer;

        return $this;
    }

    public function getQuestion(): ?Question
    {
        return $this->question;
    }

    public function setQuestion(?Question $question): self
    {
        $this->question = $question;

        return $this;
    }

    public function getValid(): ?bool
    {
        return $this->valid;
    }

    public function setValid(bool $valid): self
    {
        $this->valid = $valid;

        return $this;
    }
}

还有我的Question.php - 我在哪里制作了buildAnswerWithValidKey()功能。

<?php

namespace AppEntity;

use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositoryQuestionRepository")
 */
class Question
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $question;

    /**
     * @ORMOneToMany(targetEntity="AppEntityAnswer", mappedBy="question")
     */
    private $answers;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getQuestion(): ?string
    {
        return $this->question;
    }

    public function setQuestion(string $question): self
    {
        $this->question = $question;

        return $this;
    }

    /**
     * @return Collection|Answer[]
     */
    public function getAnswers(): Collection
    {
        return $this->answers;
    }

    /**
     * Sets the Answers
     *
     * @param mixed $answers
     * @return void
     */
    public function setAnswers($answers)
    {
        $this->answers = $answers;
    }

    public function addAnswer(Answer $answer): self
    {
        if (!$this->answers->contains($answer)) {
            $this->answers[] = $answer;
            $answer->setQuestion($this);
        }

        return $this;
    }

    public function removeAnswer(Answer $answer): self
    {
        if ($this->answers->contains($answer)) {
            $this->answers->removeElement($answer);
            // set the owning side to null (unless already changed)
            if ($answer->getQuestion() === $this) {
                $answer->setQuestion(null);
            }
        }

        return $this;
    }

    public function buildAnswerWithValidKey()
    {
        $answers = [];
        $valid = [];
        $answersWithValidKey = [];

        /** @var Answer $answer */
        foreach ($this->getAnswers() as $answer) {
            $answers[] = $answer->getAnswer();
            $valid[] = $answer->getValid();
        }

        //Sets answers as item and valid as key as required by 'choices'
        $answersWithValidKey[] = array_combine($answers, $valid);

        return $answersWithValidKey;
    }
}

编辑:

这是我的ExamType

 <?php

namespace AppForm;

use AppEntityQuestion;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeHiddenType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class ExamType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /**
         * @var Question $question
         */
        $question = $options['question'];


        $builder
            ->add(
                //Used to check in the validation
                'question',
                HiddenType::class,
                [
                    'data' => $question->getId()
                ]
            )
            ->add(
                'Answers',
                ChoiceType::class,
                [
                    'choices' => $question->buildAnswerWithValidKey(),
                    'expanded' => true,
                    'label' => $question->getQuestion()
                ]
            )
            ->add(
                'Evaluate',
                SubmitType::class
            );
    }

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

        $resolver->setRequired('question');
        $resolver->setAllowedTypes('question', Question::class);


    }
}

基本上我只想在用户选择正确答案时返回某种消息。

答案

通常,要从表单中检索数据,您必须在处理完请求后调用$form->getData()并检查它是否有效。

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { 
    $answerData = $form->getData();              
    if (!empty($answerData['Answers'] )) { 
          // do something useful
    }  
}

但是,表单将根据其buildForm()方法返回数据内容,而数据对象将尝试将内容放入,由data_class中的FormType选项定义。如果要在数组中返回结果,则data_class应为null。 (所以这必须设置,替代是一个对象,以某种方式编码返回)

以上是关于检查提交的单选按钮是否为true - symfony的主要内容,如果未能解决你的问题,请参考以下文章

如何检查单选按钮是不是在 Android 的单选组中被选中?

单选按钮检查属性未在 Ionic 中设置为 True

如何从插入到 innerHtml 的单选按钮中获取值

jQuery Reset 选中后退按钮时的单选选项

使用 jquery 检查禁用的单选按钮

单击提交后如何获取选定的单选按钮以显示特定的隐藏 div?