Write Checkbox to CakePHP Session - cakephp

i would like to have a form where i have an additional checkbox (will not store input to db) which will be readout in the controller.
For Example.
In a Job Edit view i can select a user. Under this user is a checkbox. This checkbox will send after i have assigned the Job to the User an email.
In my Controller i write
$post_array = $this->request->data;
if ($post_array['Job']['mailcheck'] == NULL) {
// DO SOMETHING
} else {
// DO SOMETHING
}
But it doesn´t read out the checkbox value...
Any ideas how to solve this problem?
Thx for help

While mark's answer is correct, allow me to elaborate.
Keep in mind that checkboxes sometimes behave curiously. An unchecked checkbox may not get posted at all, and that may be why your condition fails.
Regarding why you couldn't make it work:
It seems you are performing a redirect in either case, which is why you never see the edit form. Check to see if you missed something or just try this:
if ($this->request->is('post')) {
if (!empty($this->request->data['Job']['mailcheck'])) {
$this->redirect(array('action' => 'sendMails',$id));
} else {
$this->redirect(array('action' => 'sorted'));
}
}

This suffices:
if (!empty($this->request->data['Job']['mailcheck'])) {
// yes, checkbox was selected
} else {
// no, it was not selected
}

Related

Redirect user to the second last page in CakePHP

I have a model class Event which has the following actions in question: view and delete.
The deletion can only happen from the view action. Getting to the view action is possible from two places that are:
events/dashboard
and
calendar/view_calendar
the latter takes three parameters: user_id, month and year so that would for example be
calendar/view_calendar/120/5/2014
So depending on which action user got to for example events/view/1400, he has to be redirected accordingly.
The referer does not work as it redirects to the events/view with the id of event which has already been deleted.
Any help or guidance is much appreciated.
Put a second Parameter to the view, like
events/view/1400/0
for dashboard
and
events/view/1400/1
for view_calendar
and pass these params to your delete action, like
events/delete/1400/1
In your delete function you can you use the usual redirect:
if($secondParam == 1) {
$this->redirect(array('action' => 'view_calendar'));
} else {
if($secondParam == 0) {
$this->redirect(array('action' => 'dashboard'));
}
}
You can save somewhere the information about the referrer when you land in events/view and the pass it to events/delete.
You can use a named parameter or a query string so your link to the delete action becomes appear something like
events/delete/1400/referrer:dashboard
or
events/delete/1400/referrer:view_calendar
or
events/delete/1400/?referrer=dashboard

Validate associated models in CakePHP2

I'm a noob in CakePHP and I've been trying to do some complex validations here:
I have the following models:
- Fonts (name, file);
- Settings(value1,value2,value3,type_id,script_id);
- Types(name)
Whenever I create a Font I also create a default setting associated to it. Also, this setting has a type associated. After the Font is created I can associate more settings to it (Font hasMany Settings), but I need to make sure that two settings of the same type are not added to that font. I don't know how to handle this case. Any help is appreciated. Thanks.
I'd use a simple beforeSave validation
//in setting.php model
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['font_id']) && isset($this->data[$this->alias]['type_id']) {
$otherSettings = $this->find('all', array('conditions'=>
array('type_id'=>$this->data[$this->alias]['type_id'],
'font_id'=>$this->data[$this->alias]['font_id']);
//check if it's insert or update
$updated_id = null;
if ($this->id)
$updated_id = $this->id;
if (isset($this->data[$this->alias][$this->primaryKey]))
$updated_id = $this->data[$this->alias][$this->primaryKey];
if (count($otherSettings) > 0) {
if ($updated_id == null)
return false; //it's not an update and we found other records, so fail
foreach ($otherSettings as $similarSetting)
if ($updated_id != $similarSetting['Setting']['id'])
return false; //found a similar record with other id, fail
}
}
return true; //don't forget this, it won't save otherwise
}
That will prevent inserting new settings to the same font with the same type. Have in mind that this validation will return false if the validation is incorrect, but you have to handle how you want to alert the user of the error. You can throw exceptions from the beforeSave and catch them in the controller to display a flash message to the user. Or you could just not save those settings and let the user figure it out (bad practice).
You could also create a similar function in the model like checkPreviousSettings with a similar logic as the one I wrote above, to check if the settings about to be saved are valid, if not display a message to the user before attempting a save.
The option I prefer is the exception handling error, in that case you'd have to replace the return false with
throw new Exception('Setting of the same type already associated to the font');
and catch it in the controller.
Actually, the better approach is to not even display the settings with the same type and font to the user, so he doesn't even have the option of choosing. But this behind-the-scenes validation would also be needed.

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)) {
...
}
}

CakePHP 2.0 Accessing model field values for view/controller comparisons - Only letting users edit/delete their own posted items

I am fairly new to CakePHP, I am trying to only allow those users who created an event to be able to edit or delete an event, so I am comparing the current user id, with the 'user_id' field of the event the current event (saved when a user creates an event). Any help would be appreciated thanks, my code(Andrew Perk) is as follows:
public function isAuthorized($user) {
$this->loadModel('User');
if ($user['role'] == 'admin') {
return true;
}
if (in_array($this->action, array('edit', 'delete'))) {
if ($user['id'] != $this->request->data['Event']['user_id']) { ///THIS IS THE LINE I FEEL IS WRONG - PLEASE ADVISE
//echo debug($event['user_id']);
//$this->Session->setFlash(__('You are not allowed to edit someones event'));
return false;
}
}
return true;
}
There are a few ways you can accomplish this. The one I have found that usually works best is to put a callback in the model that will set the user_id for the record you are trying to modify. Then it doesn't have to get all mixed up in controller everywhere you are trying to CRUD a record.
You can read more about limiting user data here: http://blogchuck.com/2010/06/limit-data-by-user-with-cakephp/
This will also apply to deleting data.
Hope it helps. Happy coding!

Filtering data using ajax observefield

I ve tried to implemented filtering data (list base on selected category) using dropdown with observefield and ajax pagination. I use session to remember selected category in order to keep pagination.
Here is my code (Cakephp 1.2)
In view :
echo $form->select('Category.id', $categories, null, array('id' => 'categories'),'Filter by Categories')
echo $ajax->observeField('categories' ,array('url' =>'update_category','update' => 'collectionDiv'));
In Controller:
if(!empty($this->data['Category']['id']))
{
$cat_id=$this->data['Category']['id'];
$filters=array('Collection.category_id' => $cat_id);
$this->set('collections', $this->paginate('Collection', $filters));
$this->Session->write($this->name.'.$cat_id', $category_id);
}
else
{
$cat_id=$this->Session->read($this->name.'.cat_id');
$filters=array('Collection.category_id' => $cat_id);
$this->set('collections', $this->paginate('Collection'));
}
The filter work as I wanted but the problem is when I select empty value('Filter by Category) it still remember last category session so I can't back to the default list (All record list without filter).
I've tried to make some condition but still not success. Is there another way? Please I appreciate your help. thank
hermawan
Perhaps I don't understand the question, but it looks to me like it might be worth changing:
else
{
$cat_id=$this->Session->read($this->name.'.cat_id');
$filters=array('Collection.category_id' => $cat_id);
$this->set('collections', $this->paginate('Collection'));
}
to:
else
{
$this->set('collections', $this->paginate('Collection',array()));
}
In effect your code appears to be doing this anyway. Check what the URL is at the top of the browser window after it has returned. Does it still contain pagination directives from the previous query?
You might want to review http://book.cakephp.org/view/167/AJAX-Pagination and make sure you've 'ticked all the boxes'.
I got it, It work as I hope now. I my self explain the condition and solution.
When I select category from combobox, then it render the page the code is :
If ($this->data['Category']['id']) {
$cat_id=$this->data['Category']['id'];
$this->Session->write($this->name.'.category_id', $category_id);
// I will use this session next when I click page number
$filters=array('Collection.art_type_id' => $category_id);
$this->set('collections', $this->paginate('Collection', $filters));
}else{
//if clik page number, next or whatever, $this->data['Category']['id'] will empty so
// use session to remember the category so the page will display next page or prev
// page with the proper category, But the problem is, when I set category fillter to
// "All Category" it will dislpay last category taked from the session. To prevent it
// I used $this->passedArgs['page']. When I clik the page paginator it will return
// current number page, but it will be empty if we click dropdown.
if (!empty($this->passedArgs['page']) {
$cat_id=$this->Session->read($this->name.'.category_id');
$filters=array('Collection.category_id' => $cat_id);
$this->set('collections', $this->paginate('Collection',$filters));
}else{
$this->set('collections', $this->paginate('Collection'));
}
}
From this case, I think that observefield will not send passedArg as we get from url such from ajax link or html->link. I hope this will usefull to anybody

Resources