텍스트 필드에 자동 완성 추가


10

사용자 정의 모듈에서 drupal 8의 텍스트 필드에 자동 완성을 구현하려고했습니다.

내가 원하는 것은 자동 완성을 통해 입력 한 가능성있는 제목을 가져 와서 표시하는 것이므로 폴더 디렉토리의 DefaultController.php 클래스 내에서 public function autocomplete를 선언했습니다.-> 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);
    }
}

그런 다음 폴더 디렉토리에 EditForm.php를 생성했습니다-> 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;
    }
}

또한 mymodule.routing.yml을 만들었습니다.

  mymodule.autocomplete:
  path: '/mymodule/autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
  requirements:
    _permission: 'access content'

여전히 자동 완성 기능이 구현되지 않습니까? 아무도 내가 잃어버린 것을 지적 할 수 있습니까 ??


당신은 또한 매개 변수를 전달해야 drupal.org/node/2070985
SHREYA 셰티

1
@ShreyaShetty 아니요 d7에서는 '#autocomplete_path'=> 'mymodule / autocomplete'를 사용했기 때문에 매개 변수가 필요하지 않으므로 d8에서는 '#autocomplete_route_name'=> 'mymodule.autocomplete'를 사용하므로 매개 변수를 사용하지 않았습니다.
나도

답변:


10

클래스는 요청을 확인하고 $ string에 넣는 데 필요한 수정이 필요합니다.

<?php

namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Unicode;

class DefaultController extends ControllerBase
{

  /**
   * Returns response for the autocompletion.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object containing the search string.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing the autocomplete suggestions.
   */

  public function autocomplete(request $request) {
    $matches = array();
    $string = $request->query->get('q');
    if ($string) {
      $matches = array();
      $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('title', '%'.db_like($string).'%', 'LIKE');
      //->condition('field_tags.entity.name', 'node_access');
      $nids = $query->execute();
      $result = entity_load_multiple('node', $nids);
      foreach ($result as $row) {
        //$matches[$row->nid->value] = $row->title->value;
        $matches[] = ['value' => $row->nid->value, 'label' => $row->title->value];
      }
    }
    return new JsonResponse($matches);
  }
}

여전히 요청을 가져 와서 $ 문자열로를 배치 한 후 작동하지 않았다
메이크업 - 날 - 살아

요청이 인쇄되었는지 확인 했습니까?
vgoradiya

나는 \Drupal::entityQuery('node')선택과는 별도로 사용하는 것이 바람직 하다고 생각 합니다.
vgoradiya

브라우저의 개발 도구에서 네트워크 탭을 본 후 응답에서 적절한 결과를 볼 수 있었지만 UI에는 표시되지 않았습니다. 약간의 파기 후에 z-index양식이 포함 된 DOM 요소에 a를 설정하는 사용자 정의 CSS가 있음을 발견했습니다 . 값이 너무 커서 자동 완성 결과가 겹쳤습니다. 내 관습을 낮추면 z-index문제가 해결되었습니다.
tyler.frankenstein

11

엔터티를 선택하려면 더 쉬운 방법이 있습니다. Drupal 8에는 표준 entity_autocomplete 필드 유형이 있습니다. 양식 요소를 다음과 같이 지정하십시오.

$form['node'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
];

자세한 정보는 사용자 정의 자동 완성 필드 를 참조하십시오.

또한 노드 / 엔티티 테이블에 대해 데이터베이스 쿼리를 수행하지 마십시오. 이를 위해 \ Drupal :: entityQuery ()를 사용하십시오.


안녕하세요 Berdir, 노드에 대해서는 완벽하게 작동하지만 taxanomy에는 작동하지 않으므로 위의 코드를 사용하여 내 경우 "city"에서 taxanomy에서 데이터를 얻는 방법 ??
Sachin

5
  1. routing.yml 파일을 작성하고 다음 코드를 추가하십시오 : admin_example.autocomplete :

:

  path: '/admin_example/autocomplete'
  defaults:
    _controller: '\Drupal\admin_example\Controller\AdminNotesController::autocomplete'
  requirements:
    _permission: 'access content'
  1. mymodule / src / Form / EditForm.php에서 빌드 한 형식이 정확합니다.

컨트롤러에서 코드를 변경해야합니다. 코드는 다음과 같습니다.

public function autocomplete(Request $request)
{
 $string = $request->query->get('q');
    $matches = array();
      $query = db_select('node_field_data', 'n')
          ->fields('n', array('title', 'nid'))
          ->condition('title', $string . '%', 'LIKE')
          ->execute()
          ->fetchAll();
    foreach ($query as $row) {
        $matches[] = array('value' => $row->nid, 'label' => $row->title);
    }

    return new JsonResponse($matches);
}

안녕하세요 Shreya, 귀하의 솔루션을 사용했지만 양식으로 이동하는 대신 [{ "value": "1", "label": "Patel Residency"}, { "value": " 2 ","label ":"Jain Plaza "}, {"value ":"3 ","label ":"Kanha Resort "}, {"value ":"38 ","label ":"Hira Residency "} ]. 양식으로 이동하고 필드가 자동 완성으로 작동해야합니다.
Sachin

2

@vgoradiya 코드를 사용하고 foreach 루프에서 다음과 같이 시도하십시오.

    foreach ($result as $row)
    {
        $matches[] = ['value' => $row->nid, 'label' => check_plain($row->title)];
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.