symfony2 relation between two entities - symfony

i am started to learn symfony2, Here i have some basic doubts on entity relations. Totally i have two entities 1.Admission.php and 2.Mstcity.php , just i wanna make relation between these two entities.
mysql Table structure:1.admission= id, name , mst_city_id 2. mst_city = id,city_name .. just i am having simple admission form. in that form i need to load the city_name select box . the relation id is in admission table mst_city_id is foreign key of mst_city table .
admission.mst_city_id=mst_city.id ...... > need city_name by this matching
just help me to understand this process

There's no point for me to repost here the symfony docs, so go ahead and read them HERE There are examples in the docs that show exactly what you want to do.

Assuming you have proper Associations set in place, you can just add the field with entity as widget type
$builder->add('mst_city_id', 'entity', array(
'class' => 'BundleName:mst_city',
'property' => 'city_name',
));

You should check which type of relations you use -One2One, One2Many, Many2Many
Define relations in mappers/annotations and check for owned side
Create form types and bind data from it to entities
Persist and flush entities

Related

Doctrine ORM : Joined table inheritance

Related to this previous topic : Database : Account table with Joined Tables Inheritance
I've created a joined tables inheritance in my database (MySQL) :
client_id attributes are both PK and FK.
Now I need to represent it with Doctrine ORM but I can't find a solution of how to make that.
I created, with Symfony commands, the Client entity and for the ClientCompany entity I don't know which relationship to use nor how to use the Client ID as primary key of the CompanyClient entity.
Does anyone know how to do it?
First of all, be really carefull with inheritance, this is a really good feature of doctrine but need to be used with a lot of cautious because of it's counterpart.
For your case, i would advise to not try to put "person" and "company" under the same abstract "client" class for conception reason i already explain in this answer since a company and a person are totally different things: Symfony 6 inheritance Mapping : How to submit a form depends on a clicked radio button?
But i will still answer on how to properly do a join table inheritance :
AbstractClient.php
#[Entity]
#[InheritanceType('JOIN_TABLE')]
#[DiscriminatorColumn(name: 'discr', type: 'string')]
#[DiscriminatorMap(['person' => Person::class, 'company' => Company::class])]
abstract class Client
{
// you do not need clientType since it is hold by the "discr" column
// And if you want to know what type your client is you can do it using
// if($client instanceof Person::class) { do something}
}
Person.php
#[Entity]
class Person extends Client
{
// ...
}
Company.php
#[Entity]
class Company extends Client
{
// ...
}
Take a look at #[InheritanceType('JOIN_TABLE')]
It will create one table for each entity and they will share ids.
If you create a company with id 2, there will be a client with id 2. So a Person with id 2 will never be possible.
But if you use 'SINGLE_TABLE' it will create only one table with all the field of all the entity which will be empty depending on which child you inserted inside.
But again i strongly advise you to not use join table inheritance for your usecase

setQueryBuilder sort by name easy admin

I am developping a Symfony 5.4 application with easy admin (v3.5). I have an entity Article and an entity Category. I have a ManyToMany relationship between my two entities. In my easy admin Article crud controller, I can create new Article entities and add a Category to my entity. Everything works fine. Now what I would like to do is to sort the result given by the select tag for my Category association by name.
In my code i have tried this :
//App\Controller\Admin\ArticleCrudController.php
AssociationField::new('categories')->setQueryBuilder(
function (QueryBuilder $queryBuilder) {
return $queryBuilder->getEntityManager()->getRepository(Category::class)->findBy([], ['name' => 'ASC']);
}
)->setFormTypeOptions([
"by_reference" => false,
]),
based on easy admin association field documention.
When i dump my $queryBuilder line, i do have all my entites sorted by name. But when I open the select tag, they do not appear sorted. (I would expect "Espace métiers" to appear first, then "Gourvernance et pilotage" and so on).
I have noticed that the documentation I am using is for version 4.x and that mine is 3.5 but as I have a result when I dump I am still asking just in case.

How to store array of key => value data in on ORM and allow edits via Sonata admin bundle

Coming over from Python to do an application in SF2 and would love some help
I need to create a list of books, this has been easy and Sonata admin bundle has been really easy to setup but now I'm stuck one one section
I need the following fields:
Title
ie. Harry Potter
Description
ie. Book about wizards
Themes
ie. ['Animals' => ['Donkey', 'Cat'], 'Seasons' => ['Winter', 'Summer']]
Grammar
ie. ['Possessive pronoun' => ['my']]
The Themes and Grammar I would identify as:
Area
Target: The target (string)
Examples: list of examples (array)
Is there any Doctrine & Sonata admin related data structure that would be good to use in this situation? I do not need the "areas" to be their own models but would like to list each area target and it's examples on a template.
Thankyou!
The simplest solution is to store Area as an Entity and also Example as an entity. Then you can make many-to-one relations called "grammar" and one-to-many relation called themes both pointing to Area entity and also one-to-many relation in Area entity that points to Example entity. In Area entity I advise you to write __toString function in Area Entity. This function can return string composed with target and examples. This will let you print Area properly - for example on sonata admin list.
If you build query in Sonata Admin make sure you extend default query with left joins to Area and Example entities.

Removing a relation between entities in EF Code First Many to many relationship

I have an application built with entity framework 5 code first, where I'm using code first against an existing database. I have two entities, Foo and Bar, which are connected through a many to many relationship using a table in sql server with foreign key to each of the two tables. In code, the two entity types each have a collection of the other, and in the dbcontext they are mapped together like this:
modelBuilder.Entity<Foo>()
.HasMany(e => e.Bars)
.WithMany(s => s.Foos)
.Map(l =>
{
l.ToTable("FooBar");
l.MapLeftKey("FooId");
l.MapRightKey("BarId");
}
);
The problem is that I can add relationship between the entities by adding eachother to their collections and saving, however when I do the opposite, removing eachother from their collections, the record in the relationship table are not being removed.
I ended up just importing the bridge table in the model. If anyone knows how this is supposed to work, please leave an answer here.

Add a search form in a manyToMany Relation interface

How to implement a search form in a many to many relation between entities.
I want to search items from an entity before to add them to my other entity. I am using a long list of items (product) that i need to link to Shops and i can't use a simple listbox to select my items.
I need you to point me to a tutorial or any explaination to deal with this interface problem.
The goal is to use a minimum of javascript
I would suggest to create an view where you could select a category or define your search condition. And a second View where you only display products by the previously selected condition. In your second view you could use an entity Field Type ( http://symfony.com/doc/current/reference/forms/types/entity.html#query-builder ) and provide a custom query for the entities like:
use Doctrine\ORM\EntityRepository;
// ...
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:Product',
'query_builder' => function(ProductRepository $er) {
return $er->createQueryBuilder('p')
->where('p.category = 1);
},
));
This solution doesn't require JavaScript at all.
I spent lot's of time trying to figure out the best solution to make the compromise between re-usability, performance and ergonomy and i found a nice solution
I did this way :
I created a custom form field that show a collection like entity field type but i pass field names that I want to show in a nice table :
->add('products','reflist',array(
'columns'=>array('name','cost','description'),
'actions'=>array('select'=>true,'remove'=>true),
'entityName'=>'VendorProductBundle:Product',
'searchForm'=> 'Vendor\ProductBundle\Form\ProductSearchType'
));
Then I created a generic searching service that takes in input the entity to search on. The result is sent in a popup paginated.
Finally, I created a controller related to my new field to manage actions like add, remove
Thats's it for the logic.
I can't really share the work since it is really dependent of my framework (depend of search service, layout,etc...)

Resources