jeudi 29 janvier 2015

Minimizing multiple if else conditions in cakephp

I have this method in cakephp controller. Here I try to save the user subscription data to the subscription table based on whether the user is already registered to the site or not. I have two form fields named Name and Email. So if a user is logged in and clicks on the subscribe button, the form pop-up comes up with his name and e-mail already filled in the boxes and if he submits it, he will be subscribed. When a user who is not registered and not logged in, but just want to subscribe, he will have an empty subscription form to fill.


Later I added some modifications that if any user, registered or not registered, wants to subscribe with the same e-mail, a pop-up will show saying: "you are already registered". So far I have done this. It works okay but with a lot of if and else conditions. Any idea about how to minimize this will be helpful. I am new to cakephp and all these things. My controller method code is below:



function subscription_add() {
if(!empty($this->data)){
if($this->Session->check('User')){
$is_subscribed = $this->Subscription->find('count', array('conditions'=>array('Subscription.email' => $this->data['Subscription']['email'])));
if($is_subscribed > 0){
$this->Session->setFlash('You are already Subscribed !','default',array(),'E');
$this->redirect(array('action' => 'index'));
}
else{
$this->data['Subscription']['user_type'] = 1;
$this->data['Subscription']['user_id'] = $this->Session->read('User.id');
$this->Subscription->create();
if ($this->Subscription->save($this->data)) {
$this->Session->setFlash('Congrats ! You are Subscribed ', 'default', array(), 'S');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('You are not subscribed. Please, try again.', 'default',array(),'E');
}
}
}
else{
$subscribed = $this->Subscription->find('count', array('conditions'=>array('Subscription.email' => $this->data['Subscription']['email'])));
if($subscribed > 0){
$this->Session->setFlash('You are already Subscribed !','default',array(),'E');
$this->redirect(array('action' => 'index'));
}else{
$this->Subscription->create();
if ($this->Subscription->save($this->data)) {
$this->Session->setFlash('Congrats ! You are Subscribed ', 'default', array(), 'S');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('You are not subscribed.. Please, try again.', 'default',array(),'E');
}
}
}


}
}

Aucun commentaire:

Enregistrer un commentaire