簡體   English   中英

在 Drupal 中按下提交后如何調用服務

[英]How to invoke a service after pressing submit in Drupal

我對 Drupal 非常陌生,我被要求使用提交按鈕創建表單,並使用表單中的值向 API 發出獲取請求的服務。 API 是一個簡單的 API,用戶可以輸入一個國家/地區,它會返回來自該國家/地區的正確問候語的響應。

這是我的路由文件:

hello_world.salutation:
  path: '/hello'
  defaults:
    _controller: Drupal\hello_world\Controller\HelloWorldSalutation::salutation
    _form: Drupal\hello_world\Form\GreetingForm
    _title: 'Get a greeting from a different language'
  requirements:
    _permission: 'administer site configuration'

第一個問題是我不知道如何使表單和 controller 在同一路由中,第二個是當用戶輸入提交時我不知道如何調用該服務。

這是我的服務文件:

services:
  hello_world.salutation:
    class: Drupal\hello_world\HelloWorldSalutation
    arguments: [ '@config.factory' ,'@tempstore.private']
  cache.nameofbin:
    class: Drupal\Core\Cache\CacheBackendInterface
    tags:
      - { name: cache.bin }
    factory: [ '@cache_factory', 'get' ]
    arguments: [ nameofbin ]

為了簡單起見,我將跳過 GreetingFrom class 中的一些行,但如果需要,我可以添加它們。

這是來自 GreetingForm class 的 submitForm function。 這個想法是將輸入放在全局臨時存儲中,所以我想我可以訪問 controller 中的值。

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $search_str = $form_state->getValue('greeting');
    // check the input
    $params['items'] = $form_state->getValue('greeting');
    // 2. Create a PrivateTempStore object with the collection 'greetingForm_values'.
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    // 3. Store the $params array with the key 'params'.
    try {
      $tempstore->set('params', $params);
    } catch (\Exception $error) {
      // dump the error for now, read error, --fix this!
      dpm($error);
    }
  }

來自 controller 的稱呼 function 看起來像這樣:

  public function salutation()
  {
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    $params = $tempstore->get('params'); // this value should come from the search form
    return [
      '#markup' => $this->salutation->getGreeting($params),
    ];
  }

非常感謝任何幫助,如果需要,請詢問更多信息。

路由文件

在您的用例中,我相信您可以堅持使用表單。 請從您的hello_world.salutation路由中丟棄 Controller 規范,因為它應該是_form_controller ,而不是單一路由。

服務方法調用

對於您的服務定義,您可以通過將服務靜態調用為:

$salutation_service = \Drupal::service('hello_world.salutation');
$salutation_service->somePublicMethodCall();

或者通過依賴注入,當我查看this->salutation->getGreeting($params)時,我假設你已經在做?

表格 x Controller

從提供的詳細信息中,我無法真正說出您為什么需要 Controller,但是如果您需要重定向到 Controller,那么您可以為您的HelloWorldSalutation::salutation()方法創建一個單獨的路由並從GreetingForm::submitForm()通過$form_state object:

$url = \Drupal\Core\Url::fromRoute('hello_world.salutation');
$form_state->setRedirectUrl($url);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM