drupal 8 querying all entitys of a type i just made - drupal

I just made an entity 'car'
I have added 10 of these entities in the drupal cms.
Now i want all ID's of the entitys 'car' in my controller
This is what i tried so far that did not work:
$query = \Drupal::entityQuery('car');
$query->condition('status', 1);
$ids = $query->execute();
$entity_query = \Drupal::service('entity.query')->get('car');
$uids = $entity_query->execute();
Both give me much more then just the 'car' entity.
they deliver other content types as well
Can someone help me how i can get all published 'car' nodes (id's)
so i can get all info for them with the load() command?
tnx

Problem solved:
Create an instance of the entity.
Then use that instance to build the entityForm
$entity = $this->entityTypeManager()->getStorage('car')->create(array());
$form = \Drupal::service('entity.form_builder')->getForm($entity,'default');
(I did create the entity using the drupal console and the default form you can set in the annotation section form in the entity file)

Related

Create new element with doctrine entity manager?

I use doctrine entity manager in my script, select and update works always, so entity manager is initialized correctly:
$article = $entityManager->find('Models\Article', 5);
echo $article->getTitle();
or:
$article->setTitle('Updated!');
but when I try to create/save new element then the page breaks, the code is:
$item = new Article();
$item->setAuthorId(1);
$item->setTitle('Created item!');
$entityManager->persist($item);
$entityManager->flush();
It's created like on official documentation page
What I do wrong here?
Seems you can't specify the relation of the object with the Author entity:
$item->setAuthorId(1);
Probably your entity Article Have a relation with the entity Author. In this case you should have a proper setter method (simple setAuthor(Author $author) ) that assign the reference of an Author object. In this case you could use the following:
$item->setAuthor($entityManager->find('Models\Author', 1););
Or Better
$item->setAuthor($entityManager->getReference('Models\Author', 1););
You could also use a short way of reference the class object with the class keyword, as example:
$item->setAuthor($entityManager->getReference(Author::class, 1););
Hope this help

Symfony2 Gedmo Translatable with APY DataGrid and KNP Paginator

I have a few problems using Gedmo\DoctrineExtensions Translatable.
First is APY DataGrid - can't make it to show translated strings in grid on non default locale. If I use Translatable with default settings, all strings in grid are displayed in default language. If I implement Translatable in Entity and add annotations for table and other stuff, then I can see translated strings in grid, BUT after switching locales these stays the same. Seems like QueryCache is used, but can't find how to set not to use it. Here's a part for grid:
use APY\DataGridBundle\Grid\Source\Entity;
<...>
$source = new Entity('MainBundle:Entity');
$source->addHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');
Of course it would be better to have translations without making annotations and separate entities for them.
Second problem is KNP pagination. Actually didn't dig into it, but similar problem.
The main problem is, when I run some query by translatable field of an entity. Let's say I have an Entity with name Krepšinis (it's basketball in Lithuanian) and I have translated this string to Basketball. Default language is LT. When in default language I perform a search, everything is ok, but if I change locale to EN and try searching for basket, it doesn't return any results and if I search for krep, it returns me Basketball. Code for search:
// Controller
$repository = $this
->getDoctrine()
->getManager()
->getRepository('MainBundle:Entity');
$query = $repository
->search($term)
->getQuery()
->useQueryCache(false)
->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker');
// Repository
public function search($query)
{
$qb = $this->createQueryBuilder('t');
$term = $qb->expr()->literal('%' . $query . '%');
$query = $qb->where($qb->expr()->like('t.name', $term));
return $query;
}
Any help is appreciated
if content is translated, you need to use query hints as you have already went through. But in order to have it cached for different locales, you need to set the locale hint to the query:
<?php
// hint the locale in order to make query cache id unique
$query->setHint(
\Gedmo\Translatable\TranslatableListener::HINT_TRANSLATABLE_LOCALE,
'en' // take locale from session or request
);
Which is described in the documentation read it carefully.
ORM query cache is based on DQL, query parameters and query hints.

Symfony 2 Variable Entity Naming

I feel like this shouldn't be to hard, but try as I might, I keep getting errors.
What I'm wanting to do, is to have a single "add" function that will handle the basic functionality of adding records to any / all tables. Basically, the post data will contain the table name, as well as the fields / values to be inserted. The controller itself, confirms the user has access to do these things, and then verifies the fields are valid, before creating a new instance of the entity, that's where things go haywire:
$entityName = 'Products';
$row = new $entityName(); //doesn't work
$row new Products(); //works
I haven't found a way or any examples of creating a new entity using the Entity Manager, or else that might work, because i've created functions using EM to do queries, updates, and deletes, but I just can't get this to work with the add functions.
1. Your problem is almost certainly namespacing (see below). Try this instead:
$entityName = 'My\Bundle\Entity\Products';
$row = new $entityName();
Should work. ;)
2. If you want to create new instances using an EntityManager, try this:
$entityName = 'My\Bundle\Entity\Products';
$row = $em->getClassMetadata($entityName)->newInstance();
...assuming $em is your EntityManager. :-)
3. To "prove" that your problem is namespacing, try this in a plain .php file that you run from the command line:
namespace Foo;
class Test {}
$class1 = 'Foo\Test';
$class2 = 'Test';
$x = new Test(); // Will work
$y = new $class1(); // Will work
$z = new $class2(); // Will trigger "Class 'Test' not found" fatal error
Two things:
Try with "Products" instead of 'Products'
I suppose that your entity Products has a namespace, it is required (even if you declared an use statement). So try with "My\Bundle\Entity\Products".

How to create a unique form using multiple entities fields in symfony2

I want to create a form using some fields from multiple entities. I have all the distinct entites needed already created and i am not using form classes. I need to know how to do to render a form and handle its data so i can save them to the correct tables in my database.
Here is a part of my controller in charge of doing that
public function createPublicSpaceAction() {
//My entities
$Room = new Room();
$GuestList = new GuestList();
$Guest = new Guest();
//I need to know what to do from here
return $this -> render('AcmeUserBundle:Default:Forms/createPublicSpace.html.twig', array());
}
I kept trying to find a solution and i came up with the idea that one form needs one entity. So maybe the solution would be to merge those entities in one so i can build the form easily. I would then have to persist data to corresponding tables. But i can't think of how to merge entities.
I figured out a temporary solution. For those who want to know, I manually created an entity that looks like a merge of all the entity I need. This new entity has no link with Doctrine therefore it cannot create a table. Its goal is simply to allow me to build up a form and be able to manipulate data through that form. I then assign all data submitted to corresponding entities fields and persist them to the database.
Once again i know this is not the best solution. But for some reasons I won't tell, it is for me at this moment. I hope this can help some that are in the same situation than me and do not hesitate to post links that could help or better ways to do that.
It is highly recommended to use form classes http://symfony.com/doc/current/book/forms.html#creating-form-classes
They are designed to save time and make a lot of things just easier.
However to answer your question consider the following. Your action needs to handel a post request. So catch the request object with the post data:
use Symfony\Component\HttpFoundation\Request;
public function createPublicSpaceAction(Request $request)
Then get a form builder intance and create the form:
$builder = $this->createFormBuilder();
$builder->add('floor', 'text', array(
'label' => 'Room floor',
'data' => $room->getFloor()
));
add as much form fields as you need. There are several built-in field types: http://symfony.com/doc/current/book/forms.html#built-in-field-types
Create the form:
$form = $builder->getForm();
Pass the form to your template:
return $this -> render('AcmeUserBundle:Default:Forms/
createPublicSpace.html.twig', array(
'roomForm' = $form
));
To get posted data within your action:
if ('POST' == $request->getMethod()) {
$data = $request->request->get("form");
}
And in your template you can render the form by yourself or let twig do the job:
{{ form_widget(form.floor)}}
So this are the most importend things to mention. However you should go through http://symfony.com/doc/current/book/forms.html They actually tell you everything I wrote down.
Good luck ;)

Creating a new entity in Symfony2 with Doctrine by using the "namespace"

You know that in Symfony2 a new entity can be defined as in the following example:
use Acme\StoreBundle\Entity\Product;
public function defaultController() {
$product = new Product();
$product->setName('Pippo');
$product->setPrice(19.99);
....
// Use Doctrine EntityManager to store the Product object
}
Suppose that you know that the Product class has the following namespace: "AcmeHomeBundle:Product". It would by nice to create the $product object by using the namespace (e.g. by using the EntityManager or something similar).
public function defaultController() {
$item = createObjectFromNamespace("AcmeHomeBundle:Product");
$item->setName('Pippo');
$item->setPrice(19.99);
....
// Use Doctrine EntityManager to store the Item object
}
Do you know if this is possible?
Suppose that you have a string that provides the entity type
You should do this...
$entityInfo = $this->em->getClassMetadata("entityNameSpace:entityName");
$entityMember = $entityInfo->newInstance();
If you wanna use a setter method by string:
$entitySetMethod = "set".\ucfirst("entityDataMemberName");
\call_user_func(array($entityMember, $entitySetMethod), $parameter);
If you really want to, you can do this:
$product = new Acme\JournalBundle\Entity\Product();
$article = new Acme\JournalBundle\Entity\Article();
But you'd have to type it out every time you wanted to create a new entity in that namespace. If you simply used a use statement at the top of you class:
use Acme\JournalBundle\Entity\Product,
Acme\JournalBundle\Entity\Article;
You could then create new articles and products with a simple:
$product = new Product();
$article = new Article();
They do the same thing.
Acme\StoreBundle\Entity\Product IS the namespace of your entity. AcmeStoreBundle:Product is just an alias for the namespace to be used in DQL as a shorter alternative to the real namespace.
Why would you want to create objects with aliased namespace? I suppose you could create some kind of a factory using alias to map it to a real namespace, create an object and return it. But what's the point?
Entity aliases are defined via Configuration: http://www.doctrine-project.org/api/orm/2.2/source-class-Doctrine.ORM.Configuration.html#153
you can not only set them but also retrieve, so if you really need this functionality you should be able to do this with Configuration instance.
It's hard to find anything about entity aliases in Doctrine docs. Symfony docs explain the purpose of it a little:
alias - Doctrine offers a way to alias entity namespaces to simpler, shorter names to be used in DQL queries or for Repository access. When using a bundle the alias defaults to the bundle name.

Resources