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

Asked

Viewed 827 times

-3

In a company CRUD for example, we often find extensive forms, with many fields and probably the user will forget or fill out some(s) incorrectly, so by giving Submit in the form which is the best way to save and rewrite the entered data, if there is an error, so that you do not need to complete the form from scratch again?

I think of some solutions:

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

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

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

These are the ways I can imagine, but I don’t know which would be the most cost-effective for software agility, and whether there are other ways. Which would be the best and which would give less headache?

  • Another mass negative question, in my opinion, a valid question. It’s not based on opinions, it’s based on discovering which way is most used, because many people have this doubt and it can have several ways to do it, so it would take the form that you would find most usable.

2 answers

2


Your question suggests many answers, however, a good way to solve this. It’s 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();

1

Whenever you think "what’s best to do X or Y," change this question to "what’s the recommended means to do X under such and such a context".

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

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

But note that this will depend on the context.

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

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

Anyway, this depends a lot on the context. In a virtual store, for example, the focus is to sell. A user puts things in the cart and for some reason closes the browser. When he comes back on this site he will have to redo the entire purchase, fetch 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 he is not logged in, he would have a better chance to make the sale without bothering him.

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

  • The only problem with using cookies is that it may be disabled, so it wouldn’t work in that browser with settings to disable them.

  • Don’t worry about it. Because whoever disables cookie or javascript does it deliberately. In practice, you will not be able to use the services on almost any website. What you can do is detect if a cookie is enabled. If not, issue a warning to the user that they may lose everything they typed in a failure.

  • Just pointing out again that the answer is generic and in fact does not answer anything with anything due to your question which is very generic.

Browser other questions tagged

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