What technique do I use to keep a form field completed or selected after $_POST[]?

Asked

Viewed 2,145 times

8

I am developing a real estate system and would like to ask how I can keep the data of a form such as inputs, selects and checkbox selected after giving a $_POST on the form.

I don’t know how to store this data for all the browsing of that customer that is on the site but I imagine there must be something related to sessions.

Thanks for the help.

  • 2

    Send with an AJAX to prevent page reloading and prevent it from being touched in the values of the HTML elements.

  • By ajax at one time or another he goes home or to the contact page and loses the data.

  • 1

    I get it, so you want when he goes back to the page the data is still there, even when he closes the browser? If yes you can use COOKIES, if not the use of SESSIONS would be the solution.

4 answers

6

Small examples showing how it can be done:

COOKIE:

PHP transparently supports HTTP cookies. Cookies is a mechanism for storing data in the remote browser and allows the ratreaming or identification of the return of users. You can create cookies using the setcookie() or setrawcookie() function. Cookies are a part of the HTTP header, so setcookie() needs to be called before any other data is sent to the browser. This is the same limitation that the header() function has. You can use buferized output functions to delay script impressions until you have decided whether or not to set any cookie or send any headers.

Form:

<form action="server.php" method="POST">
    <?php
        if (isset($_COOKIE["valor"])){
            echo '<input type="text" name="valor" value="'.$_COOKIE["valor"].'" />';
        } else {
            echo '<input type="text" name="valor" value="" />';
        }
     ?>
</form> 

Server:

<?php
   $valor = $_POST['valor'];
   setcookie("valor",$valor);
?>

SESSION:

Session support in PHP consists of a way to preserve data through subsequent accesses. This allows you to create more customized applications and increases the appeal of your web site.

Form:

<form action="server.php" method="POST">
    <?php
        session_start();
        if (isset($_SESSION["valor"])){
             echo '<input type="text" name="valor" value="'.$_SESSION["valor"].'" />';
        } else {
             echo '<input type="text" name="valor" value="" />';
        }
    ?>
</form> 

Server:

<?php

    session_start();
    $valor = $_POST['valor'];
    $_SESSION['valor'] = $valor;

?>

Differences:

Cookie - The information is recorded on your computer, an example of this and a login system of a discussion forum, if you enter it today tomorrow if you enter, you will still be logged in.

Session - Information is saved to the server. If Windows enters visit a website, and exit, your session ends, or you can expire.

References:

http://php.net/manual/en/features.cookies.php

http://php.net/manual/en/book.session.php

https://omundodomario.wordpress.com/2010/02/23/diferenca-entre-cookie-e-session/

  • Could you exemplify using input and select so that I understand better and can apply to my project? Thank you

6

I consider to this answer that you want the values "selected after giving a $_POST in the form", therefore it is not necessary to keep this data in the session, only on the page submitted by the form.

There is no equal way for all field types, so I suggest having functions for each type, below describe examples of functions for text and select types, which can serve as basis for other types.

I used the functions of the sprintf() to mount the HTML, could concatenate, for example. But it goes from each developer.

To get the POST values I used filter_input(), that makes some validations, avoiding the use of empty() or isset().

function inputTextComValor($nome_do_campo) {
  vprintf('<input type="text" name="%s" value="%s"/>', array(
     $nome_do_campo,
     filter_input(INPUT_POST, $nome_do_campo), // equivale a $_POST[$nome_do_campo]
  ));
}

function selectComValor($nome_do_campo, $valores) {
  $selecionado = filter_input(INPUT_POST, $nome_do_campo);
  $opcoes = '';
  foreach ($valore as $chave => $valor) {
    $opcoes .= vsprintf('<option value="%s' %s>%s</option>, array(
      $chave,
      $chave == $selecionado ? 'selected' : '',
      $valor,
    ));
  }
  printf('<select name="%s">%s</select>', $nome_do_campo, $opcoes);
}
  • I don’t know how to use it. It generates me another field instead of replicating in the same field. It can help me?

2

I don’t know if this is what you want, but you can make your page have 2 types of behavior, a pattern and one for $_POST requests, and when submitting your form, submit to the page itself.

I usually use this to validate, and when something is invalid, I can continue with the data that the user has previously entered without the need to use AJAX to validate.

If you want to go to other pages and not lose this information, it is best to use cookies.

I believe you don’t need to use Sesssions.

1

Just to complement the answers, in frameworks like Laravel 4 it is possible to do it as follows:

On the controller

return Redirect::back()->withInput();

In view:

{{ Form::text('name', Input::old('name') }}

Explanation

When you redirect calling the method withInput, you are saving the content of $_POST current in a flash (session values that are only displayed once.

The method Input::old is in charge of capturing these values.

So my recommendation is that if you’re not using any framework, use the session to save those values. Do this in a way that you can create as flash, to ensure that values, once used, will be removed at the same time from the session.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.