텍스트 필드에 자동 완성 추가 구현하려고했습니다. 내가 원하는 것은 자동 완성을

사용자 정의 모듈에서 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'

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



답변

클래스는 요청을 확인하고 $ 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);
  }
}

답변

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

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

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

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


답변

  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);
}

답변

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

    foreach ($result as $row)
    {
        $matches[] = ['value' => $row->nid, 'label' => check_plain($row->title)];
    }