Slug icon indicating copy to clipboard operation
Slug copied to clipboard

Add the possibility to get the slug in a callback?

Open burzum opened this issue 8 years ago • 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.

burzum avatar Jun 27 '17 14:06 burzum

@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.

burzum avatar May 15 '18 20:05 burzum

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 avatar May 16 '18 05:05 ADmad

@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()?

burzum avatar May 16 '18 09:05 burzum

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.

ADmad avatar May 16 '18 13:05 ADmad