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

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));

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

The disabled attribute is fine but actually, input fields have a 'readonly' attribute. And it sounds like you want the field to still be shown to the user so using 'hidden' isn't really addressing what you want done.
So an alternative (and actually specifically addressing your requirement for 'read only'):
echo $this->Form->input('fieldname', array('readonly' => 'readonly'));
I found that using disabled prevents jquery click triggers from firing versus readonly still fires e.g. using a bootstrap datepicker text field
Here's a link to WC3 for it: http://www.w3schools.com/tags/att_input_readonly.asp

if you really want to make a field read only why you want to use form field, just echo the value, one can easily change disable or readonly attribute of form field with simple javascript or firebug.

Okay, after having tried several approaches, here is what I like.
1) Use readonly (disabled will remove the value after hitting "save", when you are in update mode, which sucks):
echo $this->Form->input('email', array('readonly' => 'readonly'));
2) To prevent this from updating when removing 'readonly' via browser plugins, you can add this to beforeSave of your model:
if(isset($this->data[$this->alias]['id'])) // id is only set if we update
{
unset($this->data[$this->alias]['email']);
}
Field lists are not comfortable. Why should I add all the fields, when I actually only want to exclude one?
Unsetting will prevent CakePHP from updating it in the database. Of course, after hitting save with an (invalidly) updated e-mail address, this update will be shown in the form once. But as the user has manipulated the HTML form and since the database field stays unchanged, this should not matter.

You can do either of two things:
Make the field hidden
(Ex. echo $this->Form->input ('username, array ('type' => 'hidden'));
Reset the value of username to it's original value, before submitting the form or possibly in beforeSave.

Related

How to ensure that empty select multiple option still will show up as key in request->data in cakephp3?

I am using select. I want to ensure that in CakePHP3 FormHelper, I always have the key inside request->data regardless if it is empty.
Currently, my code is
<?= $this->Form->select('rooms[]', $rooms, ['id' => 'room-tags', 'multiple', 'empty' => '']); ?>
I have tried hiddenField. It does not work.
I need to ensure that inside request->data I will always have the key rooms which points to an empty array.
You are defining the multiple option wrong, while passing it as a value makes it into the HTML element as an attribute, the form helper will not be recognize it as an option.
This is how you have to define it in order to for it to act as a option.
'multiple' => true

CakePHP default validation not working in IE

The below code is creating input box with label and 'required'=>'required' is mandatory field. This is not working in IE.
<?php $this->Form->input('name', array('type'=>'text','placeholder'=>__('name'),'required' => 'required'));?>
Any input with required="required" is to prevent submitting the form if the input is empty with a hint of Please fill in this field (or similar). This is one of the many features introduced in html5 capable browsers.
Set 'required' => 'false' on your input fields and you will notice that cakephp's validation will take over, assuming you have your validation rules in the Model offcourse
<?php $this->Form->input('name', array('type'=>'text','placeholder'=>__('name'),'required' => 'false'));?>

Cakephp - keep selected value for dropdownlist after submit

How can I keep the selected value for a dropdownlist after form submission in Cakephp?
If more info (or some code) is needed just tell me please.
UPDATE
Here is part of the code in my view:
echo $this->Form->create('Chart');
echo $this->Form->input('username',
array('label'=>('Usernames List'),
'default'=>('Select username'),
'options'=>$usernames, 'selected'=>false));
echo $this->Form->end('Create Chart');
So, when I press 'Create Chart', the dropdownlist doesn't keep the username that I selected, but it goes back to the first one.
The Form helper uses the data stored in $this->data to prepopulate fields. Make sure that when you are submitting the form, the view that is rendered after has the appropriate model/key data stored in $this->data in order for the Form helper to correctly fill in the appropriate values.
Can we see your controller action possibly? That may help draw a more accurate conclusion.
you should never use the view to set defaults or values (especially selected/value is wrong as it - like your code - destroys the idea of persistent forms).
use the controller instead
#see http://www.dereuromark.de/2010/06/23/working-with-forms/ (Default Values)
add value in dropdown like this:
<?php echo $this->form->select('Schedule.showsid', array('0'=>'title', '1'=>'description'));?>

CakePHP form helper - change value of hidden input for checkbox/radio

Using CakePHP's form helper to generate a checkbox is easy enough; to use the example from the documentation:
echo $this->Form->checkbox('done',array('value' => 555));
This will produce the following HTML:
<input type="hidden" name="data[User][done]" value="0" id="UserDone_" />
<input type="checkbox" name="data[User][done]" value="555" id="UserDone" />
This is all well and good, and the hidden field serves to force submission of a value for the "done" field even if the box remains unchecked.
Now, for the sake of argument, let's say the database definition of this field is ENUM('yes','no'). Of course I can easily change the value of the checkbox to "yes". However, if it's unchecked, a value of "0" is submitted from the hidden element. This produces no error or warning from mysql, as 0 is always a legal value for an enum field; it appears as an empty string.
Can I change value of the hidden field that CakePHP generates (to "no"), or do I need to suppress the auto-generation and create the hidden field myself? (An annoyance that grows with the number of checkboxes.)
I believe this all applies to radio button groups, too—at least if they don't have a default selection.
I'm using CakePHP 1.3. Thanks.
With FormHelper::checkbox, you can use hiddenField to set the default value.
<?php echo $this->Form->checkbox('done', array('value'=>'yes', 'hiddenField'=>'no');?>
With FormHelper::radio, you can only set value to default to one of the options, if the values match. This will also suppress the hidden field.
<?php echo $this->Form->radio('done', array('yes' => __('Yes')), 'no' => __('No'), array('value'=>'no');?>
Also, you should remember that CakePHP does not support enums (and I am sure this sort of scenario is one reason)
If your field data is truly binary (yes/no true/false enables/disabled etc.) then for the sake of CakePHP conventions you should just use an int(1) or tinyint(1) field and then convert the boolean value to yes/no etc in the view.
Then you don't have to worry about creating your own hidden input values and disabling the generated hidden inputs.
Another option would be to override the form->helper checkbox method that gets called by form->input to accept a new key in the options array that sets the value to something other than a 0 / false.
Unfortunately, FormHelper::checkbox allows you to disable the hidden element, but not to select its value, so you will need to do so and create the hidden field yourself. For example:
<?php echo $this->Form->hidden('done',array('value'=>'no'))?>
<?php echo $this->Form->checkbox('done',array('value'=>'yes','hiddenField'=>false))?>
With FormHelper::Radio worked for me like that
echo $this->Form->radio(
'done',
['yes' => __('Yes'), 'no' => __('No')],
['hiddenField' => false]
);

CakePHP: Field label in model

Are there any approaches to set in model field label? I dont want use 'label' property in form helper.
Please make sure I understand this correctly, you want to set a field label in the model, rather than using the form helper?
That violates basic MVC architecture. While Cake is flexible on some things, I don't think this is a possible option. I also don't see why you'd want to do it -- is there some reason that you don't want to use the label property in the form helper?
The basic issue is that the label for a form is part of the presentation layer, while the model represents the data. As such, it isn't possible (and I can't think of a situation where it'd make sense...) to assign a label to a data field which would then be used whenever that field is output.
If I misunderstood your question, please clarify.
What I do is setting up a convention in my models. I added a public attribute called "fieldLabels" to all the models, to assign default text labels for generic forms.
Example:
class MyModel extends AppModel {
// ...
public $fieldLabels = array(
'username' => 'User name',
'email' => 'e-mail address',
'phone' => 'Phone No.',
);
// ....
}
Then I pass around the labels to the view and use the extra parameter for the input, as sibidiba said:
echo $this->Form->input('title', array(
'label' => $fieldLabels['title'] . ': ',
));
In case I need special labels, I'll handle each case as an exception. Of course, if you want internationalization, that's a whole different topic.
Do you want to set the label's value? This is done in the view, but of course the value can originate from the controller/model. Like this:
echo $this->Form->input('title', array(
'label' => $titleLabel,
));
you can also disable the label element:
echo $this->Form->input('title', array(
'label' => null,
));
Not 100% sure, but I think you might be looking for Model::displayField
i suggest u directly use the helper u want.. bcos $form-input() creates div .. labels..
i personally had to weed out this on each line
with the direct helper like
$form->text()
$form->textarea()
$form->select()
u can keep the code much cleaner.
Note: $form->input saves time when used right...

Resources