My problem that when i use the loop , the data inside don't show up ,
this is the code here im using the loop even " mes boutiques " dont show, , only "shirts & tops" show up
and this function where im calling this template in the controller
Your function affichDQL() must have a problem, you should test the result in your controller with dump($enseignes); to see if you haves results. You can add an check in your twig too with {% dump(enseignes) %}
Your template looks ok. The problem probably is in the repository method that probably return the DQL: a string representing the query in Doctrine.
I suspect you have a method like this in your entity method:
// retrieve the DQL string of what was defined in QueryBuilder
$dql = $qb->getDql();
So you need to replace with something like this:
// retrieve the associated Query object with the processed DQL
$query = $qb->getQuery();
// Execute Query
$result = $query->getResult();
return $result;
Hope this help
Related
I need load and object from the database and need to store it in session .
The problem is that the loaded object is too big that when i print it my browse crushes .
How can i load just the pure object from the database ?
And here is the code :
if ($session->get('record')->getId()) {
$record = $this->container->get('myweb.record_repository')->findOneById($session->get('record')->getId());
$session->set('record', $record);
print_r($session->get('record'));
die;
}
Try to hydrate as array... in symfony there is the option to Query::HYDRATE_ARRAY and then normalize it to an object
You're not dumping your code correctly.
With Symfony, there is the dump() function.
You can either use it in controller, or in twig.
In controller:
//Check if parameter exists first, else you might trigger an error
if($session->has('record') && $session->get('record')->getId() !== null) {
$record = $this->container->get('myweb.record_repository')->findOneById($session->get('record')->getId());
$session->set('record', $record);
dump($session->get('record'));
exit();
}
In Twig (you can pass a variable name)
{{ dump() }}
Then again, like I said in comment, it's most likely pointless to store your object in session.
Doctrine will query for the object most of the time.
Lets say you do this:
$relatedEntity->getRecord();
Doctrine won't look into the session for the object, it will query database.
I'm new to symfony 2, working with FOSUserBundle along with PUGXMultiUserBundle and I have troubles retrieving the list of users with a specific role, for example : ROLE_ADMINISTRATEUR to notifiy them about something. Anyway, inspired by this this is my UserRepository class:
<?php
namespace OC\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findByRoles($role)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('u')
->from('OCUserBundle:User', 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"'.$role.'"%');
return $qb->getQuery()->getResult();
}
}
and this is the code inside in the controller's action:
$em=$this->getDoctrine()->getManager();
$repository2=$em->getRepository('OCUserBundle:User');
$roles='ROLE_ADMINISTRATEUR';
$users=$repository2->findByRoles(array('roles'=>$roles));
Return $this->render('OCUserBundle:Default:test.html.twig',array(
'users'=>$users));
and my test.html.twig page:
{% for a in users %}
{{a.username}}
{% endfor %}
All what I get is an empty page. Any help would be appreciated
I try to do this also without PUGXMultiUserBundle with the function:
$users = $repositoryUser->findByRoles("ROLE_SUPER_ADMIN");
But it's doesn't work i get an empty array, so i do it manually:
$qb = $em->createQueryBuilder();
$qb->select('u') ->from('AppBundle:User', 'u') ->where('u.roles LIKE :roles') ->setParameter('roles', '%"'."ROLE_SUPER_ADMIN".'"%');
$users = $qb->getQuery()->getResult();
Maybe this can help people who are in the same case of me.
Did you try by correcting this line :
$users=$repository2->findByRoles(array('roles'=>$roles));
By :
$users=$repository2->findByRoles('ROLE_ADMINISTRATEUR');
?
Your method seems to search for users for ONE role. The LIKE condition expects a string and not an array.
The method would be then more like findByRole() and not findByRoles().
Solved. Actually, using PUGXMultiUserBundle, you can select from a particular table, (you can associate a type of user with a role) so I changed the action inside the controller to this:
$em=$this->getDoctrine()->getManager();
$repository2=$em->getRepository('OCUserBundle:UserAdministrateur');
$admins=$repository2->findAll();
Return $this->render('OCUserBundle:Default:test.html.twig',array(
'admins'=>$admins));
Works like a charm. HOpe this helps someone.
I just had the same problem as the OP. Actually the thing with the above piece of code from the OP, are the double quotes: ->setParameter('roles', '%"'.$role.'"%');
These didn't seemed right from the first look. Changed to: ->setParameter('roles', '%'.$role.'%'); and all works fine.
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 }}
I'm using Symfony2 + Doctrine + Translatable from DoctrineExtensions.
I have an entity article which has a couple of translatable fields like Title and Content. What is happening now is that I've created a bunch of articles in Chinese language, but have not added a translation for English. This is giving me some problems when I try to display a top 8 most recent articles on my homepage... When I view my homepage in English, it will show a bunch of title-less articles there (the Chinese articles that dont have a translation in English).
I found a solution for this in the Translatable extension by using ORM query Hint:
"\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER".
This lets you directly query the translated fields of your entity which are actually stored in ext_translations and not in the entity's table.
As a result the code I use to fetch the articles for the homepage looks like this:
public function getNewestArticles($limit = 1){
$dql =
"SELECT a FROM NewsBundle:Article a
WHERE a.published = 1
AND a.title != ''
ORDER BY a.created_at DESC";
$query = $this->_em->createQuery($dql);
$query->setMaxResults($limit);
$query->setHint(
\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
);
$result = $query->getResult();
return $result;
}
This actually works, but the generated query is so inefficient that it slows down the page a lot... I'm talking 1800 ms for that query. I've also tried to just put the fields I need in the select statement, which improves the performance, but still not enough.
Any ideas?
you can try to optimize the query manually. use locale as the parameter in your repository
public function getNewestArticles($locale, $limit = 1){
//your own superfast query
}
in the controller then set the locale with
$locale = $request->getLocale();
$em->getNewestArticles($locale, $limit);
additional question: have you set indexes on your tables?
I have been looking for hours for a way of setting a condition on the list of items that an APYDataGridBundle grid should return but could not find an answer.
Is there a way to set a DQL Query and pass it to the grid to display the exact query results I want to fetch?
This is the code:
public function filteredlistAction(){
// Create simple grid based on the entity
$source = new Entity('ACMEBundle:MyEntity');
// Get a grid instance
$grid = $this->get('grid');
// Attach the source to the grid
$grid->setSource($source);
...
...
**$grid->getColumns()->getColumnById('myentity_filter_column')->setData('the exact value I tried to match');**
// Manage the grid redirection, exports and the response of the controller
return $grid->getGridResponse('ACMEBundle:MyEntity:index_filteredlist.html.twig');
}
You can add a callback (closure or callable) to run before QueryBuilder execution - its done like this :
$source->manipulateQuery(
function ($query)
{
$query->resetDQLPart('orderBy');
}
);
$grid->setSource($source);
$query is an instance of QueryBuilder so you can change whatever you need to
Example taken from docs here
A more "complicated" query.
$estaActivo = 'ACTIVO';
$tableAlias = $source->getTableAlias();
$source->manipulateQuery(
function ($query) use ($tableAlias, $estaActivo)
{
$query->andWhere($tableAlias . '.estado = :estaActivo')
->andWhere($tableAlias . '.tipoUsuario IN (:rol)')
->setParameter('estaActivo', $estaActivo)
->setParameter('rol', array('VENDEDOR','SUPERVISOR'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
);
Cheers!