It's not possible to add an if statement or any other logic directly within an XML file like checkout_index_index.xml.
However, You can use LayoutProcessor to achieve your requirement.
The LayoutProcessor in Magento is a class that is used to process and modify the layout of the checkout page.
In the context of the checkout page, the LayoutProcessor is used to modify the structure of the JavaScript layout configuration array. This array defines the layout of the checkout page, including the arrangement of fields, their sort order, visibility, and so on.
Here is the example code for the same.
app/code/VendorName/ModuleName/etc/frontend/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\Checkout\Block\Checkout\LayoutProcessor">
<plugin disabled="false" name="remove_discount_code_dynamically_based_on_requirement" sortOrder="10" type="VendorName\ModuleName\Plugin\Magento\Checkout\Block\Checkout\LayoutProcessor"/>
</type>
</config>
app/code/VendorName/ModuleName/Plugin/Magento/Checkout/Block/Checkout/LayoutProcessor.php
<?php
namespace VendorName\ModuleName\Plugin\Magento\Checkout\Block\Checkout;
class LayoutProcessor
{
/**
* @var \VendorName\ModuleName\Helper\Data
*/
protected $coreHelper;
/**
* @param \VendorName\ModuleName\Helper\Data $coreHelper
*/
public function __construct(
\VendorName\ModuleName\Helper\Data $coreHelper
) {
$this->coreHelper = $coreHelper;
}
public function afterProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
array $jsLayout
) {
$afterMethods = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['afterMethods']['children'];
$summary = $jsLayout['components']['checkout']['children']['sidebar']['children']['summary']['children']['totals']['children'];
if (array_key_exists('discount', $afterMethods) && !$this->coreHelper->getConfigData('custom/checkout/apply_discount_code')) {
unset($jsLayout['components']['checkout']['children']['steps']['children']
['billing-step']['children']['payment']['children']['afterMethods']
['children']['discount']);
}
return $jsLayout;
}
}
Here, the afterProcess method is run after the process method of the Magento\Checkout\Block\Checkout\LayoutProcessor class. It modifies the $jsLayout array to hide the discount code field based on a configuration setting.
The if statement checks if the 'discount' key exists in the $afterMethods array and if the 'custom/checkout/apply_discount_code' configuration setting is disabled. If both conditions are true, it removes the 'discount' element from the $jsLayout array, effectively hiding the discount code field on the checkout page.