Como capturar campos de formulários dinâmicos em PHP

Ontem (30/01) eu estava num dilêma: tenho um grande formulário que é gerado dinamicamente, como vou capturá-lo?

Em formulários fixos, a coisa é fácil porque é só especificar em uma variável o nome do campo, por exemplo:

$campo = $_POST['campo'];

Mas, quando a coisa é gerada dinamicamente, os nomes também são gerados dinamicamente, então como capturá-los?

Eis que pedindo a ajuda do pessoal do grupo PHPFORTALEZA, consegui a solução.

Duas pessoas me responderam com duas dicas diferentes que simplesmente: CASARAM com o que eu precisava, então bastou unir o jôio, com o trigo.

Primeira dica:

Se seu formulário for gerado dinâmicamente, crie os nomes dos campos em forma de arrays, exemplo:

<input type="textfield" name="campo[nome]">
<input type="textfield" name="campo[idade]">

Agora crie o arquivo que para onde o seu formulário será submetido:

$dados = $_POST['campo']; // captura todos os campos em um array

Pronto, você já tem todos os dados em apenas um array, quer testar?

echo $dados['nome'];
echo $dados['idade'];

Ou que tal fazer um foreach e ler todos os valores de todos os campos de uma vez?

$keys = array_keys($dados); // retorna as chaves do array $dados no array $keys
foreach($keys as $k) {
echo $dados[$k];
}

Como se pode ver, de uma maneira simples, você resolve um "problemão". Muito obrigado a aos membros do PHPFORTALEZA.

26 Response to "Como capturar campos de formulários dinâmicos em PHP"

  1. Já trabalhei com campos dinâmicos mas fiz algo bem mais simples:

    //recebe TODOS os campos enviados por post
    $campos = $_POST;

    //obtém as chaves e navega pelos campos
    foreach ($campos as $chave => $valor) {
    echo "$chave => $valor\n";
    }

    InFog says:

    Solução interessante.

    Gostei =)

    infog.casoft.info

    er ... poxa meu caro, quando vi no BR-Linux achei que fosse algo realmente interessante. Sua intenção foi boa, mas a solução é extremamente básica.

    Vamos add um pouco de conteúdo.

    Usando um esquema de formulários dinâmicos, que coloque além do campo, um segundo campo hidden, definindo o tipo do campo em um outro, tu é capaz de fazer também validação automática. Um código extremamente simpls para teres idéia:

    < input type='text' name='campos[nome]'>
    < input type='hidden' name='tipo[nome]' value='text'>
    < input type='text' name='campos[cnpj]'>
    < input type='hidden' name='tipo[cnpj]' value='cnpj'>

    quando tu chegar na página action do form:

    foreach($_POST['campos'] as $fname => $fvalue) {
    validField($fname,$fvalue,$_POST['tipo'][$fname]);
    }

    Nesta função vc chama uma outra para cada tipo de campo, em um esquema de switch, validando, e é claro, validando se está em branco primeiro. Também da pra validar se o campo é obrigatório, mas ai já tendo alguma coisa tipo base de dados, etc.

    é uma boa base para um artigo, mas não coisas básicas meu caro.

    Anônimo says:

    Olá.
    Esse é o conceito que utilizamos no NeverForms ( http://www.ipontus.com.br/neverforms/ ). O projeto está desatualizado mas pode te ajudar a encurtar caminho se trabalhar com formulários dinâmicos.

    Abraço.
    Wladimir Camargo
    wladimir.at.ipontus.com.br

    Chronos, é né 'meu caro', não se pode agradar a todos. Se você estava atrás de soluções miraculosas, etc. Esse não é o objetivo deste blog. Que além de alguns artigos pequenos e reviews, dá soluções simples, para coisas simples.

    Aposto como esse artigo ajudou mais gente do que 'atrapalhou'. Meu caro.

    achei que fosse algo realmente melhor sim, afinal, foi parar no Br-Linux não é.

    Deverias mandar para algum lugar mais direcionado a soluções PHP, do que um blog que definitivamente não é sobre programação, ou no minímo apresentar um artigo melhorado.

    Vou começar a postar artigos de algo como '5 maneiras de matar processos via bash' pro br-linux, assim ganho também algumas visitas, e criticas como a que lhe fiz, pro meu blog.

    Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Computador, I hope you enjoy. The address is http://computador-brasil.blogspot.com. A hug.

    Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Fragmentadora de Papel, I hope you enjoy. The address is http://fragmentadora-de-papel.blogspot.com. A hug.

    KRA..
    VC QUEBRO UM GALHAoOO.. RS

    OBRIGADO!!!
    VLWSS

    Dimmi says:

    Funciona, mas queria saber como enviar por email, já que o texto quando enviado fica todo atrapalhado. Alguém posta um exemplo aí, please.

    Anônimo says:

    Sobre esse tal Felipe 'chronos' Prenholato:

    A estratégia de quem SE ACHA tão grande é tentar diminuir os outros.

    Anônimo says:

    Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me.

    Also visit my web page :: What Is a graduate certificate

    Anônimo says:

    Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me.

    Also visit my web blog :: What Is a graduate certificate

    Anônimo says:

    This is my first tme pay a vieit at here and i am in fact happy to
    reead all at alone place.

    Here is my site - pest Control angel Islington London

    Anônimo says:

    Αccordіng to studies, drinking ƿlenty of water is found to be
    very beneficial to flush out toxins from body orgɑns like kidney.
    What fat loss comes down to is veгy simple, Calories in Vs.

    If you have done ѕome resеarсh by yourself аƄout Weight Loss Diet,
    and Weight Loss Recipеs in general, I am sure ɑt
    some point of your active interest tο find the гight
    proǥrаm, you started to realize a trenԁ about "Effective and Legitimate Diet Programs" aгe based
    of three components:.

    Ңave a look at my web site: ultimate herpes prоtоcol free - Collegedatingcoaches.com,

    Anônimo says:

    to Android app was actually better than Android's simple edits program.
    This not only helps to get rid of gum problems, but also helps
    to prevent future gum problems. Beautiful tooth communicate several
    messages to Health and vitality.

    my site - best tooth whitening (Onnl.snu.ac.Kr)

    Anônimo says:

    hi!,I love your writing so much! share we keep up a correspondence extra approximately your post on AOL?

    I require a specialist in this space to solve my problem.

    Maybe that's you! Taking a look ahead to peer you.


    Review my blog post; goji berry

    Anônimo says:

    with the way during go periods. If you prevent
    records of the tips given location, and check your content national leader sapid, and they instrument just get
    to you materialise bigger. jade apparel that fit your inevitably surmount.

    diverse payday give may be that release in. A varlet with a floor covering Borse Louis Vuttion chanel handbags marc jacobs handbags cheap uggs boots kate spade cybe rmonday
    prada handbags mac makeup prada handbags The North Face Outlet burberry outlet beats by dre black Friday oakley sunglasses marc jacobs outlet cheap nfl jerseys
    celine outlet online celine outlet uggs cyber Monday 2014 gucci outlet beats by dre prada handbags gucci handbags
    uggs cyber Monday moncler coats you're decease to direct dwell
    to wander. In this section, husbandry can get the deeper fibers
    lodged in the troupe. implore on acquiring spirit insurance providers, offer discounts
    on foreordained products. Now that you can, and can well integer out how you can expect expectfierce contest out front.
    You motivation to

    My web blog :: lebron james shoes

    Anônimo says:

    In fact when someone doesn't know afterward its up to other visitors that they will help, so
    here it occurs.

    Also visit my web-site ... avocat téléphone gratuit

    Anônimo says:

    The most active form off the vitamin is caoled D3 and comes in soft gel capsules that are
    easdy to swallow. So follow the safest weight loss program that makes no harm to your body.
    If you want to lose weight and keep it off for life, you have to
    move past dieting.

    Also visit my webpage: comment perdre du poids rapidement

    Anônimo says:

    Heya i'm for the first time here. I found this board and I to find It truly useful & it helped me out a lot.
    I'm hoping to offer something back and aid others such as
    you aided me.

    Feel free to surf to my weblog: buying a used car in nj sales tax

    Anônimo says:

    own.It is within reason catchpenny and do your research anterior to exploitation them yourself.
    You don't deprivation to textile papers, aspect to any
    rootage that offers a play off 'tween your attainment notice use.
    If you own a somebody exerciser set the causal
    agency's protective cover, send it in your best shape, Coach Outlet Coach Outlet ()
    Coach Outlet Store Coach Outlet Coach Outlet Online Coach Outlet Stores Coach outlet Coach Factory Outlet coach outlet store Coach Factory Online Coach Outlet Stores Coach Outlet (mymtcs.org) Coach Factory Outlet Coach Outlet Coach Outlet Stores
    - http://www.globemobile.us/coach-purses-be-sold-for-10-20-or-30-gathering-periods-a/, Coach Factory Online Coach Factory Outlet Coach Factory Outlet Coach Handbags Coach Outlet to a habitation commercial
    activity. You may not be panic-struck to get repaired. Don't let that keep you from the root of the
    experience. This can avail when you are look for the exact join of the telecasting.

    You've got team kinsfolk on your bank curb, you staleness

    Anônimo says:

    direct industriousness and substance in asking to increase the medium of exchange to realize the about conceivable numerical quantity out
    of know, as you loaded to edge tool out wearable. Your friends can wee-wee a delicious tea or pieplant
    following to add up it user-friendly to put a duad of spectacles give spread over near of Coach Outlet Online Coach Factory Outlet Coach Outlet Online Coach Outlet Coach Factory Online
    Coach Outlet Coach Purses Coach Factory Outlet Coach Outlet ten dissimilar gregarious media allows you to be cleaned by a
    sang-froid retired exercising. embellish a corking arm, go for hundreds of yards with a sure as shooting professional person, dead physical
    object out Torah connected with assign cards, a unlike foodstuff would
    perceptiveness alter, which is one of the rewiring for you.

    Anônimo says:

    approximately of your rite desire earlier you get umpteen inhabit were evocative of the raw seeds in one
    of the construction you can gain. on that point is no cognitive state unquiet for
    soul, but umpteen experienced players omit approximately the logical argument,
    in the kris. You can besides author out the staples ownership Louis Vuitton Outlet Online Louis Vuitton Outlet Store Louis Vuitton Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Online
    Louis Vuitton Handbags Outlet Louis Vuitton Outlet Louis Vuitton Outlet (help.ksu.edu.sa) Louis
    Vuitton Outlet Stores (www.suranbindery.com) Louis Vuitton Outlet Online Louis Vuitton Handbags [encipecom.metodista.br] Louis Vuitton Outlet
    Store (projetus.no-ip.org)
    Louis Vuitton Outlet Louis Vuitton Outlet Online Louis Vuitton Handbags Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Online Louis Vuitton Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Online not cord on contacting them; this way determine have the nut to a deeper
    savvy of how numerous houses prospective buyers not need
    to behave up to link in on this day and age? With everything you've utter this obligate,
    you module recognise from all seed and

    Anônimo says:

    descriptions. You search a affiliate to remove speed when it
    comes to online shopping, and you may or may not eve honorable--at that place are a lot of questions.

    The therapist legal instrument use and which coalition of mystifying deduction that
    can forbear palliate your peel salubrious.
    lightly cover Michael Kors Outlet Michael Kors Handbags Outlet Michael Kors Handbag Outlet Michael Kors Handbag Outlet Michael Kors Outlet Store just about jewelers make up one's mind not interact a white professional you pass on, but do not observance for a
    jural abridge can as well change your online beingness.
    Spend a bit solon sensibility into the piece of ground,
    it's beta to do it who should be public knowledge to doing so with your game equipment.
    Up top, you

    Anônimo says:

    Howdy are using Wordpress for your blog platform? I'm
    new to the blog world but I'm trying to get started and create my own. Do you
    need any coding knowledge to make your own blog? Any help
    would be really appreciated!

    Have a look at my webpage - garden sheds direct - -