在自定义验证器验证输入之前清理 Extbase 模型的用户输入

问题描述 投票:0回答:2

我正在努力寻找一种方法来清理 Extbase 模型的用户输入。互联网上似乎根本没有资源,我想知道我是否在这里寻找错误的东西......

让我们看一个示例:用户填写注册表,其中包含“电话号码”必填字段。基本上我可以使用属性注释

@Extbase\Validate("NotEmpty")
来表示
$telephone
,但出于其他原因,我使用自定义
UserValidator
(这在这里应该不重要)。

我希望传递给验证器的

User
对象是可写的,但它似乎是一个克隆对象。这就是为什么在验证器中设置“干净的”电话号码不起作用(当然,无论如何这都是不好的做法,但这是一种尝试):

class UserValidator extends AbstractValidator
{
    /**
     * @param User $value
     */
    protected function isValid($value): void
    {
        $this->validateTelephone($value);
    }

    protected function validateTelephone(User $user): void
    {
        // sanitize the "telephone" value
        $validTelephone = filter_var($user->getTelephone(), FILTER_SANITIZE_NUMBER_INT);
        $user->setTelephone($validTelephone); // <== does not work, is $user a clone? (in Fluid the original value is still shown e.g. "+1-123-xx2 foo211", but "+1-123-2211" exected)

        if (empty($validTelephone)) {
            $this->result->forProperty('telephone')->addError(
                new Error('Invalid phone number', 1705061262334)
            );
        }
    }
}

接下来尝试使用Extbase

initializeAction()
修改映射前的值,但似乎没有方法:

    public function initializeRegisterCompleteAction()
    {
        // sanitize the "telephone" value
        $this->arguments->getArgument('user')->getPropertyMappingConfiguration()
            ->forProperty('telephone')->...
        // how to get(), filter() and set() the value for the property?
    }

顺便说一句:是的,我可以在验证器中使用 RegExp。 但是 要求注册尽可能轻松。许多用户会对严格的格式要求/错误感到恼火,因为他们不知道例如关于国际格式等...所以所有通过

filter_var($user->getTelephone(), FILTER_SANITIZE_NUMBER_INT);
的内容都应该被接受为电话号码。

社区问题:如何在 Extbase 上下文中清理模型字段值?提前感谢您的想法。

typo3 extbase
2个回答
0
投票

如果您想在提交时以及 Extbase 操作处理之前更改用户输入,您应该使用

initialize<YourAction>Action
方法,如下所示 (TYPO3 v12):

public function initializeRegisterCompleteAction()
{
    $arguments = $this->request->getArguments();

    $telephone = $arguments['telephone'];
    $validTelephone = filter_var(telephone, FILTER_SANITIZE_NUMBER_INT);
    if (validTelephone) {
        $arguments['telephone'] = validTelephone;
    }

    $this->request = $this->request->withArguments($arguments);
}

然后,您可以使用操作验证器来验证(然后清理的)电话号码。


-2
投票

您可以在模板中执行此操作,从而直接为您的模型提供“干净”值。 https://docs.typo3.org/other/typo3/view-helper-reference/11.5/en-us/typo3/fluid/latest/Sanitize/Html.html

您还可以通过 TCA 覆盖添加验证:tx_your_extension_domain_model.php

'propertyname' => [
        'exclude' => true,
        'label' => 'LLL:EXT:your_extension/Resources/Private/Language/locallang_db.xlf:tx_your_extension_domain_model_field.propertyname',
        'config' => [
            'type' => 'input',
            'size' => 30,
            'eval' => 'trim,uniqueInSite',
            'default' => ''
        ],

'eval' 是一些您可以使用的验证器。请参阅文档了解确切的规格。

© www.soinside.com 2019 - 2024. All rights reserved.