Back to Top

Create a Multilanguage file upload field in the PrestaShop

Updated 14 May 2024

In this blog, we are going to learn how to create a multilanguage file upload field in the HelperForm Class of PrestaShop.

So let’s see together how to do that with PrestaShop.

Sometimes, we need to upload files language-wise in the module.

We will add the file upload field to the module configuration page using the renderForm function.

public function renderForm()
    {
        $fields_form = [
            'form' => [
                'legend' => [
                    'title' => $this->l('Settings'),
                    'icon' => 'icon-cogs',
                ],
                'input' => [
                    [
                        'type' => 'file_lang',
                        'label' => $this->l('Multilang image'),
                        'name' => 'WK_MULTILANG_IMG',
                        'lang' => true,
                    ]
                ],
                'submit' => [
                    'title' => $this->l('Save'),
                ],
            ],
        ];

        $lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));

        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $helper->default_form_language = $lang->id;
        $helper->module = $this;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitStoreConf';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = [
            'uri' => $this->getPathUri(),
            'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id,
        ];

        return $helper->generateForm([$fields_form]);
    }

In the above code, we used the file type field and ‘type’ => ‘file_lang’ instead of ‘type’ => ‘file’ and added new params ‘lang’ => true for multilanguage.

Searching for an experienced
Prestashop Company ?
Find out More

The rest code is the same as we used for form creation.

Now we will create form.tpl file on the below path

module_name/views/templates/admin/_configure/helpers/form/

We have overridden the form.tpl file using our module and use the below code in the form.tpl file

 {extends file="helpers/form/form.tpl"}
 {block name="field"}
     {if $input.type == 'file_lang'}
         <div class="col-lg-8">
             {foreach from=$languages item=language}
                 {if $languages|count > 1}
                     <div class="translatable-field lang-{$language.id_lang}" {if $language.id_lang != $defaultFormLanguage}style="display:none"{/if}>
                 {/if}
                 <div class="form-group">
                     <div class="col-lg-6">
                         <input id="{$input.name}_{$language.id_lang}" type="file" name="{$input.name}_{$language.id_lang}" class="hide" />
                         <div class="dummyfile input-group">
                             <span class="input-group-addon"><i class="icon-file"></i></span>
                             <input id="{$input.name}_{$language.id_lang}-name" type="text" class="disabled" name="filename" readonly />
                             <span class="input-group-btn">
                                 <button id="{$input.name}_{$language.id_lang}-selectbutton" type="button" name="submitAddAttachments" class="btn btn-default">
                                     <i class="icon-folder-open"></i> {l s='Choose a file' mod='wkmultilangfile'}
                                 </button>
                             </span>
                         </div>
                     </div>
                     {if $languages|count > 1}
                         <div class="col-lg-2">
                             <button type="button" class="btn btn-default dropdown-toggle" tabindex="-1" data-toggle="dropdown">
                                 {$language.iso_code}
                                 <span class="caret"></span>
                             </button>
                             <ul class="dropdown-menu">
                                 {foreach from=$languages item=lang}
                                 <li><a href="javascript:hideOtherLanguage({$lang.id_lang});" id="dropdown-lang-item-link-{$lang.id_lang}" tabindex="-1">{$lang.name}</a></li>
                                 {/foreach}
                             </ul>
                         </div>
                     {/if}
                 </div>
                 <div class="form-group">
                     {if isset($fields_value[$input.name][$language.id_lang]) && $fields_value[$input.name][$language.id_lang] != ''}
                     <div id="{$input.name}-{$language.id_lang}-images-thumbnails" class="col-lg-12">
                         <img src="{$uri}img/{$fields_value[$input.name][$language.id_lang]}" class="img-thumbnail"/>
                     </div>
                     {/if}
                 </div>
                 {if $languages|count > 1}
                     </div>
                 {/if}
                 <script>
                 $(document).ready(function(){
                     $('#{$input.name}_{$language.id_lang}-selectbutton').click(function(e){
                         $('#{$input.name}_{$language.id_lang}').trigger('click');
                     });
                     $('#{$input.name}_{$language.id_lang}').change(function(e){
                         var val = $(this).val();
                         var file = val.split(/[\\/]/);
                         $('#{$input.name}_{$language.id_lang}-name').val(file[file.length-1]);
                     });
                 });
             </script>
             {/foreach}
             {if isset($input.desc) && !empty($input.desc)}
                 <p class="help-block">
                     {$input.desc}
                 </p>
             {/if}
         </div>
     {else}
         {$smarty.block.parent}
     {/if}
 {/block}

In the above code, we extended the helper form tpl and overridden the field block.

we have checked the if condition for the file_lang type field and wrote the multilanguage field code and in the else part return the parent field block for other fields.

Now file upload field will appear language-wise.

Image with multi language

Now we will save the images language-wise using the code below.

public function postProcess()
    {
        if (Tools::isSubmit('submitStoreConf')) {
            $languages = Language::getLanguages(false);
            $values = [];
            $update_images_values = false;

            foreach ($languages as $lang) {
                if (isset($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']])
                    && isset($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['tmp_name'])
                    && !empty($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['tmp_name'])) {
                    if ($error = ImageManager::validateUpload($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']], 4000000)) {
                        return $this->displayError($error);
                    } else {
                        $ext = substr($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['name'], strrpos($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['name'], '.') + 1);
                        $file_name = md5($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['name']) . '.' . $ext;

                        if (!move_uploaded_file($_FILES['WK_MULTILANG_IMG_' . $lang['id_lang']]['tmp_name'], dirname(__FILE__) . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . $file_name)) {
                            return $this->displayError($this->l('An error occurred while attempting to upload the file.'));
                        } else {
                            if (Configuration::hasContext('WK_MULTILANG_IMG', $lang['id_lang'], Shop::getContext())
                                && Configuration::get('WK_MULTILANG_IMG', $lang['id_lang']) != $file_name) {
                                @unlink(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . Configuration::get('WK_MULTILANG_IMG', $lang['id_lang']));
                            }

                            $values['WK_MULTILANG_IMG'][$lang['id_lang']] = $file_name;
                        }
                    }

                    $update_images_values = true;
                }
            }

            if ($update_images_values && isset($values['WK_MULTILANG_IMG'])) {
                Configuration::updateValue('WK_MULTILANG_IMG', $values['WK_MULTILANG_IMG']);
            }

            return $this->displayConfirmation($this->l('The settings have been updated.'));
        }

        return '';
    }

Here we did it on the configuration page.

We can do the same step for the admin controller form.

That’s all about this blog. Hope it will help you.

If you are facing any issues or doubts in the above process, please feel free to contact us in the comment section.

We would be happy to help.

Also, you can explore our PrestaShop Development Services & a large range of quality PrestaShop Modules.

For any doubt contact us at [email protected].

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home