Passing $options to form builder in symfony2 - php

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']).

Related

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.

Query_builder Symfony form builder error

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.

Can't post blank to database: postgreSQL and Codeigniter

In my View Page, I have a blank input but whenever I have to post to my database, it gets error.
View Page:
<label for="column1">COLUMN1:</label>
<input type="input" name="column1">
Model Page:
'column1' => $this->input->post('column1'),
This code will not satisfy if my input is blank. How can I post it to my database with the value of 0 instead of blank(cause it will not satisy).
Column1 is an integer type so blank value in not an integer as what I understand. Can anyone help me.
BTW I'm using Codeigniter and PostgreSQL
EDIT------- MY REAL CODE
Model
public function changeNow_table2_A(){
$seq = $this->input->post('seq');
$data = array(
'tech_voc' => $this->input->post('tech_voc'),
'bacc' => $this->input->post('bacc'),
'post_bacc' => $this->input->post('post_bacc'),
'llb' => $this->input->post('llb'),
'md' => $this->input->post('md')
);
$this->db->where('seq', $seq);
$this->db->update('table2', $data);
} // this work
I tried changing only
'bacc' => empty($this->input->post('bacc'))? 0 : $this->input->post('bacc'),
// changing 'bacc' to this, it gets server error.
Not sure if you resolved this yet - just in case, here is another answer.
$column1 = $this->input->post('column1');
$data = array('testcol' => 'testing',
'column1' => (empty($column1) || !is_numeric($column1)) ? 0 : $column1);
This will set column1 to 0 if column1 is empty or if column1 is not a number
Prior to version 5.5 the empty function only supports variables. Meaning empty($this->input->post('field')) will throw a fatal error. PHP 5.5 included support for using expressions as arguments to empty. The error was most likely a result of using a function as an argument to the empty function. Check your version of php to confirm this.
here is the php empty documentation
You could make use of a ternary operator.
'column1' => empty($this->input->post('column1'))? 0 : $this->input->post('column1'),

Symfony sfWidgetFormDoctrineChoice with multiple option on

I have created a form in which i embed another form. My question is about this embedded form - I'm using a sfWidgetFormDoctrineChoice widget with option multiple set to true. The code for this embedded form's configure method:
public function configure()
{
unset($this['prerequisite_id']);
$this->setWidget('prerequisite_id', new sfWidgetFormDoctrineChoice(array(
'model' => 'Stage',
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'multiple' => true
)));
$this->setValidator('prerequisite_id', new sfValidatorDoctrineChoice(array(
'model' => 'Stage',
'multiple' => true,
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'column' => 'id'
)));
}
I unset the prerequisite_id field because it is included in the base form, but I want it to be a multiple select.
Now, when I added the validator, everything seems to work (it passes the validation), but it seems like it has problems saving the records if there is more than one selection sent.
I get this PHP warning after submitting the form:
Warning: strlen() expects parameter 1 to be string, array given in
D:\Development\www\flow_dms\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\database\sfDoctrineConnectionProfiler.class.php
on line 198
and more - I know, why - in symfony's debug mode I can see the following in the stack trace:
at Doctrine_Connection->exec('INSERT INTO stage_has_prerequisites
(prerequisite_id, stage_id) VALUES (?, ?)', array(array('12', '79'),
'103'))
So, what Symfony does is send to Doctrine an array of choices - and as I see in the debug sql query, Doctrine cannot render the query correctly.
Any ideas how to fix that? I would need to have two queries generated for two choices:
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (12, 103);
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (79, 103);
stage_id is always the same (I mean, it's set outside this form by the form in which it is embedded).
I have spend 4 hours on the problem already, so maybe someone is able to provide some help.
Well, I seem to have found a solution (albeit not the best one, I guess). Hopefully it'll be helpful to somebody.
Finally, after much thinking, I have concluded that if the problem comes from the Doctrine_Record not being able to save the record if it encounters an array instead of a single value, then the easiest solution would be to overwrite the save() method of the Doctrine_Record. And that's what I did:
class StageHasPrerequisites extends BaseStageHasPrerequisites
{
public function save(Doctrine_Connection $conn = null)
{
if( is_array( $this->getPrerequisiteId() ) )
{
foreach( $this->getPrerequisiteId() as $prerequisite_id )
{
$obj = new StageHasPrerequisites();
$obj->setPrerequisiteId( $prerequisite_id );
$obj->setStageId( $this->getStageId() );
$obj->save();
}
}
else
{
parent::save($conn);
}
}
(...)
}
So now if it encounters an array instead of a single value, it just creates a temporary object and saves it for each of this array's values.
Not an elegant solution, definitely, but it works (keep in mind that it is written for the specific structure of the data and it's just the effect of my methodology, namely See What's Wrong In The Debug Mode And Then Try To Correct It Any Way Possible).

CakePHP array() is empty, but query seems to be getting the correct results

I am trying to extract ONLY the PlanDetails where PlanDetail.company_id = Company.id AND PlanDetail.id' => $id.. ( you can see the conditions in my controller below)..
Controller:
function pd_list_by_company($id = null) {
$this->recursive = 2; // I am going to use containable to trim this.
return $this->PlanDetail->find('all',
array('conditions' =>
array('AND' =>
array('PlanDetail.company_id' => 'Company.id',
array('PlanDetail.id' => $id)))));
}
Test View:
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company');
debug($planDetailsByCompany );
Output result of my debug??
Array()
If I remove the conditions and just have the find all, I get all PlanDetails as expected, so I know the data is being passed.. SQL debug dump even shows the query:
WHERE ((`PlanDetail`.`company_id` = 'Company.id') AND (`PlanDetail`.`id` IS NULL))
And yes, I did notice the $id is NULL, and I know the value needs to be there.. So maybe my question is why is the $id value not being passed to the controller even though I can see the PlanDetail.id value on a find('all') w/ out the conditions??
Thanks for any tips.
Since $id seems to be null, I would assume that you call the function without the parameter. And you don't get an error message, because as far as PHP is concerned the parameter is optional. In this case it's clearly required, so you should make it a required parameter in your function declaration:
function pd_list_by_company($id) {
Also you could simplify the return statement, you do not need the AND:
return $this->PlanDetail->find('all',
array('conditions' =>
array('PlanDetail.company_id' => 'Company.id','PlanDetail.id' => $id)
)
);
To answer the question why is the $id not being passed is because you're not passing it
To pass say $id of 2 you need to do the following in your requestAction
$this->requestAction('/planDetails/pd_list_by_company/2');
Seems to me that your code should just be
return $this->PlanDetail->find('array('PlanDetail.id' => $id));
Assuming you have the $this->PlanDetail->recursive flag set to > 0, your Model should already know about and return the associated data for any 'Company' table.....
I'm used to an old (1.3) version of CakePHP but the find() function is pretty basic and is designed to only return one row.
and yes, you definitely need to call the function with the id appended to the url, eg.
$planDetailsByCompany = $this->requestAction('/planDetails/pd_list_by_company/999');

Categories