Update : As Gerry suggested i fix the problem but i can't display nothing using twig. I dump the variable and this is what i get:
object(Acme\Bundle\NewBundle\Entity\database)#275 (10) {
["id":"Acme\Bundle\NewBundle\Entity\database":private]=> int(2)
["username":"Acme\Bundle\WebBundle\Entity\database":private]=> string(4) "almighty"
["password":"Acme\Bundle\NewBundle\Entity\database":private]=> string(7) "blabla"
["from":"Acme\Bundle\NewBundle\Entity\database":private]=> string(6) "bitola" ....
I have tried with:
{{% for i in user %}}
{{i.username}} - username
{{i.password}} - password
{{% endfor %}}
Still no luck .. the variable has data in it, but it is an object and not an array.So how can i display is ?
Thanks.
You just need to assign the result of the find() method to your template. find() returns the resulting object (if a match).
$user = $this->getDoctrine()
->getRepository('AcmeNewBundle:database')
->find($username);
return $this->render('AcmeNewBundle:Default:hello.html.twig',array('user' => $user));
If your user object has a property username, you can display it in your template like so:
{{ user.username }}
Related
I'm following the steps outlined in this documentation https://symfony.com/doc/current/controller/upload_file.html to allow a file to be uploaded. It is working perfectly for adding a new item, but when I try to edit my entity, I'm getting the following error:
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.
I've tried code like what is suggested in that article to append the path of the folder as File type to the entity like this in my update method:
public function editAction(Request $request, Advertiser $advertiser)
{
$advertiser->setLogo(
new File($this->getParameter('logo_directory') .'/' . $advertiser->getLogo())
);
$editForm = $this->createForm(AdvertiserType::class, $advertiser);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('advertiser_list');
}
return $this->render('advertiser/index.html.twig', [
'form' => $editForm->createView()
]);
}
The logo_directory parameter is properly defined (and working fine for creating new entities).
Please let me know if you have any ideas what I am doing wrong.
Thanks for the help.
UPDATE: In this article The form's view data is expected to be an instance of class ... but is a(n) string there is a proposed solution to include in the form builder code the following:
->add('file', FileType::class, array('data_class' => null))
So I'm doing this now and the edit form will show - but it doesn't prepoulate with the previous selection.
->add('logo', FileType::class, array('data_class' => null), ['label' => 'Logo (JPG or PNG file)'])
Any thoughts on how this can be changed to allow the form to show with the previous selection pre-populated?
Setting a null data_class will remove the warning but it will not work, you don't need it at this point.
This is due to the fact that once your file is persisted, what remains in your database is just a path, not the file itself (which is on disk);
If you want to edit this entity again, the path (a string) must be converted to a File entity again; That's what the error message says.
.. and this is what you did when you wrote :
$advertiser->setLogo(
new File($this->getParameter('logo_directory') .'/' . $advertiser->getLogo())
);
Now, the problem that remains is that you want to prepopulate the file field. In fact, that is not possible, since the file field points to a location in your own computer, not to a file on your server (and you cannot automatically upload something from someone's computer like that, that would be very dangerous).
What you want to do is possibly indicate that a file is already stored, get its path and maybe display it to your user.
So in your Twig template, something like that (change with your real logo directory) :
{% if form.logo.vars.data %}
<img src="{{ asset('/uploads/logos_directory/' ~ form.logo.vars.data.filename) }}"/>
{% endif %}
Hope it's clear.
I use Symfony 4.1, and I get a simple error.
I have a relation in my entities (ManyToOne), but I have now in my table an ID with no relation.
In my twig template :
{{ agency.brand.id and agency.brand.slogan.id ? agency.brand.slogan.title : '' }}
My problem is Slogan for a specific Brand doesn't not exist.
So I get this error :
An exception has been thrown during the rendering of a template
("Entity of type 'App\Entity\Slogan' for IDs expId(27) was not
found").
I tried everything to test in my Twig if the relation exists, but I get the error everytime.
It's weird because :
agency.brand.slogan.id // return 27
agency.brand.slogan.title // generate error
I tried to add this in my Brand Entity :
public function haveSlogan()
{
try {
if($this->getSlogan()) {
return true;
}
} catch (EntityNotFoundException $e) {
return false;
}
}
And to test in my Twig :
if agency.brand.haveSlogan
But it return true all the time.
How can I catch this error in Twig ?
You probably have inconsistent data in your database. The error says the following:
There is an ID for a slogan in your brand table record (which is 27). However,
there is no record in the slogan table with id 27.
Solution: in your brand table change the foreign key to slogan from 27 to NULL. In that case you can check in your template:
{% if agency.brand.slogan %}
I'm new in symfo but I need to translate content of my site.
I'm using a2lix (last version) and KNP doctrine behaviors (Translatable).
Let's say that I have 2 entities (e.g. Articles and Categories).
As in the doc (https://github.com/KnpLabs/DoctrineBehaviors) for translations, I'm using 2 classes for Categories (Category and CategoryTranslation).
To retrieve the translations, of my category, I'm using a query with the locale. I get the locale with Request $request ($locale = $request->getLocale();). Here is an example of my controller and the query in my repository.
Controller
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$locale = $request->getLocale();
$entities = $em->getRepository('AcmeBundle:Category')->findAllByLocale($locale);
return $this->render('CTCArtworkBundle:Backend/Artwork:index.html.twig', array(
'entities' => $entities,
));
}
Repository
I'm trying to retrieve informations for the locale.
public function findAllByLocale($locale){
return $this->createQueryBuilder('a')
->join('a.translations', 'aTrans')
->where('aTrans.locale = :locale')
->setParameter("locale", $locale)
->addSelect('aTrans')
->getQuery()
->getResult()
;
}
I don't know if it's a good practice but it works for me. I retrieve fr/en categories in my Twig template like so when I change the url :
<tr>
<th>Category</th>
<td>{{ category.translations|First.name }}</td>
</tr>
My problem
For the translation of my article, I do the same. I have 3 properties
- title
- description
- category (I'm using a2lix_translatedEntity (http://a2lix.fr/bundles/translation-form/#bundle-additional))
When I try to render a record of Article, I never retrieve the translation for my category Name but well for title and description.
I also read that (https://github.com/KnpLabs/DoctrineBehaviors#guess-the-current-locale) but I don't really understand. Is that a way to always pass locale ?
What am I doing wrong ?
I'm blocked and don't find any documentation to resolve my problem. Sorry for my english ;-)
Any help would be very appreciate. Many Thanks
KNP has its own way to guess the current locale, simply by accessing current request scope. The whole "passing locale" thing is useful if you want to pull records for specific locale.
Now, for your category translation. Since you did not include your entities, I will try to show you some examples to access your translations.
In your Category entity, lets say you have a property name that would return your category name. Then you can define a simple helper method that would return that name, by current locale:
public function getName() {
if( $name == $this->translate()->getName() ) {
return $name;
}
return '';
}
So, what have we done here?
$this->translate()->getName() - this line looks for your translation entity (in this case that would be CategoryTranslation) and invokes method getName() . Then, we either return translated category name, or an empty string if no translation has been added.
And lastly, this is how you can access your category name in your twig template:
Since we defined our helper method, there is no longer any need to access .translations in your template. You can simply call:
{{ category.name }}
Hope you got the idea.
And you can also use this
{{ category.translate.name }}
With DoctrineBehaviors v2, you can add this to your Category class:
public function __call($name, $arguments)
{
return $this->proxyCurrentLocaleTranslation($name, $arguments);
}
Here's what it does. So, in your Category entity, lets say you have a property description that would hold your category description. The code above will generate a corresponding property getter: getDescription(). Which ultimately will allow you to use this property in your Twig template:
{{ category.description }}
What is the format of the array returned using the getResult() method in the following example, using Doctrine and Symfony2:
$query = $this->_em->createQuery('SELECT p.id, p.nameProduct FROM ArkiglassProductBundle:Product p');
return $query->getResult();
And I would like to know how to access each case and print every row.
<?php
$query = $em->createQuery('SELECT u.username, u.name FROM CmsUser u');
$users = $query->getResults(); // array of CmsUser username and name values
echo $users[0]['username'];
taken from the doctrine documentation
Are you asking about "0" in $users[0]?
I hope I am not misunderstanding your question.
getResults() returns an array of database results. Once you've given your array a name you can access each element using the index.
Of course if you want to loop over it you will probably use a foreach loop so you won't have to use the index:
$products = $query->getResults();
foreach ($products as $product){
echo $product->id.' '.$product->nameProduct;
}
This said... this pseudo code is here for the sake of explanation. If you are using Symfony you will have to display your results in a view file, probably using twig like Manuszep did in his example.
In his case you will have to use a for in loop like he did.
The query returns an array of Users:
array(
0 => array(username => 'aaa', name => 'bbb'),
1 => array(username => 'ccc', name => 'ddd')
)
So the $users[0] element means the first user in the list.
You can use a for loop to iterate:
{% for user in users %}
{{ user.username }} - {{ user.name }}
{% endfor %}
I'm trying to manipulate the query string values in a URL.
I can get the current URL or route either from the Request object or Twig's functions, but it's the query string I'm struggling with.
I don't need app.request.attributes.get('_route_params') as this gets the query string params that are in the route.
I need to get query string params that are actually in the URL.
I want to be able to do the two things listed below in both Symfony2 (in a PHP controller) and Twig (in a Twig template):
Get all current query string values in the URL and display them
Do 1, but change one of the query string values before displaying them
I can't find anyone who knows how to do this.
You can use app.request.query.all to get your query strings.
If you want to change a param in Twig you can do this
{% set queryParams = app.request.query.all %}
{% set queryParams = queryParams|merge({queryKey: newQueryValue}) %}
To get the query string "https://stackoverflow.com?name=jazz"
{{ app.request.query.get('name') | default('default value if not set'); }}
Into controller
use Symfony\Component\HttpFoundation\Request;
public function fooAction(Request $request)
{
$params = $request->query->all();
}
please, pay attention: $request->query->all(); will return an array with keys named as query parameters
Into twig
As long you pass from controller (read this as always) you can pass your parameters to a view in that way
use Symfony\Component\HttpFoundation\Request;
public function fooAction(Request $request)
{
$params = $request->query->all();
return $this->render('MyFooBundle:Bar:foobar.html.twig', array('params' => $params));
}
Into your twig template foobar.html.twig you can access all query string parameters simply by using the params variable.
e.g with this request URL: http://example.com/?foo=bar&secondfoo=secondbar
{% for paramName, paramValue in params %}
<div>{{ paramName }}: {{ paramValue }}</div>
{% endfor %}
<div>{{ params.secondfoo }}</div>
twig output:
<div>foo: bar</div>
<div>secondfoo: secondbar</div>
<span>secondbar</span>
Another method is to use app.request.query.all in twig, without passing anything to twig from your controller.
Final note
If you want to modify one of those parameters when passing an array to twig from your controller, simply change one of the array values, as you would with normal values (i.e.: $params['id'] = $params['id'] - 1;)
Hi Stephen we have tried ur solution to get the value but it going to default value.
http://localhost:4000/about/investors/key-dates-and-events-details?year=2017#q1
i have used like this on my twig file
{{ app.request.query.get('year') | default('default value if not set'); }} Quareter Q1
Please let me know.