DRUPAL8 Module development block and form tutorials

Source: Internet
Author: User
Tags extend drupal

Previous tutorial: Drupal8 Module Development routing, controller, and menu links tutorial

In this tutorial, we'll learn about further development, where we can find the Sandbox module code example that we need in this library (link is external), which has two important new features: chunks and forms.

To do this, we'll create a custom chunk to return some configurable text, and after that, we'll create a simple form to print out the data that the user submits to the screen.

Do not know how to download this library of students look here:

Drupal8 Block

In Drupal8, when there was a cool new change, the previous block API had been converted into a plug-in form (a whole new concept), which meant that chunks would be reusable blocks of functionality (under the engine),

You can now create a block chunk in the background UI interface and reuse it anywhere in the entire site, and you won't be limited to using only one block at a time.

Let's first create a simple chunk to print "Hello world" to the screen! In general, we first need to create a class in the Src/plugin/block directory under the module root folder

File demoblock.php, we'll name this new chunk "Demoblock" for the moment, so you end up in this file and see the code like this:

The code is as follows Copy Code
<?php

namespace Drupaldemopluginblock;

Use Drupalblockblockbase;
Use Drupalcoresessionaccountinterface;

/**
* Provides a ' Demo ' block.
*
* @Block (
* id = "Demo_block",
* Admin_label = @Translation ("Demo block"),
* )
*/

Class Demoblock extends Blockbase {

/**
* {@inheritdoc}
*/
Public Function build () {
Return Array (
' #markup ' => $this->t (' Hello world! '),
);
}

/**
* {@inheritdoc}
*/
Public function access (Accountinterface $account) {
return $account->haspermission (' access content ');
}

}




Like all other class class files, we first declare the namespace of the class at the beginning. We then use the Blockbase class to make it easy for us to inherit and extend it, and also to use the Accountinterface class so that we can get the currently logged-on user. And then some of the following code you certainly haven't seen in Drupal 7, this is: annotations annotations. The

Annotations annotation is a PHP discovery tool that, using these annotations, lets Drupal know that we want to register a new chunk (@ block) and we set the ID number: Demo_block and Admin_label:demo Block (these gaze will be identified by Drupal through the gaze translation system).

  Next, we extend the Blockbase class in the Demoblock class, we will implement two methods (most common), and the Build () method is the heaviest because it returns an array of printable chunks of information, access () Method Controls access to this block, and the argument passed to it is an instance of the Accountinterface class, where the current user information parameter is actually passed.

  Another interesting thing to note is that we no longer use the global T () function to translate text directly, but we inherit the T () method using the parent class, so you see $this->t ().

  So, you can now empty the cache, and then go to the Block configuration page, the coolest thing is that you have now successfully created a block, and you can put this block on any site you set the regions area.

Drupal 8 block configuration

Now that we know how to create a new chunk, let's learn more about how to add a configuration form to it with the API, and we'll allow you to edit this chunk and give you a text entry box So that you can enter a name, and then the front desk of the

will display "Hello World" with the name of the "please".

First, we need to define a text box, so in our Demoblock class, we can add a new method called Blockform ():

  code is as follows copy code
/**
 * {@inheritdoc}
 */
Public Function Blockform ($form, & amp; $form _state) {
  
  $form = Parent::blockform ($form, $form _state);
  
&nbs P $config = $this->getconfiguration ();
 
  $form [' demo_block_settings '] = Array (
    ' #type ' => ' TextField ',
    ' #title ' => $this->t (' Who '),
    ' #description ' => $this->t Want to say hello to? ',
    ' #default_value ' => isset ($config [' demo_block_settings '])? $confi g[' demo_block_settings ']: ',
  ';
  
  return $form;
}


This form API should look familiar and seem to be similar to the previous Drupal 7, however, looking at it, you will find something new in it, first of all, we get the $form array from the parent class (so we are in the existing

form based on the new Create our fields), the standard oriented to the image, and then we get the configuration information through the GetConfiguration () method defined by the Blockbase class, and we take the demo_block_settings value as the

#default_value的默认值.

Next, it's time to submit the value of the field we passed and save it in the block configuration:

The code is as follows Copy Code

/**
* {@inheritdoc}
*/
Public Function Blocksubmit ($form, & $form _state) {

$this->setconfigurationvalue (' demo_block_settings ', $form _state[' values '] [' demo_block_settings ']);

}



This method also exists in the Demoblock class, which is used to hold the value of the demo_block_settings (note the consistency of the key name)

Finally we need to adjust our build () method, Let it contain the name first when you print Hello:

  code is as follows copy code


/**
 * {@inheritdoc}
 */
Public Function build () {   
  $config = $this->getconfiguration ()
  
  if isset ($config [' Demo_ Block_settings '] &&!empty ($config [' demo_block_settings '])) {
    $name = $config [' Demo_ Block_settings '];
 }
  Else {
    $name = $this->t (' to no one ');
 }
  
  Retu RN Array (
    ' #markup ' => $this->t (' Hello @name! ', Array (' @name ' => $name)),
 ; &n Bsp
}



Now, this should look pretty easy, and we get the configuration information for the block, if our field value exists, we print it out, if it does not exist, print "to no one", you can now empty the cache, edit the block, fill out a value, and then save, then you can see in the foreground "Hello + Name value "up.


Drupal 8 Form

Finally, in this tutorial, we'll explore how to create a simple form, because of the space constraints, I will not overwrite its configuration management (with the form submission to store the value), instead, I'll illustrate a simple form setting, and then let the submitted value simply print on the screen to demonstrate that it works.

In Drupal 8, form definition functions are organized together in a class category, so let's define a simple Demoform class, in src/form/demoform.php:

The code is as follows Copy Code

<?php

/**
* @file
* Contains Drupaldemoformdemoform.
*/

namespace Drupaldemoform;

Use Drupalcoreformformbase;

Class Demoform extends Formbase {

/**
* {@inheritdoc}.
*/
Public Function Getformid () {
Return ' Demo_form ';
}

/**
* {@inheritdoc}.
*/
Public function Buildform (array $form, array & $form _state) {

$form [' email '] = Array (
' #type ' => ' email ',
' #title ' => $this->t (' Your. com email address. ')
);
$form [' show '] = Array (
' #type ' => ' submit ',
' #value ' => $this->t (' Submit '),
);

return $form;
}

/**
* {@inheritdoc}
*/
Public function Validateform (array & $form, array & $form _state) {

if (Strpos ($form _state[' values '] [' email '], '. com ') = = FALSE) {
$this->setformerror (' email ', $form _state, $this->t (' This isn't a. com email address. ');
}
}

/**
* {@inheritdoc}
*/
Public function SubmitForm (array & $form, array & $form _state) {

Drupal_set_message ($this->t (' Your email address is @email ', array (' @email ' => $form _state[' values ' [' email '])) ;
}

}


In addition to the change in OOP ideas, everything should look as familiar as the previous Drupal 7. The form API remains largely unchanged (except for the addition of some new form elements and the encapsulation of the associated class class), so what happens?

First, we use the namespace class and the core Formbase class, so we can expand it in our own Demoform class, and then we implement 4 methods, 3 of which should be familiar. The Getformid () method is new and must be available, this method is used to simply return the form's machine name, the Buildform () method is also necessary, it is used to build a form, how to use? In fact, similar to what you built in Drupal 7, the Validateform () method is optional, it's like Drupal 7, used to validate form submission data, and finally, the SubmitForm () method is used to process submitted form data. Everything is not quite logical organization.

So, what do we want to achieve with this form? We have an email field (a new form element for Drupal 8) that we want the user to fill out, and by default, Drupal checks to see if a value is entered in the correct mailbox format. But in our validation function we will make sure that it is a legitimate email address with a. com suffix, and if not, we will set an error prompt on the field, finally submit the processing, then print a message on the page.

The last thing we need to do to use this form is to provide a route for this form, so edit the Demo.routing.yml file and add the following code:

The code is as follows Copy Code

Demo.form:
Path: '/demo/form '
Defaults
_form: ' Drupaldemoformdemoform '
_title: ' Demo Form '
Requirements
_permission: ' Access content '


This should look familiar, because we have an article about how to route a simple page, the only big difference is that under defaults, we replace the previous _content with _form, and specify a form class for _form,

This class is just the one we created.

After emptying the cache, you can enter the address to navigate to Demo/form, and then you can see the form and test it.

If you are familiar with the Drupal_get_form in Drupal 7 and know how to load a form, you can use the Global Drupal class (link is external) in Drupal 8, such as Formbuilder () method to get a form, like this

The code is as follows Copy Code
$form = Drupal::formbuilder ()->getform (' Drupaldemoformdemoform ');



Then you can return to $form and render the output.


Conclusions


In this article, we continue to explore two new topics in the development of the Drupal 8 module: chunks and forms. We've seen how to create our own chunks (and then you can create new chunks in the Block admin interface). We also learned how to add and store a custom configuration value (this value you can use later). In the topic of the form, we saw a simple implementation of the Formbase class, which we used to print the data submitted by the user to the screen.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.