Displaying symfony object values in twig template - symfony

Im new to Symfony / Twig and am having problems passing object values to my twig templates.
Here is some of my controller code that shows the content of the object:
$prevArticles = $section->getArticles();
print_r($prevArticles);
die()
Displays:
Array
(
[0] => Imagine\NewsletterBundle\Entity\Article Object
(
[id:protected] =>
[title:protected] =>
[headline:protected] =>
[link:protected] =>
[image:protected] =>
[excerpt:protected] =>
[check:protected] =>
[attachment:protected] =>
[field1:protected] =>
[field2:protected] =>
[field3:protected] =>
[magazines:protected] =>
[top_logo_advert:protected] => /uploaded_images/cece0b1859ea2b1af95f1f274620ba77.jpg
[top_logo_alt:protected] => Picture of blomange
[top_logo_link:protected] => www.google.com
)
)
So then I pass my object to my twig template like so:
return $this->render('ImagineNewsletterBundle:Section:'.$builder->getTemplate(), array('prevArticles' => $prevArticles));
Then in my twig template I want to display the value of 'top_logo_advert' but its not working:
{% for article in prevArticles %}
{{ article.top_logo_advert }}
{% endfor %}
I get the error message:
Method "top_logo_advert" for object "Imagine\NewsletterBundle\Entity\Article" does not exist in ImagineNewsletterBundle:Section:build_advert.html.twig at line 62

You must access it via :
{{ article.topLogoAdvert }} or {{ article.getTopLogoAdvert() }}
Both solutions works. Next time, just reminder that properties like 'my_property_1' is converted into myProperty1 in the twig engine.

Related

How to get a custom value for a field type in sonata?

With Sonata, when I create a contract with a choiceType, the user can choose contract1 or contract2 and in my database I would get "451" for contract1 and "678" for contract2.
In my Field List all my data are displayed but for my contract I've got either "451" or "678" and I would like instead of those numbers, contract1 or contract2.
This is my field for creating the contract :
$mapper
->add('contract', ChoiceType::class, [
'choices' => [
'contract1' => '451',
'contract2' => '678',
],
])
And in my code for the field, I don't know how to tell it if 451 then 'contract1'. I started like that :
->add('contract', null, [
'label' => 'Contract',
])
Any idea ?
You can use the form entity type which would solve your problem:
$builder->add('contract', EntityType::class, [
// looks for choices from this entity
'class' => Contract::class,
// uses the Contrzct.name property as the visible option string
'choice_label' => 'name',
// Query builder to select your to specific contract
'query_builder' => function (ContractRepositoty $contractRepository) {
return $contractRepository->createQueryBuilder('support_time_slot')
->where('contract.id in :ids')
->setParameter('ids', [461,678])
->orderBy('contract.name');
},
// used to render a select box, check boxes or radios
'multiple' => true,
'expanded' => true,
]);
I found a solution. I created a specific template and in it I translated the value I wanted:
->add('contract', null, [
'label' => 'Contract',
'template' => 'AdminBundle:ContractAdmin:list__operation.html.twig'
])
And my Twig :
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{% if value %}
{{ ('contract.operation.'~value~'.value')|trans }}
{% endif %}
{% endblock %}

How to get ACF image field in taxonomy to show

I have a custom field called category_image which is an image field for categories.
I have another custom field called categories_to_show which is a taxonomy for the homepage to select which categories to show.
The categories_to_show is working fine, but I'm struggling to get category_image. If I print_r it's not in the array.
In my page-home.php file:
$context['categories_to_show'] = get_field('categories_to_show') ?? '';
In my page-home.twig file:
{% for c in categories_to_show %}
{{c.name}}
{{c.category_image}}
{% endfor %}
c.name works, c.category_image does not. But not suprising as it's not in the categories_to_show array:
Array ( [0] => WP_Term Object ( [term_id] => 4 [name] => Technology [slug] => technology [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => category [description] => [parent] => 0 [count] => 1 [filter] => raw ) [1] => WP_Term Object ( [term_id] => 1 [name] => Uncategorized [slug] => uncategorized [term_group] => 0 [term_taxonomy_id] => 1 [taxonomy] => category [description] => [parent] => 0 [count] => 1 [filter] => raw ) )
Could anyone point me in the right direction?
It looks like your problem is that you have a WP_Term object, but you’ll want to have a Timber\Term object so that you can access the meta data more easily.
In PHP, you can use Timber::get_terms() to convert an array of term IDs or WP_Term objects into Timber\Term objects.
PHP
$context['categories_to_show'] = get_field('categories_to_show')
? Timber::get_terms( get_field('categories_to_show') )
: [];
Then, if you loop through your categories, you can access all methods that are available for Timber\Term.
You can use c.category_image to access the category_image meta value, but I’d use the meta() function for a more future-proof way.
Twig
{% for c in categories_to_show %}
{{ c.name }}
{{ c.meta('category_image') }}
{% endfor %}
Depending on what the meta value for your image contains, you might also have to convert it to a Timber\Image object first before you can work with it.
{# Full #}
{{ Image(c.meta('category_image')).src }}
{# Large size #}
{{ Image(c.meta('category_image')).src('large') }}
Pro tip – you might save some performance if you choose to return only the image ID for your image field instead of an image array in your ACF field settings.
Of course, if you prefer to work with the image array that ACF returns, that’s fine as well.

Symfony Twig parse Json

I have route that is using cUrl.
The cUrl returns Json data.
So, I did $data = json_decode($results);
It returns:
(
.....
[dovecot] => stdClass Object
(
[info_str] => Running
[name] => Dovecot
[version] => 2.3.4
)
[exim] => stdClass Object
(
[info_str] => Running
[name] => Exim
[version] => 4.91
)
.......
}
So when I do return $data; on my route to twig and do:
{% for info in data %}
{{ info }}
{% endfor %}
It doesn't show anything.
My point point is to print only the [name], so I also tried:
{% for info in data %}
{{ info.name }}
{% endfor %}
And it's not working.

Symfony Form builder: how to organise/group fields into HTML sections from the controller

I would like in the form builder controller to say this field belongs to this group then in the view/theme organize all of group1 into div1, group2 into div2, etc..
I tried something like this (creating sub forms) but that is not working; I am not able to display the group
$builder->add(
$builder->create('group1', FormType::class, array('inherit_data' => true))
->add('brand', TextType::class, array(
'label' => 'brand',
'invalid_message' => 'Enter a brand',
))
);
twig
{{ form_row(form.group1) }}
In case someone else is looking; my error was that I forgot to loop through
{% for row in form.group1 %}
{{ form_row(row) }}
{% endfor %}

How to loop through form fields in Sensio Generator Bundle

I have overridden the Sensio Generator Bundle for CRUD in order to better suit my needs.
What I would like to do is to be able to loop through the entity fields.
It is done by default in show.html.twig but not in new and edit views.
When I implement the same logic in new.html.twig.twig it doesn't work though it does for edit.html.twig.twig.
{#app/Resources/SensioGeneratorBundle/skeleton/crud/views/new.html.twig.twig#}
{% for field, metadata in fields %}
{% if field not in 'id' %}
{{ '{{ form_row(edit_form.' ~ field ~ ')}}' }}
{% endif %}
{% endfor %}
When running the generator, the error is: Variable "fields" does not exist in "crud/views/new.html.twig.twig" at line 9
Ok, in fact it is an issue in Sensio Generator Bundle.
In the file: sensio\generator-bundle\Sensio\Bundle\GeneratorBundle\Generator\DoctrineCrudGenerator.php the generateNewView function is missing a paramter. It is not passing the fields as opposed to generateShowView.
Here is the comparison:
protected function generateNewView($dir)
{
$this->renderFile('crud/views/new.html.twig.twig', $dir.'/new.html.twig', array(
'bundle' => $this->bundle->getName(),
'entity' => $this->entity,
'route_prefix' => $this->routePrefix,
'route_name_prefix' => $this->routeNamePrefix,
'actions' => $this->actions,
));
}
versus
protected function generateShowView($dir)
{
$this->renderFile('crud/views/show.html.twig.twig', $dir.'/show.html.twig', array(
'bundle' => $this->bundle->getName(),
'entity' => $this->entity,
'fields' => $this->metadata->fieldMappings,
'actions' => $this->actions,
'route_prefix' => $this->routePrefix,
'route_name_prefix' => $this->routeNamePrefix,
));
}
I'll try to post this as an improvement.

Resources