symfony - PHP/Symfony2: Call methods "dynamically" -


i have questionnaire users need fill in. have questionnaire entity properties $question1, $question2, $question3, etc. corresponding methods getquestion1(), setquestion1(), etc.

i receive questions in controller function in array this:

$questions = array("1" => 'answer question 1', "2" => 'answer question 2',...);

is there way can call corresonding set method "dynamically" in loop don't have run type out everything?

something like:

foreach ($questions $key => $question) {     $questionnaire->setquestion.$key($question); } 

i know above won't work, there way can way, there 100 questions , don't want type out. makes controller function more generic if questions added/removed later on not have make changes controller function.

i approach angle:

how crating entity called question? add 1:n relation between questionnaire , question. entity this:

class question {     /**      * @orm\column(type="text")      */     private $answer;      /**      * @orm\manytoone(targetentity="questionnaire")      */     private $questionnaire; } 

on other side questionnaire entity:

class questionnaire {         /**      * @orm\onetomany(targetentity="question")      */     private $questions;      public function getquestions()     {         return $this->questions;     } } 

now can iterate on questions of questionnaire simple foreach loop:

foreach ($questionnaire->getquestions() $question)  { //... 

this give advantage can add, remove , change questions without messing controller or form type code.

edit:

in order make work form should change this:

public function buildform(formbuilderinterface $builder, array $options) {   $this->add(     'question',     'entity',     array(       'class' => 'question'       // more options want...     )   );         // ... 

and in controller call this:

$questionnaire = new questionnaire(); $questionnaire->addquestion(/* ... */);  $this->createform(new questionnairetype(), $questionnaire); //... 

as template use this:

{% question in form.questions %}      {{ form_widget(question) }} {% endfor %} 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -