在这种情况下,我们应该在模型/表中使用附加字段,例如 slug 就像在 pages TCA 中一样。首先要做的是在typo3conf/ext/zoo/ext_tables.sql中将它添加到我们的SQL中
CREATE TABLE tx_zoo_domain_model_animal (
name varchar(255) DEFAULT '' NOT NULL,
color varchar(255) DEFAULT '' NOT NULL,
slug varchar(2048), -- quite large value, but your name/slug may be loooong
);
如果我们的表的TCA typo3conf/ext/zoo/Configuration/TCA/tx_zoo_domain_model_animal.php,我们需要为新字段添加配置
<?php
return [
'ctrl' => [...],
'interface' => [
// add slug to showRecordFieldList
'showRecordFieldList' => 'sys_language_uid, l10n_parent, l10n_diffsource, hidden, name, slug, color',
],
'types' => [
// add slugto showitem
'1' => ['showitem' => 'sys_language_uid, l10n_parent, l10n_diffsource, hidden, name, slug, color, --div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.access, starttime, endtime'],
],
'columns' => [
'sys_language_uid' => [...],
'l10n_parent' => [...],
'l10n_diffsource' => [...],
't3ver_label' => [...],
'hidden' => [...],
'starttime' => [...],
'endtime' => [...],
'name' => [...],
'color' => [...],
// add config for slug
'slug' => [
'exclude' => true,
'label' => 'Slug',
'displayCond' => 'VERSION:IS:false',
'config' => [
'type' => 'slug',
'size' => 50,
'generatorOptions' => [
'fields' => ['name'],
'replacements' => [
'/' => '-'
],
],
'fallbackCharacter' => '-',
'eval' => 'uniqueInSite', // optionaly 'unique' can be used to make sure it's unique within whole TYPO3 instance.
'default' => ''
]
],
],
];
最后编辑我们的路由增强器以使用slug 而不是typo3conf/sites/yoursite/config.yaml 中的name:
routeEnhancers:
Zoo:
type: Extbase
limitToPages:
- 107 # it's always good idea to limit enhancers only to pages containing plugin
extension: Zoo
plugin: Showroom
routes:
- routePath: '/'
_controller: 'Animal::list'
- routePath: '/{animal-name}'
_controller: 'Animal::show'
_arguments:
animal-name: animal
aspects:
animal-name:
type: PersistedAliasMapper
tableName: tx_zoo_domain_model_animal
routeFieldName: slug
感谢这种方法 slug 字段将在后端表单编辑期间得到正确处理:
ProTip 像往常一样,每次更改代码后,尤其是在config.yaml 不要忘记 清除所有缓存数百万次:D
除了cmets中的问题
对非唯一 URI 使用数字后缀是很长一段时间内 TYPO3 中路由(或一般的 URL 重写)的标准行为。实际上,使用添加的 slug 字段可以让您为每个项目输入自定义 slug,而不是使用 elephant-1 和 elephant-2。
您也可以选择修改 slug 字段的 TCA,以组合来自 DB 的更多字段,而无需手动编辑 slug:
'slug' => [
'exclude' => true,
'label' => 'Slug',
'displayCond' => 'VERSION:IS:false',
'config' => [
'type' => 'slug',
'size' => 50,
'generatorOptions' => [
'fields' => ['name', 'color'], // combine more fields
'fieldSeparator' => '/', // or '-' if you want slug like 'elephant-cyan' instead of `elephant/cyan`
'replacements' => [
'/' => '-'
],
],
'fallbackCharacter' => '-',
'eval' => 'uniqueInSite', // optional 'unique' can be used
'default' => ''
]
],
根据 color 字段的值自动创建 slug,例如:
BE预览:
TCA 中的外观配置
由于 TYPO3 版本:10.x,可以使用 presented in documentation 类向 slug 字段添加自定义前缀,它只会添加类似于您可以在翻译页面/记录中看到的前缀。
实际上它继承了两个参数,$parameters 和 $reference 到 TYPO3\CMS\Backend\Form\FormDataProvider\TcaSlug,所以它可以用于添加路由的语言部分,但是,它已经完成了,所以我暂时找不到许多其他用途。