Chia sẻ 1 số Ajax Command khá hay trong Drupal 8

Chia sẻ 1 số Ajax Command khá hay trong Drupal 8

Everyone understands how the usual configuration form works, created using the Form API. The user clicks the Save button: the page reloads, the form is updated. But what if we need to change some form values without reloading the page?

<?php

/**
* @file
* Contains Drupal\ajax_example\AjaxExampleForm
*/

namespace Drupal\ajax_example\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class AjaxExampleForm extends FormBase {

  public function getFormId() {
    return 'ajax_example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['user_name'] = array(
      '#type' => 'textfield',
      '#title' => 'Username',
      '#description' => 'Please enter in a username',
      '#ajax' => array(
        // Function to call when event on form element triggered.
        'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::usernameValidateCallback',
        // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
        'effect' => 'fade',
        // Javascript event to trigger Ajax. Currently for: 'onchange'.
        'event' => 'change',
        'progress' => array(
          // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
          'type' => 'throbber',
          // Message to show along progress graphic. Default: 'Please wait...'.
          'message' => NULL,
        ),
      ),
    );

    $form['random_user'] = array(
      '#type' => 'button',
      '#value' => 'Random Username',
      '#ajax' => array(
        'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::randomUsernameCallback',
        'event' => 'click',
        'progress' => array(
          'type' => 'throbber',
          'message' => 'Getting Random Username',
        ),

      ),
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message('Nothing Submitted. Just an Example.');
  }

  public function usernameValidateCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();

    // Check if Username exists and is not Anonymous User ('').
    if (user_load_by_name($form_state->getValue('user_name')) && $form_state->getValue('user_name') != false) {
      $text = 'User Found';
      $color = 'green';
    } else {
      $text = 'No User Found';
      $color = 'red';
    }

    // Add a command to execute on form, jQuery .html() replaces content between tags.
    // In this case, we replace the desription with wheter the username was found or not.
    $ajax_response->addCommand(new HtmlCommand('#edit-user-name--description', $text));

    // CssCommand did not work.
    //$ajax_response->addCommand(new CssCommand('#edit-user-name--description', array('color', $color)));

    // Add a command, InvokeCommand, which allows for custom jQuery commands.
    // In this case, we alter the color of the description.
    $ajax_response->addCommand(new InvokeCommand('#edit-user-name--description', 'css', array('color', $color)));

    // Return the AjaxResponse Object.
    return $ajax_response;
  }

  public function randomUsernameCallback(array &$form, FormStateInterface $form_state) {
    // Get all User Entities.
    $all_users = entity_load_multiple('user');

    // Remove Anonymous User.
    array_shift($all_users);

    // Pick Random User.
    $random_user = $all_users[array_rand($all_users)];

    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();

    // ValCommand does not exist, so we can use InvokeCommand.
    $ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'val' , array($random_user->get('name')->getString())));

    // ChangedCommand did not work.
    //$ajax_response->addCommand(new ChangedCommand('#edit-user-name', '#edit-user-name'));

    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'change'));

    // Return the AjaxResponse Object.
    return $ajax_response;
  }
}
Bạn thấy bài viết này như thế nào?: 
Average: 9.8 (4 votes)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Bình luận (0)

 

Add Comment

Filtered HTML

  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Các thẻ HTML được chấp nhận: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Tự động ngắt dòng và đoạn văn.

Plain text

  • No HTML tags allowed.
  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Tự động ngắt dòng và đoạn văn.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Sức mạnh tiềm tàng website: tối ưu Domain Authority

Sức mạnh tiềm tàng website: tối ưu Domain Authority

Domain Authority là một đơn vị xếp hạng biểu diễn từ 0 đến 100 trên tất cả các tên miền dựa vào khoảng hơn 150 yếu tố được phân tích từ thứ hạng website trên Google

Bill Gates: Máy tính bảng không thích hợp cho giáo dục

Bill Gates: Máy tính bảng không thích hợp cho giáo dục

Đồng sáng lập Microsoft, Bill Gates nghĩ rằng MTB không thể đáp ứng các nhu cầu của giáo dục. Thay vào đó, ông cho rằng máy tính giá thấp sẽ là một giải pháp tốt vì nó sẽ giúp sinh viên có thể tương tác tốt hơn.

Hướng dẫn cài đặt Drupal VM PHP 7.0.x (configurable) trên Windows

Hướng dẫn cài đặt Drupal VM PHP 7.0.x (configurable) trên Windows

Drupal VM is a virtual machine that contains many convenient utilities for local Drupal development

Công ty diệt chuột T&C

 

Diet con trung