cancel
Showing results for 
Search instead for 
Did you mean: 

How to add an IMG in knockout html template

SOLVED

How to add an IMG in knockout html template

I am trying to show an image in the knockout template but I could not. This is what I have:

 

<img data-bind="attr: {'src': getImage()}, src: getImage()" />
<p data-bind="html: getInstructions()"></p>

 

 

getInstructions do show the instructions but image is not shown. Both variables are correctly configured in backend.

 

This is configuration provider:

 

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Desytec\Transbank\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\Escaper;
use Magento\Payment\Helper\Data as PaymentHelper;

class WebpayConfigProvider implements ConfigProviderInterface
{
    /**
     * @var string[]
     */
    protected $methodCode = Webpay::CODE;

    /**
     * @var Webpay
     */
    protected $method;

    /**
     * @var Escaper
     */
    protected $escaper;

    /**
     * @param PaymentHelper $paymentHelper
     * @param Escaper $escaper
     */
    public function __construct(
        PaymentHelper $paymentHelper,
        Escaper $escaper
    ) {
        $this->escaper = $escaper;
        $this->method = $paymentHelper->getMethodInstance($this->methodCode);
    }

    /**
     * {@inheritdoc}
     */
    public function getConfig()
    {
        $config = [];
        if ($this->method->isAvailable()) {
            $config['payment']['instructions'][$this->methodCode] = $this->getInstructions();
            $config['payment']['image'][$this->methodCode] = $this->getImage();
        }
        return $config;
    }

    /**
     * Get image from config
     *
     * @return string
     */
    protected function getImage()
    {
        return $this->method->getImage();
    }

    /**
     * Get instructions from config
     *
     * @return string
     */
    protected function getInstructions()
    {
        return nl2br($this->escaper->escapeHtml($this->method->getInstructions()));
    }
}

And this is corresponding js file:

 

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
/*browser:true*/
/*global define*/
define(
        [
            'jquery',
            'Magento_Checkout/js/view/payment/default',
            'Magento_Checkout/js/action/place-order',
            'Magento_Checkout/js/action/select-payment-method',
            'Magento_Customer/js/model/customer',
            'Magento_Checkout/js/checkout-data',
            'Magento_Checkout/js/model/payment/additional-validators',
            'mage/url'
        ],
        function ($,
                Component,
                placeOrderAction,
                selectPaymentMethodAction,
                customer,
                checkoutData,
                additionalValidators,
                url) {
            'use strict';
            return Component.extend({
                defaults: {
                    template: 'Desytec_Transbank/payment/webpay'
                },
                placeOrder: function (data, event) {
                    if (event) {
                        event.preventDefault();
                    }
                    var self = this,
                            placeOrder,
                            emailValidationResult = customer.isLoggedIn(),
                            loginFormSelector = 'form[data-role=email-with-possible-login]';
                    if (!customer.isLoggedIn()) {
                        $(loginFormSelector).validation();
                        emailValidationResult = Boolean($(loginFormSelector + ' input[name=username]').valid());
                    }
                    if (emailValidationResult && this.validate() && additionalValidators.validate()) {
                        this.isPlaceOrderActionAllowed(false);
                        placeOrder = placeOrderAction(this.getData(), false, this.messageContainer);
                        $.when(placeOrder).fail(function () {
                            self.isPlaceOrderActionAllowed(true);
                        }).done(this.afterPlaceOrder.bind(this));
                        return true;
                    }
                    return false;
                },
                selectPaymentMethod: function () {
                    selectPaymentMethodAction(this.getData());
                    checkoutData.setSelectedPaymentMethod(this.item.method);
                    return true;
                },
                afterPlaceOrder: function () {
                    window.location.replace(url.build('mymodule/standard/redirect/'));
                },
                /**
                 * Get value of instruction field.
                 * @returns {String}
                 */
                getInstructions: function () {
                    return window.checkoutConfig.payment.instructions[this.item.method];
                },
                /**
                 * Get value of image field.
                 * @returns {String}
                 */
                getImage: function () {
                    return window.checkoutConfig.payment.image[this.item.method];;
                }
            });
        }
);

 

 

Any help please?

3 REPLIES

Re: How to add an IMG in knockout html template

Your syntax (duplicating the src attribute inside and outside the attr expression) differs from both the Knockout documentation and Magento 2 core code.

How to render an IMG HTML tag with variable attributes inside a Magento 2 Knockout template? https://mage2.pro/t/954

Re: How to add an IMG in knockout html template

Hello, I have duplicated that attribute after several tests, but, finally, I have found the getImage method in config provider is called. The problem is that the field cannot be retrieved from configuration.

 

I have this method:

 

 

protected function getImage()
{
      return $this->method->getImage();
}

 

 

That $this->method->getImage() call, returns null. When I replace with $this->method->getInstructions(), src attribute is filled with the content of instructions field.

 

So, the only problem is that the config is not storing the value well of only that field. This is strange since when I go to backend, I see that the image field is correctly set.

 

I have defined this in system.xml of etc/adminhtml folder:

 

<field id="instructions" translate="label" type="textarea" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Instructions</label>
</field>
<field id="image" translate="label" type="text" sortOrder="51" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Image</label>
</field>                

What else do I need to do?

 

Thanks

Jaime

Re: How to add an IMG in knockout html template

Finally, the problem was that I needed to add the field in config.xml :-)

 

Thanks