I have a form that has 3 steps. I use SESSIONS to keep values from step to step. When I open the same form in another tab and complete the first step, this immediately replaces the Session values from the other form.
So how can I create sessions with field values that are attached to a specific form? I need to avoid Session conflicts.
If the forms are indeed different, then put it in a multi-dimensional array:
$_SESSION['register']['field1']=$_POST['field1'];
$_SESSION['contact']['field1']=$_POST['field1'];
If it is the same form and it is just a new tab, you can either check if the value was set before and ignore it, set a flag to say there is a form submission in progress, or entirely delete the old session values so the new form in the new tab has no values attached.
I use this function to handle form input:
function Hold_Form_Input($formname)
{
$FormPost = array();
foreach ($_POST as $key => $entry)
{
$FormPost[$key]= $entry;
}
$_SESSION[$formname]= $FormPost;
}
And I pass the form name in with a hidden input.
Related
stack: symfony2/doctrine2/php/mysql
a multipage form constist of two steps. each step is realized in a controller action.
in step1, the form is displayed. form-input is validated in the same action. if the form is valid the user should be redirected to the second step/action. in the second step the user has to confirm his input. after confirmation the data should be stored in the db.
thus form-entities/form-data are/is needed in the second step/action. however i do not want to store it in the db before confirmation.
do i really need to serialize all objects? to the session?
is there a better approach?
any suggestions?
First of all, I would recommend validating the input via JavaScript before posting and not in the controller action on the server.
If you don't want to serialize the data to the session you can simply pass it on to the next page when you receive it in the first action and then post it to the second action, I'm imagining something like this:
firstAction() {
$exampleData = $_POST['exampleData'];
// Do whatever you need, then pass the data on to the next page
return $this->render('SomeBundle:Views:secondPage.html.php',
array('exampleData' => $exampleData));
On the second page you then just have to access $exampleData with JavaScript and best put it in some hidden input field inside the form.
<!-- secondPage.html.php -->
<script type="text/javascript">
var exampleData = <?php echo $exampleData ?>;
$('#hiddenInput').val(exampleData);
</script>
The second controller action will then receive $exampleData as well without having it serialized in the session.
Sorry if there are any syntax errors, haven't used symfony2 in a while :)
tried to use serialization, but entities are quite complex with "many" associations. thus serialization is too slow. even after detaching.
first solution (simplified):
store the POST variables to the session inside the first step/action.
$postParams = $this->getRequest()->request;
$session = $this->getRequest()->getSession();
if (!$session) {
$session = new Session();
}
$session->set($sessionKey, $postParams);
in the second step/action i used the form to repopulate my entity.
$cancellation = $manager->initCancellationSomehow();
$session = $this->getRequest()->getSession();
if (!$session) {
$session = new Session();
}
$parameterBag = $session->get($sessionKey);
$cancellation = $this->getCancellation($customerId);
$form = $this->createForm(
new CancellationType(),
$cancellation,
array(
'em' => $this->getDoctrine()->getManager())
);
$form->bind($parameterBag->get('form'));
[..]
second solution:
well my first thought was to store cancellation in the db. therefore i added a state attribute (active/temp/..). unconfirmed cancellations get marked as temp. if the user confirms the state gets changed form temp to active. temp collections get deleted after on hour by a garbarge collector which runs at a low priority.
i like the second solution because the user has to confirm the final cancellation, which is already stored in the db. if the frontend does not work as expected the user will likely notice corrupted cancellations (e.g. wrong entries selected). if he confirms, only the state is changed. feels safe. in the first solution the user confirms what should be stored in the db, but isn't till now. feels unsecure.
I have made an interface whereby the user can create his own form. I've just managed to load that form in a separate php file.
What I want to know is that after posting the form, how do I capture all the id and values of the inputs in an array so that I can display the the form (read-only) and display it on another page.
If your <form> method attribute is post - you send POST request to server. You can access all POST data through $_POST like var_dump($_POST);.
If your <form> method attribute is get or you have no method set - you send GET request to server. You can access all GET data through $_GET like var_dump($_GET);.
No matter which input fields was in form - they all would be here.
$post = array();
foreach($_POST as $key => $value) {
$post[$key] => $value;
}
But this example is not too good. It's not protected against SQL-injection - pay attention to it. But with it you can get all $_POST data in $post array.
When you post a form, you have the "array" $_GET or $_POST according to the method (but you could use $_REQUEST which gets both post and get "arguments") where you have all the data you need to process the content of the form. The PHP array_keys returns the keys which are the names given for each field in the form. Using each key in a loop, you can do some kind of processing over the "content" of that field, that you can retrieve using the current key in the loop; e.g.
foreach(array_keys($_GET) as $a)
{
echo $a . " => " . $_GET[$a];
}
I have a form in the footer of my website that appears on each page. I need to make it so if a user submits the form with blank fields, it will flag the error message in the form. It currently directs them to a different page where there data is submitted to another server. I'm already using JavaScript for this, but need to add an additional validation layer with server-side code.
I know how to detect if the form fields are empty, but how can I use server-side code to redirect back to the referring page and include some parameters that can be used in the footer to detect which fields were empty?
I'm assuming I'd have to use PHP's header() with the http_referer, but how can I pass the parameters back to that page without anything showing up in the URL?
Keep a record in $_SESSION of the invalid/empty fields and flag them with CSS in your form:
session_start();
// When you begin validating your form, clear out any old fields from $_SESSION
$_SESSION['previous'] = array();
$_SESSION['invalid'] = array();
// when you encounter an empty or invalid field,
// add it to an array in $_SESSION
$_SESSION['invalid']['fieldname'] = TRUE;
// Store the previous POST value too
$_SESSION['previous']['fieldname'] = $_POST['fieldname'];
In your form, you can check if there's an invalid field and add a CSS class to indicate invalidity. This sets the class invalid:
<input name='fieldname' type='text'
class='<?php if (isset($_SESSION['invalid']['fieldname'])) echo "invalid";?>'
value='<?php if (isset($_SESSION['previous']['fieldname'])) echo htmlentities($_SESSION['previous']['fieldname'], ENT_QUOTES); ?>'
/>
Do this for all your form fields. Use the same method to retain the previous $_POST values and echo them out into the field's value attribute.
I don't think there is a need to send them to another page. As you already know data validation is easy to do using Javascript, and PHP.
you should check the POSTed form data at the top of the file.
Validate the data. Put errors into an array so you can echo the errors at anytime.
Check to see if you found any errors.
// Loop through the $_POST array, which comes from the form...
$errors = array();
foreach($_POST AS $key => $value)
{
// first need to make sure this is an allowed field
if(in_array($key, $allowedFields))
{
$$key = $value;
// is this a required field?
if(in_array($key, $requiredFields) && $value == '')
{
$errors[] = "The field $key is required.";
}
}
}
If there are errors, redisplay the page and list the errors so the users know what they did wrong, and can fix them. This method also allows you to repopulate the form fields with saved values so if there is an error the user doesn't have to type everything in again.
I have a multi-step form which asks the subscriber to check their details before proceeding with the renewal process.
What I want to do is check if the form has been modified from its pre-filled values (extracted from a Web Service) and then write it to my own local MySQL database. This should only happen if the values have been modified from the original.
I know I can do this by using the == operator but I was wondering if there was a more efficient way to do this?
You can do it with (multidimensional) arrays. Name the form/service variables carefully then compare them upon submit with array_diff which tells you which values has been modified.
Because you said this is a multi-step form, of course you can collect previously submitted values in a $_SESSION variable too.
You could do this with javascript on client side:
HTML
<input type="text" id="username">
Javascript
var input = $('#username');
if (input.defaultValue != input.value) {
//Do stuff if different
} else {
//Do stuff if equal
}
I created one module in drupal name as newmodule.I use form alter to alter user registration form for adding one field location.When i submit the form, how i can get the value of the new field which i created .
To elaborate on the previous answers, somewhere in your hook_form_alter function, you want to tell the form to run your own #submit handler, e.g.:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$form['new_field'] = array( ... ); // You already did this, right?
$form['#submit'][] = 'mymodule_submit_handler'; // Add this
}
Note: you should be appending on #submit here, not replacing it. Then in your submit handler, you can get the value easily, e.g.:
function mymodule_submit_handler($form, &$form_state) {
$value = $form_state['values']['new_field'];
}
The form value is stored in
$form_state['values']['field_name']
By default. If you set #tree to TRUE this behavior will change, and the values will be in a nested array instead of a flat one.
Two type of functions will be called, where you have access to the $form_state variable.
Validation functions is used validate the form data, to check if the user inputted data is acceptable, like a valid email address etc. To add a validation function add this in your form alter implementation:
$form['#validate'][] = 'name_of_your_validate_handler';
Submit functions is used to act upon a form with valid data. Typically you insert data into the database, set redirects and such here, to add a submit function add this in your form alter implementation:
$form['#submit'][] = 'name_of_your_submit_handler';
Both validation and submit functions take the same args:
function validate_or_submit_func(&$form, &$form_state) {
// $form is the form array created by drupal_get_form
// $form_state contains valuable info like, the submitted values and other options.
}
New module also needs a _submit hook invoked so you can dump out the $form and $form_state values so you can see them.