nbonniot nbonniot - 3 months ago 14
Twig Question

SF2 Twig : How to customize rendering of CoolectionType embedded in CollectionType?

I'm designing an app with a Survey entity. Each survey can have multiple SurveyQuestion entities (CollectionType in form, attribute Survey->questions) and each SurveyQuestion can have multiple SurveyAnswer entities (SurveyQuestion->availableAnswers).

Forms are logically spread in SurveyType, QuestionType and AnswerType.

How can I set template fragment for availableAnswers?

I looked around 2 leads :

First, form_theme targeting specific type : in Survey form twig

{# Theming for questions #}
{% form_theme form.questions 'LCHModuleBundle:Survey/form:question.html.twig' %}

{# Theming for answers #}
{#{% form_theme form.availableAnswers 'LCHModuleBundle:Survey/form:answer.html.twig' %}#}


Looks impossible to access availableQuestions because it's a field from one item of questions collection.

Second, block naming (according to this) :

In Survey form twig :

{% form_theme form with ['LCHModuleBundle:Survey/form:question.html.twig', 'LCHModuleBundle:Survey/form:answer.html.twig'] %}



  • For question



In question.html.twig :

{#Question list rendering#}
{% block _lchmodule_bundle_survey_type_questions_widget %}...{% endblock %}


In QuestionType :

class QuestionType extends AbstractType
{
const NAME= "lchmodule_bundle_question_type";.

public function getName()
{
return self::NAME;
}

/**
* @return string
*/
public function getBlockPrefix()
{
return self::NAME;
}
}



  • For answer



In answer.html.twig :

{% block _lchmodule_bundle_answer_type_availableAnswers_widget %}...{% endblock %}


In AnswerType :

class AnswerType extends AbstractType
{
const NAME = "lchmodule_bundle_answer_type";
/**
* @return string
*/
public function getName()
{
return self::NAME;
}

/**
* @return string
*/
public function getBlockPrefix() {
return self::NAME;
}
}


THeming is working great for questions, but not for answers. How can I access availableQuestions theming regarding the fact that it's an embedded CollectionType within an CollectionType?

Thanks for your lights,

Nicolas

Answer

On the main form, print your collection items as :

{% for collectionItem in form.collections %}
    {% include 'AppBundle:Blog:collection.item.html.twig' %}
{% endfor %}

so that the colleciton items can be in separate twig file. Now in separate twig file (collection.item.html.twig), define your form_theme or do necessary changes.

hope this helps.

Comments