Я работаю с drupal 8 и создаю пользовательскую форму в папке /src/Form
с ajax. Сейчас я пытаюсь показать форму в файле ветки. но он не отображается.
Любой совет?
Заранее спасибо.
modules / custom / my_module / src / Form / SimpleForm. php
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
/**
* Our simple form class.
*/
class SimpleForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_module';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
//$form = parent::buildForm($form, $form_state);
$form['#theme'] = 'simple_form';
$form['massage'] = [
'#type' => 'markup',
'#markup' => '<div class="result_message"></div>',
];
$form['number_1'] = [
'#type' => 'textfield',
'#title' => $this->t('First number'),
];
$form['number_2'] = [
'#type' => 'textfield',
'#title' => $this->t('Second number'),
];
$form['actions'] = [
'#type' => 'button',
'#value' => $this->t('Calculate'),
'#ajax' => [
'callback' => '::setMessage',
]
];
return $form;
}
public function setMessage(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(
new HtmlCommand(
'.result_message',
'<div class="my_top_message">' . $this->t('The result is @result', ['@result' => ($form_state->getValue('number_1') + $form_state->getValue('number_2'))])
)
);
return $response;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
modules / custom / my_module / my_module.module
<?php
/**
* Implements hook_theme().
*/
function my_module_theme($existing, $type, $theme, $path)
{
return [
'simple_form' => [
'render element' => 'form',
],];}
файл маршрутизации
my_module.simple_form:
path: 'simple-form'
defaults:
_form: '\Drupal\my_module\Form\SimpleForm'
_title: 'my custom form'
requirements:
_permission: 'access content'
modules / custom / my_module / templates / simple-form. html .twig
<h4>{{form.form_number_1}}</h4>