Как вставить изображение в шаблон с помощью HelperForm? - PullRequest
0 голосов
/ 28 февраля 2019

Я создаю пользовательский модуль с помощью PrestaShop 1.7, и я хочу иметь возможность загрузить изображение для фона.Изображение должно отображаться, если определено поле background_image.

Я могу это сделать, но изображение находится за пределами формы, как вы можете видеть на изображении ниже.

image in wrong position

Изображение должно отображаться непосредственно над полем фонового изображения, как показано ниже (* см. Ниже).

image in correct position

Вот мой файл .tpl:

{if isset($background_image)}
<div>
    <div class="col-lg-3"></div>
    <div>
        <img src="/modules/cb_sectionaboutus/img/{$background_image}" class="img-thumbnail" width="400" />
    </div>
</div>
{/if}

А вот часть основного файла PHP модуля:

/**
 * Load the configuration form
 */
public function getContent()
{
    /**
     * If values have been submitted in the form, process.
     */
    if (((bool)Tools::isSubmit('submitCb_sectionaboutusModule')) == true) {
        $this->postProcess();
    }

    $this->context->smarty->assign('module_dir', $this->_path);

    /* Passes the background image to the template */
    $data = $this->getDataFromDB();
    $background_image = $data['background_image'];
    $this->context->smarty->assign('background_image', $background_image);

    // About section & Documentation
    $output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
    return $output.$this->renderForm();
}

/**
 * Create the form that will be displayed in the configuration of your module.
 */
protected function renderForm()
{
    $helper = new HelperForm();

    $helper->show_toolbar = false;
    $helper->table = $this->table;
    $helper->module = $this;
    $helper->default_form_language = $this->context->language->id;
    $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);

    $helper->identifier = $this->identifier;
    $helper->submit_action = 'submitCb_sectionaboutusModule';
    $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 = array(
        'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
        'languages' => $this->context->controller->getLanguages(),
        'id_language' => $this->context->language->id
    );

    return $helper->generateForm(array($this->getConfigForm()));
}

/**
 * Create the structure of your form.
 */
protected function getConfigForm()
{
    return array(
        'form' => array(
            'legend' => array(
                'title' => $this->l('Settings'),
                'icon' => 'icon-cogs'
            ),
            'input' => array(
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Title'),
                    'name' => 'title',
                    'desc' => $this->l('Enter the title'),
                    'class' => 'rte',
                    'autoload_rte' => true
                ),
                array(
                    'type' => 'file',
                    'label' => $this->l('Background Image'),
                    'name' => 'background_image',
                    'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
                    'display_image' => true
                )
            ),
            'submit' => array(
                'title' => $this->l('Save'),
            ),
        ),
    );
}

/**
 * Set values for the inputs.
 */
protected function getConfigFormValues()
{
    $data = $this->getDataFromDB();

    return array(
        'title' => $data['title'],
        'background_image' => $data['background_image']
    );
}

/**
 * Get the data from the database
 */
public function getDataFromDB()
{
    $sql = 'SELECT * FROM ' . _DB_PREFIX_ . $this->name . ' WHERE id_' . $this->name . ' = ' . 1;
    return Db::getInstance()->ExecuteS($sql)[0];
}

/**
 * Save form data.
 */
protected function postProcess()
{
    /* Current data */
    $data_from_db = $this->getDataFromDB();

    /* New data */
    $form_values = $this->getConfigFormValues();

    /* Sets the background image as the old value, in case there is no new upload */
    $form_values['background_image'] = $data_from_db['background_image'];

    /* Validates the background image file */
    $file_name = $this->validateFile();
    /* Checks whether the background image has been successfully uploaded */
    if ($file_name) {
        /* Sets the new background image */
        $form_values['background_image'] = $file_name;
    }

    // Has rows in table --> UPDATE
    if ($data_from_db) {
        $sql = $sql = "UPDATE " . _DB_PREFIX_ . $this->name . " SET ";
        foreach (array_keys($form_values) as $key) {
            $sql .= $key . " = '" . $form_values[$key] . "', ";
        }
        $sql = trim($sql, " ");    // first trim last space
        $sql = trim($sql, ",");    // then trim trailing and prefixing commas
        $sql .= " WHERE id_" . $this->name . " = " . 1;
    }

    // No rows in table --> INSERT
    else {
        $columns = "id_cb_sectionaboutus, " . implode(", ", array_keys($form_values));
        $values = array_map('Tools::getValue', array_keys($form_values));
        $values = "1, " . "'" . implode("', '", array_values($values)) . "'";
        $sql = 'INSERT INTO ' . _DB_PREFIX_ . $this->name . ' (' . $columns . ') VALUES (' . $values . ')';
    }

    Db::getInstance()->ExecuteS($sql);
}

Как вставить загруженный файл?изображение в середине формы с помощью HelperForm?

Я бы предпочел решение с помощью HelperForm, но я не знаю, работает ли оно, поэтому я приму любой ответ, который даст мне хорошее решение.

1 Ответ

0 голосов
/ 05 марта 2019

PHP-файл - getConfigForm функция

protected function getConfigForm()
{
    // ADDED THESE LINES
    $image = '';
    $background_image = $this->getDataFromDB()['background_image'];
    if ($background_image) {
        $image_url = $background_image ? '/modules/cb_sectionaboutus/img/' . $background_image : '';
        $image = '<div class="col-lg-6"><img src="' . $image_url . '" class="img-thumbnail" width="400"></div>';
    }

    return array(
        'form' => array(
            'legend' => array(
                'title' => $this->l('Settings'),
                'icon' => 'icon-cogs'
            ),
            'input' => array(
                array(
                    'type' => 'file',
                    'label' => $this->l('Background Image'),
                    'name' => 'background_image',
                    'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
                    'display_image' => true,
                    'image' => $image  // ADDED THIS OPTION
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Title'),
                    'name' => 'title',
                    'desc' => $this->l('Enter the title'),
                    'class' => 'rte',
                    'autoload_rte' => true
                )
            ),
            'submit' => array(
                'title' => $this->l('Save'),
            ),
        ),
    );
}

и удаление всего из шаблона.

...