Add the possibility to get the slug in a callback?
Opened this issue · 4 comments
We have one special case in which we need to take the english translation instead of the japanese or chinese title of a profile. I couldn't find a better way to inject the logic required for this than extending the behavior and overriding the slug method:
class WaSlugBehavior extends SlugBehavior {
/**
* Generates slug.
*
* @param \Cake\ORM\Entity|string $entity Entity to create slug for
* @param string $string String to create slug for.
* @param string $separator Separator.
* @return string Slug.
*/
public function slug($entity, $string = null, $separator = '-') {
if ($entity instanceof EntityInterface
&& $entity->get('language_id') === LanguagesTable::JAPANESE
&& !empty($entity->get('translations'))
) {
foreach ($entity->get('translations') as $translation) {
if ($translation->get('locale') === LanguagesTable::ENGLISH) {
$entity = $translation->get('profile_title');
$string = null;
break;
}
}
}
return parent::slug($entity, $string, $separator);
}
}
A simple solution might be to make the display field option taking a callable as well?
Any other suggestion is welcome.
@ADmad what about this one? Nobody ever provided feedback. I don't mind implementing it in the case it's not getting rejected after I've done the feature.
Can't think of a better way right now other than making displayField
a callable as you suggested. You can make a PR without tests initially.
@ADmad what do you think about this?
$callable($entity, $string, $separator, $table) { ... }
My main concern is what should I return? Just a string to override the $string that is then passed on or do we want to return that result from slug()?
We would still need the processing done by slug()
for things like uniqueness check. So the change would be in _getSlugStringFromEntity()
where you would check if displayField
is a callback and return the string returned by the callback.