yii2redactor

How to limit max char on redactor limiter plugin?


I have this code in my view

<div class="col-xs-6">
        <?php echo $form->field($model, 'deskripsi_produk')->widget(Redactor::className(),['clientOptions'=>['autoresize'=>'true', 'limiter' => 20, 'plugins' => ['limiter'], 'buttons'=> ['html', 'formatting', 'bold', 'italic','underline','lists','horizontalrule'],]]);?>
        </div>

it can limit 20 char but How I can limit text area to max string defined on model instead of limit with specific number?

Here is my model

class TbProduk extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public  $image;
    public static function tableName()
    {
        return 'tb_produk';
    }

public function rules()
{
    return [
        ...
        [['deskripsi_produk'], 'string', 'max' => 2000],
        [['deskripsi_produk'], 'checkDesc'],
        ...
    ];
}
}

Solution

  • Trying to get the value via rules is a terrible idea. Instead you should create a constant in TbProduk that will hold the length:

    class TbProduk extends \yii\db\ActiveRecord
    {
        const DESKRIPSI_PRODUK_LENGTH = 2000;
        ...
        public function rules()
        {
            return [
                ...
                [['deskripsi_produk'], 'string', 'max' => static::DESKRIPSI_PRODUK_LENGTH],
                ...
            ];
        }
    }
    

    And in your view:

    <div class="col-xs-6">
        <?php echo $form->field($model, 'deskripsi_produk')->widget(Redactor::className(),['clientOptions'=>['autoresize'=>'true', 'limiter' => TbProduk::DESKRIPSI_PRODUK_LENGTH, 'plugins' => ['limiter'], 'buttons'=> ['html', 'formatting', 'bold', 'italic','underline','lists','horizontalrule'],]]);?>
    </div>