CakePHP 2.4 pagination sort on I18n translated field
-
26-12-2019 - |
Pergunta
I'm using SmoothTranslate Behavior for CakePHP. Its uses Cake's TranslateBehavior.
I have a Model wich contains contents ("Content"). I have fields what are translated, so i have an I18n model too.
When i'm tring to sort by a Translated field like this:
<?php echo $this->Paginator->sort('I18n__title.content',__('Title')); ?>
The paginator component drops this because the I18n__title is a automatic generated alias for the translated field, and not an alias of teh model ("Content").
PaginatorComponent line 396:
$correctAlias = ($object->alias == $alias);
$object->alias is "Content" but the $alias of the column is "I18n__title".
The whole code of PaginatorComponent:
foreach ($options['order'] as $key => $value) {
$field = $key;
$alias = $object->alias;
if (strpos($key, '.') !== false) {
list($alias, $field) = explode('.', $key);
}
$correctAlias = ($object->alias == $alias);
if ($correctAlias && $object->hasField($field)) {
$order[$object->alias . '.' . $field] = $value;
} elseif ($correctAlias && $object->hasField($key, true)) {
$order[$field] = $value;
} elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field, true)) {
$order[$alias . '.' . $field] = $value;
}
}
Can the CakePhp 2.x sort by a translated field?
Solução
Yes, it can be done. On the controller method you should have a call to the paginator component like this:
$articles = $this->paginate();
You need to change it to something like this, adding I18n__title.content to the whitelist parameter like this:
$articles = $this->paginate(null, array(), array('I18n__title.content', ... other fields you wanna sort must also be added));
This way you avoid it to be deleted on the query as a non recognized field in the model (check validateSort method on PaginatorComponent)