【问题标题】:Is it possible to pass arguments to a form in Drupal 8?是否可以将参数传递给 Drupal 8 中的表单?
【发布时间】:2013-11-18 19:54:49
【问题描述】:

想象一下这样的 YAML 路由配置:

foobar.example:
  path: 'example/{entity_type}/{bundle_name}'
  defaults:
    _form: '\Drupal\foobar\Form\FoobarExampleForm'
    _title: 'Example Form'
    foo: 0
    bar: 1

参数 foo 和 bar 将被传递给控制器​​,但是如何将参数传递给表单?我意识到 entity_type 和 bundle_name 可以使用 arg() 或 menu_get_object() 来检索。还有其他方法可以将参数传递给表单吗?

【问题讨论】:

    标签: yaml form-api drupal-8


    【解决方案1】:

    如果您询问是否将附加值传递到未由路由加载的表单中,您可以这样做:

    public function buildForm(array $form, FormStateInterface $form_state, $item = array()) { 
      // Form code here
    }
    

    当你调用它时,这样做

    $form = \Drupal::formBuilder()->getForm('\Drupal\MYMODULE\Form\MYFORMCLASS', $item);
    

    重要提示:如果在声明函数时没有给它一个默认值,你会得到一个 PHP 致命错误。所以不要这样做(没有 = array()):

    public function buildForm(array $form, FormStateInterface $form_state, $item) {
    

    【讨论】:

      【解决方案2】:

      你可以像这样获取变量(foo 和 bar)

      public function buildForm(array $form, FormStateInterface $form_state, $foo = NULL, $bar = 1) {
         echo $foo;
         echo $bar;
      }
      

      【讨论】:

        【解决方案3】:

        我认为这可能不是最好的解决方案,但 arg() 可以帮助您。以 arg(0) 形式调用会给你'example',arg(1) 给 {entity_type} 和 arg(2) {bundle_name}

        【讨论】:

          猜你喜欢
          • 2021-11-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-14
          相关资源
          最近更新 更多