How to deal with missing values in the array in twig - php

Some of the values that I'm requesting may or maynot be returning a value as the api takes someones profile and they have left out fields in registration etc.
If I request something which isn't there in my twig template I get the error
throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type "%s" does not exist', $arrayItem, get_class($object)), -1, $this->getTemplateName());
I could solve this by doing this code on each value but it's messy and not clever is there a way of not getting the error, like in other php frameworks, it will just leave a blank
{% if profile.aboutMe %}
{{ profile.aboutMe }}
controller
return $this->render('LoginLogBundle:Default:userprofile.html.twig',array('profile'=>$user)));

You can use the default() filter to display some text when a object or a value is not defined:
{{ profile.aboutMe|default('No profile') }}
{# or #}
{{ profile.aboutMe|default('-') }}
{# or #}
{{ profile.aboutMe|default('') }}
{# etc. #}

Related

I am unable to get values in twig template in drupal 9

I have mapped the fields of a content type (a webform) to node using Webform content creator in drupal 9 now the issue is that i am not getting those mapped fields in my twig template. All I am getting are previously mapped values. I have double checked the fields in content type and mapping in webform content creator.
You can use Drupal module Devel (https://www.drupal.org/project/devel) to find the right key to display.
Or debug in twig some of these:
{{ content.field_name.0 }}
{{ node.field_name.0.target_id }}
get keys you need:
{{ dump(content|keys) }}
dump like this for small fields:
{% for k,v in content.field_name %}
- {{ k }}: {{ dump(v.value) }}<br>
{% endfor %}
the variable content.field_name can be changed if you found the right field from your dump before

symfony 4 - Custom error page & custom error message

I want to create my custom error page (404, 403, etc.) in Symfony 4 so I have exception, e.g.
if (!$thisVarIsNull) {
throw $this->createNotFoundException(
'This is my custom message'
);
}
and I have created basic template in location templates/bundles/TwigBundle/Exception/error.html.twig:
{% extends "base.html.twig" %}
{% block title %}
We got a problem
{% endblock %}
{% block body %}
<div>
<p>
{{ status_code }} :: {{ exception.message }}
</p>
</div>
{% endblock %}
but the exception.message does not return anything. Where is the problem?
What you are looking for is {{ status_message }} instead of {{ exception.message }}.
Well, I checked over docs. There is no variable exception.
You can only get 2 things
CODE - {{ status_code }}
STATUS_TEXT - {{ status_text }}
Additionally
error.html.twig will be rendered when you get all erros except 404/403
Please also create templates for 404/403 (in same folder), otherwise the default ones will be rendered.
error404.html.twig
error403.html.twig
You can easily test everything in development by using /_error/{statusCode}...
For example: yoursite.com/_error/404

form_widget with dynamic form name

In my Twig template I have a FOR LOOP that creates a multiple number of forms like so:
{% for thing in things %}
{% set form_id = 'myform_' ~ thing.Id %}
{% set form_name = attribute(form, 'myform_' ~ thing.Id) %}
{{ form_widget(form_id) }}
{{ form_widget(form_name) }}
{% endfor %}
I would like this to generate the following:
{{ form_widget(myform_1) }}
{{ form_widget(myform_2) }}
.... and so on.
I left my 2 failed attempts in there, (form_id and form_name), to save anyone from suggesting those as possible solutions.
To summarize; I need to insert the dynamically created value (myform_1, myform_2) inside of {{ form_widget() }}
You can render dynamic fields form with dynamic name in Twig with special function of Twig :
{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}
With this function you can easily generate dynamic string name for your field dynamic into your form like this
{{ form_widget(attribute(form, 'myfielddynamicname' ~ var ~ ' lastchar')) }}
With this variable "var" (array or others type) you can render lot of dynamic form name like :
myfielddynamicnamefoolastchar
myfielddynamicnamebarlastchar
myfielddynamicnameneolastchar
For more understanding you can read this official twig documentation function
here : attribute twig function documentation
The things myform_1 and myform_2 simply are variables with FormView object as you define in your controller.
I don't know if Twig allows on dynamic variables call, although you can collect these form objects in array in controller before passing to view. After this step, you can just iterate thought this array It will manage the problem you are facing with.
Don't create a loop in your Twig: the layout should only render a single form. Then you can build the forms in your controller and render each one of them.
See this documentation on the Symfony book on how to get the result of a rendered template. You can concatenate the single render results and return a response with the full content.

phalcon : volt get value from array which key taken from variable

In phalcon templating engine volt (which is similar to twig) you can fetch all records by :
{% for product in products %}
Name: {{ product.name }}
Description: {{ product.description }}
price: {{ product.price}}
{% endfor %}
So, in my scenario, I'm building a crud template which will be used for different kind of models. What I wanted to achieve in this template is that every columns in this view are not hard-coded. So I store the columns I wanted to show into an array (defined in the controller, passed to the view) :
$cols = ['name','description','price']
In the view, to make it display all columns :
{% for product in products %}
{% for col in cols %}
{{ col }}: {{ product.col }}
{% endfor %}
{% endfor %}
Obviously, this will result in error, because there is no "col" in product.
Is there any solution or alternative for this ?
While frustrated tinkering with volt extension, I found a simpler solution :
Convert the model object into array. In the controller : $products->toArray()
Simply, in the view, to display specific value of specific key from an array : {{ product[key] }}
Problem solved, though because it is now not in form of object, I can't access object property using dot like {{ product.some_field }}, instead {{ product['some_field'] }}.
You should use the readAttribute() function:
http://forum.phalconphp.com/discussion/1231/volt-access-to-object-property-using-variable
{{ product.readAttribute(col) }}

How to get a Doctrine2 Entity method from a Symfony2 Form in Twig

I'm in a Twig template, and I have a "form" variable that represents a Doctrine2 Entity Form.
This Entity has properties that are mapped into the form, but the Entity has also some methods that I would like to access from my Twig template.
I would love to do something like this:
{{ form.myMethod }}
or maybe something like this:
{{ form.getEntity.myMethod }}
but unfortunately it doesn't work.
How could I achieve what I need?
To access your entity from your FormView in a twig template you can use the following code
{{ form.get('value') }}
Where form is your FormView object. This will return your entity and from there you can call any methods on it. If you embed a collection of entities or a single entity in your form you can access it the same way
{{ form.someembedform.get('value') }}
or
{% for obj in form.mycollection %}
{{ obj.get('value').someMethod }}
{% endif %}
An even more convenient syntax to get the underlying entity instead of:
{{ form.get('value') }}
is this:
{{ form.vars.value }}
Then you can call any entity method like this:
{{ form.vars.value.someMethod }}
See also the Form chapter in the Symfony documentation.
Just in order to update the subject:
form.get('value')
is deprecated since symfony 2.1. Copy from Symfony\Component\Form\FormView :
/*
* #deprecated Deprecated since version 2.1, to be removed in 2.3. Access
* the public property {#link vars} instead.
*/
public function get($name, $default = null) ....
so, I guess
form.vars.value.youMethod()
should be the way to go. It has worked form me.
... and there it goes my first post here. hope it helps!
Lost few hours trying to figure out what's going on and why
{{ form.vars.value }}
is NULL.
If you have form.element (not the form object itself) object, for example if you are overriding a form_row template that has passed the form.row object, you can get the Entity like this:
{{ form.getParent().vars.value.MyEntityMethod }}
hope that helps someone!
EDIT: Year and so later - another useful tip:
{% block sonata_type_collection_widget %}
{% for child in form %}
{{ child.vars.form.vars.value.name }}
{% endfor %}
{% endblock %}
object methods should work in twig, I know I used them in some project.
try to use ()
like {{ form.myMethod() }}
It seems that at some point the value is actually null. So you can use
{{ (form.vars.value != null) ? form.vars.value.yourEntityMethod():'' }}
tested in SF v3.0.6.
None of the above worked for me in version 2.6.7. I used customised form widgets to achieve this:
{# src/AppBundle/Resources/views/Form/fields.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{%- block entity_widget -%}
<div {{ block('widget_container_attributes') }}>
{%- for n, child in form %}
{{- form_widget(child, {
'entity': form.vars.choices[n].data
}) -}}
{{- form_label(child) -}}
{% endfor -%}
</div>
{%- endblock %-}
{%- block radio_widget -%}
{# You now have access to entity #}
{%- endblock %-}
use {{ form.getData.myMethod }}.

Categories