What is the best way to persist data in an application?

-4

In a company CRUD for example, we often find extensive forms with many fields and probably the user will forget or fill in some incorrectly, so by giving submit in the form what is the best way to save and rewrite the typed data if there is an error, so you do not need to fill out the form again?

I think of some solutions:

  • Use session variables to store all typed data and to rewrite them check if the variable exists and then writes it to the document.

  • Do all the submit by Ajax, do not reload the page by giving submit, but rather submit the data for validation. (but it seems to me that the application loses performance).

  • Validate everything with Javascript, although some fields will need to query the database to be validated.

These are the ways that I can imagine, but I do not know which would be the most profitable for the agility of the software, and if there are other ways. Which would be the best and would give you less headache?

    
asked by anonymous 22.03.2016 / 05:39

2 answers

1

Your question, suggests many answers, however, a good way to solve this. Is using exceptions. Example:

<?php
class Form
{
    private $data = array();
    public $html;

    public function validationForm()
    {
      $errors = array();
       try {

         if ($this->data['nome'] == '') {
            $errors[] = 'O nome não pode ficar em branco!';
         }
          if ($this->data['email'] == '') {
            $errors[] = 'O email não pode ficar em branco!';
         }
         $totalErrors = count($errors);
         if ($totalErrors) {
              $exception = new Exception('errors');
              $exception->setParams(array('status' => false,'title'=>$totalErrors.' erros:', 'errors' => $errors, 'collection' => $this->data);
              throw exception;
         }

         return array(
           'status'=>true,
           'collection' => $this->data
         )

       } catch(Exception $e) {

         return $e->getMessage();

       }
    }

    public function renderForm()
    {
        if ($_POST) {
          $this->data = $_POST;
          $validation = $this->validationForm();
        }

        $form = array(
                'formName' => 'teste',
                'id' => 'teste',
                'method' => 'post',
                'action' => '?send',
                'inputs' =>
                    array(
                    'label' => 'Nome:'
                    'type'  => 'text',
                    'name'  => 'nome',
                    'id'    => 'nome',
                    ),
                    array(
                    'label' => 'Email:'
                    'type'  => 'text',
                    'name'  => 'email',
                    'id'    => 'nome',
                    ),
                    array(
                    'type' => 'submit',
                    'value' => 'Enviar',
                    'name' => 'enviar'
                    )
        );

        $this->html = '';
         if (!$validation['status']) {
             $this->data = $validation['collection'];
             $this->html .= '<div class="erros">
                              '.$validation['title'].'
                                <ul>
                              ';
               foreach ($validation['errors'] as $erro){
                   $this->html .= '<li>- '.$erro.'</li>';
               }                  
             $this->html .= '
                                </ul>
                              </div>';
         } else {
         //grava os dados
            var_dump($validation['collection']);
         }
        $this->html .= '<form name="'.$form['formName'].'" id="'.$form['id'].'" action="'.$form['action'].'" method="'.$form['method'].'">';
        foreach ($form['inputs'] as $input) {
           $value = (isset($input['value'])) ? $input['value'] : '';
            $this->html .= '<label>'.$input['label'].'</label>
              <input type="'.$input['type'].'" name="'.$input['name'].'" "'.$input['id'].'" value="'.$value.'">';
        }
        $this->html .= '</form>';
        return $this->html;
    }
} 
$form = new Form();
echo $form->renderForm();
    
22.03.2016 / 08:06
1

Whenever you think "what's the best way to do X or Y," change that question to "what are the recommended ways to do X under such and such context."

To say that X is better or that Y is better is something pretentious and wrong because everything depends on the context to which it applies.

Speaking directly on the subject matter, the basic, simple and safe way is to save on cookies.

But see that this will depend on the context.

Does the form have sensitive data? (credit card, password, things like that).

Of course, if you have such data, do not save it in a cookie. Save only what is not sensitive or use another medium as session variables in conjunction with cookies.

Anyway, it depends a lot on context. In a virtual store, for example, the focus is on selling. A user places things in the cart and for some reason closed the browser. When he returns to this site he will have to redo the whole purchase, get the products and put them in the cart. In this process the user can become impatient and give up buying. If the site had the ability to save the cart and identify the customer even if it is not logged in, it would have a better chance of realizing the sale without bothering it.

As you can see, this was an example within a specific context of a shopping cart. And yet there are different ways to solve.

    
22.03.2016 / 05:58