Drupal:从SubmitForm()

时间:2019-12-22 22:44:35

标签: drupal drupal-8

我正在尝试在自定义模块中提交表单时做一些事情。其中一些是通过从控制器调用函数来完成的。那就是我得到的:

Error: Class 'Drupal\ice_cream\Controller\OrderController' not found in Drupal\ice_cream\Form\OrderForm->submitForm() (line 77 of modules\custom\ice_cream\src\Form\OrderForm.php).

据我所知,命名空间没有错吗?还是与该错误无关?

这是我的OrderForm.php和SubmitForm()的样子:

<?php

namespace Drupal\ice_cream\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\ice_cream\Controller\OrderController;

/**
 * Implements the order form.
 */
class OrderForm extends FormBase {

... (omitted code for getFormid and buildForm)

    public function submitForm(array &$form, FormStateInterface $form_state) {

        //Check if the order is ice or waffles.   
        if($form_state->getValue('foodType') == 'ice'){
          //Save order to the DB.
          OrderController::saveOrder($form_state->getValue('foodType'), $form_state->getValue('taste'));

          ... (more code)
        }

    }
}

这是控制器的外观:

<?php

namespace Drupal\ice_cream\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;

/**
 * Order controller for interacting (insert, select,...) with the ice cream table in the DB.
 */
class OrderController extends ControllerBase {

  /**
   * Saves an order for either Ice or Waffles with their options (tast or toppings).
   */
  public function saveOrder($foodType, $options) {

    $connection = Database::getConnection();

    //Check if ice or waffles (to only insert the right field with $options).
    if($foodType == "ice"){
        $result = $connection->insert('ice_cream')
        ->fields([
            'foodType' => $foodType,
            'taste' => $options,
            'toppings' => "",
        ])
        ->execute();
        return true;

    }elseif($foodType == "waffles"){
        $result = $connection->insert('ice_cream')
        ->fields([
            'foodType' => $foodType,
            'taste' => "",
            'toppings' => $options,
        ])
        ->execute();
        return true;

    }

  }

}

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码:

$obj= new OrderController;
$obj->saveOrder($form_state->getValue('foodType'), $form_state->getValue('taste'));

答案 1 :(得分:0)

已解决:

只是和我的导师解决了。代码或多或少是正确的,仍然需要使我的函数在OrderController中保持静态,并且在使用'touch'终端命令创建文件时,我忘记了文件名中的.php扩展名也犯了一个愚蠢的错误……