CakePHP Cancel button does not fire - forms

In my view, I have a form with submit and cancel buttons. Both actions return me to my index page. The only difference is Submit does a normal db submit and displays the message 'Your Invoice has been updated.', whereas the Cancel should cancel the update and display 'Update canceled.'. Here's the controller code:
public function edit($id = null) {
$this->Invoice->id = $id;
$this->set('invoice', $this->Invoice->read(null, $id));
//Check for $_GET
if ($this->request->is('get')) {
$this->request->data = $this->Invoice->read();
} else {
// Bail if cancel button pressed
if (isset($this->params['form']['cancel'])) {
$this->Session->setFlash('Update canceled.');
$this->redirect(array('action' => 'index'));
} else if ($this->Invoice->save($this->request->data)) {
$this->Session->setFlash('Your Invoice has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to update your Invoice.');
}
}
}
And here is the view:
<fieldset>
<legend>Enter New Values</legend>
<li><?php echo $this->Form->input('purchaseOrderNumber'); ?></li>
<li><?php echo $this->Form->input('siteAddress'); ?></li>
<li><?php echo $this->Form->input('siteCity'); ?></li>
<li><?php echo $this->Form->input('siteState'); ?></li>
<?php
echo $this->Form->button('Submit Form', array('type' => 'submit'));
echo $this->Form->submit('Cancel', array('div' => false, 'name' => 'cancel'));
?>
However, no matter which button is pressed, it ALWAYS returns the first message. It also performs the db submit.
I tried unsuccessfully using XDebug with Netbeans but that's a story for a different time. Usually my mistakes are obvious to others. So, I'm hoping someone can set me back on track.

I was just working on the same problem, and I found a solution that works without simply linking back to index. At Wylie's suggestion to debug $this->params, I noticed that the 'form' array was not being created. However, there was an array called 'data' in which the 'cancel' parameter was defined.
So in the controller where you are checking which button was pressed, instead of
if (isset($this->params['form']['cancel'])) {
use
if (isset($this->params['data']['cancel'])) {
and you will get a working cancel button.

Related

CodeIgniter - save method and redirects

I have a page to manage courses, built with CI 3. When the user hits the save button, the form is submitted to the save method. My problem is how do I redirect the user to the previous page with the form populated with the data inserted?
At the moment what's happening is that after submit, the save method loads the views of the /new page, and the URL stays as /save with the data populated.
Already tried the redirect, but it loses the data the user had inserted.
Here a snippet of my save method:
public function save()
{
$this->checkIsAdmin();
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', $this->lang->line('common_name'), 'required');
if ($this->form_validation->run() === FALSE)
{
$this->feedback_message->create('Please check fields', 'error');
$this->baseInfo['page_title'] = "Registar novo curso";
$this->mybreadcrumb->add('Registar curso', base_url('course/new'));
$data['schools'] = $this->School_model->listSchools();
$this->load->view('web/top', $this->baseInfo);
$this->load->view($this->templatesFolder.'tabs_start', array('courseId' => 0));
$this->load->view($this->templatesFolder.'manage', $data);
$this->load->view($this->templatesFolder.'tabs_end');
$this->load->view('web/footer');
/*redirect("/course/new", "location");*/
}else{
$saved = $this->Course_model->saveCourse();
if($saved){
$this->feedback_message->create('Success', 'success');
}else{
$this->feedback_message->create('Error '.$_POST['name'], 'error');
}
redirect('course/');
}
}
To re-populate the form you have to use the set_value('field_name') function in your input field like below:
<input type="text" name="name" value="<?php echo set_value('name'); ?>" />
Return the previous view as:
$this->load->view('view_name',$All_Data_For_View);
Still If you aren't understand then read the CI form validation again.

CakePHP - Model validation does not work

again alot of similar questions out there but none of them really help me.
HTML5 form validation seems to be triggering with messages "Please fill in this field" instead of the model validation messages which should be "Please enter the model"
I have a form to add Computers to the database.
Here is my form:
echo $this->Form->create('Computer');
echo $this->Form->input('Computer.model', array('label' => 'Model'));
echo $this->Form->input('Computer.memory', array('label' => 'memory'));
echo $this->Form->input('Computer.hdd', array('label' => 'hdd'));
echo $this->Form->input('Computer.price', array('label' => 'price'));
echo $this->Form->end('Save Computer');
Here is the full controller code with index and add actions
<?php
class ComputersController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function index() {
$this->set('computers', $this->Computer->find('all'));
}
public function add() {
if ($this->request->is('post')) {
if (!empty($this->request->data)) {
$this->Computer->save($this->request->data);
$this->Session->setFlash(__('Your Computer has been saved, or so it seems.....'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Not sure why we got here 1.'));
} else {
$this->Session->setFlash(__('By right, this should be the index page'));
}
}
}
?>
Here's the model
<?php
class Computer extends AppModel {
public $validate = array(
'model' => array(
'Please enter model name'=> array(
'rule'=>'notEmpty',
'message'=>'Please enter model'
)
)
);
}
?>
I read from other forms that triggering the model save function, which I do, will automatically trigger the model validation. How can i get the model validation to work?
Thanks
Kevin
As you were saying, if you have the notEmpty validation in the model, CakePHP adds required="required" on the input attributes. This is handled by the browser, so you see the default Please enter this field message when you try to submit an empty value. An advantage is that if you are using the browser in a different language, the message will be displayed in that language.
If you want to change that message, you can try a solution like the ones from this question. (this is probably not what you want)
If you want to remove that client-side message, you can disable it using novalidate
echo $this->Form->create('Computer', array('novalidate' => 'novalidate'));
This way, the HTML5 required property will be ignored, and you will get the message from the model.
I am not sure if there is a way to tell Cake to use the server-side value on the client.
$this->{Model}->save() returns false if the validation fails, but in your case you're redirecting with a flash message after save function. so first check the form is saving perfectly or not, if perfectly saving then redirect to listing page other wise render your view file with a flash message where you can view the validation messages.
if ($this->Computer->save($this->request->data)) {
$this->Session->setFlash(__('Your Computer has been saved, or so it seems.....'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to save form'));
}
Note: To disable html validation just do
$this->Form->inputDefaults(array(
'required' => false
));
in your view file
Hope this helps you.
Set 'novalidate' => true in options for FormHelper::create()
echo $this->Form->create('Computer', array('novalidate' => true));
For more information, go to http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html

Zend: Redirect from form without validation

I have a form for the creation of new "groups". I now added a small "go back" image with which the user should be able to go back one step. I don't know why, but when I click this new image, the controller and action used for the form which I want to leave (/admin/creategroup) is called again with HTTP POST set. Therefore, the form validation is done, and I'm stuck at this form with the validation errors displayed.
This is a snippet of the code from my form with both image-buttons. I wan't the "go back"-image to redirect me to the specified controller without validating the form:
$this->addElement('image', 'btnBack', array (
'name' => 'btnBack',
'id' => 'btnBack',
'label' => '',
'title' => 'Go back',
'alt' => 'Go back',
'src' => '/img/undo.png',
'onClick' => "window.location='/admin/groupoverview'"
));
$this->addElement('image', 'btnSave', array (
'name' => 'btnSave',
'id' => 'btnSave',
'label' => '',
'title' => 'Save this new group',
'alt' => 'Save this new group',
'src' => '/img/save.png',
'onClick' => "document.forms[0].submit();"
));
Edit:
I already thought of the possibility to check in /admin/creategroup whether it was called from the 'btnBack'-image or the 'btnSave'-image and skip form validation and redirect correctly if the source was the 'btnBack'-image.
I just think that there should be a nicer solution to directly redirect from the form and circumvent calling /admin/creategroup again.
Edit2:
My view script:
<div id="createGroupMask">
<br/>
Use the form below to create a new group
<?php
$this->form->setAction($this->url());
echo $this->form;
?>
</div>
My action in the controller:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
Now there is something to work with:
The isValid() loop is incorrect, your form will never evaluate as inValid with respect to the elements you've presented, you will never get to the else.
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
/* This is incorrect */
// Form data was invalid
// => This is where I land when pressing the 'back' image
// No further code here
}
}
$this->view->form = $form;
}
My problem is that I'm not sure what is going to be submitted from your form, I'm not really familiar with how your using "onClick" and what I presume is javascript. It looks like element btnBack should redirect on click and element btnSave should POST. However this does not seem to be happening.
I have done this type of thing in PHP and ZF with submit buttons, perhaps the flow of what I did will help:
NOTE: for this type of flow to work you must give the button element a label. The label is used as the submit value.
//psuedoCode
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
//I would probably opt to perform this task with a switch loop
if ($form->getValue('btnBack') === some true value) {
$this->_redirect('new url');
}
if ($form->getValue('btnSave') === some true value) {
//Process and save data
}
} else {
//Display form errors
}
$this->view->form = $form;
}
I think when all is said and done the crux of your problem is that you did not give your button elements a label.
I tried adding labels to my images, but this didn't work.
I also tried to use the isChecked() method on my btnBack-image like this:
if ($form->btnBack->isChecked()) {
// 'Go back' image was clicked so this is no real error, just redirect
}
This didn't work either.
I finally was able to check which image was clicked via the following method as answered in Zend form: image as submit button:
public function creategroupAction()
{
$form = new Application_Form_CreateGroup();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
// Data for new group is valid
...
} else {
// Form data was invalid
if (isset($this->_request->btnBack_x)) {
// 'Go back' image was pressed, so this is no error
// -> redirect to group overview page
$this->_redirect('/admin/groupoverview');
}
}
}
$this->view->form = $form;
}
I guess this doesn't thoroughly answer the original question as the validation is still done and I'm only checking for this 'special case' where the 'Go back' image was clicked, but I'll mark it as answered anyways.
Tim Fountain suggested an even cleaner approach in my somewhat related question:
Zend forms: How to surround an image-element with a hyperlink?

calling echo $this->action('panLogin','user') and $this->action('panRegister','user') on same script

I have a problem, i'm trying to render 2 forms (login and register) on one layout scrpt (header.phtml), every time i submit on one of the forms both actions for the controller are getting fired and i'm unsure how to fix it.
The forms are getting rendered fine within the layout, however when you click 'Login' or 'Register' on the forms the code fires in both the 'login' and 'register actions.
the header layout script snippet:-
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo $this->action('panlogin', 'user');
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo $this->action('panregister', 'user');
?>
</div>
the action scripts (phtmls)
panregister.phtml
<div id="pan-register">
<?php
$this->registerForm->setAction($this->url);
echo $this->registerForm;
?>
</div>
panlogin.phtml
<div id="pan-login">
<?php
$this->loginForm->setAction($this->url);
?>
</div>
the user controller actions:-
class Ajfit_UserController extends Zend_Controller_Action
{
protected $_loginForm;
protected $_registerForm;
public function init()
{
$this->_loginForm = new Ajfit_Form_User_Login(array(
'action' => '/user/login',
'method' => 'post',
));
$this->_registerForm = new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
}
//REGISTER ACTIONS
public function panregisterAction(){
$this->registerAction();
}
public function registerAction(){
$request = $this->_request;
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
$this->view->registerForm = $this->_registerForm;
}
//LOGIN ACTIONS
public function panloginAction(){
$this->loginAction();
}
public function loginAction(){
$request = $this->_request;
if(!$auth->hasIdentity()){
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
}
$this->view->loginForm = $this->_loginForm;
}
}
Please can someone with a little more knowlegde with the action('act','cont'); ?> code with in a layout script help me out with this problem.
Thanks
Andrew
While David is correct where best practices are concerned, I have on occasion just added another if() statement. Kinda like this:
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('submit') == 'OK') {
just make sure your submit label is unique.
Eventually I'll get around to refactoring all those actions I built early in the learning process, for now though, they work.
Now to be nosy :)
I noticed: $formData = $this->_request->getPost(); while this works, if you put any filters on your forms retrieving the data in this manner bypasses your filters. To retrieve filtered values use $formData = $this->getValues();
from the ZF manual
The Request Object
GET and POST Data
Be cautious when accessing data from the request object as it is not filtered in any way. The router and
dispatcher validate and filter data for use with their tasks, but
leave the data untouched in the request object.
From Zend_Form Quickstart
Assuming your validations have passed, you can now fetch the filtered
values:
$values = $form->getValues();
Don't render the actions in your layout. Just render the forms:
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo new \Ajfit\Form\User\Login(array(
'action' => '/user/login',
'method' => 'post'
));
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
?>
</div>
Then, whichever form gets used will post to its own action.

Problem passing URL variables in post form submission with CakePHP FormHelper

I'm writing my first CakePHP application and am just writing the second part of a password reset form where a user has received an email containing a link to the site and when they click it they're asked to enter and confirm a new password.
The url of the page is like this:
/users/reset_password_confirm/23f9a5d7d1a2c952c01afacbefaba41a26062b17
The view is like:
<?php echo $form->create('User', array('action' => 'reset_password_confirm')); ?>
<?php
echo $form->input('password', array('label' => 'Password'));
echo $form->input('confirm_password', array('type' => 'password', 'label' => 'Confirm password'));
echo $form->hidden('static_hash');
?>
<?php echo $form->end('Reset password'); ?>
However this produces a form like:
<form id="UserResetPasswordConfirmForm" method="post" action="/users/reset_password_confirm/8">
The problem is the user id (8 in this case) is being added to the form action. It's not really a problem here, but when I want to pass through the hash to my controller:
function reset_password_confirm($static_hash=null) {
// function body
}
$static_hash is now populated with 8 rather than the hash from the URL.
I know I could sort this out by creating the form tag myself rather than using $form->create but is there a more cakey way of doing this?
$form->create('User', array('action' => '…', 'id' => false));
Just explicitly set params you don't want passed to null or false. This is unfortunately a case where Cake tries to be a little too intelligent for its own good. ;o)
You could probably also do something like this to POST to the same URL again:
$form->create('User', $this->here);
How about passing it as a parameter instead of form data :
<?php
echo $form->create('User', array('action' => 'reset_password_confirm', $static_hash));
echo $form->input('password', array('label' => 'Password'));
echo $form->input('confirm_password', array('type' => 'password', 'label' => 'Confirm password'));
echo $form->end('Reset password');
?>
and in the controller :
function reset_password_confirm($static_hash = null) {
// Check if form is submitted
if (!empty($this->data)) {
// if it submitted then do your logic
} else {
$this->set('static_hash', $static_hash); // Else, pass the hash to the view, so it can be passed again when form is submitted
}
}
Hope this help :)