Multi step/page form in PHP & CodeIgniter - php

I'm trying to build a multi step/page form in PHP and CodeIgniter and I was wondering if any of you could help me.
How can I have a multi step form in CI that updates rather than inserts again when you return to the previous step with the back button? How can I have a form that doesn't have those back button POST form resend messages?
Edit: without JS if possible
Thanks!

Here's my answer from another question. It gives you forward/backward ability without the chance to lose data, instantly jumps between pages, is EASY to code, needs no sessions, and is framework-independent (can be used in any situation):
I develop a product for the Psychology market that does 250 question psychological based testing. To make a test that isn't completely overwhelming, I break the form up into 25 question segments while outputting it in a loop via div tags with a sequential ID appended (ie. div1, div2, div3) Each div is set to display:none but the first.
I then provide the user with a button that toggles the current div + 1 (ie if on div 1, it would do a $(#div2).show() etc. Back buttons do the opposite.
The important part is that the form covers ALL divs. Then its just a matter of swapping out the forward/back button at the end with a submit button.
Voila! Yes, low-tech. But FAST....and no chance to EVER lose values going forward or backward.
So, a rough truncated example:
<form>
<div id="div1">
First 25 Questions
<input type="button">shows next div</input>
</div>
<div id="div2" style="display:none">
Second 25 Questions
<input type="submit">Submit Form</input>
</div>
</form>

Create a unique ID which you use in all steps of your wizard. Save that ID to the database upon the initial saving of your form.
Forward this ID to the next steps using a input type="hidden".
When saving a step, first try to match the ID and, if you find it int the database, perform an update instead of an insert.
To avoid the "do you want to resend post data", perform each wizard step in two CodeIgniter controller actions:
SaveStep5(POST: form instance ID + other "wizards step 5" inputs):
looks up the form instance ID in the database and performs insert/update commands;
redirects to LoadStep6 and passes the form instance ID in a GET parameter;
LoadStep6(GET: form instance ID);
looks up the form instance in the database,
if the instance is not found: error handling
if the instance is found, renders the input form for "step 6"

If you want to avoid those messages which warn the user about resending posts, and you also want to have multiple proper pages rather than just different steps in javascript, you can put the answers in the URL as GET parameters..
so after the first form submission, you will get form2.php? in the URL.. you can add those answers as hidden variables in form2 and so on.
It is not a very elegant solution though. I'd recommend you to use javascript: add a custom handler for form submission and submit form content via ajax, and then load the next form on ajax complete.
Also, like the other person answered, on the server end, you will need a unique ID which fetches/updates the submission data in the database.

I like the approach of waiting on the database update until all steps have been completed. You could store all the data in the intermediate steps in a session. I suppose you could even save the model object you're using (if you're using one) in a session and after all steps have been completed you can do the database insert.

I have a model to store my wizard data with a variable for each field on the form:
class Class_signup_data extends CI_Model {
const table_name="signups_in_progress";
public $market_segment; // there is a field named 'market_segment' in the wizard view
...
...
I have one controller to handle the whole process, with parameters for the session_id and the stage of the process we are at:
class Signup extends CI_Controller {
public function in_progress($session_id=NULL,$stage=1) {
$this->index($session_id,$stage);
}
public function index($session_id=NULL,$stage=1) {
if ($session_id===NULL) $session_id=$this->session->userdata('session_id');
...
...
In this controller I have a switch for which stage we are at - it looks for a 'Prev' button first:
switch ($stage) {
case 2:
if ($this->input->post('prev')) { // if they click Previuous, the validations DON'T need to be met:
$signup_data->save_to_db(array_merge(array('ip'=>$_SERVER['REMOTE_ADDR'],'session_id'=>$session_id,'signup_stage' => '1',
'signup_complete' =>'0'),$this->input->post()),$this->db,$session_id);
$this->load->helper('url');
redirect("/signup/in_progress/".$session_id."/1");
And later in the switch I use CI's Validations to display a form and process 'Next' if it was clicked or it is just being called with /signup/in_progress/session/2:
$this->form_validation->set_rules("your rules");
if ($this->form_validation->run() == FALSE) {
$this->load->view('signupStage2',array('signup_data'=>$signup_data));
} else {
$signup_data->save(array_merge(array('ip'=>$_SERVER['REMOTE_ADDR'],'session_id'=>$session_id,'signup_stage' => '3',
'signup_complete' =>'0'),$this->input->post()),$this->db,$session_id);
$this->load->helper('url');
redirect("/signup/in_progress/".$session_id."/3");
};
At the bottom of each view (eg 'signupStage2.php') I have the prev and next buttons:
<span class="align-left"><p><input type="submit" name="prev" class="big-button"
value="<- Prev" /><input type="submit" name="next" class="big-button"
value="Next ->" /></p></span>

Related

Submit form to different action with typo3 flow

I have a page with a form for creating users. A user has an hobby, which can be created on the same page by clicking on the second button which opens the page for creating a hobby. After creating the hobby, the previous user form should be shown with the user input inserted before going to the hobby page.
Is there a way to do something like with typo3 flow / fluid without using AJAX?
I tried to submit the input to a different action by clicking on the createHobby button --> The action redirects to the new hobby page, where the user can create the hobby and after creation it should redirect back to the user form with the already filled out input fields by the user .
I used...
<input type='submit' value='Create' formaction='/hobby/create' />`
to achive this, but it seems there are some problems with the uris... I get following error:
#1301610453: Could not resolve a route and its corresponding URI for the given parameters.
I think the using the attribute formaction is not a good solution for every case, as it is not supported by IE < 10 as you can see here. I think a JavaScript backport should also be considered (dynamically change the action attribute of the form when clicking on the second button, before actually submitting the form).
Concerning your error, you should not – and probably never – use direct HTML input, instead try to focus on Fluid ViewHelpers, which allow TYPO3 to create the correct HTML input.
Try this instead:
<f:form.submit value="Create" additionalAttributes="{formaction: '{f:uri.action(controller: \'hobby\', action: \'create\')}'}" />
You can make an $this->forward(...) in an initializeActiondepending on an param of your action.
Lets imagine your default Form action is "create". So you need an initializeCreateAction:
public function initializeCreateAction()
{
if ($this->arguments->hasArgument('createHobby')) {
$createHobby = $this->request->getArgument('createHobby');
if ($createHobby) {
$this->forward('create', 'Hobby', NULL, $this->request->getArguments());
}
}
}
Now you must name your input createHobby and assign your createAction this param:
In fluid:
<f:form.button type="submit" name="createHobby" value="1">Create Hobby</f:form.button>
In your Controller:
public function createAction($formData, $createHobby = false)
{
...
}
can you explain something more ... what you show has nothing to do with typo3, I don't know where you inserted that, what version of typo3 , using any extension extra ?

How to store data with js and redirect to a different view with the same click (Laravel 4.1)

I have a view in my project that has a few steps. The steps are handled through button clicks that take the user to the next step, and along the way, data is stored using JS and AJAX. On the last click, I want a user to make a selection from a list of checkbox selections, and I want to store and use this data to affect the next view (this last button click should redirect to another view).
I can store the data fine with ajax, but what I can't seem to figure out is how to send the data to the next view.
Basically, I want to collect the clicked data, send it back to my controller with ajax, store it, and then use it in a hyperlink (using a route) to effect the next view (using SESSION data):
<input id="btn-next" type="button" name="next" class="next action-button faded" value="Next" />
I hope that was clear. Any ideas on how to do this?
EDIT:
Ok, basically, it works like this:
Step 1:
Series of checkboxes (choose up to 3):
[] [] [] [] []
"Next Button" takes you to step 2 (with js, view is the same)
Step 2:
Series of checkboxes (passed from before) (choose 1):
[id1] [id2]
"Next Button" takes you to another view
In the new view:
It could say something like "You chose id2! Awesome!"
When a user clicks one of these boxes, and then clicks the next button, I want the id info from the box checked, to go back to my controller, be stored in my db (I am already doing this), but also, I want to carry this information to the next view, so that it affects the view using session data (using Session::get in Laravel).
My main question, is how do I pass this data back to the view, while also storing it using ajax and my controller. I assume this needs to be done using a route that takes the id info, but how do I pass that id info to the button hyperlink as shown above?
EDIT 2:
function loadStep3() {
var data = $('#onBoarding-hidden #step2').val();
if(data) {
var result = jQuery.parseJSON(data);
if(result[0]) {
result = jQuery.parseJSON(result[0]);
if(result.name) {
$('#step3 .name').html(result.name);
}
}
}
If I have understood it correctly, you want to store something upto next request. For this, you can use Session::flash('key','val') to put some data in session.
This data will be retained in session for just one request. Reference -
http://laravel.com/docs/session#flash-data
Basically you just need to put the data to the session and from the next request you may access it and in this case you may flash the data to the session only to get it back for the next request. So you may try this:
Session::flash('identifier', 'value');
Then on the next request after you redirect; you may access that data using this;
Session::get('identifier');
So it could something like this:
Session::flash('myId', Input::get('fieldname'));
Then in your view on the next request, get it from the session using:
#if(Sessuin::has('myId'))
<input id="btn-next" type="button" name="next" class="next action-button faded" value="Next" />
#endif
For more information about Session check it on Laravel website.
Update: From your comment I got the idea that you may do it:
if(result.name) {
window.location.href = 'url?name='+result.name;
}
Then on the next request (where you are being redirected) access the name from query string:
$name = Input::get('name');
Now you may use the $name as you want.

Submit two forms to the same page

I have been on this site all day and can't seem to find what I need - no duplicate post intended.
I have a form containing a link which calls a modal popup containing a different form.
###### PARENT PAGE #############
<form...>
...
link
...
</form>
**** MODAL POPUP ****
<form...>
...
<input type="submit" />
</form>
**** END MODAL POPUP ****
### END PARENT PAGE #############
When I submit the form in the modal popup, the parent page is refreshed to show the updated info in the corresponding section of the page; except that the first form is not submitted and when the page refreshes to update the necessary section, the contents of the first form is lost.
I have tried using ajax to refresh only the necessary section of the page but that doesn't work as the sections that need refreshing use php variables with contents from mysql.
The system does what it needs to do and I don't mind the refresh. But I need a way to keep the user data entered into the first form.
Is it possible to submit the first form at the same time as the second to the same php page or any other way of preserving the user data in the first form on page reload without submitting it.
You cannot do this with pure php. You'll need javascript and write it in a way that when you hit submit on the modal it 'puts' the information back into the parent form.
One way is to make the modal form submit button not an actual submit button.
You might even be able to get away with taking the filled out section dom elements in the modal injected back into the parent form. Some jquery plugins already do this. For example colorbox
Here is a working example using only ONE <form> tag and jquery colorbox. http://jsbin.com/olalam/1/edit
I am not a php developer, so I'll suggest an alternative approach.
Before you refresh the page, you can serialize the form and store the data locally (e.g. in a cookie) then restore the data back into the form. Granted, that will require a bit more JS code, but should get you what you want.
UPDATE: Since you mentioned that you might need a little assistance on the JS front, here is some guidance:
Grab the jquery.cookie plugin here.
Grab the jquery.deserialize plugin here.
Use the following code as a starting point.
.
// the name of the cookie
var cookieName = 'myCookieName';
function beforeSubmit() {
// serialize the form into a variable
var serializedForm = $('#id-of-form').serialize();
// store the serialized form
$.cookie(cookieName, serializedForm, { path: '/' });
}
function afterRefresh() {
// read the cookie
var serializedForm = $.cookie(cookieName);
// de-serialize the form
$('#id-of-form').deserialize(serializedForm, true);
}
HTH

Calling a php function with the help of a button or a click

I have created a class named as "member" and inside the class I have a function named update(). Now I want to call this function when the user clicks 'UPDATE' button.
I know I can do this by simply creating an "UPDATE.php" file.
MY QUESTION IS :-
Can I call the "update() function" directly without creating an extra file? I have already created an object of the same class. I just want to call the update function when the user clicks on update button.
an action.php example:
<?
if (isset($_GET[update])){
$id=new myClass;
$id::update($params);
exit;}
//rest of your code here
?>
Your button is in your view. Your method is in your class . You need a controller sitting in the middle routing the requests. Whether you use 1 file or many files for your requests is up to you. But you'll need a PHP file sitting in the middle to capture the button click (a POST) and then call the method.
As far as I know you can't do this without reloading your page, checking if some set parameters exist which indicate the button is clicked and than execute the button. If this is what you are looking for... yes it is possible on page reload. No as far as I know it is not possible directly because your php-function has to parse the results again.
Remember that a Model-View-Controller way is better and that this will allow you to ajax (or regular) requests to the controller-class.
You do it on the same page and have an if statement which checks for the button submission (not completely event driven) like so
if (isset($_POST['btn_update']))
{
update();
}
<input type="submit" name="btn_update" value="Update" />
That will have to be wrapped in a form.
Or you could do it with AJAX so that a full page refresh isn't necessary. Check out the jQuery website for more details.

Add and remove form fields in Cakephp

Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.

Categories