Paginator->sort() using joined model does not work - join

My models association chain:
ArchitectPurchase belongsTo ArchitectProfile belongsTo User
My action:
$this->ArchitectPurchase->recursive = -1;
$this->ArchitectPurchase->Behaviors->attach('Containable');
$this->paginate['joins'] = array(
array(
'table' => 'architect_profiles',
'alias' => 'ArchitectProfileJoin',
'type' => 'inner',
'conditions' => array(
'ArchitectProfileJoin.id = ArchitectPurchase.architect_profile_id'
)
),
array(
'table' => 'users',
'alias' => 'User',
'type' => 'inner',
'conditions' => array(
'User.id = ArchitectProfileJoin.user_id'
)
)
);
$this->paginate['order'] = 'User.name DESC';
$this->paginate['contain'] = array(
'ArchitectProfile' => array(
'fields' => array('ArchitectProfile.id'),
'User' => array(
'fields' => array('User.name')
)
)
);
$this->set('architectPurchases', $this->paginate());
This action works fine, ordering the results by User.name DESC. But when I use the link created with
echo $this->Paginator->sort('User.name')
in my view, it does not work!
Looking at the core files, I found that the validateSort method of the PaginatorComponent was the problem:
if ($object->hasField($field)) {
$order[$alias . '.' . $field] = $value;
} elseif ($object->hasField($key, true)) {
$order[$field] = $value;
} elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
$order[$alias . '.' . $field] = $value;
}
As the User model is not directly associated with the ArchitectPurchase model, I get
$order = array()
instead of
$order = array('User.name' => 'asc')
I tried to use the $whitelist parameter, but still not working...
So I had to hack the core (noooo!!!), commenting from line 345 to 363 to make it work.
Am I doing something wrong or is this a 2.2.1 issue?

Thanks for posting this, I was actually having the same issue and with your insight of the problem I was able to solve it.
I posted a ticket on the issue tracker of CakePHP if anyone is interested, but basically they said it won't be fixed and offered two recommendations to bypass the problem.
The way I fixed it is I forced the model to be related with the one that has the field I'm interested in order by.

Related

CakePHP, counting values form joined table

can you please help me with CakePHP query code. I managed to make MySQL code but I am not able to convert it to CakePHP
Here is MySQL code
SELECT team_name, count(team_members.id)
FROM teams
LEFT JOIN team_members ON teams.id = team_members.team_id
WHERE teams.user_id = 15
GROUP BY teams.id
and here is how I tried to get the code from CakePHP:
$email = $this->request->getQuery('email');
$user = $this->Users
->find('all')
->where(['email' => $email])->first();
$options = array(
'joins' =>
array(
array(
'table' => 'TeamMembers',
'alias' => 'TeamMembers',
'type' => 'left',
'foreignKey' => false,
'conditions'=> array('TeamMembers.team_id = Teams.id')
),
),
);
$teams = $this->Teams->find('all', $options)
->select(["team_name","id",'count_members' => 'count(*)'])
->where(['Teams.user_id' => $user->id])
->group(['Teams.id']);
Try this:
$teams = \Cake\ORM\TableRegistry::get('Teams');
$query = $teams->find();
$res = $query
->select([
'team_name',
'count' => $query->func()->count('team_members.id')
])
->join([
'table' => 'team_members',
'type' => 'LEFT',
'conditions' => 'teams.id = team_members.team_id',
])
->group('teams.id');
$teams=$this->Team->find('all',array(
'recursive'=>-1,
'conditions'=>array('Team.user_id = 15'),
'joins'=>array(
array('table'=>'team_members',
'alias'=>'TeamMember',
'type'=>'left',
'conditions'=>array(
'Team.id = TeamMember.team_id',
),
),
),
'fields'=>array(
'count(TeamMember.id) as total_team_members',
'Team.team_name'
),
'group' =>array('Team.id ASC'),
)
);

Zend 2: Unit tests for form class

I'm just starting using PHPUnit with Zend and need little help to figure out how these tests should work.
I want to test if form return any error message if I do not pass any POST parameters.
The problem is that one field from my form is using Doctrine's DoctrineModule\Form\Element\ObjectSelect
...
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'user',
'attributes' => array(
'id' => 'user-label',
),
'options' => array(
'object_manager' => $em,
'target_class' => 'Application\Entity\User',
'property' => 'username',
'label' => 'User:',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function($entity) {
return $entity->getUsername();
},
),
));
...
I get following error:
Fatal error: Call to a member function getIdentifierFieldNames() on null
I tried override this field with mocked object, however Zend doesn't allow objects in type, just class name (string), so this code doesn't work:
public function testIfFormIsValid()
{
$objectSelect = $this->getMockBuilder('DoctrineModule\Form\Element\ObjectSelect')
->disableOriginalConstructor()
->getMock();
$objectSelect->expects($this->any())
->method('getValueOptions')
->will($this->returnValue(array()));
$form = new \AppModuleComment\Form\Comment('form', array(
'em' => $this->em // Mocked object
));
$form->add(array(
'type' => $objectSelect,
'name' => 'user',
'attributes' => array(
'id' => 'user-label',
),
'options' => array(
'object_manager' => $this->em,
'target_class' => 'Application\Entity\User',
'property' => 'username',
'label' => 'User:',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function($entity) {
return $entity->getUsername();
},
),
));
$data = array(
'id' => null,
'user' => null
);
$form->setData($data);
$this->assertTrue($form->isValid(), 'Form is not valid');
}
What am I doing wrong? How should I test such code?
It seems you are testing functionality of Zend or Doctrine (or both) and not your own code. When you use libraries you should trust these libraries.
What happens is: Form\Form::add() uses Form\Factory::create() to create from the array an element. Form\Factory::create() uses Form\FormElementManager::get() to get an element from the given type.
Your type is an object and because Form\FormElementManager::get() can not handle objects your script will fail.
It seems you want to test that if post is empty Form::valid() calls ObjectSelect::valid() but this does not verify if the value is null. That's code from Doctrine / Zend not yours. Don't test it.
More interesting it gets when you want to mock the result of an select from within Doctrines ObjectSelect. But that's another question.

ZF2 - Form creation missing validators

I am having a little trouble adding validators to a ZF2 form object. I an building a form from a schema set in a database so I can validate a set of user input quickly.
This is the code that generates the form object
//initialise the form
$form = new Form();
//need to loop through the schema to create the form
for($i=0; $i < count($schema); $i++)
{
$form_options = array();
//add the basics to the form
$form_options['name'] = $schema[$i]['field_name'];
$form_options['type'] = $schema[$i]['field_type'];
//check if this is a required field
if($schema[$i]['is_required'] == 'true')
{
$form_options['required'] = true;
}
//add functions to filter the input form
$function_filters = explode(',', $schema[$i]['function_filter']);
if(!empty($function_filters))
{
$filters = array();
for($j=0; $j < count($function_filters); $j++)
{
$filters = array('name' => $function_filters[$j]);
}
$form_options['filters'] = $filters;
}
//add validators to the field array
$validators = array();
if(!is_null($schema[$i]['min_length']) && !is_null($schema[$i]['max_length']))
{
$validators[] = array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => (int) $schema[$i]['min_length'],
'max' => (int) $schema[$i]['max_length'],
)
);
}
//our regex validator if it exists
if(!is_null($schema[$i]['regex_filter']) || strlen($schema[$i]['regex_filter']) != 0)
{
$validators[] = array(
'name' => 'regex',
'options' => array(
'pattern' => $schema[$i]['regex_filter'],
'messages' => array(
\Zend\Validator\Regex::INVALID => $schema[$i]['regex_invalid'],
\Zend\Validator\Regex::NOT_MATCH => $schema[$i]['regex_not_match'],
\Zend\Validator\Regex::ERROROUS => $schema[$i]['regex_errorus'],
)
)
);
}
//only add the validators if theres something in there
if(!empty($validators))
{
$form_options['validators'] = $validators;
}
$form->add($form_options);
}
//return our form object
return $form;
The block of code behaves the way I expect it, the output of $form_option after it's performed the above code looks like this:-
Array
(
[name] => username
[type] => Text
[required] => 1
[filters] => Array
(
[name] => StripTags
)
[validators] => Array
(
[0] => Array
(
[name] => StringLength
[options] => Array
(
[encoding] => UTF-8
[min] => 3
[max] => 50
)
)
[1] => Array
(
[name] => regex
[options] => Array
(
[pattern] => /^[a-zA-Z0-9_]{3,50}$/
[messages] => Array
(
[regexInvalid] => L_REGEX_INVALID
[regexNotMatch] => L_REGEX_USERNAME
[regexErrorous] => L_REGEX_ERRORUS
)
)
)
)
)
When I came to test it, it ignores the StringLength & Regex validators entirely, and only pay attention to the required validator for the last form element.
Anyone have any idea what's gone wrong?

dynamic dropdown get in zf2?

I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);

How to store the choice array_keys as values when using sfWidgetFormChoice when multiple equals true

Here’s my widget in the Form.Class:
$this->widgetSchema['schools'] = new sfWidgetFormChoice(array(
'choices' => Doctrine_Core::getTable('school')->getUsersSchools($userId),
'renderer_class' => 'sfWidgetFormSelectDoubleList',
'renderer_options' => array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
)));
The above works just fine, but the values that are stored are unassociated to the choices list referenced above. I need to store the ids of the array retrieved as the values. Instead, the list that is retrieved is chronological and the ids are ignored.
Here's the schoolTable query:
public function getUsersSchools($id){
$q =Doctrine_Query::create()
->select('id')
->from('school')
->where('user_id = ?', $id)
->execute();
return $q;
}
If I understand your question correctly you would like to store associated school ids.
Use the sfWidgetFormDoctrineChoice widget instead and it will work out of the box, as it using primary keys as ids.
$query = Doctrine_Core::getTable('school')->queryForSelect($userId);
$this->setWidget('schools', new sfWidgetFormDoctrineChoice(array(
'model' => 'school',
'query' => $query,
'multiple' => true,
'renderer_class' => 'sfWidgetFormSelectDoubleList',
'renderer_options' => array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
),
)));
$this->setValidator('schools', new sfValidatorDoctrineChoice(array(
'model' => 'schoool',
'query' => $query,
'multiple' => true,
)));
// in SchoolTable class
public function queryForSelect($userId)
{
return $this->createQuery('s')
->andWhere('s.user_id = ?', $userId)
;
}
If you has a proper schema (I presume the schools should be a many-to-many association), then the current from should has a schools_list field (properly defined in the generated base from) and then you can modify that field to be rendered by sfWidgetFormSelectDoubleList:
$this->widgetSchema['schools_list']->setOption('renderer_class', 'sfWidgetFormSelectDoubleList');
$this->widgetSchema['schools_list']->setOption('renderer_options', array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
));

Resources