Last active
February 16, 2018 13:01
-
-
Save druman/6e0f97cccc71f2ab711503d014bd0015 to your computer and use it in GitHub Desktop.
Drupal 8 Form API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// /src/Form/CollectPhone.php | |
namespace Drupal\helloworld\Form; | |
use Drupal\Core\Form\FormBase; | |
use Drupal\Core\Form\FormStateInterface; // work witd data | |
/** | |
* Build CollectForm | |
*/ | |
class CollectPhone extends FormBase { | |
public function getFormId() { | |
return 'collect_phone'; | |
} | |
/** | |
* Создание нашей формы. | |
* | |
* {@inheritdoc}. | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
// Объявляем телефон. | |
$form['phone_number'] = array( | |
'#type' => 'tel', | |
// Не забываем из Drupal 7, что t, в D8 $this->t() можно использовать | |
// только с английскими словами. Иначе не используйте t() а пишите | |
// просто строку. | |
'#title' => $this->t('Your phone number'), | |
'#default_value' => $config->get('phone_number') | |
); | |
$form['name'] = array( | |
'#type' => 'textfield', | |
'#title' => $this->t('Your name') | |
); | |
$form['actions']['#type'] = 'actions'; | |
$form['actions']['submit'] = array( | |
'#type' => 'submit', | |
'#value' => $this->t('Send name and phone'), | |
'#button_type' => 'primary', | |
); | |
return $form; | |
} | |
/** | |
* Валидация отправленых данных в форме. | |
* | |
* {@inheritdoc} | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
// Если длина имени меньше 5, выводим ошибку. | |
if (strlen($form_state->getValue('name')) < 5) { | |
$form_state->setErrorByName('name', $this->t('Name is too short.')); | |
} | |
} | |
/** | |
* Отправка формы. | |
* | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
drupal_set_message($this->t('Thank you @name, your phone number is @number', array( | |
'@name' => $form_state->getValue('name'), | |
'@number' => $form_state->getValue('phone_number') | |
))); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// create /src/Form/CollectPhoneSettings.php | |
/** | |
* @file | |
* Contains \Drupal\helloworld\Form\CollectPhoneSettings. | |
*/ | |
namespace Drupal\helloworld\Form; | |
use Drupal\Core\Form\ConfigFormBase; | |
use Drupal\Core\Form\FormStateInterface; | |
/** | |
* Defines a form that configures forms module settings. | |
*/ | |
class CollectPhoneSettings extends ConfigFormBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'collect_phone_settings'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
protected function getEditableConfigNames() { | |
// Возвращает названия конфиг файла. | |
// Значения будут храниться в файле: | |
// helloworld.collect_phone.settings.yml | |
return [ | |
'helloworld.collect_phone.settings', | |
]; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$config = $this->config('helloworld.collect_phone.settings'); | |
$form['default_phone_number'] = array( | |
'#type' => 'textfield', | |
'#title' => $this->t('Default phone number'), | |
'#default_value' => $config->get('phone_number'), | |
); | |
// Субмит наследуем от ConfigFormBase | |
return parent::buildForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
$values = $form_state->getValues(); | |
// Записываем значения в наш конфиг файл и сохраняем. | |
$this->config('helloworld.collect_phone.settings') | |
->set('phone_number', $values['default_phone_number']) | |
->save(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Hello World | |
description: 'HelloWorld module - Form API learning!' | |
type: module | |
core: 8.x | |
version: 1.0 | |
package: Examples | |
configure: collect_phone.admin_settings |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
collect_phone.form: | |
path: '/collect-phone' | |
defaults: | |
_title: 'Collect Phone - Form API example.' | |
_form: '\Drupal\helloworld\Form\CollectPhone' | |
requirements: | |
_permission: 'access content' | |
collect_phone.admin_settings: | |
path: '/admin/config/helloworld' | |
defaults: | |
_form: '\Drupal\helloworld\Form\CollectPhoneSettings' | |
_title: 'Settings for CollectPhone form.' | |
requirements: | |
_permission: 'administer site configuration' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// \Drupal\Core\Form\FormBuilderInterface | |
/* | |
ConfigFormBase - для создания форм с настройками (например: админ формы); | |
ConfirmFormBase - Формочка для подтвеждения чего-либо (например, подтверждение на удаление материала); | |
FormBase - Базовый класс для всех остальных типов форм | |
*/ | |
public function getFormId() { | |
return 'my_custom_form'; | |
} | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$form['name'] = array( | |
'#type' => 'textfield', | |
'#title' => 'Name', | |
); | |
return $form; | |
} | |
// Validation | |
// field_id - название элемента формы (ключ). | |
$form_state->getValue('field_id'); | |
// Получаем все значения формы. | |
$values = $form_state->getValues(); | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
if (strlen($form_state->getValue('name')) < 5) { | |
$form_state->setErrorByName('name', 'Name < 5 symbols'); | |
} | |
} | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
drupal_set_message($this->t('Your name is @name', array('@name' => $form_state->getValue('name')))); | |
} | |
// вызов формы из разных мест | |
$form = \Drupal::formBuilder()->getForm('Drupal\helloworld\Form\CollectPhone'); | |
// передать значение в форму | |
$form = \Drupal::formBuilder()->getForm('Drupal\helloworld\Form\CollectPhone', '+7 (800) 123-45-67'); | |
/** | |
* Implements hook_form_FORM_ID_alter(). | |
* Form ID: collect_phone | |
*/ | |
function helloworld_form_collect_phone_alter(&$form, &$form_state) { | |
$form['phone_number']['#description'] = t('Start with + and your country code.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment