How to pass ArrayCollection to DoctrineModule\Form\Element\ObjectSelect - doctrine-orm

I tried pretty much everything I found by searching here and at Google too but still no luck.
I have User entity with ManytoMany relation with Countries, here is it:
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Admin\Entity\Country", cascade={"persist", "remove"})
* #ORM\JoinTable(name="user_country_linker",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="country_id", referencedColumnName="id")}
* )
*/
protected $countries;
Now I'm trying to display DoctrineModule\Form\Element\ObjectSelect with allowed/ assigned countries only. I do have this list available by calling $this->zfcUserAuthentication()->getIdentity()->getCountries().
Is there any way to pass this ArrayCollection to ObjectSelect form element?
$this->add(array(
'name' => 'country',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'label' => 'Country',
'object_manager' => $em,
'target_class' => '\Admin\Entity\Country',
'property' => 'code',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array(),
'orderBy' => array('id' => 'asc'),
),
),
'column-size' => 'sm-10',
'label_attributes' => array('class' => 'col-sm-2'),
'help-block' => 'Select country where the entity is present'
),
'attributes' => array(
'required' => false
)
));
Many thanks for the help, I really appreciate it!

How to fill a Dropdown in your controller is best described here: zf2 create select/drop down box and populate options in controller?. This is basically AlexP's solution.
If this is not what you are looking for, maybe the method described by this post can help you. At least it could help others like me that were looking for a solution like this: http://samsonasik.wordpress.com/2014/05/22/zend-framework-2-using-doctrinemoduleformelementobjectselect-and-custom-repository/
You basically create a custom reposity which holds a custom query to retrieve possible solutions:
namespace Your\Repository;
use Doctrine\ORM\EntityRepository;
class CountriesRepository extends EntityRepository
{
public function getPossibleCountries()
{
$querybuilder = $this->_em
->getRepository($this->getEntityName())
->createQueryBuilder('c');
return $querybuilder->select('c')//... define your query here
->getQuery()->getResult();
}
}
You can then refer to that method in your ObjectSelect:
$this->add(array(
'name' => 'continent',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'object_manager' => $this->entityManager,
'target_class' => 'Your\Entity\User',
'property' => 'contries',
'is_method' => true,
'find_method' => array(
'name' => 'getCountries',
),
),
));

Related

Compare user ID exactly, not with LIKE

I have this query -
<?php
$post_args = array(
'post_type' => 'tribe_events',
'eventDisplay'=>'custom',
'start_date' => date( 'Y-m-d H:i:s', strtotime( '-365 days' ) ),
'tax_query' => array(
array(
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => 'compliance',
),
),
'meta_query' => array(
array(
'key' => 'associated_people',
'value' => $current_user,
'compare' => 'LIKE'
)
)
); ?>
At the moment it is fetching events that are associated to a particular person in a custom post type called people. I'm doing this using a relationship advanced custom field called associated_people.
I'm using the 'compare' => 'LIKE' code to do this also, but it's fetching other id's that are like the current one. e.g. If it's looking for ID 117, it's also bringing back 17, 11, 7..etc.
Is there a way to look at just the exact ID?
So far we have tried changing it to 'compare' => '='
Any help would be much appreciated. Thanks!
We solved it by changing the way the value was called -
<?php
$post_args = array(
'post_type' => 'tribe_events',
'eventDisplay'=>'custom',
'start_date' => date( 'Y-m-d H:i:s', strtotime( '-365 days' ) ),
'tax_query' => array(
array(
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => 'compliance',
),
),
'meta_query' => array(
array(
'key' => 'associated_people',
'value' => '"' . $current_user . '"',
'compare' => 'LIKE'
)
)
); ?>

Doctrine Module objectSelect setvalue not working

I have a simple question regarding Doctrine Modules Object Select.
I have a simple objectSelect form element
$this->add(array(
'name' => 'timezone',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'label' => _('Timezone:'),
'label_attributes' => array('class' => 'required'),
'object_manager' => $this->getEntityManager(),
'target_class' => 'Application\Entity\Timezones',
'property' => 'timezone',
'is_method' => true,
'find_method' => array(
'name' => 'FindAll',
),
),
));
Now I want to select a certain option as default, I have used the setValue method to do this but it is not working.
$this->get('timezone')->setValue(335);
Does anyone know why this is?
Many thanks in advance.
I figured out why it wasn't working.
In my controller I was binding my form to a Doctrine entity which was empty. This was overriding my values I set. I added the values in my controller after the form was bound and this fixed the issue.
$entityManager = $this->getEntityManager();
$site = new Sites($this->getServiceLocator());
$form = new AddSiteForm($this->getServiceLocator());
$form->setHydrator(new DoctrineObject($entityManager));
$form->bind($site);
$form->get('timezone')->setValue(335);
$form->get('currencyCode')->setValue('GBP');

Cakephp validating if my user checked at least one option

I have a problem validating if my user checked at least one option from a list of checkboxes.
Here is what i tried:
My view looks like this:
echo $this->Form->input('market_segment_targeted', array(
'multiple' => 'checkbox',
'label'=>array('text' => 'Market segment targeted', 'class'=>'w120'),
'options' => array(
'Home users' => 'Home users',
'SOHO' => 'SOHO',
'SMB' => 'SMB',
'Enterprise' => 'Enterprise'
),
));
In my controller i have added this snippet of code:
$validate_on_fly = array(
'market_segment_targeted' => array(
'notEmpty' => array(
'rule' => array('multiple', array('min' => 1)),
'required' => true,
'message' => 'Please select at least one!'
))
)));
$this->Partner->validate = Set::merge(
$this->Partner->validate,
$validate_on_fly
);
Any ideas what am i doing wrong?
Thank you
In CakePHP you can use Model Validation for checkboxes. Here is a quick example.
Your Form can look like:
$this->Form->create('User');
$this->Form->input('User.agree', array('type'=>'checkbox', 'hiddenField'=>false, 'value'=>'0'));
$this->Form->submit('Save'):
$this->Form->end();
Then in your Model under public $validate, use:
'agree'=>array(
'Not empty'=>array(
'rule'=>array('comparison', '!=', 0),
'required'=>true,
'message'=>'You must agree to the ToS'
)
)

ZF2 Doctrine2 Form validation NoObjectExists

I'm using \DoctrineModule\Validator\NoObjectExists to validate my form submission. But, like the ZendDB adapter, I need to exclude all the rows where FieldX equals to SomethingX.
How can I achive that?
This is my form, filter input:
$filter->add(
$factory->createInput(array(
'name' => 'example',
'required' => false,
'validators' => array(
array(
'name' => '\DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $this->mainRepository,
'fields' => 'example'
),
),
),
))
);
Thanks.

Cakephp display other model associated with foreign key

I have the models Item and Actor with a HABTM relation (working fine).
Now, I added the Role model, wich holds the actorid, itemid (as foreign key) and the actors' role.
In my Item view, I'd like to display the actor and its' role.
I have set recursive =2.
When I debug $items, I receive all the roles belonging to that actor.
Instead I'd like only the role displayed, that contains the viewed itemid AND actorid.
I believe I might need to tweak my models but don't know how.. Any suggestions?
Item Model
public $hasAndBelongsToMany = array(
'Actor' => array(
'className' => 'Actor',
'joinTable' => 'item2actor',
'foreignKey' => 'item_id',
'associationForeignKey' => 'actor_id',
'unique' => 'true'
));
public $hasMany = array(
'Role' => array(
'className' => 'Role',
'foreignKey' => 'actorid',
));
Actor Model
public $hasAndBelongsToMany = array(
'Item' => array(
'className' => 'Item',
'joinTable' => 'item2actor',
'foreignKey' => 'actor_id',
'associationForeignKey' => 'item_id',
'unique' => 'true'));
public $hasMany = array(
'Role' => array(
'className' => 'Role',
'foreignKey' => 'actorid',
));
Instead of using a -very large- query and recursive I suggest using Containable behavior with which it's much easier to maintain the data you want to receive from DB.
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html # Cake Book.