简体   繁体   中英

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

  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.

example:

private static $slug = 0;

and in the __construct()

self::$slug = 0;

and in 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.

Than created the method getFormId something like this

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

Than in buildForm method I simply call

$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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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