Changing a fieldset label on an ui-components form
-
08-01-2021 - |
Pregunta
I have a form built with ui-components.
And when changing a field, I'm trying to change the label of the fieldset that contains that field.
Here is what I have (the significant part)
THe fieldset definition:
<fieldset name="steps">
<settings>
<label translate="true">Step config</label>
<collapsible>true</collapsible>
</settings>
<field name="title" formElement="input" component="[Namespace_Module]/js/fieldset-title">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="fit" xsi:type="boolean">false</item>
</item>
</argument>
<settings>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<dataType>text</dataType>
<label>Title</label>
<dataScope>title</dataScope>
</settings>
</field>
</fieldset>
and the fieldset-title
js file that handles my title field looks like this:
define([
'Magento_Ui/js/form/element/abstract',
'uiRegistry'
], function (Abstract, uiRegistry) {
'use strict';
return Abstract.extend({
onUpdate: function (value) {
var fieldset = uiRegistry.get({'name': this.parentName});
fieldset.label(value);
}
});
});
What I'm saying here is ... "when the value of my input changes, set the same value as fieldset label".
Additional info:
Inside js, fieldset is retrieved properly. I get the fieldset instance I need.
The value
variable is what I'm expecting it to be.
Other than
fieldset.label(value);
I tried fieldset.label = value;
fieldset.setLabel(value);
, fieldset.getLabel(value);
Solución
I've done it in a very ugly way (yep...jquery). If someone has a cleaner method, please share.
my custom component looks like this now.
define([
'Magento_Ui/js/form/element/abstract',
'jquery'
], function (Text, $) {
'use strict';
return Text.extend({
onUpdate: function (value) {
$('#' + this.uid).closest('.fieldset-wrapper').find('.fieldset-wrapper-title span:first').html(value);
return this._super();
}
});
});
Not very proud of if, but it works with a standalone fieldset.
But if this fieldset is part of a record of a dynamic-records component, the title is reset once a new record is added or deleted.
Otros consejos
I have updated the code a bit in a clean and better manner. It may be useful to others :)
define([
'Magento_Ui/js/form/element/abstract',
'jquery'
], function (Text, $) {
'use strict';
return Text.extend({
onUpdate: function (value) {
$("label[for=" + this.uid + "]").text(value);
return this._super();
}
});
});