[D8] Alterar campo de formulario para añadirle autocompletado

drupal autocomplete

Primero debemos crear un Controller que sea el que devuelva el json para rellenar el autocomplete.

<?php

namespace Drupal\banners\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Unicode;


class CampaingsController extends ControllerBase
{
    public function autocomplete($string='')
    {
        $matches = [];
        $campaigns = explode(",", trim(\Drupal::config('banners.bannerconfig')->get('campaign')));


        foreach ($campaigns as $campaing) {
            $matches[] = ['value' => trim($campaing), 'label' => trim($campaing)];
        }

        return new JsonResponse($matches);
    }
}

Comprobado que ésto devuelve el contenido deseado, en mi_modulo.routing.yml definimos el autocomplete:

banners.campaings_autocomplete:
  path: '/banners/campaings_autocomplete'
  defaults:
    _controller: '\Drupal\banners\Controller\CampaingsController::autocomplete'
  requirements:
    _permission: 'access content'

 

Y ahora ya podemos acceder al autocompete, en mi caso se lo he puesto a un campo via un hook_form_alter:

$form['field_campana']['#type'] = 'textfield'; //asegurémonos que el campo es un "textfield"
$form['field_campana']['#autocomplete_route_name'] = 'banners.campaings_autocomplete';

Ahora debería funcionar :-)

drupal8

Añadir nuevo comentario

Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, refresh the CAPTCHA or submit the form and a new image will be generated. Not case sensitive.