Sunday, January 23, 2022

[FIXED] Cakephp forms - Is there a way to make a field read only (in the view)

Issue

I have a Cakephp 1.3 form that allows users to edit the profile data. But some of the information in the forms needs to be read only (sometimes).

Is my only option to echo and format the field contents in the read only case or is there a flag in the Cake form that allows for read only fields. Ideally the read only fields would be greyed out similar to other interfaces.

    echo $this->Form->create('User', array('url' => array('controller' => 'User', 'action'=>'editUser')));

    echo $this->Form->input('id', array('type'=>'hidden'));

If (!isset($IsAdmin)) {
    // Only display username - read only! Add code here
    echo $this->Form->input('username', array('label' => __d('users', 'User',true)));
} else {
    // Admins can edit user names
    echo $this->Form->input('username', array('label' => __d('users', 'User',true)));
}           

 ... more fields here

    echo $this->Form->end(__d('users', 'Submit',true));

Solution

You can add a 'disabled' key to the options array, however realise that this is only the front-end/presentation of the form, people will be able to override the 'disabled' property of the input field and modify its value.

To prevent unwanted changes to be saved, you need to specify a 'fieldList' when saving the data using your model

To output a disabled form field;

echo $this->Form->input('fieldname', array('type'=>'hidden', 'disabled' => 'disabled'));

Then, when saving the data, specify a fieldlist (documentation: http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html#saving-your-data)

$this->MyModel->save($this->data, true, array('field1', 'field2'));

The fieldlist should include all fields that are allowed to be updated by the user



Answered By - thaJeztah

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.