Increment slugs when accessed indirectly in URI formats #13930
-
Currently, Craft-CMS adds an incrementing index to slugs when validating elements with a URI, in order to avoid duplicate element routing URLs. However, it only does so if the element's Sometimes, the logic to generate the element's URI is more complex, and using a function in the Craft-CMS could observe the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Alternatively to observing access to the This way, a module or plugin could try and rectify the shot using the use yii\base\Event;
use yii\base\ModelEvent;
use craft\base\Element;
Event::on(
Element::class,
Element::EVENT_AFTER_VALIDATE,
function(ModelEvent $event)
{
$element = $event->sender;
if (
$element->hasErrors('uri')
&& !ElementHelper::doesUriFormatHaveSlugTag($element->uriFormat)
&& strpos($element->uri, $element->slug) !== false // maybe checking for the presence of 'craft.myModule.elementUri(' in the uriFormat instead?
) {
try {
ElementHelper::incrementSlugForUniqueUri($element); // logic from `ElementHelper::setUniqueUri()` but without checking for the '{slug}' token
$element->clearErrors('uri');
} catch (OperationAbortedException) {} // leave the error on the model's 'uri' attribute
}
}
); However, this approach puts the responsibility of "fixing" Craft's expected behaviour on the project developers. It also requires more computation, and potentially complex/unreliable if statements to detect whether the slug is used to render the element's URI. Update: I just realised that this approach would actually break validation if Craft or a plugin adds other validation rules to the element's |
Beta Was this translation helpful? Give feedback.
-
We used to do something like that, but changed it due to errors like #2995. I’ve added a new |
Beta Was this translation helpful? Give feedback.
We used to do something like that, but changed it due to errors like #2995.
I’ve added a new
EVENT_SET_ELEMENT_URI
event to the Elements service for Craft 4.6, which can be used to completely override how the URI gets defined (5d5c79c).