I want to reorder the list of available content types on the create content page. I have node-add-list.html.twig and entity-add-list.html.twig inside my custom theme template folder. Twig then outputs the array of all types or bundles/content types in alphabetical order. How can I sort this a different way? And can I hard code the links I want in this file or can I output each content type individually?
2 Answers
You can do this in preprocess by overriding this code from node.module:
function template_preprocess_node_add_list(&$variables) {
$variables['types'] = array();
if (!empty($variables['content'])) {
foreach ($variables['content'] as $type) {
$variables['types'][$type->id()] = array(
'type' => $type->id(),
'add_link' => \Drupal::l($type->label(), new Url('node.add', array('node_type' => $type->id()))),
'description' => array(
'#markup' => $type->getDescription(),
),
);
}
}
}
Or you can replace the foreach loop in the twig template
node-add-list.html.twig
<dl>
{% for type in types %}
<dt>{{ type.add_link }}</dt>
<dd>{{ type.description }}</dd>
{% endfor %}
</dl>
with a hard-coded list:
<dl>
<dt>{{ types.article.add_link }}</dt>
<dd>{{ types.article.description }}</dd>
<dt>{{ types.page.add_link }}</dt>
<dd>{{ types.page.description }}</dd>
</dl>
-
I see how you can edit the page, but how would you specifically sort the content types with these methods?– AmyMar 22, 2017 at 17:09
-
you would have to reorder the array
types
in preprocess, for example reverse the order$variables['types'] = array_reverse($variables['types']);
– 4uk4Mar 22, 2017 at 17:12 -
THanks 4k4. {{ types.article.add_link }} This works on a plain Drupal site. Now I am trying it on another site that has the Group module and workbench. I think when using the group module it uses the template entity-add-list.html.twig for site authors instead of node-add-list.html.twig. And the output is {{ bundle.add_link }}<p>{{ bundle.description }} instead of {{ type.add_link }}{{ type.description }}. So I tried {{ bundle.article.add_link }}{{ bundle.article.description }} but it did not work. I dont think the output for bundle is coming from the node.module #501 because that uses type Mar 22, 2017 at 20:09
-
This is the generic entity add list. Try plural of bundle:
{{ bundles.article.add_link }}
. You should also be able to manipulate thebundles
array in preprocess:mytheme_preprocess_entity_add_list()
– 4uk4Mar 22, 2017 at 20:34 -
Thanks I did try the plural but it didn't work. I will try mytheme_preprocess_entity_add_list() Mar 22, 2017 at 21:04
Unfortunately not so easy. Please take a look, I've already answered that in a previous question.