How to add custom informations to a fieldΒΆ
Natively we add a lot of related informations to product edit fields: data coming from a variant group, validation errors, etc. As an integrator, you can also add custom informations for your own needs and we will go through each steps in this cookbook to achieve this.
Let’s say that we want to display the minimum and maximum values allowed for a number field, for that we need to create a form extension listening to the pim_enrich:form:field:extension:add event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 'use strict';
/**
* src/Acme/Bundle/CustomBundle/Resources/public/js/product/form/attributes/number-min-max.js
*/
define(
[
'jquery',
'underscore',
'pim/form'
],
function ($, _, BaseForm) {
return BaseForm.extend({
configure: function () {
this.listenTo(this.getRoot(), 'pim_enrich:form:field:extension:add', this.addFieldExtension);
return BaseForm.prototype.configure.apply(this, arguments);
},
addFieldExtension: function (event) {
//The event contains the field and an array of promises. The field will wait for all the promises to be resolved before rendering.
//You can add a promise to this array to be sure that the field will wait for it before rendering itself
event.promises.push($.Deferred().resolve().then(function () {
var field = event.field;
if ('pim_catalog_number' === field.attribute.type) {
if (!_.isNull(field.attribute.number_min)) {
//To add html or a DOM element to a field, you can add the addElement method:
// addElement: function (position, code, element)
field.addElement(
'footer',
'number_min',
'<span>Min value: ' + field.attribute.number_min + '</span>'
);
}
if (!_.isNull(field.attribute.number_max)) {
//To add html or a DOM element to a field, you can add the addElement method:
// addElement: function (position, code, element)
field.addElement(
'footer',
'number_max',
'<span>Max value: ' + field.attribute.number_max + '</span>'
);
}
//You can also disable the field with the setEditable method of the field
//field.setEditable(false);
}
}.bind(this)).promise());
return this;
}
});
}
);
|
You can now register it in the requirejs configuration file:
1 2 3 4 5 | # Acme/Bundle/CustomBundle/Resources/config/requirejs.yml
config:
paths:
acme/product-edit-form/attributes/number-min-max: acmecustom/js/product/form/attributes/number-min-max
|
And register your extension to the product edit form:
1 2 3 4 5 6 7 8 | # Acme/Bundle/CustomBundle/Resources/config/form_extensions.yml
extensions:
pim-product-edit-form-number-min-max:
module: acme/product-edit-form/attributes/number-min-max
parent: pim-product-edit-form-attributes
targetZone: self
position: 100
|
Don’t forget to clear your cache and you are good to go !