Drupal 8, page callbacks are completely rewritten by utilizing Symfony Routing component. This session will explain many parts of routing, how to convert from Drupal 7 menu system to Drupal 8 routing system and it will cover how to define local tasks, local actions, and contextual links in Drupal 8.
9. D7 hook_menu
SECTION TITLE
● Routing (page and access callbacks)
● Menu links
● Local actions
● Local tasks
● Breadcrumbs
● Contextual links
● Title
● Weight
14. D7: page callback
/**
* Menu callback; logs the current user out, and redirects to the home page.
*/
function user_logout() {
global $user;
watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
module_invoke_all('user_logout', $user);
// Destroy the current session, and reset $user to the anonymous user.
session_destroy();
drupal_goto();
}
17. D8: Path (required)
For dynamic properties, you can include them in curly braces.
For example -
‘/admin/structure/views/{js}/display/{view}/{display_id}/{type}'
The {display_id} element in the URL is called a slug and is
available as $display_id in the controller method.
18. D8: dynamic path example
views_ui.form_display:
path: '/admin/structure/views/{js}/display/{view}/{display_id}/{type}'
defaults:
_content: 'Drupalviews_uiFormAjaxDisplay::getForm'
class Display extends ViewsFormBase {
public function getForm(ViewStorageInterface $view, $display_id, $js, $type =
NULL) {
$this->setType($type);
return parent::getForm($view, $display_id, $js);
}
21. D8: Page Types
_content : -display content on a page
_form : - display form on a page.
_controller : - use to generate raw data like json output
_entity_view : - for example - node.teaser
_entity_form : - display a form for a entity
_entity_list : - display list of entity like node
23. D8: Available Checks
_permission - A permission string (e.g. - _permission: ‘access
content’)
_role : A specific user role (e.g.- administrator)
_entity_access: In case where an entity is part of route, can check
a certain access level before granting access (e.g. node.view)
_custom_access: You can also do custom access checking on
route.
Same as title callback (define as method on class)Read more -
https://www.drupal.org/node/2122195
24. D8: Access check
user.role_add:
path: '/admin/people/roles/add'
defaults:
_entity_form: user_role.default
_title: 'Add role'
requirements:
_permission: 'administer permissions'
Some permissions based on roles , permissions
_permission: ‘administer nodes’
_role: ‘administrator’
Based upon access to Entities
_entity_access: $entity_type.$operation
check to see if everyone has access
_access: TRUE
28. D8: Form Router
Forms are classes
There is no method in forms as forms are presented as one class
Use _form instead of _content or _controller
user.pass:
path: '/user/password'
defaults:
_form: 'DrupaluserFormUserPasswordForm'
_title: 'Request new password'
requirements:
_access: 'TRUE'
options:
_maintenance_access: TRUE
29. D7: User Password Form
function user_pass() {
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Username or e-mail address'),
'#size' => 60,
'#maxlength' => max(USERNAME_MAX_LENGTH,
EMAIL_MAX_LENGTH),
'#required' => TRUE,
'#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
);
[...]
}
function user_pass_validate($form, &$form_state)
function user_pass_submit($form, &$form_state)
30. D8: Form Interface
namespace DrupalCoreForm;
* Provides an interface for a Form.
interface FormInterface {
* Returns a unique string identifying the form
public function getFormId();
*Form constructor.
public function buildForm(array $form, array &$form_state);
* Form validation handler.
public function validateForm(array &$form, array &$form_state);
* Form submission handler.
public function submitForm(array &$form, array &$form_state);
}
31. D8: User Password Form
class UserPasswordForm extends FormBase {
public function getFormId() { return ‘user_pass’; }
public function buildForm(array $form, array &$form_state) {
$form['name'] = array(
'#type' => 'textfield',
'#title' => $this->t('Username or email address'),
'#size' => 60,
'#maxlength' => max(USERNAME_MAX_LENGTH,
EMAIL_MAX_LENGTH),
'#required' => TRUE,
);
public function submitForm(array &$form, array &$form_state) {....}
public function validateForm(array &$form, array &$form_state) {...}
32. D7: Form Validation
function user_pass_validate($form, &$form_state) {
[...]
form_set_error('name', t('Sorry, %name is not recognized as a user
name or an e-mail address.', array('%name' => $name)));
}
33. D8: Form Validation
public function validateForm(array &$form, array &$form_state) {
[...]
$this->setFormError('name', $form_state, $this->t('Sorry, %name is not
recognized as a username or an email address.', array('%name' =>
$name)));
}
34. D8: Form Base
class* * Base class for implementing system configuration forms.
DrupalcoreformConfigFormBase
for example -
class MenuSettingsForm extends ConfigFormBase
** generic base class - thisincludes string translation, link generator
DrupalCoreFormFormBase
for example -
class UserLoginForm extends FormBase
** base class for a confirmation form.
DrupalCoreFormConfirmFormBase
for example -
class LoggingForm extends ConfigFormBase
50. Options
Useful Tips
_admin_route -- whether to use the admin theme for this route
_maintenance_access -- whether route is publicly available when the site
is in maintenance mode
_access_mode -- whether requirements are ANY or ALL
This is a general overview of how routing works. So request comes in via your mobile devices or browser and you get a response in the format of JSON or HTML, an image, a redirect or a 404 return.
Drupal routing works with Symfony HTTP Kernel, but you don’t need to know the details how it works.
In Symfony there is an object which converts request into response which is called HTTP kernel. router matches the incoming URl to a specific route and returns information about the route including controller that should be executed. Symfony kernel executes the controller, which returns a response object.
hook_menu did too much in Drupal 7 and it was very complicated to understand what it was doing or it was very difficult to do any advanced task with it.
This example is from user module from Drupal 7. As you can see it has path - user/logout, title as change log out, access callback, page callback, weight, menu-name, and this callback happens to be in separate file - user.pages.inc
So this part takes over the routing aspect from drupal 7. This is routing yml for Drupal 8. modulename.routing.yml
There is a machine name - user.logout of the route(modulname.something), path is - user/logout, it is same as what used to be in the key array items. There is two other section - defaults and requirements. The new thing is the controller part here which is following PSR-4 standard here but I am not covering here but this is the controller we are using here = DrupaluserControllerUserController instead of old page callback.
Controller has a class name - DrupaluserControllerUserController and logout is method name.
For the requirement, it is same as access callback in hook_menu in Drupal 7, here we have if user is logged in as requirement instead of access argument.
This is a page callback in Drupal 7. All it does is logs out the user, closes the session and takes user to the homepage.
This is Drupal 8 version, In d8 everything is in objects and classes. so here we have a namespace. In Drupal 8, we are using psr -4 (to know where files are). we have a method here which is for logout. All it does is logs out the current user and redirect user to homepage. So the general concept is that instead of having a function in a one file you have it in in method in a class.
Path is required in Drupal 8.
If you are using node IDs in the URL, the ID can be automatically be converted to a node object by ParamConvertor system so it loads an entity from an existing entity ID.
In this example above, its using id as one of the parameter, you can see order doesn’t matter here. so we have a entity type view here and in the method, it loads the complete views object.
In some cases, you can provide default value under defaults. By default drupal passes some parameter.
if you go to user/somenumber/cancel/confirm page then something will be displayed and if you dont provide default value for timestamp and hashed_pass then it will return 404 page.
So we do have title_callback here, if you go to user/specific user page then you want to display user name as the title so we are using title_callback here. same syntax as controller.
5 available defaults in Drupal 8. it is required in drupal 8
Controller is for non-HTML, JSON or only for partial HTML but no theming or block will be output.
entity_view - value is entity_type.view_mode. for example node.teaser will return render array of the node in teaser mode.
entity_form - for example _entity_form: node.default will display the default node form.
entity_list : - for example view_mode returns the list of view modes.
requirements - determines what conditions must be met in order to grant access to the route.
role - since this can be different for sites so its recommended to use permission based on access restriction.
_format:json - so it only matches requests when the accept header is json
_module
In Drupal 8, routing is very powerful. So now you need to check access on the page like does the user has certain role or permission so symfony provides requirements. So here is _permission and also there is role so you can specify if user has permission to access the content based on role and permission.
There is also _entity_access permission. So if user go to node.edit so if user has permission to edit the node
In Drupal 8, you can also have multiple access checks. In the above route, there are two access check. options “any” means if either of the requirements is true then user will be able to access the page. If there is _access_mode: All then both requirements need to meet in order to access the page. This is very powerful than Drupal 7. Default is “ALL”
A very interesting thing here - _node_operation_route:TRUE - You can configure in node module that all node related routes show the admin theme so this is a flag which flags the route here.
In Drupal 8, we are using form api such as user login page. In the previous example we saw _controller, _content and so on. in Drupal 8 forms are classes. use _form . there is no method so one form is presented as one class. here in this example, we have a user login form
In Drupal 8, we are using form api such as user login page. In the previous example we saw _controller, _content and so on. in Drupal 8 forms are classes. use _form . there is no method so one form is presented as one class. here in this example, we have a user login form
In Drupal 8, here is user login form, it has a getFormId function, buildform function, and submit function, validateAuthentication, validateName and validateFiinal function. build form lets you build the form structure. submit method is executed when form is submitted.
validateName function is for -- Sets an error if supplied username has been blocked.
validateAuthentication function is for checking supplied username/password against local users table.
validateFinal function is for checking if user was not authenticated, or if too many logins were attempted,
Code was too long to paste here so just wanted to show you an example of form in Drupal 8.
In Drupal 8, here is user login form, it has a getFormId function, buildform function, and submit function, validateAuthentication, validateName and validateFiinal function. build form lets you build the form structure. submit method is executed when form is submitted.
validateName function is for -- Sets an error if supplied username has been blocked.
validateAuthentication function is for checking supplied username/password against local users table.
validateFinal function is for checking if user was not authenticated, or if too many logins were attempted,
Code was too long to paste here so just wanted to show you an example of form in Drupal 8.
In Drupal 8, here is user login form, it has a getFormId function, buildform function, and submit function,
validateFinal function is for checking if user was not authenticated, or if too many logins were attempted,
Just want to show you submitForm method in detail here for user login form. so after user submits login form then you want to redirect user to somewhere and in this case user is directed to user.view route so you are redirecting user to user/123 page so you are not using path here anymore but you are giving routename here,
Just want to show you submitForm method in detail here for user login form. so after user submits login form then you want to redirect user to somewhere and in this case user is directed to user.view route so you are redirecting user to user/123 page so you are not using path here anymore but you are giving routename here,
There are some helper classes for form .
ConfigFormBase - Provides an generic base class for a confirmation form.
FormBase - generic base class - includes string translation, link generator,
ConfirmFormBase -
in Drupal 8 you have menu local tasks in its own file so here we have user.links.task.yml file.
in Drupal 8 you have menu local tasks in its own file so here we have user.links.task.yml file.
in Drupal 8 you have menu local tasks in its own file so here we have user.links.task.yml file.
in Drupal 8 you have menu local tasks in its own file so here we have user.links.task.yml file. here we don’t path anymore but we have route_name, base_route, title, and weight.
base_route so tabs appear on same page.
in Drupal 8 you have menu local tasks in its own file so here we have user.links.task.yml file. here we don’t path anymore but we have route_name, base_route, title, and weight.
base_route so tabs appear on same page.
in Drupal 8 we have local action which is add content here in this image. so you can easily create some content.
in Drupal 8, you can define local action in node.links.action.yml. you have machine name, route name, title. important thing to notice is “appears on” where this local action should appear.
in Drupal 8, you can define local action in node.links.action.yml. you have machine name, route name, title. important thing to notice is “appears on” where this local action should appear.
in Drupal 8, if you hover over any block then you get this “configure block” icon so in drupal 8 you can configure block where should it appear and you can do that in contextual yml file.
in Drupal 8, you can configure block where should it appear and you can do that in contextual yml file for example - block.links.contextual.yml. again machine name, title, group, and route name. everything which is related to block contextual link should appear under block group
in Drupal 8, you can configure block where should it appear and you can do that in contextual yml file for example - block.links.contextual.yml. again machine name, title, group, and route name. everything which is related to block contextual link should appear under block group
Check BlockViewBuilder - group block is defined there in the render array
in Drupal 8, you can configure block where should it appear and you can do that in contextual yml file for example - user.links.contextual.yml. again machine name, title, group, weight, and route name so its like i want to display delete role on user.role_delete route.
hook_menu did too much in Drupal 7 and it was very complicated to understand what it was doing or to do anything very advanced tasks.
hook_menu did too much in Drupal 7 and it was very complicated to understand what it was doing or to do anything very advanced tasks.