added example for developpers module

This commit is contained in:
Bachir Soussi Chiadmi
2018-01-06 11:28:03 +01:00
parent 5017966908
commit 5ec2f4311c
396 changed files with 26299 additions and 0 deletions
@@ -0,0 +1,14 @@
name: Email Example
type: module
description: Demonstrates how to send and alter Drupal-generated email messages.
package: Example modules
# core: 8.x
dependencies:
- examples:examples
- drupal:node
# Information added by Drupal.org packaging script on 2017-12-17
version: '8.x-1.x-dev'
core: '8.x'
project: 'examples'
datestamp: 1513537386
@@ -0,0 +1,4 @@
email_example.description:
title: 'E-mail Example: Contact Form'
description: 'Callback for generating form.'
route_name: email_example.description
@@ -0,0 +1,99 @@
<?php
/**
* @file
* Example of how to use Drupal's mail API.
*/
use Drupal\Component\Utility\SafeMarkup;
/**
* @defgroup email_example Example: Email
* @{
* Example of how to use Drupal's mail API.
*
* This example module provides two different examples of the Drupal email API:
* - Defines a simple contact form and shows how to use MailManager::mail()
* to send an e-mail (defined in hook_mail()) when the form is submitted.
* - Shows how modules can alter emails defined by other Drupal modules or
* core using hook_mail_alter by attaching a custom signature before
* they are sent.
*/
/**
* Implements hook_mail().
*
* This hook defines a list of possible e-mail templates that this module can
* send. Each e-mail is given a unique identifier, or 'key'.
*
* $message comes in with some standard properties already set: 'to' address,
* 'from' address, and a set of default 'headers' from MailManager::mail(). The
* goal of hook_mail() is to set the message's 'subject' and 'body' properties,
* as well as make any adjustments to the headers that are necessary.
*
* The $params argument is an array which can hold any additional data required
* to build the mail subject and body; for example, user-entered form data, or
* some context information as to where the mail request came from.
*
* Note that hook_mail() is not actually a hook. It is only called for a single
* module, the module named in the first argument of MailManager::mail(). So
* it's a callback of a type, but not a hook.
*/
function email_example_mail($key, &$message, $params) {
// Each message is associated with a language, which may or may not be the
// current user's selected language, depending on the type of e-mail being
// sent. This $options array is used later in the t() calls for subject
// and body to ensure the proper translation takes effect.
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
// Send a simple message from the contact form.
case 'contact_message':
$from = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('E-mail sent from @site-name', ['@site-name' => $from], $options);
// Note that the message body is an array, not a string.
$account = \Drupal::currentUser();
$message['body'][] = t('@name sent you the following message:', ['@name' => $account->getUsername()], $options);
// Because this is just user-entered text, we do not need to translate it.
// Since user-entered text may have unintentional HTML entities in it like
// '<' or '>', we need to make sure these entities are properly escaped,
// as the body will later be transformed from HTML to text, meaning
// that a normal use of '<' will result in truncation of the message.
$message['body'][] = SafeMarkup::checkPlain($params['message']);
break;
}
}
/**
* Implements hook_mail_alter().
*
* This function is not required to send an email using Drupal's mail system.
*
* hook_mail_alter() provides an interface to alter any aspect of email sent by
* Drupal. You can use this hook to add a common site footer to all outgoing
* email, add extra header fields, and/or modify the email in anyway. HTML-izing
* the outgoing email is one possibility.
*/
function email_example_mail_alter(&$message) {
// For the purpose of this example, modify all the outgoing messages and
// attach a site signature. The signature will be translated to the language
// in which message was built.
$options = [
'langcode' => $message['langcode'],
];
$signature = t("\n--\nMail altered by email_example module.", [], $options);
if (is_array($message['body'])) {
$message['body'][] = $signature;
}
else {
// Some modules use the body as a string, erroneously.
$message['body'] .= $signature;
}
}
/**
* @} End of "defgroup email_example".
*/
@@ -0,0 +1,6 @@
email_example.description:
path: 'examples/email-example'
defaults:
_form: '\Drupal\email_example\Form\EmailExampleGetFormPage'
requirements:
_permission: 'access content'
@@ -0,0 +1,148 @@
<?php
namespace Drupal\email_example\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Mail\MailManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
/**
* File test form class.
*
* @ingroup email_example
*/
class EmailExampleGetFormPage extends FormBase {
/**
* The mail manager.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Constructs a new EmailExampleGetFormPage.
*
* @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
* The mail manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(MailManagerInterface $mail_manager, LanguageManagerInterface $language_manager) {
$this->mailManager = $mail_manager;
$this->languageManager = $language_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.mail'),
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'email_example';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['intro'] = [
'#markup' => t('Use this form to send a message to an e-mail address. No spamming!'),
];
$form['email'] = [
'#type' => 'textfield',
'#title' => t('E-mail address'),
'#required' => TRUE,
];
$form['message'] = [
'#type' => 'textarea',
'#title' => t('Message'),
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Submit'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!valid_email_address($form_state->getValue('email'))) {
$form_state->setErrorByName('email', t('That e-mail address is not valid.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_values = $form_state->getValues();
// All system mails need to specify the module and template key (mirrored
// from hook_mail()) that the message they want to send comes from.
$module = 'email_example';
$key = 'contact_message';
// Specify 'to' and 'from' addresses.
$to = $form_values['email'];
$from = $this->config('system.site')->get('mail');
// "params" loads in additional context for email content completion in
// hook_mail(). In this case, we want to pass in the values the user entered
// into the form, which include the message body in $form_values['message'].
$params = $form_values;
// The language of the e-mail. This will one of three values:
// - $account->getPreferredLangcode(): Used for sending mail to a particular
// website user, so that the mail appears in their preferred language.
// - \Drupal::currentUser()->getPreferredLangcode(): Used when sending a
// mail back to the user currently viewing the site. This will send it in
// the language they're currently using.
// - \Drupal::languageManager()->getDefaultLanguage()->getId: Used when
// sending mail to a pre-existing, 'neutral' address, such as the system
// e-mail address, or when you're unsure of the language preferences of
// the intended recipient.
//
// Since in our case, we are sending a message to a random e-mail address
// that is not necessarily tied to a user account, we will use the site's
// default language.
$language_code = $this->languageManager->getDefaultLanguage()->getId();
// Whether or not to automatically send the mail when we call mail() on the
// mail manager. This defaults to TRUE, and is normally what you want unless
// you need to do additional processing before the mail manager sends the
// message.
$send_now = TRUE;
// Send the mail, and check for success. Note that this does not guarantee
// message delivery; only that there were no PHP-related issues encountered
// while sending.
$result = $this->mailManager->mail($module, $key, $to, $language_code, $params, $from, $send_now);
if ($result['result'] == TRUE) {
drupal_set_message(t('Your message has been sent.'));
}
else {
drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
}
}
}
@@ -0,0 +1,73 @@
<?php
namespace Drupal\Tests\email_example\Functional;
use Drupal\Core\Test\AssertMailTrait;
use Drupal\Tests\examples\Functional\ExamplesBrowserTestBase;
/**
* Tests for the email_example module.
*
* @ingroup email_example
*
* @group email_example
* @group examples
*/
class EmailExampleTest extends ExamplesBrowserTestBase {
use AssertMailTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['email_example'];
/**
* The installation profile to use with this test.
*
* @var string
*/
protected $profile = 'minimal';
/**
* Test our new email form.
*
* Tests for the following:
*
* - A link to the email_example in the Tools menu.
* - That you can successfully access the email_example page.
*/
public function testEmailExampleBasic() {
$assert = $this->assertSession();
// Test for a link to the email_example in the Tools menu.
$this->drupalGet('');
$assert->statusCodeEquals(200);
$assert->linkByHrefExists('examples/email-example');
// Verify if we can successfully access the email_example page.
$this->drupalGet('examples/email-example');
$assert->statusCodeEquals(200);
// Verifiy email form has email & message fields.
$assert->fieldValueEquals('edit-email', NULL);
$assert->fieldValueEquals('edit-message', NULL);
// Verifiy email form is submitted.
$edit = ['email' => 'example@example.com', 'message' => 'test'];
$this->drupalPostForm('examples/email-example', $edit, 'Submit');
$assert->statusCodeEquals(200);
// Verifiy comfirmation page.
$assert->pageTextContains('Your message has been sent.');
$this->assertMailString('to', $edit['email'], 1);
// Verifiy correct email recieved.
$from = \Drupal::config('system.site')->get('mail');
$this->assertMailString('subject', "E-mail sent from $from", 1);
$this->assertMailString('body', $edit['message'], 1);
$this->assertMailString('body', "\n--\nMail altered by email_example module.", 1);
}
}