Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to disable a field on update in Yii

Tags:

php

yii

I want to disable or make readOnly a field when user will update, i.e. username. When registered user update their information, they will see that username disable. I tried based on this answer but it does not work for me rather giving an error User has an invalid validation rule. The rule must specify attributes to be validated and the validator name. I wrote in the rules:

array('username', 'readOnly'=>true, 'on'=>'update'),

and in the form:

echo $form->textFieldRow($model,'username',array(
         'class'=>'span5',
         'maxlength'=>45,
         'readOnly'=>($model->scenario == 'update')? true : false
     ));

But do not understand why this shows error.

like image 286
StreetCoder Avatar asked Dec 19 '22 16:12

StreetCoder


1 Answers

That validation rule is meaningless.

The error message tells you that the validator name is missing:

 array('username', 'ValidatorNameGoesHere', 'readOnly'=>true, 'on'=>'update'),

But even if you fill in something for the validator name it still won't work because there is no validator in Yii that has a readOnly attribute; this role is played by the safe attribute.

Making certain fields read-only when updating in a secure manner (i.e. one that the user cannot override) means that you will have to look at the submitted data, determine independently if the data includes the PK of an existing model (which tells you if you are adding or updating) and set the model's scenario based on that. If you don't do this, your users can easily manipulate the HTTP requests sent to the server and bypass the read-only logic.

After the scenario is set you can easily enforce the read-only logic with a couple of rules:

 array('username', 'safe', 'except'=>'update'),
 array('username', 'unsafe', 'on'=>'update'),
like image 197
Jon Avatar answered Dec 29 '22 00:12

Jon