Answer the question
In order to leave comments, you need to log in
Form output in twig Drupal 8?
I'm trying to display a custom form module in the twig
WebinarForm.php template engine
<?php
namespace Drupal\webinar_form\Form;
use Drupal\Core\Form\FormBase; // Базовый класс Form API
use Drupal\Core\Form\FormStateInterface; // Класс отвечает за обработку данных
/**
* Наследуемся от базового класса Form API
* @see \Drupal\Core\Form\FormBase
*/
class WebinarForm extends FormBase
{
// метод, который отвечает за саму форму - кнопки, поля
public function buildForm(array $form, FormStateInterface $form_state)
{
$form['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Ваше имя'),
'#description' => $this->t('Имя не должно содержать цифр'),
'#required' => TRUE,
];
$form['title1'] = [
'#type' => 'textfield',
'#title' => $this->t('Ваше имя1'),
'#description' => $this->t('Имя не должно содержать цифр'),
'#required' => TRUE,
];
// Add a submit button that handles the submission of the form.
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Отправить форму'),
];
$form['#theme'] = 'webinar_form';
return $form;
}
// метод, который будет возвращать название формы
public function getFormId()
{
return 'webinar_form';
}
// ф-я валидации
public function validateForm(array &$form, FormStateInterface $form_state)
{
$title = $form_state->getValue('title');
$is_number = preg_match("/[\d]+/", $title, $match);
if ($is_number > 0) {
$form_state->setErrorByName('title', $this->t('Строка содержит цифру.'));
}
}
// действия по сабмиту
public function submitForm(array &$form, FormStateInterface $form_state)
{
$title = $form_state->getValue('title');
drupal_set_message(t('Вы ввели: %title.', ['%title' => $title]));
}
}
<?php
/*
function webinar_form_theme($existing, $type, $theme, $path) {
return array(
$theme['webinar_form'] => [
'render element' => 'form',
]
);
}
*/
function webinar_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'webinar_form') {
$form['#theme'] = 'webinar_form';
}
}
/**
* Implements hook_theme().
*/
/*
function webinar_form_theme($existing, $type, $theme, $path) {
$info = [
'webinar_form' => [
'render element' => 'form',
'path' => drupal_get_path('module', 'mymodulename'),
],
];
return $info;
}
*/
webinar_form.routing:
path: '/webinars'
defaults:
_title: 'Webinar Form'
_form: '\Drupal\webinar_form\Form\WebinarForm'
requirements:
_permission: 'access content'
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question