在 cakephp 模板中显示实体字段的最大长度 3.x

Display the max-length of entity-field in template of cakephp 3.x

我有一个 cakephp 3.x 项目,其表单包含输入字段 "description"。该模型为此字段定义了 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 现在是硬编码的。是否可以从我的 table 或实体中获取此值?类似于 $product->geMaxLength('description');?

不知道这样做是否正确或最好,但您可以从 Controller 中的 Table 对象中检索您的 Validator,然后获取 ValidatorSet 和你的字段 ValidatorRule

这里假设你的型号名称是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()