【问题标题】:Display the max-length of entity-field in template of cakephp 3.x在 cakephp 3.x 的模板中显示实体字段的最大长度
【发布时间】:2018-07-09 12:20:12
【问题描述】:

我有一个包含输入字段“描述”的表单的 cakephp 3.x 项目。模型为此字段定义了 160 个字符的 maxLength:

$validator
    ->allowEmpty('description')
    ->add('description', 'length', [
        'rule' => ['maxLength', 160],
        'message' => 'Products description cannot be longer than 160 characters'
    ]);

在我的模板中,我有一个小的 javascript 脚本,它向用户显示他已经使用了 160 个字符中的多少个140 of 160 characters used

160 现在是硬编码的。是否可以从我的表或实体中获取此值? $product->geMaxLength('description'); 之类的东西?

【问题讨论】:

  • 不,我以前没看过。然而,本节没有提供答案,因为 max-length 仅在验证器中,而不是(还)在模式定义中。
  • 啊,我还以为架构也包含这个限制,比如varchar(160)

标签: cakephp cakephp-3.0


【解决方案1】:

不知道这样做是正确的还是最好的方法,但您可以从Controller 中的Table 对象中检索您的Validator,然后获取ValidatorSetValidatorRule你的领域

我在这里假设您的模型名称是Products

你的ProductsController.php:

$maxLength = $this->Products
    ->getValidator()       // gets the validator for the ProductsTable
    ->field('description') // gets a ValidationSet for a field
    ->rule('length')       // gets the Rule for the length 
    ->get('pass');         // gets the value of the maxLength

然后您可以将 thuis 值传递给视图

$this->set('maxLength', $maxLength);

以便您可以在视图中使用该值

$this->Form->control('description', ['label' => 'max '.$maxLength.' chars']);

API 参考

getValidator()

field()

rule()

get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多