我尝试在自定义模块中为drupal 8在文本字段中实现自动完成
我想要的只是获取并显示通过自动完成输入的可能标题,因此在文件夹目录-> mymodule / src / Controller / DefaultController.php中的DefaultController.php中的类中声明了一个公共函数自动完成。
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
class DefaultController extends ControllerBase
{
public function autocomplete($string)
{
$matches = array();
$db = \Drupal::database();
$result = $db->select('node_field_data', 'n')
->fields('n', array('title', 'nid'))
->condition('title', '%'.db_like($string).'%', 'LIKE')
->addTag('node_access')
->execute();
foreach ($result as $row) {
$matches[$row->nid] = check_plain($row->title);
}
return new JsonResponse($matches);
}
}
然后在文件夹目录-> mymodule / src / Form / EditForm.php中创建一个EditForm.php
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class EditForm extends FormBase
{
public function getFormId()
{
return 'mymodule_edit_form';
}
public function buildForm(array $form, FormStateInterface $form_state)
{
$form = array();
$form['input_fields']['nid'] = array(
'#type' => 'textfield',
'#title' => t('Name of the referenced node'),
'#autocomplete_route_name' => 'mymodule.autocomplete',
'#description' => t('Node Add/Edit type block'),
'#default' => ($form_state->isValueEmpty('nid')) ? null : ($form_state->getValue('nid')),
'#required' => true,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Create'),
);
return $form;
}
}
还创建了mymodule.routing.yml
mymodule.autocomplete:
path: '/mymodule/autocomplete'
defaults:
_controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
requirements:
_permission: 'access content'
仍然无法实现自动完成功能?有人可以指出我在想什么吗?
您还需要传递参数drupal.org/node/2070985
—
Shreya Shetty
@ShreyaShetty不,我不需要参数,因为在d7中我会使用'#autocomplete_path'=>'mymodule / autocomplete',所以在d8中我使用了'#autocomplete_route_name'=>'mymodule.autocomplete',所以我从不使用参数我也不需要一个....
—
化妆我活