0
votes

I am using Symfony 3.4.

I have countries and questions entities. Then I have an answers entity which is linked to both countries and questions.

In question I define the expected type of answer (boolean, string, etc..).

In order to capture so in answers entity, I have several fields matching the several field types I have defined.

I would like to display one form for a given country in order to edit answers corresponding to the different questions.

I am using a collectionType from country form in order to do so.

But my two issue are:

  • how to display the questions themselves within embedded forms
  • how in each answer can I hide fields that are not required (not of the type corresponding to the question).

What seems very simple when handling one question seems obscure when having to handle all questions/answers for a given country.

Here is my code:

countries entity

    <?php

namespace cwt\psmdbBundle\Entity;

use APY\DataGridBundle\Grid\Mapping as GRID;
use Doctrine\ORM\Mapping as ORM;

/**
 * countries
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="cwt\psmdbBundle\Entity\Repository\countriesRepository")
 */
class countries
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @ORM\OneToMany(targetEntity="cwt\psmdbBundle\Entity\CcdbServicesAnswers", mappedBy="country", cascade={"persist", "remove"})
     */
    private $ccdbServicesAnswers;

questions entity:

    <?php

namespace cwt\psmdbBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use APY\DataGridBundle\Grid\Mapping as GRID;

/**
 * CcdbServicesQuestions
 *
 * @ORM\Table(name="ccdb_services_questions")
 * @ORM\Entity(repositoryClass="cwt\psmdbBundle\Repository\CcdbServicesQuestionsRepository")
 */
class CcdbServicesQuestions
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="question", type="string", length=255)
     */
    private $question;

    /**
     * @ORM\ManyToOne(targetEntity="cwt\psmdbBundle\Entity\CcdbServicesCategories")
     * @ORM\JoinColumn(nullable=false)
     * @GRID\Column(field="category.name", title="Category")
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="cwt\psmdbBundle\Entity\FieldTypes")
     * @ORM\JoinColumn(nullable=false)
     * @GRID\Column(field="fieldType.name", title="Field Type")
     */
    private $fieldType;

    /**
     * @ORM\OneToMany(targetEntity="cwt\psmdbBundle\Entity\CcdbServicesAnswers", mappedBy="question", cascade={"persist", "remove"})
     */
    private $ccdbServicesAnswers;

answers entity:

    <?php

namespace cwt\psmdbBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * CcdbServicesAnswers
 *
 * @ORM\Table(name="ccdb_services_answers")
 * @ORM\Entity(repositoryClass="cwt\psmdbBundle\Repository\CcdbServicesAnswersRepository")
 */
class CcdbServicesAnswers
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string|null
     *
     * @ORM\Column(name="stringField", type="string", length=255, nullable=true)
     */
    private $stringField;

    /**
     * @var string|null
     *
     * @ORM\Column(name="textField", type="text", nullable=true)
     */
    private $textField;

    /**
     * @var bool|null
     *
     * @ORM\Column(name="booleanField", type="boolean", nullable=true)
     */
    private $booleanField;

    /**
     * @var int|null
     *
     * @ORM\Column(name="integerField", type="integer", nullable=true)
     */
    private $integerField;

    /**
     * @var float|null
     *
     * @ORM\Column(name="floatField", type="float", nullable=true)
     */
    private $floatField;

    /**
     * @var float|null
     *
     * @ORM\Column(name="percentageField", type="float", nullable=true)
     */
    private $percentageField;

    /**
     * @var string|null
     *
     * @ORM\Column(name="comment", type="string", length=255, nullable=true)
     */
    private $comment;

    /**
     * @ORM\ManyToOne(targetEntity="countries", inversedBy="ccdbServicesAnswers")
     * @ORM\JoinColumn(nullable=false)
     */
    private $country;

    /**
     * @ORM\ManyToOne(targetEntity="cwt\psmdbBundle\Entity\CcdbServicesQuestions", inversedBy="ccdbServicesAnswers")
     * @ORM\JoinColumn(nullable=false)
     */
    private $question;

Here is my country form:

<?php

namespace cwt\psmdbBundle\Form;

use cwt\psmdbBundle\Entity\countries;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class countriesCCDBServicesAnswersType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('ccdbServicesAnswers', CollectionType::class, array(
                'entry_type' => CcdbServicesAnswersType::class,
                'entry_options' => array('label' => false),
            ))
        ;

    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'cwt\psmdbBundle\Entity\countries'
        ));
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'cwt_psmdbbundle_countries';
    }
}

Here is my Answers form:

<?php

namespace cwt\psmdbBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
//use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class CcdbServicesAnswersType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('stringField')
            ->add('textField')
            ->add('booleanField')
            ->add('integerField')
            ->add('floatField')
            ->add('percentageField')
            ->add('comment')
//            ->add('country')
//            ->add('question')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'cwt\psmdbBundle\Entity\CcdbServicesAnswers'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'cwt_psmdbbundle_ccdbservicesanswers';
    }
}

For now pretty straight forward controller (I tried to access form fields but I don't know what to do from there):

    /**
     * Show answers for a given country.
     * @Route("/countries/{countryID}/edit", name="editCountryCcdbServicesAnswers", methods={"GET"})
     * @Security("has_role('ROLE_USER')")
     *
     */
    public function editCountriesCcdbServicesAnswers($countryID)
    {


//        // Get categories
        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('psmdbBundle:CcdbServicesCategories')->findAll();

        // $questions = $em->getRepository('psmdbBundle:CcdbServicesQuestions')->findAll();

        // Get all answers for this country
        $country = $em->getRepository('psmdbBundle:countries')->find($countryID);

        $form = $this->createCountryEditForm($country);

        foreach ($form as $field) {

            $fieldClass = get_class($field);

            if(get_class($field)=='Symfony\Component\Form\Form') {
                foreach ($field as $answerForm) {

                    foreach ($answerForm as $answerField) {

                    }

                }
            }

        }



        return $this->render('psmdbBundle:ccdb_services_answers:edit_country.html.twig', array(
            'categories' => $categories,
            'form' => $form->createView(),
            'entity' => $country,
//            'delete_form' => $deleteForm->createView(),
            'show' => 'ccdbservicesanswers_show',
            'cancel' => 'ccdbservicesanswers_show',
            'title' => 'CCDB Services',
        ));

    }

And here is the template (pretty useless as it displays all fields for each answer and doesn't display questions...):

{% extends 'psmdbBundle:templates:edit.html.twig' %}

    {% block form_body -%}
        <div class="col-lg-5">

            {{ form(form) }}

        </div>
    {% endblock form_body %}

One solution I am thinking about would be to add questions fields to my answers form in order to be able to use them in a form theme. But I have no clue if this is the best approach and I am concerned about performance.

The other solution would be to use ajax calls in a show view in order to build a form on the fly upon clicking 'edit' on a specific question but I am not convinced about the user experience!

For information, there are more than 100 questions.

1

1 Answers

0
votes

I found the solution to these two problems.

In order to show questions text, I just had to add it to the form (disabled) and then style it so it looks like text instead of input.

Then to display only the answer fields I need I used form events as you can see below. I retrieve the fieldType from the question and conditionally add required fields.

Here is my final Form:

<?php

namespace cwt\psmdbBundle\Form;

use FOS\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
//use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use cwt\psmdbBundle\Form\GpscSwitchType;

class CcdbServicesAnswersType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

            ->add('question', textType::class, array(
                    'disabled' => true,
                    'label'     => false,
                    'attr' => array('class' => 'ccdb-form-question'),
                )
            );
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $answer = $event->getData();
            $question = $answer->getQuestion();
            $fieldType = $question->getFieldType()->getName();
            $form = $event->getForm();


            switch ($fieldType) {
                case 'boolean':
                    $form->add('booleanField', GpscSwitchType::class, array(
                        'label' => false,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-3',
                        'attr' => array('class' => 'ccdb-form-answer boolean-type'),
                        'required'  => false,
                    ));
                    break;
                case 'string':
                    $form->add('stringField', textAreaType::class, array(
                        'label' => false,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-12',
                        'attr' => array('class' => 'ccdb-form-answer'),
                        'required'  => false,
                        ));
                    break;
                case 'integer':
                    $form->add('integerField', null, array(
                        'label' => false,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-2',
                        'attr' => array('class' => 'ccdb-form-answer'),
                        'required'  => false,
                        ));
                    break;
                case 'percentage':
                    $form->add('percentageField', percentType::class, array(
                        'label' => false,
                        'scale' => 2,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-2',
                        'attr' => array('class' => 'ccdb-form-answer'),
                        'required'  => false,
                        ));
                    break;
                case 'float':
                    $form->add('floatField', null, array(
                        'label' => false,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-2',
                        'attr' => array('class' => 'ccdb-form-answer'),
                        'required'  => false,
                        ));
                    break;
                case 'text':
                    $form->add('textField', CKEditorType::class, array(
                        'label' => false,
                        'horizontal_label_class' => 'col-lg-12',
                        'horizontal_input_wrapper_class' => 'col-lg-12',
                        'attr' => array('class' => 'ccdb-form-answer'),
                        'required'  => false,
                        ));
                    break;
            }

            $form->add('comment', textAreaType::class, array(
                'label' => 'Comment:',
                'horizontal_label_class' => 'col-lg-12',
                'horizontal_input_wrapper_class' => 'col-lg-12',
                'attr' => array('class' => 'ccdb-form-answer ccdb-form-comment'),
                'required'  => false,
                ));


        });
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'cwt\psmdbBundle\Entity\CcdbServicesAnswers'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'cwt_psmdbbundle_ccdbservicesanswers';
    }
}