Oto pełny i działający przykład dodania niestandardowej reguły do pola wejściowego kasy w celu sprawdzenia minimalnego wieku:
Utwórz plik wymagań.js-config.js w swoim module, aby dodać mieszanie do validator
obiektu Namespace/Modulename/view/frontend/requirejs-config.js
o następującej treści:
var config = {
config: {
mixins: {
'Magento_Ui/js/lib/validation/validator': {
'Namespace_Modulename/js/validator-mixin': true
}
}
}
};
Utwórz skrypt js w folderze modułu w Namespace/Modulename/view/frontend/web/js/validator-mixin.js
następującej treści:
define([
'jquery',
'moment'
], function ($, moment) {
'use strict';
return function (validator) {
validator.addRule(
'validate-minimum-age',
function (value, params, additionalParams) {
return $.mage.isEmptyNoTrim(value) || moment(value, additionalParams.dateFormat).isBefore(moment().subtract(params.minimum_age, 'y'));
},
$.mage.__("Sorry, you don't have the age to purchase the current articles.")
);
return validator;
};
});
STOSOWANIE
Jeśli chcesz użyć wtyczki Magento PHP do wstawienia pola wejściowego do adresu wysyłki do kasy i sprawdzenia zawartości tego pola za pomocą niestandardowej reguły, którą wcześniej dodałeś, oto przykładowy kod:
Utwórz di.xml
plik w etc/frontend
folderze modułu o następującej treści:
<?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 name="CheckoutLayoutProcessor" type="Namespace\Modulename\Plugin\Block\Checkout\LayoutProcessor" />
</type>
</config>
Następnie utwórz LayoutProcessor.php
plik app/code/Namespace/Modulename/Plugin/Block/Checkout/LayoutProcessor.php
o następującej treści, zaktualizuj go do swoich potrzeb:
<?php
/**
* diglin GmbH - Switzerland
*
* @author Sylvain Rayé <support **at** diglin.com>
* @category diglin
* @package diglin
* @copyright Copyright (c) diglin (http://www.diglin.com)
*/
namespace MyNamespace\Modulename\Plugin\Block\Checkout;
use MyNamespace\Modulename\Helper\AgeValidation;
/**
* Class LayoutProcessor
* @package MyNamespace\Modulename\Plugin\Block\Checkout
*/
class LayoutProcessor
{
/**
* @var \MyNamespace\Checkout\Helper\AgeValidation
*/
private $ageValidation;
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
private $timezone;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $scopeConfig;
/**
* LayoutProcessor constructor.
*
* @param \MyNamespace\Checkout\Helper\AgeValidation $ageValidation
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
*/
public function __construct(
AgeValidation $ageValidation,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
)
{
$this->ageValidation = $ageValidation;
$this->timezone = $timezone;
$this->scopeConfig = $scopeConfig;
}
/**
* Checkout LayoutProcessor after process plugin.
*
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $processor
* @param array $jsLayout
*
* @return array
*/
public function afterProcess(\Magento\Checkout\Block\Checkout\LayoutProcessor $processor, $jsLayout)
{
$shippingConfiguration = &$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
['children']['shippingAddress']['children']['shipping-address-fieldset']['children'];
// Checks if shipping step available.
if (isset($shippingConfiguration)) {
$shippingConfiguration = $this->processAddress(
$shippingConfiguration
);
}
return $jsLayout;
}
/**
* Process provided address to contains checkbox and have trackable address fields.
*
* @param $addressFieldset - Address fieldset config.
*
* @return array
*/
private function processAddress($addressFieldset)
{
$minimumAge = $this->ageValidation->getMinimumAge();
if ($minimumAge === null) {
unset($addressFieldset['my_dob']);
} else {
$addressFieldset['my_dob'] = array_merge(
$addressFieldset['my_dob'],
[
'component' => 'Magento_Ui/js/form/element/date',
'config' => array_merge(
$addressFieldset['my_dob']['config'],
[
'elementTmpl' => 'ui/form/element/date',
// options of datepicker - see http://api.jqueryui.com/datepicker/
'options' => [
'dateFormat' => $this->timezone->getDateFormatWithLongYear(),
'yearRange' => '-120y:c+nn',
'maxDate' => '-1d',
'changeMonth' => 'true',
'changeYear' => 'true',
'showOn' => 'both',
'firstDay' => $this->getFirstDay(),
],
]
),
'validation' => array_merge($addressFieldset['my_dob']['validation'],
[
'required-entry' => true,
'validate-date' => true,
'validate-minimum-age' => $minimumAge, // custom value in year - array('minimum_age' => 16)
]
),
]
);
}
return $addressFieldset;
}
/**
* Return first day of the week
*
* @return int
*/
public function getFirstDay()
{
return (int)$this->scopeConfig->getValue(
'general/locale/firstday',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
}
EDYTOWAĆ
Dzięki @ alan-storm za wyjaśnienie tutaj https://alanstorm.com/the-curious-case-of-magento-2-mixins/ i @ jisse-reitsma prowadzą w tym kierunku
Plus Magento 2 doc http://devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/js_mixins.html
Loading failed for the <script> with source “.../validator-mixin.js"
iScript error for: Namespace_Modulename/js/validator-mixin
.