Ir para conteúdo
Fórum Script Brasil
  • 0

problema na criação de grid dinamica


Ricardo T. do Prado

Pergunta

Pessoal,

Estou montando um GridView Dinamicamente, porém o único erro/inconveniente é que: "os lookups ficam fora da tag <TD>"

segue código abaixo comentado;

functions.php

function grid(
$table,//nome tabela
$array_campos, //campos e cabeçalhos
$chave
) {

conexao(); //já abro a conexao();
$tb="<table id='grid' width='100%'>"; //agqui é o nome que vem do css

//Cabeçalhos ------------------------------------------------------
$tb.="<tr>";

foreach($array_campos as $headers=>$fields) {
    $tb.="<th> ".$headers." </th>";
}
$tb.="<th> editar </th>";
    $tb.="<th> excluir </th>";
$tb.="</tr>";
$tb.="<tr>";

//conteudos -----------------------------------------------------------

$result = mysql_query("select * from ".$table."") or die (mysql_error());
while($values = mysql_fetch_array($result)) {

foreach($array_campos as $headers=>$fields) {
$tb.="<td>".$values[$fields]."</td>";
}

$tb.="<td width=20><a href='updaterecord.php?table=$table&key=$chave&id=".$values[$chave]."'><img src='img/true'></a></td>";
$tb.="<td width=20><a href='delrecord.php?table=$table&key=$chave&id=".$values[$chave]."'><img src='img/false'></a></td>";
$tb.="</tr>";
}
$tb.="<table>";

echo $tb;

}
Agora chamo a função GRID da seguinte forma
grid(
"usuarios",
$campos = array("codigo"=>"id",
            "nome"=>"nome",
            "login"=>"login",
            "senha"=>"senha",
            "status"=>"ativo",
            "categoria"=>lookup('imoveiscat','id','categoria')
            ),
'id');
Notem que passo uma função "lookup" para o valor da chave "Categoria", segue função abaixo
function lookup($table, $chave, $descricao){
conexao();
$lk="<select name = '".$chave."'>";
$result = mysql_query("select ".$chave.", ".$descricao." from ".$table." order by ".$descricao."") or die (mysql_error());
while($linha = mysql_fetch_row($result)){
$lk.="<option value = '".$linha[0]."'>".$linha[1]."</option>";
}
$lk.="</select>";
echo $lk;
}

Então, ele executa o código certinho, cria o lookup(combobox), porem, deixa o combobox fora da TD, se alguém puder ajudar, agradeço

Abs.

Link para o comentário
Compartilhar em outros sites

8 respostass a esta questão

Posts Recomendados

  • 0

Troca echo por return e faça um teste.

function lookup($table, $chave, $descricao) {
    conexao();
    $lk = "<select name = '" . $chave . "'>";
    $result = mysql_query("select " . $chave . ", " . $descricao . " from " . $table . " order by " . $descricao . "") or die(mysql_error());
    while($linha = mysql_fetch_row($result)) {
        $lk .= "<option value = '" . $linha[0] . "'>" . $linha[1] . "</option>";
    }
    $lk .= "</select>";
    //echo $lk;
    return $lk;
}

Link para o comentário
Compartilhar em outros sites

  • 0

você está usando algum tipo de ferramenta para inspecionar o html e os objetos gerados na página?

Ferrametas como : Firebug

Ou então faça o seguinte. Imprima na tela o retorno da sua função grid, para ver como html está sendo griado.

...

//echo $tb;
echo htmlentities($tb);

Link para o comentário
Compartilhar em outros sites

  • 0

Está imprimindo isso

<select name = 'id'><option value = '4'>aluguel</option><option value = '3'>casas</option><option value = '1'>chácaras</option><option value = '2'>fazendas</option></select>
Eu creio que o problema esteja aqui
foreach($array_campos as $headers=>$fields) {
$tb.="<td>".$values[$fields]."</td>";
}

por que estou passando uma FUNÇÃO ao invés do nome do campo na matriz.

Link para o comentário
Compartilhar em outros sites

  • 0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>CMS - Estribo</title>



<link href="estilo.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="jquery.js"></script>

<script>

$(function() {



$("#formulario").click(function() {

if($("#insert").css("display")=="none") {

$("#insert").show(1000);

} else {

$("#insert").hide("fade");

}

});

});

</script>

<script language="javascript">



function messagebox() {

  if (confirm("Deseja realmente apagar este registro?")) {

    return true;

  }

  else {

     return false;

  }

}

</script>



</head>



<body>







<div id="todo"><!-- começo das div do site -->





<div id="infouser"> 



Bem vindo (a): <b> Ricardo Tomazela do Prado </b>  <br>

Conectado ao IP:  <b> 127.0.0.1 </b>  <br>

Domínio:  <b> localhost </b>  <br>

</div>





<div id="menu">

<table id='menu'><tr><td> <img src='icones/1262004441_Keychain Access.png' width=50px></td><td> <img src='icones/1262004471_Home.png' width=50px></td><td> <img src='icones/1262004600_iCal.png' width=50px></td><td> <img src='icones/1262004428_TextEdit.png' width=50px></td><td> <img src='icones/1262004620_Address Book.png' width=50px></td><td> <img src='icones/1262004693_Network Utility.png' width=50px></td><td> <img src='icones/1262004802_Earth.png' width=50px></td></tr><tr><td> <a href=?action=usuarios>usuarios</a></td><td> <a href=?action=imoveis>imoveis</a></td><td> <a href=?action=eventos>eventos</a></td><td> <a href=?action=noticias>noticias</a></td><td> <a href=?action=artigos>artigos</a></td><td> <a href=?action=downloads>downloads</a></td><td> <a href=?action=links>links</a></td></tr><table></div>



<div id='controles'><a href='#' id='formulario'>exibir/ocultar formul�rio</a><br><a href='#' onclick='java script:window.location.reload()'>atualizar dados</a></div>

<div id="insert">



    <form method="post">

    <input type="text" name="nome"  /> Nome Completo <br>

    <input type="text" name="email"> E-mail <br>

    <input type="text" name="login" > Nome de usuário (Ex: nome.sobrenome) <br>

    <input type="password" name="senha"> Informe uma senha <br>

    

    <input type="submit" name="post" value="salvar" id="submit" >

    <input type="reset" value="limpar" name="reset" id="reset">

    <input type="submit" value="pesquisar" name="pesquisar" id="pesquisar">

    </form>

</div>





<select name = 'id'><option value = '4'>aluguel</option><option value = '3'>casas</option><option value = '1'>chácaras</option><option value = '2'>fazendas</option></select><table id='grid' width='100%'><tr><th> codigo </th><th> nome </th><th> login </th><th> senha </th><th> status </th><th> categoria </th><th> editar </th><th> excluir </th></tr><tr><td>3</td><td>Administrador</td><td>admin</td><td>admin</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=3'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=3'><img src='img/false'></a></td></tr><td>9</td><td>Ricardo Tomazela do Prado</td><td>ricardo.prado</td><td>flex2011</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=9'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=9'><img src='img/false'></a></td></tr><td>8</td><td>Administrador</td><td>admin</td><td>admin</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=8'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=8'><img src='img/false'></a></td></tr><td>7</td><td>Administrador</td><td>admin</td><td>admin</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=7'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=7'><img src='img/false'></a></td></tr><td>10</td><td>Ricardo Tomazela do Prado</td><td>ricardo.prado</td><td>flex2011</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=10'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=10'><img src='img/false'></a></td></tr><td>11</td><td>Ricardo Tomazela do Prado</td><td>ricardo.prado</td><td>flex2011</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=11'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=11'><img src='img/false'></a></td></tr><td>25</td><td>Nestor Bruno Neto</td><td>nestor.bruno</td><td>2dbb0df73a708e852b5a968d8f31fd15</td><td>T</td><td></td><td width=20><a href='updaterecord.php?table=usuarios&key=id&id=25'><img src='img/true'></a></td><td width=20><a href='delrecord.php?table=usuarios&key=id&id=25'><img src='img/false'></a></td></tr><table>

</div> <!--fim template site -->





</body>

</html>

Link para o comentário
Compartilhar em outros sites

  • 0

Ricardo,

Acredito que você deve executar a função lookup dentro da estrutura while da função Grid. Segue abaixo:

Da uma olhada.

function grid($table, //nome tabela
$array_campos, //campos e cabeçalhos
$chave) {
    
    conexao(); //já abro a conexao();
    $tb = "<table id='grid' width='100%'>"; //agqui é o nome que vem do css
    

    //Cabeçalhos ------------------------------------------------------
    $tb .= "<tr>";
    
    foreach($array_campos as $headers => $fields) {
        $tb .= "<th> " . $headers . " </th>";
    }
    $tb .= "<th> editar </th>";
    $tb .= "<th> excluir </th>";
    $tb .= "</tr>";
    
    $tb .= "<tr>";
    
    //conteudos -----------------------------------------------------------
    

    $result = mysql_query("select * from " . $table . "") or die(mysql_error());
    while($values = mysql_fetch_array($result)) {
        
        foreach($array_campos as $headers => $fields) {

                // Verifica se o campo é de categoria. 
            // true = executa a função Grid
            if($headers === 'categoria') {
                $tb .= '<td>' . lookup('imoveiscat','id','categoria') . '</td>';
            }
            else {
                $tb .= "<td>" . $values[$fields] . "</td>";
            }
        }
        
        $tb .= "<td width=20><a href='updaterecord.php?table=$table&key=$chave&id=" . $values[$chave] . "'><img src='img/true'></a></td>";
        $tb .= "<td width=20><a href='delrecord.php?table=$table&key=$chave&id=" . $values[$chave] . "'><img src='img/false'></a></td>";
        $tb .= "</tr>";
    }
    [b]$tb .= "</table>";[/b] // aqui você tinha esquecido de fechar a tag
    
    echo $tb;
}

Mas qual o objetivo dessa tag select, retornada pela função lookup? Só mostrar os dados para o usuário?

Editado por Romero Dias
Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...