Reputation: 36
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
Upvotes: 1
Views: 1831
Reputation: 27043
Try this
private static $form_index = 0;
public function __construct() {
self::$form_index += 1;
}
public function getFormId() {
return 'my_custom_form_' . self::$form_index . '_form';
}
Upvotes: 0
Reputation: 11
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;
}
Upvotes: 0
Reputation: 380
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);
Upvotes: 0
Reputation: 189
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.
Upvotes: 2
Reputation: 1716
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;
}
Upvotes: 0