Symfony form: filter collection with a parameter












1















I am using Symfony 3.4.



I have a form to edit some answers for a given country and I would need to edit these answers on a per category basis.



I have setup a filter in my entity but I don't know how to call this getter with a parameter from my form.



The dirty alternative would be to remove non required elements from my form in my controller but this is not ideal...



Here is my form:



<?php

namespace cwtpsmdbBundleForm;

use cwtpsmdbBundleEntityCcdbServicesAnswers;
use cwtpsmdbBundleEntitycountries;

use DoctrineORMEntityRepository;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormExtensionCoreTypeCollectionType;

class countriesCCDBServicesAnswersType extends AbstractType
{

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

/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'cwtpsmdbBundleEntitycountries',
'categoryID' => 1,
));
}

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


Here is my entity:



<?php

namespace cwtpsmdbBundleEntity;

use APYDataGridBundleGridMapping as GRID;
use DoctrineORMMapping as ORM;

/**
* countries
*
* @ORMTable()
* @ORMEntity(repositoryClass="cwtpsmdbBundleEntityRepositorycountriesRepository")
*/
class countries
{
/**
* @var integer
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var string
*
* @ORMColumn(name="code", type="string", length=2)
*/
private $code;

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

/**
* @ORMOneToMany(targetEntity="cwtpsmdbBundleEntityCcdbServicesAnswers", mappedBy="country", cascade={"persist", "remove"})
*/
private $ccdbServicesAnswers;


// Specific Functions

/**
* Get ccdbServicesAnswers.
*
* @return DoctrineCommonCollectionsCollection
*/
public function getAnswersOfCategory($categoryID)
{

return $this->getCcdbServicesAnswers()->filter(function(CcdbServicesAnswers $answer) use($categoryID) {
return $answer->getQuestion()->getCategory()->getId() == $categoryID;
});
}


And here is my create form function in my controller:



private function createCountryEditForm(Countries $entity, $categoryID)
{
$form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId())),
'method' => 'PUT',
'categoryID' => $categoryID,
));

$form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

return $form;
}


[UPDATE 20/11/2018]



Here is what I did so far. This work but I would prefer a cleaner solution which deals with this filter with a where clause at database level and which would be more DRY. Doing this at the conroller level means that I have to do it everywhere I need this filter.



private function createCountryEditForm(Countries $entity, $categoryID)
{
$form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId(), 'categoryID' => $categoryID)),
'method' => 'PUT',
'categoryID' => $categoryID,
));

$answers = $form->get('ccdbServicesAnswers')->getData();


foreach ($answers as $answer) {

if($answer->getQuestion()->getCategory()->getId() != $categoryID) {
$answers->removeElement($answer);
}

}

$form->get('ccdbServicesAnswers')->setData($answers);

$form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

return $form;
}









share|improve this question





























    1















    I am using Symfony 3.4.



    I have a form to edit some answers for a given country and I would need to edit these answers on a per category basis.



    I have setup a filter in my entity but I don't know how to call this getter with a parameter from my form.



    The dirty alternative would be to remove non required elements from my form in my controller but this is not ideal...



    Here is my form:



    <?php

    namespace cwtpsmdbBundleForm;

    use cwtpsmdbBundleEntityCcdbServicesAnswers;
    use cwtpsmdbBundleEntitycountries;

    use DoctrineORMEntityRepository;
    use SymfonyBridgeDoctrineFormTypeEntityType;
    use SymfonyComponentFormAbstractType;
    use SymfonyComponentFormFormBuilderInterface;
    use SymfonyComponentOptionsResolverOptionsResolver;
    use SymfonyComponentFormExtensionCoreTypeCollectionType;

    class countriesCCDBServicesAnswersType extends AbstractType
    {

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

    /**
    * @param OptionsResolver $resolver
    */
    public function configureOptions(OptionsResolver $resolver)
    {
    $resolver->setDefaults(array(
    'data_class' => 'cwtpsmdbBundleEntitycountries',
    'categoryID' => 1,
    ));
    }

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


    Here is my entity:



    <?php

    namespace cwtpsmdbBundleEntity;

    use APYDataGridBundleGridMapping as GRID;
    use DoctrineORMMapping as ORM;

    /**
    * countries
    *
    * @ORMTable()
    * @ORMEntity(repositoryClass="cwtpsmdbBundleEntityRepositorycountriesRepository")
    */
    class countries
    {
    /**
    * @var integer
    *
    * @ORMColumn(name="id", type="integer")
    * @ORMId
    * @ORMGeneratedValue(strategy="AUTO")
    */
    private $id;

    /**
    * @var string
    *
    * @ORMColumn(name="code", type="string", length=2)
    */
    private $code;

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

    /**
    * @ORMOneToMany(targetEntity="cwtpsmdbBundleEntityCcdbServicesAnswers", mappedBy="country", cascade={"persist", "remove"})
    */
    private $ccdbServicesAnswers;


    // Specific Functions

    /**
    * Get ccdbServicesAnswers.
    *
    * @return DoctrineCommonCollectionsCollection
    */
    public function getAnswersOfCategory($categoryID)
    {

    return $this->getCcdbServicesAnswers()->filter(function(CcdbServicesAnswers $answer) use($categoryID) {
    return $answer->getQuestion()->getCategory()->getId() == $categoryID;
    });
    }


    And here is my create form function in my controller:



    private function createCountryEditForm(Countries $entity, $categoryID)
    {
    $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
    'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId())),
    'method' => 'PUT',
    'categoryID' => $categoryID,
    ));

    $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

    return $form;
    }


    [UPDATE 20/11/2018]



    Here is what I did so far. This work but I would prefer a cleaner solution which deals with this filter with a where clause at database level and which would be more DRY. Doing this at the conroller level means that I have to do it everywhere I need this filter.



    private function createCountryEditForm(Countries $entity, $categoryID)
    {
    $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
    'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId(), 'categoryID' => $categoryID)),
    'method' => 'PUT',
    'categoryID' => $categoryID,
    ));

    $answers = $form->get('ccdbServicesAnswers')->getData();


    foreach ($answers as $answer) {

    if($answer->getQuestion()->getCategory()->getId() != $categoryID) {
    $answers->removeElement($answer);
    }

    }

    $form->get('ccdbServicesAnswers')->setData($answers);

    $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

    return $form;
    }









    share|improve this question



























      1












      1








      1








      I am using Symfony 3.4.



      I have a form to edit some answers for a given country and I would need to edit these answers on a per category basis.



      I have setup a filter in my entity but I don't know how to call this getter with a parameter from my form.



      The dirty alternative would be to remove non required elements from my form in my controller but this is not ideal...



      Here is my form:



      <?php

      namespace cwtpsmdbBundleForm;

      use cwtpsmdbBundleEntityCcdbServicesAnswers;
      use cwtpsmdbBundleEntitycountries;

      use DoctrineORMEntityRepository;
      use SymfonyBridgeDoctrineFormTypeEntityType;
      use SymfonyComponentFormAbstractType;
      use SymfonyComponentFormFormBuilderInterface;
      use SymfonyComponentOptionsResolverOptionsResolver;
      use SymfonyComponentFormExtensionCoreTypeCollectionType;

      class countriesCCDBServicesAnswersType extends AbstractType
      {

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

      /**
      * @param OptionsResolver $resolver
      */
      public function configureOptions(OptionsResolver $resolver)
      {
      $resolver->setDefaults(array(
      'data_class' => 'cwtpsmdbBundleEntitycountries',
      'categoryID' => 1,
      ));
      }

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


      Here is my entity:



      <?php

      namespace cwtpsmdbBundleEntity;

      use APYDataGridBundleGridMapping as GRID;
      use DoctrineORMMapping as ORM;

      /**
      * countries
      *
      * @ORMTable()
      * @ORMEntity(repositoryClass="cwtpsmdbBundleEntityRepositorycountriesRepository")
      */
      class countries
      {
      /**
      * @var integer
      *
      * @ORMColumn(name="id", type="integer")
      * @ORMId
      * @ORMGeneratedValue(strategy="AUTO")
      */
      private $id;

      /**
      * @var string
      *
      * @ORMColumn(name="code", type="string", length=2)
      */
      private $code;

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

      /**
      * @ORMOneToMany(targetEntity="cwtpsmdbBundleEntityCcdbServicesAnswers", mappedBy="country", cascade={"persist", "remove"})
      */
      private $ccdbServicesAnswers;


      // Specific Functions

      /**
      * Get ccdbServicesAnswers.
      *
      * @return DoctrineCommonCollectionsCollection
      */
      public function getAnswersOfCategory($categoryID)
      {

      return $this->getCcdbServicesAnswers()->filter(function(CcdbServicesAnswers $answer) use($categoryID) {
      return $answer->getQuestion()->getCategory()->getId() == $categoryID;
      });
      }


      And here is my create form function in my controller:



      private function createCountryEditForm(Countries $entity, $categoryID)
      {
      $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
      'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId())),
      'method' => 'PUT',
      'categoryID' => $categoryID,
      ));

      $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

      return $form;
      }


      [UPDATE 20/11/2018]



      Here is what I did so far. This work but I would prefer a cleaner solution which deals with this filter with a where clause at database level and which would be more DRY. Doing this at the conroller level means that I have to do it everywhere I need this filter.



      private function createCountryEditForm(Countries $entity, $categoryID)
      {
      $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
      'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId(), 'categoryID' => $categoryID)),
      'method' => 'PUT',
      'categoryID' => $categoryID,
      ));

      $answers = $form->get('ccdbServicesAnswers')->getData();


      foreach ($answers as $answer) {

      if($answer->getQuestion()->getCategory()->getId() != $categoryID) {
      $answers->removeElement($answer);
      }

      }

      $form->get('ccdbServicesAnswers')->setData($answers);

      $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

      return $form;
      }









      share|improve this question
















      I am using Symfony 3.4.



      I have a form to edit some answers for a given country and I would need to edit these answers on a per category basis.



      I have setup a filter in my entity but I don't know how to call this getter with a parameter from my form.



      The dirty alternative would be to remove non required elements from my form in my controller but this is not ideal...



      Here is my form:



      <?php

      namespace cwtpsmdbBundleForm;

      use cwtpsmdbBundleEntityCcdbServicesAnswers;
      use cwtpsmdbBundleEntitycountries;

      use DoctrineORMEntityRepository;
      use SymfonyBridgeDoctrineFormTypeEntityType;
      use SymfonyComponentFormAbstractType;
      use SymfonyComponentFormFormBuilderInterface;
      use SymfonyComponentOptionsResolverOptionsResolver;
      use SymfonyComponentFormExtensionCoreTypeCollectionType;

      class countriesCCDBServicesAnswersType extends AbstractType
      {

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

      /**
      * @param OptionsResolver $resolver
      */
      public function configureOptions(OptionsResolver $resolver)
      {
      $resolver->setDefaults(array(
      'data_class' => 'cwtpsmdbBundleEntitycountries',
      'categoryID' => 1,
      ));
      }

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


      Here is my entity:



      <?php

      namespace cwtpsmdbBundleEntity;

      use APYDataGridBundleGridMapping as GRID;
      use DoctrineORMMapping as ORM;

      /**
      * countries
      *
      * @ORMTable()
      * @ORMEntity(repositoryClass="cwtpsmdbBundleEntityRepositorycountriesRepository")
      */
      class countries
      {
      /**
      * @var integer
      *
      * @ORMColumn(name="id", type="integer")
      * @ORMId
      * @ORMGeneratedValue(strategy="AUTO")
      */
      private $id;

      /**
      * @var string
      *
      * @ORMColumn(name="code", type="string", length=2)
      */
      private $code;

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

      /**
      * @ORMOneToMany(targetEntity="cwtpsmdbBundleEntityCcdbServicesAnswers", mappedBy="country", cascade={"persist", "remove"})
      */
      private $ccdbServicesAnswers;


      // Specific Functions

      /**
      * Get ccdbServicesAnswers.
      *
      * @return DoctrineCommonCollectionsCollection
      */
      public function getAnswersOfCategory($categoryID)
      {

      return $this->getCcdbServicesAnswers()->filter(function(CcdbServicesAnswers $answer) use($categoryID) {
      return $answer->getQuestion()->getCategory()->getId() == $categoryID;
      });
      }


      And here is my create form function in my controller:



      private function createCountryEditForm(Countries $entity, $categoryID)
      {
      $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
      'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId())),
      'method' => 'PUT',
      'categoryID' => $categoryID,
      ));

      $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

      return $form;
      }


      [UPDATE 20/11/2018]



      Here is what I did so far. This work but I would prefer a cleaner solution which deals with this filter with a where clause at database level and which would be more DRY. Doing this at the conroller level means that I have to do it everywhere I need this filter.



      private function createCountryEditForm(Countries $entity, $categoryID)
      {
      $form = $this->createForm(countriesCCDBServicesAnswersType::class, $entity, array(
      'action' => $this->generateUrl('updateCountryCcdbServicesAnswers', array('countryID' => $entity->getId(), 'categoryID' => $categoryID)),
      'method' => 'PUT',
      'categoryID' => $categoryID,
      ));

      $answers = $form->get('ccdbServicesAnswers')->getData();


      foreach ($answers as $answer) {

      if($answer->getQuestion()->getCategory()->getId() != $categoryID) {
      $answers->removeElement($answer);
      }

      }

      $form->get('ccdbServicesAnswers')->setData($answers);

      $form->add('submit', submitType::class, array('label' => 'Update', 'attr' => array('class' => 'hidden')));

      return $form;
      }






      symfony doctrine-orm symfony-forms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 16:06







      curuba

















      asked Nov 19 '18 at 19:13









      curubacuruba

      343318




      343318
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381168%2fsymfony-form-filter-collection-with-a-parameter%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381168%2fsymfony-form-filter-collection-with-a-parameter%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Run scheduled task as local user group (not BUILTIN)

          Port of Spain