All files / web/bundles/pimui/js/form/common/fields field.js

94.55% Statements 52/55
92.59% Branches 25/27
100% Functions 4/4
94.55% Lines 52/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260                  214x                                 214x                           2187x   2187x       2187x 2187x 2187x 2187x   2187x             2205x 2205x   2205x             460x 460x   460x 21x                       460x 203x 203x 203x 25x   178x 178x     178x                       21x 21x 48x 48x 9x       12x             4309x 304x   304x     4005x 3987x 3987x   3987x 3987x 3987x     4005x                 4005x   4005x                                                                     4211x                 4005x                     3993x                 3737x                                   837x 837x   837x                 5114x         5114x                 4005x        
/**
 * Abstract attribute form field.
 *
 * @author    Yohan Blain <yohan.blain@akeneo.com>
 * @copyright 2017 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 */
'use strict';
 
define([
    'jquery',
    'underscore',
    'oro/translator',
    'pim/form',
    'pim/common/property',
    'pim/common/tab',
    'pim/template/form/common/fields/field'
], function (
    $,
    _,
    __,
    BaseForm,
    propertyAccessor,
    Tab,
    template
) {
    return BaseForm.extend({
        className: 'AknFieldContainer',
        containerTemplate: _.template(template),
        config: {},
        elements: {},
        fieldName: null,
        errors: [],
        warnings: [],
        readOnly: false,
 
        /**
         * {@inheritdoc}
         */
        initialize(meta) {
            this.config = meta.config;
 
            Iif (undefined === this.config.fieldName) {
                throw new Error('This view must be configured with a field name.');
            }
 
            this.fieldName = this.config.fieldName;
            this.readOnly = this.config.readOnly || false;
            this.errors = [];
            this.warnings = [];
 
            BaseForm.prototype.initialize.apply(this, arguments);
        },
 
        /**
         * {@inheritdoc}
         */
        configure() {
            this.listenTo(this.getRoot(), 'pim_enrich:form:entity:bad_request', this.onBadRequest.bind(this));
            this.listenTo(this.getRoot(), 'pim_enrich:form:entity:post_save', this.render.bind(this));
 
            return BaseForm.prototype.configure.apply(this, arguments);
        },
 
        /**
         * @param {Object} event
         */
        onBadRequest(event) {
            this.errors = this.getFieldErrors(event.response);
            this.render();
 
            if (this.errors.length) {
                this.getRoot().trigger('pim_enrich:form:form-tabs:change', this.getTabCode());
            }
        },
 
        /**
         * Filter errors to return only the ones related to this field.
         *
         * @param {Array} errors
         *
         * @returns {Array}
         */
        getFieldErrors(errors) {
            return errors.filter((error) => {
                const fieldNameParts = this.fieldName.split('.');
                const lastPart = fieldNameParts[fieldNameParts.length - 1];
                if (error.path === undefined) {
                    return lastPart === error.attribute || lastPart === undefined;
                }
                const splittedParts = error.path.split(/\[|\]/).filter(part => {
                    return part !== '';
                });
 
                return lastPart === error.path ||
                    lastPart === error.attribute ||
                    JSON.stringify(fieldNameParts) === JSON.stringify(splittedParts);
            });
        },
 
        /**
         * Recursively search for the first tab ancestor if any, and returns its code. Sorry.
         *
         * @returns {String}
         */
        getTabCode() {
            let parent = this.getParent();
            while (!(parent instanceof Tab)) {
                parent = parent.getParent();
                if (null === parent) {
                    return null;
                }
            }
 
            return parent.code;
        },
 
        /**
         * Renders the container template.
         */
        render() {
            if (!this.isVisible()) {
                this.$el.empty();
 
                return;
            }
 
            this.getTemplateContext().then(function (templateContext) {
                this.$el.html(this.containerTemplate(templateContext));
                this.$('.field-input').replaceWith(this.renderInput(templateContext));
 
                this.postRender(templateContext);
                this.renderExtensions();
                this.delegateEvents();
            }.bind(this));
 
            return this;
        },
 
        /**
         * Returns the context params that will be passed to templates.
         *
         * @returns {Promise}
         */
        getTemplateContext() {
            const templateParams = this.config.templateParams || {};
 
            return $.Deferred()
                .resolve(Object.assign(
                    {},
                    {
                        fieldLabel: this.getLabel(),
                        requiredLabel: this.getRequiredLabel(),
                        fieldName: this.fieldName,
                        fieldId: this.getFieldId(),
                        errors: this.errors,
                        warnings: this.warnings,
                        readOnly: this.isReadOnly(),
                        required: this.config.required || false,
                        __: __
                    },
                    templateParams
                ))
                .promise();
        },
 
        /**
         * Renders the input inside the field container.
         */
        renderInput() {
            throw new Error('Please implement the renderInput() method in your concrete field class.');
        },
 
        /**
         * Called after rendering the input.
         */
        postRender() {},
 
        /**
         * @returns {string}
         */
        getLabel() {
            return undefined === this.config.label
                ? '[' + this.fieldName + ']'
                : __(this.config.label);
        },
 
        /**
         * @returns {string}
         */
        getRequiredLabel() {
            return undefined === this.config.requiredLabel
                ? __('pim_common.required_label')
                : __(this.config.requiredLabel);
        },
 
        /**
         * Should the field be displayed?
         *
         * @returns {Boolean}
         */
        isVisible() {
            return true;
        },
 
        /**
         * Should the field be in readonly mode?
         *
         * @returns {Boolean}
         */
        isReadOnly() {
            return this.readOnly;
        },
 
        /**
         * Sets the param readOnly of the field
         *
         * @param {Boolean} readOnly
         */
        setReadOnly(readOnly) {
            this.readOnly = Boolean(readOnly);
        },
 
        /**
         * Receives the new value and updates the data model with it.
         *
         * @param {*} value
         */
        updateModel(value) {
            const data = this.getFormData();
            propertyAccessor.updateProperty(data, this.fieldName, value);
 
            this.setData(data);
        },
 
        /**
         * Reads and returns the field value from the model.
         *
         * @returns {*}
         */
        getModelValue() {
            const value = propertyAccessor.accessProperty(
                this.getFormData(),
                this.fieldName
            );
 
            return null === value ? undefined : value;
        },
 
        /**
         * Returns a pseudo-unique code used as reference inside templates (as "for" attributes values for example).
         *
         * @returns {String}
         */
        getFieldId() {
            return Math.random().toString(10).substring(2);
        }
    });
});