Passing a value of a variable to a symfony function - symfony

I want to render dynamicly a form in Symfony. I passing a array with elements of element names to the render method 'formElements' => array('formelement1', 'formelement2').
How i want to use the element names in my template to show the form labels.
{% for elementName in elementNames %}
<div class="form-lable">
{{ form_label({{ elementName }}) }}
</div>
{% endfor %}
I received the following exception:
A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in onBillBundle:Customer:new.html.twig at line 17
Is it not posible to render the form dynamicly without {{ form(delete_form) }}?

Untested...
{% for elementName in elementNames %}
<div class="form-lable">
{{ form_label(attribute(form, elementName)) }}
</div>
{% endfor %}
Docs

You don't need to surround variables in a twig statement with {{ and }}. So your code should be:
{{ form_label(elementName) }}
But of course elementName needs to be a Form Object and not a string. You can generate them in your Controller like this:
public function testAction()
{
// ...
$form = $this->createFormBuilder()
->add('name', 'text');
return ['form' => $form->createView()];
}

Related

How to passe an array to jquery in twig

I have the following code :
{% set aSessionKeys = app.session.get('aBasket')|keys %}
onkeyup="calculatePrice({{ product['product_price'] }},{{ product['product_id'] }},{{ aSessionKeys }})
And I have an error :
Notice: Array to string conversion
Can you help me please? Thx in advance. So exist a solution to passe this array?
I do like this :
{% set aKeys = aSessionKeys|join(',') %}
{{ dump(aKeys) }}
It shows good, but if I passe to jquery :
calculatePrice({{ product['product_price'] }},{{ product['product_id'] }},{{ aKeys }})
When I do in js methode calculatePrice() :
function calculatePrice(price, product_id, aKeys) {
console.log(aKeys);
var x = document.getElementById("product_quantity_"+product_id);
var total_price = price * x.value;
$("#total_price_"+product_id).html(total_price+" <small> MDL</small>");
sum = 0;
$("#total_price_basket").html();
}
It shows only the first value of aKeys
You have very popular error. You are trying to display array. But how do you imagine that? You can use {{ dump(aSessionKeys) }} for that purpose or use first element: {{ aSessionKeys.0 }} (if it is not an array or object).
But if you want to print all values from this array you can run foreach loop:
{% for element in aSessionKeys %}
{# something here #}
{{ element }}
{# something here #}
{% endfor %}
Obviously (as you are using the |keys filter) aSessionKeys contains an array, and by using {{ aSessionKeys }} in the template Twig will try to output the array as a string, which doesn’t work (or at least is not what you want).
To convert the array to a string, you should use Twig’s join() filter, which will concatenate the array values using a given delimiter string. So, if – for instance – you want to join the values using a comma, this would be the code:
{{ aSessionKeys|join(',) }}

Printing all errors in one go within twig

I want to print all errors in one go for all the fields however {{ form_errors(form) }} doesn't print anything so because of that I have to use if not form.vars.valid statement to print errors however all the individual error messages are being wrapped within <ul><li>Message</li></ul> which is annoying. I know that 'error_bubbling' => true solves the issue but creates another issue which is making field borders red.
How can I solve this issue? I simply want to print error without tags.
Note: I can use {{ form_errors(form.name)|striptags }} but it adds overheads cos my form is massive.
FORM TYPE
class BrandsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('name', 'text', array('label' => 'Name'))
->add('button', 'submit', array('label' => 'Submit'))
;
}
}
TWIG
{% extends '::base.html.twig' %}
{% block body %}
{{ form_start(form, {attr: {novalidate:'novalidate'}}) }}
{% if not form.vars.valid %}
<div class="global_form_errors">
{{ form_errors(form.name) }}
{{ form_errors(form.origin) }}
</div><br />
{% endif %}
<div>
{{ form_label(form.name) }}
{% if form.name.vars.errors|length != '' %}
{{ form_widget(form.name, { attr: {'class': 'field_red_border'} }) }}
{% else %}
{{ form_widget(form.name) }}
{% endif %}
</div>
<div>
{{ form_widget(form.button) }}
</div>
{{ form_end(form) }}
{% endblock %}
Customize the field template
You can apply a form template to your form, check this documentation at Form Theming chapter.
If you prefer theming the field directly in your template, check the gray box in this documentation at the Global Form Theming chapter.
Check this documentation for more form customization.
Pass the errors to the template
When you submit the form, your code will call this method $form->handleRequest($request); which will check if the user input properly the data.
Based on the documentation of the Form class you can get a list of errors by calling $form->getErrors(). The variable $form is an instance of the Form class and not the FormView class. You may want to enable error bubbling.
Now that you know how to get the errors you can pass them as a variable to your template.

Looping through objects in Twig/Symfony?

If I get an array of types using Doctrine like this:
$types = $this->getDoctrine()
->getRepository('Model:Type')
->findAll();
And then pass $types to the Twig template (as 'types') and loop through it:
{% for type in types %}
-- WHAT GOES HERE?
{% endfor %}
I've been doing a bit of reading, and I'm not even sure if this is possible? Can I only pass associative arrays through to Twig or do arrays of objects work? And if so, how can I access the public functions of the object in Twig?
Basically I want to call getName(), getUsage(), getId() and a few other public functions on the Type object.
Thanks
Then you could do it like below:
{% for type in types %}
{{ type.name }}
{{ type.usage }}
{{ type.id }}
{% endfor %}
{{ type.getName() }} also works, it's same with {{ type.name }}.

Make Twig syntax from string be parsed

I stored a format of shopping order in database, it's like #{{ number }} (it's just a string), how can use this {{ number }} as a execution of Twig.
For example, in my Controller, when I render the view, I also pass a $number variable:
return $this->render('MyBundle:View:index.html.twig', array('number' => 123));
and in my index.html.twig file, it's something like
{% set orderFormat = some_function_to_get_order_format() %}
// orderFormat will be #{{ number }}
// What can I do to print orderFormat to #123
Try template_from_string function.
{{ include(template_from_string("Hello {{ name }}") }}

Directly access a form field's value when overriding widget in a twig template

What I want to do is get variables stored in form view.
{% form_theme edit_form _self %}
{% block field_widget %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{# MY CODE #}
{% if type == "file" %}
<a class="BOpreview" href="{# NEED TO REPLACE VAR HERE #}">Aperçu</a>
{% endif %}
{# MY ATTEMPT #}
{{ form.title.get('value') }}
{{ form.vars.value.url }}
{% endspaceless %}
{% endblock field_widget %}
My form has properties like url, title, etc and I am trying to access them here to use it in the field widget block.
I searched for it and came on https://groups.google.com/forum/?fromgroups=#!topic/symfony2/onor9uFte9E that suggested:
{{ form.title.get('value') }}
{{ form.vars.value.url }}
which didn't work for me.
Note: If I do a var_dump on $form->createView() in my controller, I get:
object(Symfony\Component\Form\FormView)[331]
private 'vars' =>
array (size=15)
'value' =>
object(Panasonic\TestEtAvisBundle\Entity\Product)[168]
protected 'reviewArray' =>
object(Doctrine\ORM\PersistentCollection)[234]
...
protected 'testArray' =>
object(Doctrine\ORM\PersistentCollection)[221]
...
protected 'fbshareArray' =>
object(Doctrine\ORM\PersistentCollection)[317]
...
private 'id' => int 2
private 'name' => string 'Nom du produit' (length=14)
private 'title' => string '<span>Titre </span>' (length=19)
private 'image' => string 'bundles/testetavis/uploads/product/0d9d9550.png' (length=47)
private 'fbImage' => string 'bundles/testetavis/uploads/product/facebook//product_e928cd96.jpg' (length=65)
private 'description' => string '<span>Descriptif </span>' (length=24)
private 'url' => string 'http://www.google.com' (length=21)
private 'creationDate' =>
object(DateTime)[210]
...
private 'modificationDate' =>
object(DateTime)[209]
...
private 'isDeleted' => int 0
'attr' =>
array (size=0)
empty
'form' =>
&object(Symfony\Component\Form\FormView)[331]
'id' => string 'panasonic_testetavisbundle_producttype' (length=38)
'name' => string 'panasonic_testetavisbundle_producttype' (length=38)
'full_name' => string 'panasonic_testetavisbundle_producttype' (length=38)
I want to access that url for instance but can't seem to be able to do it after many variations. Including use of {{ value }}, {{ value.url }}
But inspite of vars, I can do {{ full_name }} and get panasonic_testetavisbundle_producttype.
Any ideas?
Edit2: I found out the real problem...
Edit3: Seeing that this question is quite popular I decided to clarify on what I attempted to do in case it helps someone in the same situation. If you rely strictly on what the question asks, as I stated from my research and that Besnik supported are indeed correct.
Now what I wanted to do is for every input type file, get url from object used to render form and append a preview link, using retrieved url, beside the input type file.
If you try to get the form var of an input type "file" like this "{{ form.vars.value.url }}" in my code, this doesn't work since, if I recall correctly, you receive a token instead of the url stored inside the object.
You can access the current data of your form via form.vars.value:
{{ form.vars.value.title }}
See Symfony2 Forms documentation: http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template
Dump vars by using dump function:
{{ dump(form.vars.value) }}
If you are using subforms or want to have a value of a specific field:
{{ form.FIELD.vars.VALUE }}
You can access values of the parent parent from a widget block using form.parent.vars
For example, we want to render the value from a type text field called primerNombre we will need
{{ form.vars.value.primerNombre }}
If we wanted to render the name of one of the children we will need
{% for hijo in form.hijos %}
<td><div align="left">{{ form_widget(hijo.vars.value.primerNombre) }}</div></td>
{% endfor %}
Good luck!
In Symfony > 3 you may use:
form.vars.value.Entity.someValue
Edit2:
Finally, I was indeed getting the value of the current row in {{ value }} here:
{% block field_widget %}
{% spaceless %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ **value** }}" {% endif %}/>
{# MY CODE #}
{% if type == "file" %}
<a class="BOpreview" href="{{ value }}">Aperçu</a>
{% endif %}
{% endspaceless %}
{% endblock field_widget %}
But in my case I get a token instead of the value since I am using input type file. This is due to a security measure in Symfony2.

Resources