简体   繁体   English

Drupal 8 动态表单 ID

[英]Drupal 8 Dynamic form ID

i wrote a module that dynamically create Blocks.我写了一个动态创建块的模块。 In each Block i have a Form.在每个块中,我都有一个表单。 My problem is that i want a dynamic form id for each form, but in my ModuleBlockForm.php i can only define a static one with我的问题是我想要每个表单的动态表单 id,但在我的 ModuleBlockForm.php 中我只能定义一个静态的

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

but i want something like this:但我想要这样的东西:

  public function getFormId() {
    return 'mymodule_block_form_' . $foo;
  }

Is that possible ?这可能吗?

thanks for help感谢帮助

sorry: As I can't comment yet, I'll write my comment as an answer抱歉:由于我还不能发表评论,我会写下我的评论作为答案

The problem I see in Julie Pelletier 's answer, that rand will not generate a unique number, so I would suggest to define a private static integer slug, that you append to each formId and increment it.我在Julie Pelletier的回答中看到的问题是, rand 不会生成唯一的数字,因此我建议定义一个私有静态整数 slug,将其附加到每个 formId 并增加它。

example:例子:

private static $slug = 0;

and in the __construct()并在 __construct()

self::$slug = 0;

and in getFormId()并在 getFormId()

self::$slug += 1;
return 'mymodule_block_form_' . self::$slug;

you can combine last two lines in one, I just wrote it so for readability.你可以将最后两行合二为一,我只是为了可读性而写的。

Hope that helps.希望有帮助。

You should set it as a class property in the constructor.您应该在构造函数中将其设置为类属性。 It could be either passed to the object's constructor or randomly such as:它可以传递给对象的构造函数,也可以随机传递,例如:

this->formId = rand(11111, 99999);

...and use it as: ...并将其用作:

public function getFormId() {
    return 'mymodule_block_form_' . this->formId;
}

Since my form is being build dynamically (based on the plugin_id coming into the form builder as an argument ) I was able to achieve this by defining the protected static $formId property.由于我的表单是动态构建的(基于作为参数进入表单构建器的 plugin_id),我能够通过定义protected static $formId属性来实现这一点。

Than created the method getFormId something like this比创建方法getFormId是这样的

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    $formId = 'settings_form';
    if (self::$formId) {
      $formId .= '_' . self::$formId;
    }
    return $formId;
  }

Than in buildForm method I simply call比在buildForm方法中我简单地调用

$blockId = $buildInfo['args'][0] ?? NULL;    
self::$formId = Html::cleanCssIdentifier($blockId);

The method suggested by ashraf aaref didn't work for me but the following did. ashraf aaref建议的方法对我不起作用,但以下方法对我有用

public function getFormId() {
    static $num = 0;
    $num++;
    return 'mymodule_form_' . $num;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM