Menu Close
    Searching for an experienced Akeneo Development Company ?

    How to Add Image Field In Akeneo

    Getting Start with Add Image Field in Akeneo !!

    In Akeneo PIM, If you want to render the custom image field in product edit form, you need to create a new field. We will go through each step needed to achieve this task.

    Supported Extensions: JPG, JPEG,  GIF, PNG

    Step1 : 

    Before rendering the image field you require to create image field module in public/js/product/form directory. after then you must register it in file requireJs.yml which present in your bundle directory Resources/config. 

    imageField.js

    'use strict';
    /*
     * /src/Webkul/ExampleBundle/Resources/public/js/product/form/imageField.js
     */
    
    define([
            'jquery',
            'pim/field',
            'underscore',
            'routing',
            'pim/attribute-manager',
            'webkul/template/field/media',
            'pim/dialog',
            'oro/mediator',
            'oro/messenger',
            'pim/media-url-generator',
            'jquery.slimbox'
        ],
        function ($, Field, _, Routing, AttributeManager, fieldTemplate, Dialog, mediator, messenger, MediaUrlGenerator) {
            return Field.extend({
                fieldTemplate: _.template(fieldTemplate),
                events: {
                    'change .edit .field-input:first input[type="file"]': 'updateModel',
                    'click  .clear-field': 'clearField',
                    'click  .open-media': 'previewImage'
                },
                uploadContext: {},
                renderInput: function (context) {
                    return this.fieldTemplate(context);
                },
                getTemplateContext: function () {
                    return Field.prototype.getTemplateContext.apply(this, arguments)
                        .then(function (templateContext) {
                            templateContext.inUpload          = !this.isReady();
                            templateContext.mediaUrlGenerator = MediaUrlGenerator;
    
                            return templateContext;
                        }.bind(this));
                },
    
                renderCopyInput: function (value) {
                    return this.getTemplateContext()
                        .then(function (context) {
                            var copyContext = $.extend(true, {}, context);
                            copyContext.value = value;
                            copyContext.context.locale    = value.locale;
                            copyContext.context.scope     = value.scope;
                            copyContext.editMode          = 'view';
                            copyContext.mediaUrlGenerator = MediaUrlGenerator;
    
                            return this.renderInput(copyContext);
                        }.bind(this));
                },
                updateModel: function () {
                    if (!this.isReady()) {
                        Dialog.alert(_.__(
                            'pim_enrich.entity.product.info.already_in_upload',
                            {'locale': this.context.locale, 'scope': this.context.scope}
                        ));
                    }
    
                    var input = this.$('.edit .field-input:first input[type="file"]').get(0);
                    if (!input || 0 === input.files.length) {
                        return;
                    }
    
                    var formData = new FormData();
                    formData.append('file', input.files[0]);
    
                    this.setReady(false);
                    this.uploadContext = {
                        'locale': this.context.locale,
                        'scope':  this.context.scope
                    };
    
    
                    $.ajax({
                        url: Routing.generate('pim_enrich_media_rest_post'),
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        cache: false,
                        processData: false,
                        xhr: function () {
                            var myXhr = $.ajaxSettings.xhr();
                            if (myXhr.upload) {
                                myXhr.upload.addEventListener('progress', this.handleProcess.bind(this), false);
                            }
    
                            return myXhr;
                        }.bind(this)
                    })
                    .done(function (data) {
                        this.setUploadContextValue(data);
                        this.render();
                    }.bind(this))
                    .fail(function (xhr) {
                        var message = xhr.responseJSON && xhr.responseJSON.message ?
                            xhr.responseJSON.message :
                            _.__('pim_enrich.entity.product.error.upload');
                        messenger.enqueueMessage('error', message);
                    })
                    .always(function () {
                        this.$('> .akeneo-media-uploader-field .progress').cuploaderandmoverakeneoss({opacity: 0});
                        this.setReady(true);
                        this.uploadContext = {};
                    }.bind(this));
                },
                clearField: function () {
                    this.setCurrentValue({uploaderandmoverakeneo
                        filePath: null,
                        originalFilename: null
                    });
    
                    this.render();
                },
                handleProcess: function (e) {
                    if (this.uploadContext.locale === this.context.locale &&
                        this.uploadContext.scope === this.context.scope
                    ) {
                        this.$('> .akeneo-media-uploader-field .progress').css({opacity: 1});
                        this.$('> .akeneo-media-uploader-field .progress .bar').css({
                            width: ((e.loaded / e.total) * 100) + '%'
                        });
                    }
                },
                previewImage: function () {
                    var mediaUrl = MediaUrlGenerator.getMediaShowUrl(this.getCurrentValue().data.filePath, 'preview');
                    if (mediaUrl) {
                        $.slimbox(mediaUrl, '', {overlayOpacity: 0.3});
                    }
                },
                setUploadContextValue: function (value) {
                    var productValue = AttributeManager.getValue(
                        this.model.get('values'),
                        this.attribute,
                        this.uploadContext.locale,
                        this.uploadContext.scope
                    );
    
                    productValue.data = value;
                    mediator.trigger('pim_enrich:form:entity:update_state');
                }
            });
        }
    );
    

    Step 2:

    After Creating the js module you must create image field template in public/templates/product directory. After then it is also required to register in Requirejs.yml file

    imageField.html

     
    <div class="AknMediaField <%- value && value.data && value.data.filePath ? 'has-file' : '' %>" >
        <% if (!value || !value.data || value.data.filePath === null) { %>
            <input class="AknMediaField-fileUploaderInput" id="<%- fieldId %>" type="file" data-locale="<%- locale %>" data-scope="<%- scope %>" <%- editMode === 'view' ? 'disabled' : '' %>/>
            <div class="AknMediaField-emptyContainer">
                <span title="upload icon" class="AknMediaField-uploadIcon"/>
                <span><%- _.__('pim_enrich.entity.product.media.upload')%></span>
            </div>
        <% } else { %>
            <div class="AknMediaField-preview preview">
                <% mediaThumbnailUrl = mediaUrlGenerator.getMediaShowUrl(value.data.filePath, 'thumbnail_small') %>
                <% mediaPreviewUrl   = mediaUrlGenerator.getMediaShowUrl(value.data.filePath, 'preview') %>
                <% mediaDownloadUrl  = this.getMediaDownloadUrl(value.data.filePath) %>
                <% if ('pim_catalog_image' === attribute.type && null != mediaThumbnailUrl) { %>
                    <div class="AknMediaField-thumb file"><img src="<%- mediaThumbnailUrl %>" class="AknMediaField-image"/></div>
                <% } else { %>
                    <div class="AknMediaField-thumb file">
                        <span title="upload icon" class="AknMediaField-uploadIcon"/>
                    </div>
                <% } %>
                <div class="AknMediaField-info info">
                    <div class="filename" title="<%- value.data.originalFilename %>"><%- value.data.originalFilename %></div>
                    <div class="AknButtonList AknButtonList--centered actions">
                        <% if ('pim_catalog_image' === attribute.type && null != mediaPreviewUrl) { %>
                            <span class="AknButtonList-item AknIconButton AknIconButton--grey open-media"><i class="icon icon-eye-open"></i></span>
                        <% } %>
                        <a href="<%- mediaDownloadUrl %>" class="AknButtonList-item AknIconButton AknIconButton--grey download-file" download><i class="icon icon-cloud-download"></i></a>
                        <span class="AknButtonList-item AknIconButton AknIconButton--grey clear-field <%- editMode === 'view' ? 'AknIconButton--hide' : '' %>"><i class="icon icon-trash"></i></span>
                    </div>
                </div>
            </div>
        <% } %>
        <div class="AknMediaField-progress AknProgress AknProgress--micro progress">
            <div class="AknProgress-bar bar"></div>
        </div>
    </div>

    Step 3:

    Now we need to register both above files in the requirejs configuration file:

    # src/webkul/ExampleBundle/Resources/config/requirejs.yml
    
    config:
        paths:
            webkul/product/form/imagefield: webkul/js/product/form/imageField.js
            webkul/template/product/imagefield: webkul/templates/product/form/imageField.html
    

    Step 4:

    Now add it to form:

    After creating the js module and image field template now create form extension to add the field. in the directory resources/config/form_extensions

    # src/webkul/ExampleBundle/Resources/config/form_extensions/product_edit.yml
    
    
    extensions:
        pim-product-edit-form-export-csv:            # The form extension code (can be whatever you want)
            module: webkul/product/form/imagefield   # The requirejs module we just created
            parent: pim-product-edit-form            # The parent extension in the form where we want to be registered
            targetZone: container
            position: 90                             # The extension position (lower will be first)
    

    After adding it to the form extension you must clear the cache using following commands in terminal.

    1. php bin/console c:c –env=prod
    2. rm -rf ./var/cache/** && php bin/console pim:install:asset –env=prod && php bin/console assets:install web –symlink && yarn run webpack

    After the refresh your web browser you will found new image field in product edit form.

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top