Skip to content

Commit 45b4a6b

Browse files
committed
Alternative way of addressing #762
1 parent c7464df commit 45b4a6b

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

docs/5.x/extend/element-types.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,9 @@ public function getUriFormat(): ?string
936936
}
937937
```
938938

939-
URIs are rendered and stored on a per-site basis. Whenever an element’s URL is requested, Craft will instantiate the element and call its `getRoute()` method. Internally, <craft5:craft\base\Element::getRoute()> will call a protected `route()` method, which is what you should implement in your element class:
939+
URIs are rendered and stored on a per-site basis.
940+
Whenever an element’s URL is requested, Craft will instantiate the element and call its `getRoute()` method.
941+
Internally, <craft5:craft\base\Element::getRoute()> will call a protected `route()` method, which is what you should implement in your element class:
940942

941943
```php
942944
protected function route(): array|string|null
@@ -953,6 +955,42 @@ protected function route(): array|string|null
953955
}
954956
```
955957

958+
Your route can map to any [controller action](controllers.md), including ones in your plugin’s namespace—handy when you want to organize additional view logic:
959+
960+
```php
961+
protected function route(): array|string|null
962+
{
963+
return [
964+
// Route to `mynamespace\myplugin\controllers\StoreController::actionView()`:
965+
'plugin-handle/store/view',
966+
[
967+
'product' => $this,
968+
],
969+
];
970+
}
971+
```
972+
973+
The second item in the rule array is treated as [route params](guide:structure-controllers#action-parameters), and will be automatically mapped to arguments of the same name in your action:
974+
975+
```php
976+
public function actionView(Product $product): Response
977+
{
978+
// Load a user-defined template for this product type:
979+
$type = $product->getType();
980+
$template = $type->templatePath;
981+
982+
// Gather additional data for the template:
983+
$variables = [
984+
'product' => $product,
985+
// ...
986+
];
987+
988+
return $this->renderTemplate($template, $variables);
989+
}
990+
```
991+
992+
Using an action in this way does _not_ change your elements’ URLs—we’re only switching the underlying action that builds a response.
993+
956994
## Editing Elements
957995

958996
Craft makes editing elements frictionless by providing turn-key edit screens as well as automatic support for [slideouts](#slideouts).

0 commit comments

Comments
 (0)