Translate doctrine query from default Symfony 3 translation file - symfony

In my AdRepository i'm getting an list of list conditions of the product. These have names like 'NEW', 'GOOD'... I use the following simple query to get the list:
$query = $this->createQueryBuilder('ad')
->select('ad.condition as name')
->getQuery()
->getResult();
Now I want to translate the name field from the standard Symfony translation files, so not from the database. What is the best way to do this?

I'm not sure if thats the best way to do it, but you could (I assume you're using Twig) use an if and give the translation variable depending on the condition name.
{% if condition.name === "GOOD" %}
{{ 'condition.good'|trans }}
{% else %}
...
{% endif %}
Of course thats a lot of ifs, if you have many conditions.

Related

Translate the value of twig variable

Is it possible to translate the value of twig variables in a template with the 'trans' tag?
Say for instance I am passing a product to my template. This product has a definition with a trans tag e.g {{ product.definition|trans }}. This definition could either be in EN or DE or some other language. How could I translate the definition.
What are you trying to do is not a good way, It would look like this:
messages.en.yml
product:
definition:
some_value1: Some value 1
some_value2: Some value 2
and in template, you would do something like this:
{% set definition_value = product.definition %}
{% set trans_definition = 'product.definition.' ~ definition_value %}
{{ trans_definition|trans }}
it'll work, if it finds the key. What if it cant find it?
That's why you should use DoctrineBehaviors from KnpLabs, which handles all the dynamic translations for you..
If {{ product.definition }} equals 'cellphone' the following should work.
message.language.yml:
'cellphone': This will work!
However if you want to map it with the 'product' key in your message file like this:
product:
'cellphone': This also works
add the key to the twig template like so:
{{('product.'~product.definition)|trans }}

Keep leading 0 in Twig

In my database, I have a field containing the following data : 000010 (the type is integer)
In my twig tpl, I want to display it, then I do : {{ spending.documentName }}
But the browser displays "10". As if Twig was automaticcaly performing a trim on my data.
I tried {{ spending.documentName|raw }} but it doesn't work. I dont find anything on Google about how to keep leading 0 with Twig.
Does anyone know how to proceed ?
I think you must force the format (as your type is integer).
You can use the format filter :
{{ "%06d"|format(spending.documentName) }}
Or better create a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html):
public function strpad($number, $pad_length, $pad_string) {
return str_pad($number, $pad_length, $pad_string, STR_PAD_LEFT);
}
It's clearer in your template :
{{ spending.documentName | strpad(6,'0') }}
You need to use the format filter.
Since placeholders follows the sprintf() notation, you should be able to convert sprintf('%06d', $integer); in PHP to {{ '%06d'|format($integer) }} in Twig.
Kinda late here, but ran into the same.
With twig 3.x you can use:
{{your.number | format_number({min_integer_digit:'2'})}}

Using doctrine database object in a template

I am new to Symfony and am finally beginning to understand how to query a database using a Doctrine. However, I am lost as far understanding how to use the database object content in a Twig template.
Lets say my database object contains product Id's, names, prices, for 50 different products. After I am done querying the database in the controller, I do the following, to pass the database object into the Twig template:
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $word));
}
This is where I am stuck. Now I have a Twig template, I would like to pass the DB object from the controller and then print out the database data in my Twig template.
I appreciate any suggestions as to how I can accomplish this.
Many thanks in advance!
I'll respond with an example (more easier for me to explain)
You want to search something with a slug (the var $word in your example). Let's say you want to find a article with that.
So your controller :
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
// Search the list of articles with the slug "$word" in your model
$articleRepository = $this->getDoctrine()->getRepositoy('GreatBundle:Article');
$dataObject = $articleRepository->findBySlug($word);
// So the result is in $dataObject and to print the result in your twig, your pass the var in your template
return $this->render('GreatBundle:Default:search.html.twig', array('result' => $dataObject));
}
The twig template 'GreatBundle:Default:search.html.twig'
{% for item in result %}
{{ item.title }} : {{ item.content }}
{% endfor %}
Just look the second example in the Symfony2 Book (Sf2 Book - templating), you have to use the function "for" to parse your object (like an array in php !)
Example in your twig template :
{% for item in word %}
{{ item.id }} - {{ item.name }} - {{ item.description }}{# etc... #}<br>
{% else %}
<h2>Aoutch ! No data !</h2>
{% endfor %}
Ah, and it's not the good var in your render method (but it's was for your example !)
public function searchAction($word)
{
//query database using the $word slug and prepare database object accordingly
$dataObject; // contains query results
return $this->render('GreatBundle:Default:search.html.twig', array('word' => $dataObject));
}

Using repository class methods inside twig

In a Symfony2.1 project, how to call custom entity functions inside template? To elaborate, think the following scenario; there are two entities with Many-To-Many relation: User and Category.
Doctrine2 have generated such methods:
$user->getCategories();
$category->getUsers();
Therefore, I can use these in twig such as:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for user in category.users %}
{{ user.name }}
{% endfor %}
{% endfor %}
But how can I get users with custom functions? For example, I want to list users with some options and sorted by date like this:
{% for user in category.verifiedUsersSortedByDate %}
I wrote custom function for this inside UserRepository.php class and tried to add it into Category.php class to make it work. However I got the following error:
An exception has been thrown during the rendering of
a template ("Warning: Missing argument 1 for
Doctrine\ORM\EntityRepository::__construct(),
It's much cleaner to retrieve your verifiedUsersSortedByDate within the controller directly and then pass it to your template.
//...
$verifiedUsersSortedByDate = $this->getYourManager()->getVerifiedUsersSortedByDate();
return $this->render(
'Xxx:xxx.xxx.html.twig',
array('verifiedUsersSortedByDate' => $verifiedUsersSortedByDate)
);
You should be very carefull not to do extra work in your entities. As quoted in the doc, "An entity is a basic class that holds the data". Keep the work in your entities as basic as possible and apply all the "logic" within the entityManagers.
If you don't want get lost in your code, it's best to follow this kind of format, in order (from Entity to Template)
1 - Entity. (Holds the data)
2 - Entity Repositories. (Retrieve data from database, queries, etc...)
3 - Entity Managers (Perform crucial operations where you can use some functions from your repositories as well as other services.....All the logic is in here! So that's how we can judge if an application id good or not)
4 - Controller(takes request, return responses by most of the time rendering a template)
5 - Template (render only!)
You need to get the users inside your controller via repository
$em = $this->getDoctrine()->getEntityManager();
$verifiedusers = $em->getRepository('MYBundle:User')->getVerifiedUsers();
return array(
'verifiedusers' => $verifiedusers,
);
}

writing doctrine query with symfony 2

i have two tables:
products products_images
-id -id
-name -product_id
-image_name
There is one to many relation from product to products_images table
I have created two entities with its relation defined as: Product and ProductImage
I need to get list of products and its images but the limiting the record of no of images to 1.
Currently, I did this :
$product = $this->getDoctrine()
->getRepository('TestBundle:Product');
Then in the twig template:
{% for image in product.images if loop.first %}
{% endfor %}
I used this loop to fetch one image for that product. I dont think this is efficient way to do since i have fetching all the images for that product.
What I want to do is just fetch only one image per product from the database? How can i do this ?
I'd add another method to the Product-entity, something like getThumbnail. This encapsulates the logic of which image is considered the thumbnail (i.e your view does not contain any logic of whether to display the first, last or any other product image, it just asks the product for its thumbnail):
in the view
{% if product.thumbnail %}
{{ // Output the product.thumbnail-entity }}
{% endif %}
In the entity
public function getThumbnail ()
{
return $this->getImages()->first();
}
Now, after profiling, if you're concerned that the full image collection is loaded when only a single image/product is shown, then I'd update the repository DQL to only fetch-join a single image, or make sure that the association to the images is EXTRA_LAZY

Resources