maintain form data after a post - php

I'm doing a function that receives some form data and an Excel file which I walk and earned some data to store them in my database. So far so good, the point is that after you post, validate the Excel (good or bad this is independent of what I need) the form data is clear and I would like to keep them selected. The point is that all my code to complete all validations that I have run the following:
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
I'm starting with cake and I think this may be the problem, also if I remove this code, then the data is loaded, the screen goes blank without displaying any error. It is possible, with this code, to keep the form data as they were?

You would need to store the data in the session, and then read it:
$session = $this->request->session();
$session->write('form-data', $this->request->data());
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
And then in your controller:
if ($this->request->is('post')) {
$post_data = $this->request->data();
} else {
$session = $this->request->session();
$post_data = $session->consume('form-data');
}
//do stuff with $post_data

Related

CAKEPHP 3.1 clear form after submit

Usually on cakephp2 i used to unset form data and everything was ok.
Some times i use redirects to clear it. But i cant do that in this current page.
Anyone has found this issue or a solution for this?
If you are staying on the "add" page after successfully adding a record, for example to allow entry of multiple records more quickly, you'll need to reset the entity after saving. For example, if you're entering Posts, your controller will look something like:
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data);
if ($this->Posts->save($post)) {
$post = $this->Posts->newEntity(); // <- Reset the entity
}
}
$this->set(compact('post'));
(Error checking, flash messages, etc. all left out for brevity.)
An alternative is to simply redirect to the same page.
I had the problem that not everything was deleted
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$this->Flash->success(__('Submited.'));
$this->request->data(null);
$contact = new ContactForm();
return $this->redirect('/(Same Page)');// This did the final trick for me
}
}

Gii model generation not getting past first step - strange bevavior, what's causing this?

I've installed the latest version of yii2 using the advanced template. The website is working fine. For some reason the Gii generation tool is stuck and does not react as expected after clicking the preview button. Instead of showing a new form with the "Generate" button, it shows the same form unchanged without any messages as to what is happening.
Using xdebug I can see in the "actionView" method of the DefaultController that the array value $_POST['preview'] is not set, i.e. it doesn't exist in the $_POST array. I have not changed anything in the Form of the view and everything looks OK. The submit button has the name "preview" and the form is submitted but the $_POST array is not being filled with the value of the submit button. Therefore the controller does not proceed with the next steps of the generation process.
public function actionView($id)
{
$generator = $this->loadGenerator($id);
$params = ['generator' => $generator, 'id' => $id];
// ###############################################################################
// ### THIS IF STATEMENT IS NOT TRUE BECAUSE $_POST['preview'] IS NOT SET !!! ###
// ###############################################################################
if (isset($_POST['preview']) || isset($_POST['generate'])) {
// ###############################################################################
if ($generator->validate()) {
$generator->saveStickyAttributes();
$files = $generator->generate();
if (isset($_POST['generate']) && !empty($_POST['answers'])) {
$params['hasError'] = !$generator->save($files, (array) $_POST['answers'], $results);
$params['results'] = $results;
} else {
$params['files'] = $files;
$params['answers'] = isset($_POST['answers']) ? $_POST['answers'] : null;
}
}
}
return $this->render('view', $params);
}
Does anyone have an idea what could be causing this? I have a hunch that it is something quite simple that I'm overlooking, but I've never had a situation where POST variable from a Form are not being sent to the server.
False Alarm. I've found the problem. The Gii view was creating the HTML Form incorrectly.

Yii can't access session variables

My problem: I can't access session data in the view, which I tried to save in the controller before rendering the view.
In my opinion there's an error when storing the session data. (It's necessary for me to modify the session data after creating it, not only in the single action.)
ProcessController.php
public function actionNew() {
$formhash = md5(time());
$hashList = array();
$hashList[$formhash]['processingNumber'] = '';
//fill with empty model
$hashList[$formhash]['model'] = $this->loadModel();
//store hashList in session
Yii::app()->session['hashList'] = $hashList;
$this->render('/process', array('hashValue => $formHash));
}
Now in the view I need the data from the session to show them to the user. But when dumping the hashList it just dumps "null" (Maybe because the saving in the controller didn't went well).
process.php
<?php
$form = this->beginWidget('CActiveForm', array(
'id' => 'process_form',
//several other things...
));
//Output: null
CVarDumper::dump(Yii::app()->session['hashList'],10,true);
?>
I tried to use $_SESSION instead of Yii::app()->session, which gives me access to the data in the view. But when handling other actions in the Controller the $_SESSION variable is undefined.
Any suggestions?
Thank you.
Long answer is:
Regarding to this documents:
$session=new CHttpSession;
$session->open();
$value1=$session['name1']; // get session variable 'name1'
$value2=$session['name2']; // get session variable 'name2'
foreach($session as $name=>$value) // traverse all session variables
$session['name3']=$value3; // set session variable 'name3'
You can use as well:
Yii::app()->session->set('hashList', $hashList);
Yii::app()->session->get('hashList');
And set it again.
Beside this session thing, why do not you use this:
$this->render('/process', array('hashValue => $formHash, 'hashList' => $hashList));
So you do not need to save it in a session if you can reach it directly into the view.
According to the documentation your code should work. An alternative might be to use the following, but it does the same:
Yii::app()->session->add('hashList', $hashList); // set the value
$hashList = Yii::app()->session->get('hashList'); // get the value
I expect the problem either a debugging problem, meaning you have observed cached or otherwise outdated data or a problem in parts of your code that you have not shown.

Why does CakePHP add New Rows when 'post' is replaced by 'get'?

I edit a row on the Post table or add a new row to it from edit() function in PostsController. The function looks like this:
public function edit($id = null) {
// Has any form data been POSTed?
if ($this->request->is('post')) { //Replaced 'post' by 'get' in this line
// If the form data can be validated and saved...
if ($this->Post->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('Updated the Post!');
return $this->redirect('/posts');
}
}
// If no form data, find the post to be edited
// and hand it to the view.
$this->set('post', $this->Post->findById($id));
}
I simply replaced 'post' by 'get' to see what would happen and it went on creating new rows without even taking me to the form. I still get the flash message 'Updated the Post!', but without taking any form data.
If the code in edit.ctp is required, here it is:
<?php
echo $this->Form->Create('Post');
echo $this->Form->input('id', array('type' => 'hidden','default'=>$post['Post' ['id']));
echo $this->Form->input('title',array('default'=>$post['Post']['title']));
echo $this->Form->input('body',array('default'=>$post['Post']['body']));
echo $this->Form->end('Update');
?>
Any thoughts on why this might be happening?
Edit: Added CakePHP Version
I am using CakePHP 2.4.5
What you are doing makes no sense.
Why would you want to switch the "post" by "get" here?
Of course it will then generate new rows, as you effectively trigger a save on each page load (GET).
Don't do that.
The code you had there was just fine - IF you also took PUT into consideration.
For edit forms, it is not a post, but:
if ($this->request->is('put')) {}
PS: If you want to make sure it always works for both add/edit, use
if ($this->request->is(array('post', 'put')) {}
But NEVER replace it with "get".

Sending ajax request for each element?

I have an app that has rows, each row contains data. The rows are created by the user (just cloning a sample row).
My ajax function looks like this.
save : function(el) {
//Renaming the properties to match the row index and organize
jQuery('#application-builder-layout .builder-row').each(function(row) {
// Iterate over the properties
jQuery(this).find('input, select, textarea').each(function() {
// Save original name attr to element's data
jQuery(this).data('name', jQuery(this).attr('name') );
// Rewrite the name attr
jQuery(this).attr('name', 'application[rows]['+row+'][elements]['+jQuery(this).attr('name')+']');
});
});
//Looping through each row and saving them seperately with new rowkey
setTimeout(function() {
// Iterate over the layers
jQuery('#application-builder-layout .row-box').each(function(row) {
// Reindex layerkey
jQuery(this).find('input[name="rowkey"]').val(row);
// Data to send
$data = jQuery('#application-builder-layout .row-box').eq(row).find('input, textarea, select');
//$data = $data.add( jQuery('#application-builder-layout') );
jQuery.ajax(jQuery('#form').attr('action'), {
type : 'POST',
data : $data.serialize(),
async : false,
success: function( response ) {
//console.log( response );
}
});
});
}, 500);
},
This is the jQuery, it's application style format so this function is inside a var and is called inside a submit function, the problem is not the ajax, looking at it in the console it saves the data fine, just like I have before.
The Problem I cant get all the data into the database (only the last ajax request) take a look below at "Form Data" it shows what my ajax data looks like and how it's inserting into the DB vs how it should insert, I am using json encode and usually this works, but recently I switched to OOP style coding in PHP so I am not sure if that changes anything?
The PHP:
class MyApp {
const Post_Type = 'page';
public function __construct() {
// register actions
add_action('init', array(&$this, 'init'));
}
public function init() {
// Initialize Post Type
add_action('save_post', array(&$this, 'save_post'));
}
//The main save method
public function save_post($post_id) {
// Empty the builder
if($_POST['rowkey'] == 0) {
$builder = array();
}
$builder['rows'][$_POST['rowkey']] = $_POST['application']['rows'][$_POST['rowkey']];
$builder = esc_sql(json_encode($builder));
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if($_POST['post_type'] == self::Post_Type && current_user_can('edit_post', $post_id)) {
// Update the post's meta field
update_post_meta($post_id, 'MY_DATABASE', $builder);
} else {
return;
}
}
}
The above works fine, except its not inserting the data as an array just inserting the last ajax post call, not each. I am sure in my save method I need to reconfig that somehow, but I am just hacking away and cant find info on the web, so I could really use some insight.
I hope I provided enough.
My code summed up: Just to be clear on whats going on here, let me you some basic HTML of my app.
//This gets cloned and the jQuery renames the rowkey to match the index.
<div class="row-box">
<input type="hidden" name="rowkey" value="0">
<div class="builder-row">
<textarea style="display: block;" name="html"></textarea>
<textarea style="display: block;" name="breakingbad"></textarea>
</div>
</div>
So summed up lets say there is 4 rows, the jQuery renames each row, then loops through each and submits an ajax call for each of them. Then the PHP handles the $_POST, in prior applications working with my custom DB I got it to work but working with wp database I am having issues, maybe I am missing something in my method?
Form Data: the ajax form data looks like this (this is the form data inside headers which can be found in the console(firbug) or network(chrome))
//First element
rowkey:0
application[rows][0][elements][html]:A
application[rows][0][elements][breakingbad]:123
Then if there is another row ajax posts again
//Second element
rowkey:1
application[rows][1][elements][html]:B
application[rows][1][elements][breakingbad]:456
So an and so forth, the database looks like this
{"rows":{"2":{"elements":{"html":"B","breakingbad":"456"}}}}
It should be more like this
{"rows":[{"elements":{"html":"A","breakingbad":"123"},{"elements":{"html":"B","breakingbad":"456"}]}
Holy Smokes Batman: I think I got it, It all resides inside how I handle the $_POST ill update soon with an answer..
The database looks good like this
{"rows":[
{"elements":{"html":"A","breakingbad":"123"}},
{"elements":{"html":"B","breakingbad":"456"}}]
}
Now I can continue to build.. whew this was a MASSIVE headache.

Categories