Magento 2 – How to Add Image to Payment Method in Checkout

checkoutimagemagento2payment-methods

I want add images to payment method list on checkout like :
enter image description here

I want add image before these payment methods

  • Płatność przelewem bankowym
  • Płatność przy odbiorze

Can anyone help me how I can do it?

Best Answer

Its quite a lot of works. You need to go to that payment module, find

view/frontend/web/template/payment/form.html

find something like this:

<label class="label" data-bind="attr: {'for': getCode()}">

right below it, put something like this:

<img data-bind="attr: {src: fpxImageSrc, alt: $t('Fpx MyClear'), height: '', width: '110' }" class="payment-icon"/>

and then you need to specify the knockoutJS data-bind function, in this case fpxImageSrc'. Go to

view/frontend/web/js/view/payment/method-renderer/<name of the payment>.js

then right below Component extend, it should look like:

        return Component.extend({
        defaults: {
            template: 'Vendor_PaymentModule/payment/form'
        },
        placeOrderHandler: null,
        fpxImageSrc: window.populateFpx.fpxLogoImageUrl,

Add single line fpxImageSrc or whatever name you choose, inside that file, like this one at that particular spot:

        fpxImageSrc: window.populateFpx.fpxLogoImageUrl,

then you need to create one phtml templates file, in this case I name it payment_image.phtml. The file should be inside

view/frontend/templates/payment_image.phtml

right after that, you add something like this code:

<script>
window.populateFpx = <?php /* @escapeNotVerified */ echo \Zend_Json::encode($block->getFpxConfig()); ?>;
</script>

then you need to add this phtml template on layout, the layout files can be found inside the module:

view/frontend/layout/checkout_index_index.xml

there, you need to add

    <body>
    <referenceContainer name="after.body.start">
        <block class="Vendor\PaymentModule\Block\PopulateFpx" name="populate.fpx" template="Vendor_PaymentModule::payment_image.phtml"/>
    </referenceContainer>
    ...
    </body>

after that, create block file, in this case I named it PopulateFpx.php, inside the module:

Vendor\PaymentModule\Block\PopulateFpx.php

and then:

use Magento\Framework\View\Asset\Repository as AssetRepository;

....

protected $assetRepository;

public function __construct(
    AssetRepository $assetRepository
){
    $this->assetRepository = $assetRepository;
}

public function getFpxConfig() {
    $output['fpxLogoImageUrl'] = $this->getViewFileUrl('Vendor_PaymentModule::images/fpx_logo.png');

    return $output;
}

public function getViewFileUrl($fileId, array $params = [])
{
    $params = array_merge(['_secure' => $this->request->isSecure()], $params);
    return $this->assetRepository->getUrlWithParams($fileId, $params);
}

and then put the image file, in this case I named it fpx_logo.png, inside:

view/frontend/web/images/fpx_logo.png