Stop Yii double-encoding html entities with ActiveForm

Is there any way you can stop Yii from double-encoding entities when it automatically fills in form fields with their associated model attribute data?

For example, I am passing in some already encoded entities, yes I still want Yii to encode the entities, but I don’t want it to double-encode as this then messes up data that is already encoded.

Yes I know I can just decode the data before Yii gets to it and then Yii will encode it again, but TBH I don’t feel safe doing that just in-case things change and I am inserting the data somewhere else or what not - I would just prefer Yii to not double encode.

Thanks!

Could you give us some sample code that illustrates your issue?

Well sure, here is some simplified code…

Model:




class MyModel extends Model {


    public $content;


    public function init() {

    

        $this->load(Yii::$app->request->post());

    

        $this->setData();

    

    }

    

    public function setData() {

    

        if (Yii::$app->request->isGet or !isset($this->content)) {

            $this->content = $info['content'];

        }

    

    }


}



Controller:




$model = new MyModel();


return $this->render('edit', [

                               'model' => $model

                                //.....

                           ]

);



View:




$form = ActiveForm::begin();


$form->field($model, 'content')->textArea();


ActiveForm::end();



$info[‘content’] is the value that comes from the database and is stored as entities, I can’t pass it to the database without being encoded as then html purifier will strip out unsafe code; this data may contain data that will be inside code blocks, so that’s why it’s common it will include code that may seem unsafe and is why htmlpurifier will strip it out; I know I can just bypass htmlpurifier and put the code in the database straight up, but I don’t particularity want the database filled with potentially malicious code.

So anyway, when the code is pulled from the database and set to the $content property, Yii automatically fills the content field with the value of that field, which is already encoded as entities, but Yii already encodes data it automatically fills into form fields, so basically it just needs to not double encode entities, which should be a simple setting change such as the parameter you can control when using encode.

Hmm …

The following is from the source code of yii\helpers\BaseHtml.

It’s hard-coded to use encode() with $doubleEncode being set to true. So, there’s no simple solution for you at least for the moment.

I was afraid of that. I guess I could override that method, but don’t particularly want to do that if I can void it.

I will make a feature suggestion on GitHub.