I tried to implement an autocomplete in text-field for drupal 8 in my custom module
all I wanted was to fetch and display the likely title I typed via autocomplete so declared a public function autocomplete within a class in DefaultController.php in folder directory -->mymodule/src/Controller/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);
}
}
then created an EditForm.php in folder directory -->mymodule/src/Form/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;
}
}
also created mymodule.routing.yml
mymodule.autocomplete:
path: '/mymodule/autocomplete'
defaults:
_controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
requirements:
_permission: 'access content'
still autocomplete functionality not getting implemented ? Can anybody point me what am i missing ??