【问题标题】:Drupal - Ajax validation only works when I am connectedDrupal - Ajax 验证仅在我连接时有效
【发布时间】:2019-12-15 12:26:53
【问题描述】:

我是 Drupal 世界的新手,我正在尝试使用 Drupal From API 创建一个带有 Ajax 验证的联系表单。

我面临两个问题:

  • 我的以下表单(见下文)运行良好,但仅当用户以管理员身份连接时。当我没有以管理员身份登录时,它不起作用。

  • 我还创建了一个自定义块来显示我的表单,不幸的是,当我登录时该块没有出现。

我尝试遵循本指南但没有成功:https://panshul1410.blog/2018/07/15/drupal-8-ajax-validations-for-custom-form/

这是我创建的表单:

<?php

namespace Drupal\dalcom_contact\Form;

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

class DalcomContactForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'dlcm_cform';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $params = NULL) {

    // Disable caching.
    $form['#cache']['max-age'] = 0;

    // Disable browser HTML5 validation.
    $form['#attributes']['novalidate'] = 'novalidate';

    // This will generate an anchor scroll to the form when submitting.
    $form['#action'] = '#dlcm_cform';

    $form['mail_visitor'] = [
      '#type' => 'email',
      '#placeholder' => t('E-mail*'),
      '#description' => 'Your mail',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => 'Drupal\dalcom_contact\Form\DalcomContactForm::mailValidateCallback',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => [
          'type' => 'throbber',
          'message' => NULL,
        ],
      ],
    ];

    $form['message_visitor'] = [
      '#type' => 'textarea',
      '#placeholder' => t('Message*'),
      '#description' => 'Your message',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => 'Drupal\dalcom_contact\Form\DalcomContactForm::messValidateCallback',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => [
          'type' => 'throbber',
          'message' => NULL,
        ],
      ],
    ];

    $form['accept_box'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('I accept the CME terms of use'),
      '#required' => TRUE,
      '#ajax' => [
        'callback' => 'Drupal\dalcom_contact\Form\DalcomContactForm::acceptboxalidateCallback',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => [
          'type' => 'throbber',
          'message' => NULL,
        ],
      ],
    ];

    $form['candidate_copy'] = [
      '#type' => 'checkbox',
      '#title' => t('Send me a copy of my message.'),
    ];

    $form['actions']['#type'] = 'actions';

    $form['actions']['submit'] = [
      '#type' => 'button',
      '#value' => $this->t('Send'),
      '#ajax' => [
        'event' => 'click',
        'progress' => [
          'type' => 'throbber',
          'message' => 'Sending...',
        ],

      ],
    ];

    $form['#theme'] = 'dalcom_contact_theme';

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }
  }

  public function mailValidateCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    if (!$form_state->getValue('mail_visitor') || empty($form_state->getValue('mail_visitor'))) {
      $text = 'No email registered';
      $color = 'red';
    }
    elseif (!filter_var($form_state->getValue('mail_visitor'), FILTER_VALIDATE_EMAIL)) {
      $text = 'Invalid email address';
      $color = 'red';
    }
    else {
      $text = 'Valid mail';
      $color = 'green';
    }

    $ajax_response->addCommand(new HtmlCommand('#edit-mail-visitor--description', $text));

    $ajax_response->addCommand(new InvokeCommand('#edit-mail-visitor--description', 'css', ['color', $color]));

    return $ajax_response;
  }

  public function messValidateCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    if (!$form_state->getValue('message_visitor') || empty($form_state->getValue('message_visitor'))) {
      $text = 'No messages written';
      $color = 'red';
    }
    elseif (strlen($form_state->getValue('message_visitor')) < 6) {
      $text = 'At least 7 characters';
      $color = 'red';
    }
    else {
      $text = 'Messages written';
      $color = 'green';
    }

    $ajax_response->addCommand(new HtmlCommand('#edit-message-visitor--description', $text));

    $ajax_response->addCommand(new InvokeCommand('#edit-message-visitor--description', 'css', ['color', $color]));

    return $ajax_response;
  }

  public function acceptboxValidateCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    if (empty($form_state->getValue('accept-box'))) {
      $text = 'You must accept our termes of use to continue';
      $color = 'red';
    }

    $ajax_response->addCommand(new HtmlCommand('#edit-accept-box--description', $text));

    $ajax_response->addCommand(new InvokeCommand('#edit-accept-box--description', 'css', ['color', $color]));

    return $ajax_response;
  }

}

效果很好。但是 Ajax 验证仅在我连接时有效。当我没有以管理员身份登录时,它不起作用。

这是在我的页脚中显示表单的块。

<?php

namespace Drupal\dalcom_contact_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;

/**
 * Provides a 'dalcom contact' block.
 *
 * @Block(
 *   id = "dalcom_contact_block",
 *   admin_label = @Translation("Dalcom Contact Block"),
 *   category = @Translation("Block du formulaire Dalcom Contact")
 * )
 */
class DalcomContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('\Drupal\dalcom_contact\Form\DalcomContactForm');
    return $form;
  }
}

正如上面解释的那样,当我登录时,该块不会出现。我只能通过我在module.routing.yml 中定义的路径访问表单。当它出现时(所以当我没有登录时),Ajax 在这个块表单上也不起作用。

有人知道是什么原因造成的吗? 请帮帮我。

已编辑:

这是module.routing.yml 文件

dalcom_contact.form:
  path: '/contact-us.html'
  defaults:
    _title: 'Contact Us'
    _form: 'Drupal\dalcom_contact\Form\DalcomContactForm'
  requirements:
    _permission: 'access content'

block.info.yml

name: Dalcom Contact Block
type: module
description: Block du formulaire Dalcom Contact.
core: 8.x
package: Custom
dependencies:
- node
- block

更新:

我注意到当表单没有出现时(当我连接时),它出现在它的位置

 <span data-big-pipe-placeholder-id="…"></span>

我已经对此进行了一些研究,但我无法摆脱它。也许这会帮助您了解发生了什么。

【问题讨论】:

  • 您能否也添加您的module.routing.yml
  • 嗨@KevinWenger 我添加了它
  • 嗨@KevinWenger!我为我的问题添加了更新
  • 我刚刚注意到 BigPipe 是一个默认安装的模块。我不知道它是否重要,无论如何,我然后将其卸载,现在无论我是否已连接,都会显示表单。所以现在剩下的真正问题是 Ajax,它在我连接之前无法工作。

标签: drupal-8 drupal-theming ajaxform


【解决方案1】:

我终于在 Drupal 论坛上找到了解决方案。我把它放在这里,也许它会帮助将来像我这样的新手。

缺少的只是匿名用户的基本 javascript 列表。似乎以前没有必要,但现在我们必须添加它们,否则它们不会为匿名用户加载。

所以我需要做的就是将它添加到我的 theme.libraries.yml 文件中

my_scripts:
  version: VERSION
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2016-05-22
    相关资源
    最近更新 更多