Query_builder Symfony form builder error - php

I have an entity field in my form that shows all forms in the database in a list. These forms have revision numbers. What I want to do is to show only the last revision of a form as an option in the list.
To clarify, the form table looks like this
Id || Name || Revision_number
1 || Form1 || 1
2 || Form1 || 2
The select list should only show revision 2.
So far, I have tried this
->add('form', 'entity', array(
'class' => 'AppBundle\Entity\Form',
'label' => 'label.ship.form',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('f')
->select('f, MAX(f.revisionNumber) AS max_revision');
}
))
But I get this error
Warning: spl_object_hash() expects parameter 1 to be object, string given

I've faced this problem too.
'query_builder' option should return Doctrine\ORM\QueryBuilder or a Closure and in your case (someone correct me if I am wrong) the "select" method is supposed to return a Doctrine\ORM\QueryBuilder object too. Weird, right...
What I did was create a method in the entity repository that returns the query builder itself:
public function generateStaffRolesQB() {
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('r')
->from('DatabaseModelsBundle:Role', 'r')
->where('r.id IN (1, 2)');
return $qb;
}
And in the form I use it like this:
'query_builder' => function(EntityRepository $er) {
return $er->generateStaffRolesQB();
},
Hope it helps.

Related

Subquery on symfony form field

I'm trying to generate a subquery to populate and form select in symfony but I get this error message
[Semantical Error] line 0, col 167 near 'd2 WHERE d2.distributor': Error: 'd2' is already defined.
this is my code
-`>add('doctor', EntityType::class, [
'class' => Doctor::class,
'query_builder' => function (EntityRepository $er) use ($options) {
$subquery = $er->createQueryBuilder('d2')
->select('')
->from('AppBundle\Entity\Distributor', 'd2')
->andWhere('d2.distributor = :distributor_subquery')
->setParameter('distributor_subquery', $options['user']);
$query = $er->createQueryBuilder('d');
$query->select('d')
->where('d.distributor = :distributor')
->setParameter('distributor', $options['user'])
->orWhere($query->expr()->in('d.distributor', $subquery->getDQL()))
->orderBy('d.name', 'ASC')
->addOrderBy('d.surname', 'ASC');
return $query;
},`
d2 alias is defined two times
$er->createQueryBuilder('d2')
and
->from('AppBundle\Entity\Distributor', 'd2')
but in both functions the parameter is mandatory
I tried with
$subquery = $er->createQueryBuilder() ->select('') ->from('AppBundle\Entity\Distributor', 'd2') ->andWhere('d2.distributor = :distributor_subquery')
but it doesn't work
Please see the implementation of EntityRepository::createQueryBuilder() method: it already contains the select and from parts, it gets this information from it's entity class. So you can omit calling these methods, just add a where clause and bind params:
$subquery = $er->createQueryBuilder('d2')
->andWhere('d2.distributor = :distributor_subquery')
->setParameter('distributor_subquery', $options['user']);

Eloquent update all column fields

I want to update all the tables in the Article migration to a specific Boolean value which is set by the user.
I have written this code:
public function changeComVote() {
$data = request()->validate([
'status' => 'required'
]);
Article::query()->update(['isOnly' => $data['status']]);
event(new changesMade);
}
Although $data['status'] doesn't get passed inside the query and nothing happens, when i set it manually it works like a charm, what could be the problem?
Using $data['status'] from request will give you a string as a result, not a boolean.
Try this way
Article::query()->update(['isOnly' => $data['status'] == 'true']);
You can delete that "query()" thing and use this instead
Article::update(['isOnly' => $data['status']]);
or
Article::update(['isOnly' => ($data['status']] === "true"));
You can also specify where the row by using id
Article::find($id)->update(['isOnly' => ($data['status']] === "true"));

How to render a dynamic Select (ChoiceType)?

So I am trying to generate a dynamic select for Product Table form
instead of writing all the options like this: (code from productType)
->add('id_cat', ChoiceType::class, [
'choices' => [
'cosmetique' =>'1',
'vetement' => '2',
'parfums' => '3',
],
])
I want the choices to be generated from another table Category(id,cat_name) .
For example instead of 'cosmetique' it shows cat_name and instead of 1 it shows id
(and those are values generated from the database from table Category)
I wrote this function that return all the values from table Category in a table $tab
public function cat (CategoryRepository $categoryRepository)
{
$allcat=$categoryRepository->findAll();
$tab=[];
foreach($allcat as $cat)
{
$tab=$cat->getId();
$tab[$tab]=$cat->getCatname();
}
return $tab;
}
I dont know where exactly I should place it? and how to send that $tab to ProductType.php page
If you have relation between the two entities (and i guess you have) you can easily use the entity type from Symfony to avoid problem like this which will show all the content inside the category table and submit the chosen object to be saved depending on your association :
$builder->add('category', EntityType::class, [
'class' => Category::class,
'choice_label' => 'cat_name',
]);
Or if you want to keep your way you can pass the array as an option to your form but its not a good practice.
Why not just make tab[] something like having a field named 'choices' statically built into it before populating and then add every I'd and category to it and return the table and return results of array wherever?
tab['choices']=$cat->getID();
tab['choices'][tab['choices']]=$cat->getCatname();
And then
for each ($choices as $choice)
For each ($choice as $category)
Print_r( $category)

Symfony2: How do I use in a form (query builder) left join and isnull?

I have a problem with a filter function for which I am using two tables.
The first ‚eventcheckin-table‘ is used for checking in the guests via booking-ID for a certain event. Therfore it should also verify if the ID is already checked in. The ID´s which aren´t yet checked in shall be available as an option in the ‚Entity‘ field. This problem I tried to solve in the following way:
SELECT booking.booking_id FROM booking LEFT JOIN event_checkin ON `event_checkin.booking_booking_id = booking.booking_id WHERE` event_checkin.booking_booking_id IS NULL
It works fine.
My solution for the Symfony2 Form Builder is
->add('bookingBooking', EntityType::class, array (
'class' => 'AppBundle:Booking',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('b')
->leftjoin('AppBundle:EventCheckin', 'e', 'with', 'e.bookingBooking = b.Id')
->expr()->isNull('e.bookingbooking');
},
'label' => 'Booking-ID: * ',
))
Symfony displays this message
Expected argument of type "Doctrine\ORM\QueryBuilder", "string" given
How can I solve this problem?
Thanks for your help. ;)
As i think, you can use andWhere statement like :
$er->createQueryBuilder('b')
->leftjoin('AppBundle:EventCheckin', 'e', 'with', 'e.bookingBooking = b.Id')
->andWhere('e.bookingbooking is null');
Or
$qb = $er->createQueryBuilder('b');
$qb->leftjoin('AppBundle:EventCheckin', 'e', 'with', 'e.bookingBooking = b.Id')
->add('where', $qb->expr()->isNull('e.bookingBooking'));
return $qb;
Inspired on this.

Passing $options to form builder in symfony2

I have this code in my form builder
->add('user', 'entity', array(
'class' => 'Acme\Entity\User',
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('u')
->where('u.id = :id')
->setParameter('id',$options['my'])
->orderBy('u.name', 'ASC');},))
When I echo $options['my'] I get output as 1 inside the builder.
Now when I submit the form, I get NULL as the User object.
But if I use ->setParameter('id',1) then it works fine.
Now if i use this
$options['test'] = 1 inside the build form and use
->setParameter('id',$options['test']) then it also work fine.
But ->setParameter('id',$options['my']) is not working directly. It is echoing fine as 1 in the form , so value is in that variable.
What should I do?
It is a common error of type. 1 is a string in the first case and a int in the second case. Try if this works:
->setParameter('id',intval($options['my']))
Your debug is really good though, but it is better to use var_dump rather than echo. You can also compare the types with gettype().
Compare var_dump($options['my']) with var_dump($options[test']).
Compare gettype($options['my']) with gettype($options['test']).

Categories