Wednesday 29 May 2019

How to use mongoDB with Laravel/Lumen

Hi Everybody,

Today we will learn how to use mongoDB in our Laravel/Lumen application.

Installation


Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php

WARNING: The old mongo PHP driver is not supported anymore in versions >= 3.0.

Installation using composer:

composer require jenssegers/mongodb

And add the service provider in config/app.php(Laravel):

Jenssegers\Mongodb\MongodbServiceProvider::class,

For usage with Lumen, add the service provider in bootstrap/app.php. In this file, you will also need to enable Eloquent. You must however ensure that your call to $app->withEloquent(); is below where you have registered the MongodbServiceProvider:

$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);

$app->withEloquent();

The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects.

For usage outside Laravel, check out the Capsule manager and add:

$capsule->getDatabaseManager()->extend('mongodb', function($config, $name)
{
    $config['name'] = $name;

    return new Jenssegers\Mongodb\Connection($config);
});

Upgrading

Upgrading from version 2 to 3


In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait.

Please change all Jenssegers\Mongodb\Model references to Jenssegers\Mongodb\Eloquent\Model either at the top of your model files, or your registered alias.

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {}

If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class Illuminate\Database\Eloquent\Model instead of the removed Jenssegers\Eloquent\Model. Instead use the new Jenssegers\Mongodb\Eloquent\HybridRelations trait. This should make things more clear as there is only one single model class in this package.

use Jenssegers\Mongodb\Eloquent\HybridRelations;

class User extends Eloquent {

    use HybridRelations;

    protected $connection = 'mysql';

}

Embedded relations now return an Illuminate\Database\Eloquent\Collection rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations.

$books = $user->books()->sortBy('title');

Configuration


Change your default database connection name in config/database.php:

'default' => env('DB_CONNECTION', 'mongodb'),

And add a new mongodb connection:

'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    'options'  => [
        'database' => 'admin' // sets the authentication database required by mongo 3
    ]
],

You can connect to multiple servers or replica sets with the following configuration:

'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => ['server1', 'server2'],
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    'options'  => [
'replicaSet' => 'replicaSetName'
]
],

Alternatively, you can use MongoDB connection string:

'mongodb' => [
    'driver'   => 'mongodb',
    'dsn' => env('DB_DSN'),
    'database' => env('DB_DATABASE'),
],

Please refer to MongoDB official docs for its URI format: https://docs.mongodb.com/manual/reference/connection-string/

Eloquent


This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {}

Note that we did not tell Eloquent which collection to use for the User model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the collection name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a collection property on your model:

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $collection = 'users_collection';

}

NOTE: Eloquent will also assume that each collection has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class MyModel extends Eloquent {

    protected $connection = 'mongodb';

}

Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent

Optional: Alias


You may also register an alias for the MongoDB model by adding the following to the alias array in config/app.php:

'Moloquent'       => Jenssegers\Mongodb\Eloquent\Model::class,

This will allow you to use the registered alias like:

class MyModel extends Moloquent {}

Query Builder


The database driver plugs right into the original query builder. When using mongodb connections, you will be able to build fluent queries to perform database operations. For your convenience, there is a collection alias for table as well as some additional mongodb specific operators/operations.

$users = DB::collection('users')->get();

$user = DB::collection('users')->where('name', 'John')->first();

If you did not change your default database connection, you will need to specify it when querying.

$user = DB::connection('mongodb')->collection('users')->get();

Read more about the query builder on http://laravel.com/docs/queries


Schema

The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes:

Schema::create('users', function($collection){$collection->index('name');$collection->unique('email');});

Supported operations are:
  • create and drop
  • collection
  • hasCollection
  • index and dropIndex (compound indexes supported as well)
  • unique
  • background, sparse, expire, geospatial (MongoDB specific)
All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. Read more about the schema builder on http://laravel.com/docs/schema

Geospatial indexes

Geospatial indexes are handy for querying location-based documents. They come in two forms: 2d and 2dsphere. Use the schema builder to add these to a collection.
To add a 2d index:

Schema::create('users', function($collection){$collection->geospatial('name', '2d');});

To add a 2dsphere index:
Schema::create('users', function($collection){$collection->geospatial('name', '2dsphere');});

Extensions

Auth

If you want to use Laravel's native Auth functionality, register this included service provider:
'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',

This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. If you don't use password reminders, you don't have to register this service provider and everything else should work just fine.

Queues

If you want to use MongoDB as your database backend, change the driver in config/queue.php:

'connections' => [ 'database' => [ 'driver' => 'mongodb', 'table' => 'jobs', 'queue' => 'default', 'expire' => 60, ],
'failed' => [
'database' => 'mongodb',
'table' => 'failed_jobs',
],

Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
If you want to use MongoDB to handle failed jobs, change the database in config/queue.php:
And add the service provider in config/app.php:

Sentry

If you want to use this library with Sentry, then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry

Sessions

The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session

Examples

Basic Usage

Retrieving All Models
$users = User::all();

Retrieving A Record By Primary Key
$user = User::find('517c43667db388101e00000f');

Wheres
$users = User::where('votes', '>', 100)->take(10)->get();

Or Statements
$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();

And Statements
$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();

Using Where In With An Array
$users = User::whereIn('age', [16, 18, 20])->get();

When using whereNotIn objects will be returned if the field is non existent. Combine with whereNotNull('age') to leave out those documents.

Using Where Between
$users = User::whereBetween('votes', [1, 100])->get();

Where null
$users = User::whereNull('updated_at')->get();

Order By
$users = User::orderBy('name', 'desc')->get();

Offset & Limit
$users = User::skip(10)->take(5)->get();

Distinct
Distinct requires a field for which to return the distinct values.
$users = User::distinct()->get(['name']);// or$users = User::distinct('name')->get();
Distinct can be combined with where:
$users = User::where('active', true)->distinct('name')->get();

Advanced Wheres
$users = User::where('name', '=', 'John')->orWhere(function($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get();

Group By
Selected columns that are not grouped will be aggregated with the $last function.
$users = Users::groupBy('title')->get(['title', 'name']);

Aggregation
Aggregations are only available for MongoDB versions greater than 2.2.
$total = Order::count();$price = Order::max('price');$price = Order::min('price');$price = Order::avg('price');$total = Order::sum('price');

Aggregations can be combined with where:

$sold = Orders::where('sold', true)->sum('price');
Aggregations can be also used on subdocuments:
$total = Order::max('suborder.price');
...
NOTE: this aggreagtion only works with single subdocuments (like embedsOne) not subdocument arrays (like embedsMany)

Like
$user = Comment::where('body', 'like', '%spam%')->get();

Incrementing or decrementing a value of a column
Perform increments or decrements (default 1) on specified attributes:
User::where('name', 'John Doe')->increment('age');User::where('name', 'Jaques')->decrement('weight', 50);
$count = User->increment('age');
User::where('age', '29')->increment('age', 1, ['group' => 'thirty something']);
User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']);
The number of updated objects is returned:
You may also specify additional columns to update:

Soft deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:
use Jenssegers\Mongodb\Eloquent\SoftDeletes; class User extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; }

MongoDB specific operators

Exists
Matches documents that have the specified field.
User::where('age', 'exists', true)->get();

All
Matches arrays that contain all elements specified in the query.
User::where('roles', 'all', ['moderator', 'author'])->get();

Size
Selects documents if the array field is a specified size.
User::where('tags', 'size', 3)->get();

Regex
Selects documents where values match a specified regular expression.
User::where('name', 'regex', new \MongoDB\BSON\Regex("/.*doe/i"))->get();

NOTE: you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoDB\BSON\Regex object.
User::where('name', 'regexp', '/.*doe/i'))->get();
And the inverse:
User::where('name', 'not regexp', '/.*doe/i'))->get();

Type
Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
User::where('age', 'type', 2)->get();

Mod
Performs a modulo operation on the value of a field and selects documents with a specified result.
User::where('age', 'mod', [10, 0])->get();

Near
NOTE: Specify coordinates in this order: longitude, latitude.
$users = User::where('location', 'near', [ '$geometry' => [ 'type' => 'Point', 'coordinates' => [ -0.1367563, 51.5100913, ], ], '$maxDistance' => 50,]);

GeoWithin
$users = User::where('location', 'geoWithin', [
 '$geometry' => [
        'type' => 'Polygon',
     'coordinates' => [[
            [
                -0.1450383,
                51.5069158,
            ],       
            [
                -0.1367563,
                51.5100913,
            ],       
            [
                -0.1270247,
                51.5013233,
            ],  
            [
                -0.1450383,
                51.5069158,
            ],
        ]],
    ],
]);

GeoIntersects
$locations = Location::where('location', 'geoIntersects', [
    '$geometry' => [
        'type' => 'LineString',
        'coordinates' => [
            [
                -0.144044,
                51.515215,
            ],
            [
                -0.129545,
                51.507864,
            ],
        ],
    ],
]);

Where
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where

Inserts, updates and deletes

Inserting, updating and deleting records works just like the original Eloquent.
Saving a new model
$user = new User;
$user->name = 'John';
$user->save();
You may also use the create method to save a new model in a single line:
User::create(['name' => 'John']);

Updating a model
To update a model, you may retrieve it, change an attribute, and use the save method.
$user = User::first();
$user->email = 'john@foo.com';
$user->save();
There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations

Deleting a model
To delete a model, simply call the delete method on the instance:
$user = User::first();
$user->delete();
Or deleting a model by its key:
User::destroy('517c43667db388101e00000f');
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete

Dates

Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields, you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators
Example:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $dates = ['birthday'];

}
Which allows you to execute queries like:
$users = User::where('birthday', '>', new DateTime('-18 years'))->get();

Relations

Supported relations are:
  • hasOne
  • hasMany
  • belongsTo
  • belongsToMany
  • embedsOne
  • embedsMany
Example:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function items()
    {
        return $this->hasMany('Item');
    }

}
And the inverse relation:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Item extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}
The belongsToMany relation will not use a pivot "table", but will push id's to a related_ids attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to null:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function groups()
    {
        return $this->belongsToMany('Group', null, 'user_ids', 'group_ids');
    }

}
Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships

EmbedsMany Relations

If you want to embed models, rather than referencing them, you can use the embedsMany relation. This relation is similar to the hasMany relation, but embeds the models inside the parent object.
REMEMBER: these relations return Eloquent collections, they don't return query builder objects!
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function books()
    {
        return $this->embedsMany('Book');
    }

}
You can access the embedded models through the dynamic property:
$books = User::first()->books;
The inverse relation is automagically available, you don't need to define this reverse relation.
$user = $book->user;
Inserting and updating embedded models works similar to the hasMany relation:
$book = new Book(['title' => 'A Game of Thrones']);

$user = User::first();

$book = $user->books()->save($book);
// or
$book = $user->books()->create(['title' => 'A Game of Thrones'])
You can update embedded models using their save method (available since release 2.0.0):
$book = $user->books()->first();

$book->title = 'A Game of Thrones';

$book->save();
You can remove an embedded model by using the destroy method on the relation, or the delete method on the model (available since release 2.0.0):
$book = $user->books()->first();

$book->delete();
// or
$user->books()->destroy($book);
If you want to add or remove an embedded model, without touching the database, you can use the associate and dissociate methods. To eventually write the changes to the database, save the parent object:
$user->books()->associate($book);

$user->save();
Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:
return $this->embedsMany('Book', 'local_key');
Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections

EmbedsOne Relations

The embedsOne relation is similar to the embedsMany relation, but only embeds a single model.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Book extends Eloquent {

    public function author()
    {
        return $this->embedsOne('Author');
    }

}
You can access the embedded models through the dynamic property:
$author = Book::first()->author;
Inserting and updating embedded models works similar to the hasOne relation:
$author = new Author(['name' => 'John Doe']);

$book = Books::first();

$author = $book->author()->save($author);
// or
$author = $book->author()->create(['name' => 'John Doe']);
You can update the embedded model using the save method (available since release 2.0.0):
$author = $book->author;

$author->name = 'Jane Doe';
$author->save();
You can replace the embedded model with a new model like this:
$newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor);

MySQL Relations

If you're using a hybrid MongoDB and SQL setup, you're in luck! The model will automatically return a MongoDB- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need use the Jenssegers\Mongodb\Eloquent\HybridRelations trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.
Example SQL-based User model:
use Jenssegers\Mongodb\Eloquent\HybridRelations;

class User extends Eloquent {

    use HybridRelations;

    protected $connection = 'mysql';

    public function messages()
    {
        return $this->hasMany('Message');
    }

}
And the Mongodb-based Message model:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Message extends Eloquent {

    protected $connection = 'mongodb';

    public function user()
    {
        return $this->belongsTo('User');
    }

}

Raw Expressions

These expressions will be injected directly into the query.
User::whereRaw(['age' => array('$gt' => 30, '$lt' => 40)])->get();
You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models. If this is executed on the query builder, it will return the original response.
// Returns a collection of User models.
$models = User::raw(function($collection)
{
    return $collection->find();
});

// Returns the original MongoCursor.
$cursor = DB::collection('users')->raw(function($collection)
{
    return $collection->find();
});
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible:
$model = User::raw()->findOne(['age' => array('$lt' => 18)]);
The internal MongoClient and MongoDB objects can be accessed like this:
$client = DB::getMongoClient();
$db = DB::getMongoDB();

MongoDB specific operations

Cursor timeout
To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor:
DB::collection('users')->timeout(-1)->get();

Upsert
Update or insert a document. Additional options for the update method are passed directly to the native update method.
DB::collection('users')->where('name', 'John')
                       ->update($data, ['upsert' => true]);
Projections
You can apply projections to your queries using the project method.
DB::collection('items')->project(['tags' => ['$slice' => 1]])->get();
DB::collection('items')->project(['tags' => ['$slice' => [3, 7]]])->get();

Projections with Pagination
$limit = 25;
$projections = ['id', 'name'];
DB::collection('items')->paginate($limit, $projections);

Push
Add items to an array.
DB::collection('users')->where('name', 'John')->push('items', 'boots');
DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
If you don't want duplicate items, set the third parameter to true:
DB::collection('users')->where('name', 'John')->push('items', 'boots', true);

Pull
Remove an item from an array.
DB::collection('users')->where('name', 'John')->pull('items', 'boots');
DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);

Unset
Remove one or more fields from a document.
DB::collection('users')->where('name', 'John')->unset('note');
You can also perform an unset on a model.
$user = User::where('name', 'John')->first();
$user->unset('note');

Query Caching

You may easily cache the results of a query using the remember method:
$users = User::remember(10)->get();
From: http://laravel.com/docs/queries#caching-queries

Query Logging

By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the disableQueryLog method:
DB::connection()->disableQueryLog();
From: http://laravel.com/docs/database#query-logging


Thursday 2 May 2019

Step by step guide to creating an admin form in Drupal 8

Hi Everybody,

In this blog we will focus on how to create a admin form in Drupal 8. Creating an admin form is often one of the first things you'll need to do in a custom Drupal module. An admin interface enables you to make a module's settings configurable by a site editor or administrator so they can change them on the fly.

If you've created admin forms in Drupal 7 previously, you'll see some pretty big differences in the way you define forms between Drupal 7 and Drupal 8, and there are still a lot of similarities. Forms are represented as nested arrays in both Drupal 7 and Drupal 8. But they are different in that in Drupal 7 you define your form arrays in functions and in Drupal 8 you create a form class.

In this step by step tutorial, you are going to learn how to create an admin form in Drupal 8 with a route and menu item and then use the saved form data.

It is worth pointing out that you could create most of this code with the Drupal Console. However, the best way to truly learn it is to write the code without using tools like Console to create it for you. After that, it is a create idea to use Drupal Console to create code like this for you.

Step 1: Module setup

Create the module folder


    Create a new directory in /sites called all
    Inside all create a directory called modules
    Inside modules create a directory called custom
    Create the directory called welcome inside the custom directory

Create the YAML info file


The info YAML file tells Drupal that your module exists and provides important information, such as its human readable name, machine name, description and version number.

The filename should be the machine name of your module with the .info.yml extension. In this case, it will be welcome.info.yml.

Create welcome.info.yml in the root of the welcome directory.

Add the following to welcome.info.yml:

name: Welcome  
type: module  
description: Display a message when a user logs in  
core: 8.x  
package: Custom 

The info.yml file is all you need to register the module with the Drupal system. If you head on over to Extend, you will see the Welcome module listed.

You can go ahead and enable the module (click install at the bottom of the Extend page or use Drush).
Setup the rest of the files and folders

Setup the following files and folders in the welcome module folder:

    Create a file called welcome.routing.yml.
    Create a file called welcome.links.menu.yml.
    Create a file called welcome.module
    Create a folder called src.
    In the src folder, create a new folder called Form.
    In the Form folder, create a file called MessagesForm.php.

Step 2: Create form


There are a few parts to creating an admin form:

    The form itself
    A route mapping the form to a URL, so that you can access it
    A menu item in Drupal’s menu system, so that it can be accessed from the admin menu

Set out basic class


In MessagesForm.php, set out the basic class:

<?php  
/**  
 * @file  
 * Contains Drupal\welcome\Form\MessagesForm.  
 */  
namespace Drupal\welcome\Form;  
use Drupal\Core\Form\ConfigFormBase;  
use Drupal\Core\Form\FormStateInterface;  

class MessagesForm extends ConfigFormBase {  

}  

ConfigFormBase is a base class that is used to implement system configuration forms.

Methods to use


You are going to add the following methods to this class:

    getEditableConfigNames() - gets the configuration name
    getFormId() - returns the form’s unique ID
    buildForm() - returns the form array
    validateForm() - validates the form
    submitForm() - processes the form submission

Add getEditableConfigNames() and getFormId()


Start off by adding getEditableConfigNames() and getFormId():

<?php  

/**  
 * @file  
 * Contains Drupal\welcome\Form\MessagesForm.  
 */  

namespace Drupal\welcome\Form;  

use Drupal\Core\Form\ConfigFormBase;  
use Drupal\Core\Form\FormStateInterface;  

class MessagesForm extends ConfigFormBase {  
  /**  
   * {@inheritdoc}  
   */  
  protected function getEditableConfigNames() {  
    return [  
      'welcome.adminsettings',  
    ];  
  }  

  /**  
   * {@inheritdoc}  
   */  
  public function getFormId() {  
    return 'welcome_form';  
  }  
}  

The buildForm() method


Next you can add the buildForm method to the MessagesForm class.

  /**  
   * {@inheritdoc}  
   */  
  public function buildForm(array $form, FormStateInterface $form_state) {  
    $config = $this->config('welcome.adminsettings');  

    $form['welcome_message'] = [  
      '#type' => 'textarea',  
      '#title' => $this->t('Welcome message'),  
      '#description' => $this->t('Welcome message display to users when they login'),  
      '#default_value' => $config->get('welcome_message'),  
    ];  

    return parent::buildForm($form, $form_state);  
  }  

Breakdown of buildForm()

Let’s break this down and see what each part is doing. 

$config = $this->config('welcome.adminsettings');  

This initialises the config variable. welcome.adminsettings is the module's configuration name, so this will load the admin settings.  

There is just one element to this form, the welcome message textarea:

      $form['welcome_message'] = [  
        '#type' => 'textarea',  
        '#title' => $this->t('Welcome message'),  
        '#description' => $this->t('Welcome message display to users when they login'),  
        '#default_value' => $config->get('welcome_message'),  
      ];  

The default value is returned from the configuration object. It calls the get() method with the name of the property to get, which is welcome_message. You will add the code to save this when the form saves shortly.

The title and description are displayed when you view the form.

The submitForm() method


Next you can add the submitForm method.

  /**  
   * {@inheritdoc}  
   */  
  public function submitForm(array &$form, FormStateInterface $form_state) {  
    parent::submitForm($form, $form_state);  

    $this->config('welcome.adminsettings')  
      ->set('welcome_message', $form_state->getValue('welcome_message'))  
      ->save();  
  }  

The submitForm() method is responsible for saving the form data when the form is submitted. Take a look at the code inside the method:

    $this->config('welcome.adminsettings')  
      ->set('welcome_message', $form_state->getValue('welcome_message'))  
      ->save();  

Let’s break this down line by line:

    $this is the admin settings form class.
    -> is an object operator
    config('welcome.adminsettings’): welcome.adminsettings is the name of the module's configuration.
    ->set('welcome_message', $form_state->getValue('welcome_message’)): here it is setting ‘welcome_message’ and get the values from the form state.
    ->save: save the form data.

Setting and Getting Configuration Objects


In the previous section, you have set the value for a configuration object in the submit function. And then in the method which defines the form, you have retrieved the configuration and configuration setting.

In submitForm(), retrieve the configuration:

$this->config('welcome.adminsettings')  

Also in submitForm(), set the configuration setting:

 ->set('welcome_message', $form_state->getValue('welcome_message'))  

In buildForm(), retrive the configuration:

$config = $this->config('welcome.adminsettings');  

Also in buildForm(), get the configuration setting:

$config->get('welcome_message'),  

Drupal 8 form configuration

Step 3: Access the form

The route


In order to access the form you just created, you need to add a route for it. This will map the URL to the form.

Open up welcome.routing.yml and add the following route:

welcome.admin_settings_form:  
  path: '/admin/config/welcome/adminsettings'  
  defaults:  
    _form: '\Drupal\welcome\Form\MessagesForm'  
    _title: 'MessagesForm'  
  requirements:  
    _permission: 'access administration pages'  
  options:  
    _admin_route: TRUE  

The route is mapping to a form controller (\Drupal\welcome\Form\MessagesForm). When you go to /admin/config/welcome/adminsettings you will get that form.













If you add a message and submit the form and then refresh the page, the message will remain in the textarea as it is now saved to the database and used as the default message for the form field.

Clear the cache and then go to /admin/config/welcome/adminsettings to get the form.
Menu item

With the route mapped to the form controller, you can hit the URL to get the form.  To make this more useful, we need to add it to Drupal’s menu system. 

As mentioned previously, Drupal 8 defines menu items in a .yml file. Add the following to welcome.links.menu.yml:

welcome.admin_settings_form:  
  title: 'Welcome message configuration'  
  route_name: welcome.admin_settings_form  
  description: 'Welcome message admin'  
  parent: system.admin_config_system  
  weight: 99  

Let’s break this down:

    Title: This will appear as the menu link. 
    Route: This is the route that you defined earlier. This maps to the form class.
    Description: This will appear under the title
    Parent: This menu item will be nested under the parent menu item
    Weight: This determines the relative positioning of the menu item in relation to its siblings

After you clear the cache, you should now see this in menu item under admin/config.

Step 4: use the form data


You could use the saved form data in a variety of places. To demonstrate its use, you are how to show the saved message to users when they login to the site.

To do that, you need to add an implementation of hook_user_login() to retrieve the config value.

In welcome.module, create welcome_user_login():

<?php

/**
 * @file
 * Contains welcome.module.
 */

function welcome_user_login() {

}

You can get the configuration for the module using the Drupalconfig() static method with the name of the module’s configuration (welcome.adminsettings).

$config = \Drupal::config('welcome.adminsettings');  

And then get the value for the welcome_message property with the get() method:

$config->get('welcome_message')  

Putting it all together in the hook implementation:

function welcome_user_login($account) {  
  $config = \Drupal::config('welcome.adminsettings');  
  drupal_set_message($config->get('welcome_message'));  
}  

Next, clear the cache for the changes to take effect.

And now, when you log out of the site and log back in again, you should see the message.
Wrapping up

You have created a simple admin form, saved the value to the database and then used that saved value and displayed it to users when they login.