hard-code Form input field in cakephp so user can't edit it? - cakephp

I have following form field in a registration form in cakephp. I want to make it 'hard-coded', so user can't edit it
echo $form->input('name', array('label' => __('Name *', true)));

Then don't add it to the form.
Those fields should be added in the controller (or even beforeValidate/beforeSave model layer) then right before saving:
if ($this->request->is('post')) {
$this->User->create();
// add the content before passing it on to the model
$this->request->data['User']['status'] = 1;
if ($this->User->save($this->request->data)) {
...
}
}
See "default values - hidden" here.

You can set the readonly property:
echo $form->input('name', array('label' => __('Name *', true), 'readonly' => true));
However, this only affects the UI, and so you still have to apply mark's answer to ensure the value doesn't get changed by the user.

Two options:
hard code the value before the save
use white list
If you want the field to be a read-only, from the moment it is set. use white list. this way - it doesn't matter if the user will submit the field or not. cake won't save it.
$white_list = array('title', 'category');
$this->Model->save($data,$validate,$white_list);
The other solution is as mark coded it:
$this->request->data['User']['status'] = 1;
if ($this->User->save($this->request->data)) {
...
}
Any solution should mix a UI indication that the field will not be changed. tho a good UX will not allow it in the first-place.

Related

Cakephp 3 : Multiple Forms per page for the same model

I have a page where there are multiples forms generated with the FormHelper that aim at modifying the same entity. The problem is: validation errors will show up on both forms.
With cakephp 2, this problem was solved by extending Models (see : http://bakery.cakephp.org/articles/RabidFire/2010/06/26/multiple-forms-per-page-for-the-same-model ).
However I don't see how to do this with cakephp 3.
EDIT: i'm gonna describe more precisely what I'm trying to do.
I have two forms on the same page. The first one enables a user to change his email address, the other one to change his password.
Both forms are created with the Form helper and the same user entity.
In both forms, there is a field where the user should enter his current password (as a security measure). A validator will check if the password entered is correct before letting the email or the password to be changed.
Problem: let's say the user tries to change his email but typed a wrong password, the "wrong password" message will appear on both forms.
This is sort of an edge case that the FormHelper is not ready to handle graciously. But this is a solution, you will need 2 entities:
$user = $this->Users->get($id);
$user->unsetProperty('password');
$clonedUser = clone $user;
$this->set(compact('user', 'clonedUser'));
In your view, you build your forms in a way that you can detect which entity you should pass:
echo $this->Form->create($this->request->data('_form1') ? $user : $clonedUser);
... fields here
echo $this->Form->hidden('_form1', ['value' => 1]);
echo $this->Form->create($this->request->data('_form2') ? $user : $clonedUser);
... fields here
echo $this->Form->hidden('_form2', ['value' => 1]);
What the above code does is detecting which of the forms was previously submitted and render the form with either the empty cloned entity or the entity having the errors.
Stumbled upon this because I had the same requirement. I would go with José but move the logic to the Controller instead:
$callback = $this->Inquiries->newEntity();
$inquiry = $this->Inquiries->newEntity();
if ($this->request->is('post')) {
if ($this->request->data('_type') === 'callback') {
$callback = $this->Inquiries->patchEntity($callback, $this->request->data, ['validate' => 'callback']);
$entity = &$callback;
} elseif ($this->request->data('_type') === 'inquiry') {
$inquiry = $this->Inquiries->patchEntity($inquiry, $this->request->data);
$entity = &$inquiry;
}
if (!$entity->errors()) {
// do stuff here
}
}
$this->set(compact('callback', 'inquiry'));
Pass the type of the form:
echo $this->Form->input('_type', ['type' => 'hidden', 'value' => 'inquiry']);

how to add hidden value from registeration from in db field in cakephp

I have one registration form. I want to pass hidden value in that form. I have created one field in database 'lang'. In registration form I did like this: echo $form->hidden('lang', array('value' => '1')); But its not saving the value in db. Sorry I have no experience in cakephp, so please if anybody help me in this with all processes. Thanks
You should not just pass hidden stuff through the form just for the heck of it.
If you can, add those values prior to actually saving.
See http://www.dereuromark.de/2010/06/23/working-with-forms/ for details
Basically, you do:
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->create();
// add the content before passing it on to the model
$this->request->data['Post']['lang'] = '1';
if ($this->Post->save($this->request->data)) {
...
}
}

Settings page and multi edit rows

I would like to make a configuration page like this for my CMS
http://img4.hostingpics.net/pics/72087272ok.png
I want this page (admin/settings/index) gets me the various settings (ID 1 to 21) came to my table and in case of change, I can, in this form, do an update
After 3 days of not especially fruitful research I found something. I put in my SettingsController:
admin_index public function () {
if (!empty($this->data)) {
$this->Setting->saveAll($this->request->data['Setting']);
} else {
$this->request->data['Setting'] = Set::combine($this->Setting->find('all'),
'{n}. Setting.id', '{n}. Setting');
}
}
and my view:
<?php
echo $this->Form->create('Setting', array ('class' => 'form-horizontal'));
foreach($this->request->data['Setting'] as $key => $value) {
echo $this->Form->input('Setting.' . $key . '.pair');
echo $this->Form->input('Setting.' . $key . '.id');
}
echo $this->Form->end(array('class' => 'btn btn-primary', 'label' => 'Save',
'value' => 'Update!', 'div' => array ('class' => 'form-actions')));
?>
he is recovering well all my information, I can even update. The trouble is that I do not really know how I can do to get the same result as my first screenshot. He puts everything in the textarea while in some cases I want the checkbox and / or drop-down.
please help me or explain to me how to make a page that retrieves configuration information from my table and allows me to edit without use an address like admin/settings/edit/ID
My table settings is something like this here
http://img4.hostingpics.net/pics/724403settings.png
If you are asking about how to format the output to produce a "settings" page, you will need to do it manually or add some kind of metadata to your table schema, such as "field_type".
Now Cake will automatically generate a checkbox for a boolean or tiny int, for example, but as you have varchars, ints, texts and so on, this won't work for you (pair is presumably varchar or text to allow for the different possible values.
You cannot really automagically generate the outputs you want without telling Cake.
One option would be to add a field_type to the table, so:
key value field
site_name My Site input
site_online 1 checkbox
meta_desc [some text] textarea
and something like
foreach($settings as $setting) {
echo $this->Form->{$setting['field']}($setting['key'],
array('value' => $setting['value']));
}
might do what you are after.
Or if($key=='site_name') // output a textbox
but this is not exactly ideal.

CakePHP controller name in behavior

I created relation Post hasMany Photos, Photos actsAs ImageBehavior.
How put to $data['Photo']['model'] = 'Post'? Automated?
I'm not sure what you are asking about but when you have a form, you can simply add to your $this->data['Photo']['model'] any value you want with hidden fields.
// photo/add.ctp:
$this->Form->create('Photo');
$this->Form->input('model', array('type' => 'hidden', 'value' =>'yourvalue'));
$this->Form->end('Submit');
Update
You can set this value after the form was submitted, so even if someone will replace the hidden field value you can just check it.
function add(){
if(!empty($this->data['Photo']['model']){
$this->data['Photo']['model'] = "yourvalue";
$this->Photo->save($this->data));
}
else
rest of the code...
}
rest of the code

Saving multiple records for multiple models cakephp

Hey guys, I'm super stuck after a long night.
I'm creating an app where you can create food menus dynamically, and have relationships set up as such: Menu hasMany Widget, Widget hasMany WidgetItem (and of course, WidgetItem belongsTo Widget, Widget belongsTo Menu).
The menu is created first, then the user is redirected to addSectionsToMenu, where I have set up multiple Widgets (title input), respectively with multiple items (menu items).
My widgets save and attach to the menu fine, but my WidgetItems don't save. My models are set up fine I am sure, and I spent 2 hours sorting out my $data structure. I just think I need to figure something out here.
Please help!
Thanks,
~Harley
function addSectionsToMenu($menu_id = null){
$this->layout = 'admin';
$this->set('menu_id', $menu_id);
$this->set('menu', $this->Widget->Menu->findById($menu_id));
if (!$menu_id && empty($this->data)) { $this->Session->setFlash(__('Pick a menu to add to please :)', true)); }
$saveSuccess = false;
if(!empty($this->data['Widget'])) {
$widget_count = 0;
foreach($this->data['Widget'] as $widgetKey => $widget) :
if($this->Widget->saveAll($widget)) : $saveSuccess = true; endif;
$widget_count++;
endforeach;
if ($saveSuccess) {
$this->Session->setFlash(__($widget_count.' sections have been added to the Menu', true));
$this->redirect(array('controller' => 'menus', 'action' => 'index'));
} else {
$this->Session->setFlash(__('The Menu and Sections could not be saved. Please, try again.', true));
}
}
}
I've had problems saving multiple models at once and I solved it by adjusting the validation option.
$this->Invoice->saveAll($this->data, array('validate' => true))
The explanation of the options array doesn't make complete sense to me, but the default was causing my insert to fail because the related records were not getting their foreign key from the insert of the parent record. Changing the option to "first" (the default) to "true" solved the problem and the rows are showing up in the database correctly.

Resources