How to add multiple phones to the same form dynamically?

Asked

Viewed 1,978 times

3

I’m studying PHP and SQL and I am building a system so that my mother can better manage all customers using the transport service that she provides.

I built a simple registration page with the necessary information, and would like to update it to add contacts phones dynamically.

For example, at least one contact phone is required, so a field will appear by default, but my problem is to add more phones through the same form as I would like to put a "+" button to add another field and record this in the database along with the previously entered data, without needing to create a page to register phones to a specific user, one at a time.

I imagine this requires the use of JS, but I really have no idea how to start implementing on the registration page. I can’t imagine how it would look SQL and the PHP.

To make sure that I have not forgotten any part of the code, I will be making available all the project files, everything is very simple, by containing only the registration system so far. MEGA

Anyway, from now on, I leave my thanks to those who help me.

  • 2

    Post your current code that is saving only one phone in the case.

  • 2

    Welcome to SOPT. Would like to [Edit] your post and add the code you are using, so we can analyze and suggest a change. Thank you.

  • I updated the post. I decided to add the whole project to make sure I’m not missing any excerpts. I’m doing this mainly by having walked away from the project for just over a month.

1 answer

1


Good made a quick example (better than complete your code and you do not understand).

first I have a table telefone with id, nome and telefone:

--
-- Database: `sistema`
--
CREATE DATABASE IF NOT EXISTS `sistema`;
USE `sistema`;

--
-- Estrutura da tabela `telefone`
--

CREATE TABLE IF NOT EXISTS `telefone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(255) NOT NULL,
  `telefone` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Extraindo dados da tabela `telefone`
--

INSERT INTO `telefone` (`id`, `nome`, `telefone`) VALUES
(1, 'Stack', '1111111111111'),
(2, 'Over', '22222222222222'),
(3, 'Flow', '333333333');

2nd I set up my registration page (I used jquery and bootstrap):

<?php
require_once 'minpdo.php'; //importo minha biblioteca de crud
require_once 'telefone.php'; //php com definições do meu banco e tabela

$mnpdo = new MinPDO();
try {
    $telefones = $mnpdo->consult("telefone", "*"); // consulta todos telefones
} catch (MinPDOException $ex) { //caso haja erro
    echo <<<ERRO
    <div class="text-center text-danger">
    {$ex->getMessage()}
    </div>
ERRO;
}


?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Cadastro dinâmico</title>

        <link rel="stylesheet" href="bootstrap.css" />
    </head>
    <body>
        <table class="table table-hover" id="telefones">
            <tr class="text-primary">
                <td colspan="2">
                    <strong>Nome</strong>
                </td>
                <td>
                    <strong>Telefone</strong>
                </td>
            </tr>

        <?php 
        if(!empty($telefones)) { // se tiver telefones
            for($i = 0; $i < count($telefones); $i ++) { //exibe todos
                echo <<<ITEM
            <tr>
                <td colspan="2">
                    <p>{$telefones[$i]['nome']}</p>
                </td>
                <td>
                    <p>{$telefones[$i]['telefone']}</p>
                </td>
            </tr>
ITEM;
            }
        }
        ?>
        </table>
        <table class="table table-striped">
            <tr class="text-center">
                <td>
                    <br>
                    <div class="form-group">
                        <label>Nome:</label>
                        <input name="nome" class="form-control" id="nome" type="text" />
                    </div>
                </td>
                <td>
                    <br>
                    <div class="form-group">
                        <label>Telefone:</label>
                        <input name="telefone" maxlength="15" class="form-control" id="telefone" type="tel" />
                    </div>
                </td>
                <td>
                    <br>
                    <div class="form-group">
                        <label style="opacity: 0;">...</label>
                        <input class="btn btn-primary form-control envia" value="+" type="submit" />
                    </div>
                </td>
            </tr>
        </table>
        <script src="jquery.js"></script>

        <script>
        $(function(){
            $(".envia").click(function() {
                if( $('#nome').val() != "" && $('#telefone').val() ) { //se ambos tiverem com conteudo
                    $.ajax({
                        type: "POST", //tipo de registro
                        url: "cadastra.php", //pagina de cadastro
                        data: { //envia nome e telefone
                            nome : $("#nome").val(),
                            telefone : $("#telefone").val()
                        } ,
                        success: function(retorno) {
                            if(retorno == "fail") {
                                //falha
                            } else {
                                $("table#telefones tr:last").after(retorno); //exibe novo registro
                            }
                        }
                    });
                }
            });
        });
        </script>
    </body>

</html>

The most important part here is script, note the use of Ajax, it is he who allows to make this dynamic registration, in it I inform the method, the page where I will process my data, the data and also when it succeeds etc.

Man INSERT with the page cadastra.php

<?php
require_once 'minpdo.php';
require_once 'telefone.php';

$mnpdo = new MinPDO();
if(isset($_POST['nome']) and isset($_POST['telefone'])) {
    try { //tenta inserir e dar echo (retorno do ajax) de uma linha da tabela
        $mnpdo->insert("telefone",
            array("nome", "telefone"),
            array($_POST['nome'], $_POST['telefone']) );

        echo <<<ITEM
            <tr>
                <td colspan="2">
                    <p>{$_POST['nome']}</p>
                </td>
                <td>
                    <p>{$_POST['telefone']}</p>
                </td>
            </tr>
ITEM;
    } catch (MinPDOException $ex) {
        echo "fail"; // falha do bd
    }
} else {
    echo "fail"; // não tem dados
}

Note that this is the page that makes the insert, then it is she who I quote in ajax. If all goes well she will return to the ajax the table row for my new record, if not, it returns a message "fail"


The example can be downloaded on this MEGA link, to test, run the file sistema.sql in your data manager, and enter index.php. The archive minpdo.php is a class I made of CRUD to help my projects, if I am interested on that Github link there is the tutorial on how to use it.

  • In fact what I was trying to say, is that I would like to add more fields to put phone numbers in the same form by pressing a button. For example: My form is the following: (FIRST NAME) (LAST NAME) (PHONE) [ADD PHONE] By pressing the "Add Phone" button, the form will take the following form: (FIRST NAME) (PHONE)(PHONE) [ADD PHONE] That’s what I was trying to say, for me the explanation was good, but I think it might have been a bit confusing.

  • It is partly the same thing, only hide this field of putting a nobo and put to show it only when the user presses the button

  • Okay, I’ll try. Thanks for the help and the time.

  • I completed the example by having it do what you want and also have delete and edit action. Download: https://mega.nz/#! Ntqc2t6a! JAkc10JfrBbcA0HCNytn3hTvkfHgAxVBqCAeDZaHe8A

Browser other questions tagged

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