Magento 2 Custom Option Text Template – How to Override

custom-optionsmagento2template

I tried to change the template of the text custom option in frontend.

I copied the original

/vendor/magento/module-catalog/view/frontend/templates/product/view/options/type/text.phtml

to

Vendor/Module/view/frontend/templates/catalog/product/view/options/type/text.phtml.

and add to

Vendor/Module/view/frontend/layout/catalog_product_view.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <referenceBlock name="product.info.options">
                <action method="setTemplate">
                    <argument name="text" xsi:type="string">Vendor_Module::catalog/product/view/options/type/text.phtml</argument>
                </action>
            </referenceBlock>
        </referenceContainer>
    </body>
</page>

my custom.phtml file is well called, but craches at the first lines :

<?php
    $_option = $block->getOption();
    $class = ($_option->getIsRequire()) ? ' required' : '';
?>

$_option being null after $_option = $block->getOption();

Thank you for your help,

EDIT 1:

I tried for catalog_product_view.xml

 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
<referenceBlock name="product.info.options">
                <referenceBlock name="text">
                    <action method="setTemplate">
                        <argument name="template" xsi:type="string">Vendor_Module::catalog/product/view/options/type/text.phtml</argument>
                    </action>
                </referenceBlock>
    </referenceBlock>
        </body>
    </page>

but it is not working…

Best Answer

After hours searching on internet, it is apparently not possible to change Custom Options templates using the standard XML way...

Therefore, here is a clean solution using Plugin :

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="\Magento\Catalog\Block\Product\View\Options\Type\Text">
        <plugin name="my_module_change_cotexttemplate" type="My\Module\Plugin\Catalog\Product\View\Options\TextCustOptionPlugin" sortOrder="1"/>
    </type>
</config>

My\Module\Plugin\Catalog\Product\View\Options\TextCustOptionPlugin.php

<?php

namespace My\Module\Plugin\Catalog\Product\View\Options;


class TextCustOptionPlugin
{
    public function beforeSetTemplate(
        \Magento\Catalog\Block\Product\View\Options\Type\Text $subject,
        $template
    ) 
    {
         return ['My_Module::catalog/product/view/options/type/text.phtml'];
    }
}

if it can help !