Валидация полей форм в Joomla 6
У каждого поля в форме Joomla есть поле type, но за валидацию значения отвечает атрибут validate.
Например: number — очевидно что значение должно быть числом.
<field name="count" type="number" label="MOD_ARTICLES_FIELD_COUNT_LABEL" description="MOD_ARTICLES_FIELD_COUNT_DESC" default="5" filter="integer" min="0" validate="number" />
Или UserId — тут сложнее, значение должно быть реальным id сужествующего пользователя.
<field name="default_value" type="user" label="PLG_FIELDS_USER_DEFAULT_VALUE_LABEL" validate="UserId" />
А в моём компоненте нужна валидация id компании.
Добавляем в поле атрибут validate="CompanyId":
<field name="company_id" type="text" label="COM_WISHBOXBONUSSYSTEM_FIELD_COMPANY_LABEL" required="true" validate="CompanyId" />
Добавляем класс правила (в моём случае по сути копия правила UserId):
<?php /** * @copyright (c) 2013-2026 Nekrasov Vitaliy <nekrasov_vitaliy@list.ru> * @license GNU General Public License version 2 or later; */ namespace Joomla\Component\WishboxBonusSystem\Administrator\Form\Rule; use Joomla\CMS\Form\Form; use Joomla\CMS\Form\FormRule; use Joomla\Database\DatabaseAwareInterface; use Joomla\Database\DatabaseAwareTrait; use Joomla\Database\ParameterType; use Joomla\Registry\Registry; use SimpleXMLElement; use function defined; // phpcs:disable PSR1.Files.SideEffects defined('_JEXEC') or die; // phpcs:enable PSR1.Files.SideEffects /** * Form Rule class for the Joomla Platform. * * @since 1.0.0 */ class CompanyIdRule extends FormRule implements DatabaseAwareInterface { use DatabaseAwareTrait; /** * Method to test the validity of a Joomla User. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the `<field>` tag for the form field object. * @param mixed $value The form field value to validate. * @param ?string $group The field name group control value. This acts as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param ?Registry $input An optional Registry object with the entire data set to validate against the entire form. * @param ?Form $form The form object for which the field is being tested. * * @return boolean True if the value is valid, false otherwise. * * @since 1.0.0 * * @noinspection PhpMissingReturnTypeInspection */ public function test(SimpleXMLElement $element, $value, $group = null, ?Registry $input = null, ?Form $form = null) { // Check if the field is required. $required = ((string) $element['required'] === 'true' || (string) $element['required'] === 'required'); // If the value is empty, null or has the value 0 and the field is not required return true else return false if (($value === '' || $value === null || (string) $value === '0')) { return !$required; } // Get the database object and a new query object. $db = $this->getDatabase(); $query = $db->createQuery(); // Build the query. $query->select('COUNT(*)') ->from($db->qn('#__wishboxbonussystem_companies')) ->where($db->qn('id') . ' = :companyId') ->bind(':companyId', $value, ParameterType::INTEGER); // Set and query the database. return (bool) $db->setQuery($query)->loadResult(); } }
И в модели нашей сущности (в моём случае OperationModel) подключаем префикс класса:
public function getForm($data = [], $loadData = true) { FormHelper::addRulePrefix("\\Joomla\\Component\\WishboxBonusSystem\\Administrator\\Form\\Rule"); return parent::getForm($data, $loadData); }
