chell515 Posted October 25, 2010 at 03:37 PM Report #351730 Posted October 25, 2010 at 03:37 PM Boas, Estou com uma dúvida em relação a como fazer com que as minhas checkbox's fiquem checkadas segundo os values retornados pelo SQL. Tenho uma página a seguinte pagina de ASP e gostava de conceguir fazer um select à BD que me retornasse os hobbies que os clientes têm e que chekasse as checkbox's referentes a esses hobbies. Alguem me poderia ajudar, pois não faço a minima ideia de como tenho de fazer isto. Obrigao e cumpz
Machacaz Posted October 27, 2010 at 12:47 AM Report #352030 Posted October 27, 2010 at 12:47 AM De que modo a query te é retornada? como um objecto? lista? Supondo que os valores são 1 e 0, acho que um foreach te resolvia a coisa: int i = 0; foreach(var xis in ListaBD) { if(listabd.value ==0) {chkboxID.checked = false;} else { checkboxID.checked = true; } } Como deves ter reparado, o checkboxID assim não funciona bem. Se o id fosse dado com um número, por exemplo: chkbox_1 podias alterar o id por cada iteração do foreach. desde que o número de items na lista fosse igual ao número de checkboxs não haveria problemas - lembrando tb que o primeiro item da lista começa no "0".
chell515 Posted October 27, 2010 at 08:23 AM Author Report #352038 Posted October 27, 2010 at 08:23 AM Eu estou a ir buscar a query da seguinte forma: Set RSHobbies = myconn.Execute("SELECT CAST(LC_RelClienteHobbie.HobbieID + '' AS int) FROM LC_RelClienteHobbie WHERE ClienteID=" & clienteID & "for xml path('')") Neste caso ele vai retornar uma coisa deste genero: "1356", em que cada numero representa um hobbie (os hobbies vai de 1 a 6) Mesmo assim vou colocar aqui a pagina integral para que possas ver melhor 😄 <!--metadata type="typelib" file="c:\program files\common files\system\ado\msado15.dll" --> <!--METADATA TYPE="typelib" NAME="Microsoft ActiveX Data Objects 2.8 Library" UUID="{2A75196C-D9EB-4129-B803-931327F72D5C}" VERSION="2.8"--> <% Dim myconn Dim connString Dim clienteID Dim i Set myconn = Server.CreateObject("ADODB.Connection") connString = "Provider=SQLNCLI;" & "Server=172.**.**.**;" & "Database=*******;" & "Uid=*******;" & "Pwd=*********;" myconn.Open(connString) clienteID = Request.QueryString("rdcliente") Response.Cookies("cliente_id") = clienteID Set RSNome = myconn.Execute("SELECT LC_Clientes.Nome FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSMorada = myconn.Execute("SELECT LC_Clientes.Morada FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSEstadoCivil = myconn.Execute("SELECT LC_Clientes.EstadoCivilID FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSProfissao = myconn.Execute("SELECT LC_Clientes.ProfissaoID FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSContacto = myconn.Execute("SELECT LC_Clientes.Contacto FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSEmail = myconn.Execute("SELECT LC_Clientes.Email FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSDataNasc = myconn.Execute("SELECT LC_Clientes.DataNascimento FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSHobbies = myconn.Execute("SELECT CAST(LC_RelClienteHobbie.HobbieID + '' AS int) FROM LC_RelClienteHobbie WHERE ClienteID=" & clienteID & "for xml path('')") %> <html> <head> <!-- Formatação do layout (CSS) --> <link rel="stylesheet" type="text/css" href="mystyle.css" /> <!-- JavaScript --> <script type="text/javascript"> function validateEmail(txtEmailUpdate) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; var address = txtEmailUpdate.value; if (reg.test(address) == false) { alert('Email inválido'); return false; } else if (reg.test(address) == true) { alert('Email válido'); return true; } } function validateContacto(txtContactoUpdate) { var regTMN = /^96[0-9]{7}/; var regVodafone = /^91[0-9]{7}/; var regMoche = /^92[0-9]{7}/; var regOptimus = /^93[0-9]{7}/; var regPT = /^21[0-9]{7}/; var regZON = /^30[0-9]{7}/; var number = txtContactoUpdate.value; if (regTMN.test(number) == true) { alert('numero telefone válido'); return true; } else if (regVodafone.test(number) == true) { alert('numero telefone válido'); return true; } else if (regMoche.test(number) == true) { alert('numero telefone válido'); return true; } else if (regOptimus.test(number) == true) { alert('numero telefone válido'); return true; } else if (regPT.test(number) == true) { alert('numero telefone válido'); return true; } else if (regZON.test(number) == true) { alert('numero telefone válido'); return true; } else { alert('numero telefone inválido'); return false; } } function checkbox() { if (formUpdate.chkHobbieUpdate01.click() == false) { formUpdate.chkHobbieUpdate01.click == true; } else { formUpdate.chkHobbieUpdate01.click == false; } if (formUpdate.chkHobbieUpdate03.click() == false) { formUpdate.chkHobbieUpdate03.click == true; } else { formUpdate.chkHobbieUpdate03.click == false; } } function checkAll() { formUpdate.chkHobbieUpdate01.checked = true; formUpdate.chkHobbieUpdate02.checked = true; formUpdate.chkHobbieUpdate03.checked = true; formUpdate.chkHobbieUpdate04.checked = true; formUpdate.chkHobbieUpdate05.checked = true; formUpdate.chkHobbieUpdate06.checked = true; } function uncheckAll() { formUpdate.chkHobbieUpdate01.checked = false; formUpdate.chkHobbieUpdate02.checked = false; formUpdate.chkHobbieUpdate03.checked = false; formUpdate.chkHobbieUpdate04.checked = false; formUpdate.chkHobbieUpdate05.checked = false; formUpdate.chkHobbieUpdate06.checked = false; } </script> <title></title> </head> <body class="background" > <center> <script type="text/vbscript" src="contacts.vbs"></script> </center> <center> <form method="post" id="formUpdate" action="ContactosPOST_Update.asp"> <table> <thead> <tr> <th colspan="4"> Actualização dos dados </th> </tr> </thead> <tbody> <tr> <td> Nome: </td> <td colspan="3"> <input name="txtNomeUpdate" type="text" style="width: 100%" value="<% =RSNome("Nome") %>" /> </td> </tr> <tr> <td> Morada </td> <td colspan="3"> <input name="txtMoradaUpdate" type="text" style="width: 100%" value="<% =RSMorada("Morada") %>" /> </td> </tr> <tr> <td> Contacto: </td> <td colspan="2"> <input name="txtContactoUpdate" type="text" style="width: 100%" value="<% =RSContacto("Contacto") %>" maxlength="9" /> </td> <td> <input name="btnValidarContacto" id="btnValidarContacto" type="button" value="Validar" class="button" onclick="validateContacto(txtcontacto)" /> </td> </tr> <tr> <td> Email: </td> <td colspan="2"> <input name="txtEmailUpdate" type="text" style="width: 100%" value="<% =RSEmail("Email") %>" /> </td> <td> <input name="btnValidarEmail" id="btnValidarEmail" type="button" value="Validar" class="button" onclick="validateEmail(txtemail)" /> </td> </tr> <tr> <td> Data de Nascimento: </td> <td> <input type="text" name="txtdatanascimento" id="txtdatanascimento" style="width: 100%" value="<% =RSDataNasc("DataNascimento") %>" /> </td> </tr> <tr> <td> Estado Civil: </td> <td colspan="3"> <select name="ddlEstCivilUpdate" style="width: 100%;"> <option value="0">"Escolha uma Opção"</option> <option value="7">Solteiro/a</option> <option value="10">Divorciado/a</option> <option value="9">Viúvo/a</option> <option value="8">Casado/a</option> </select> </td> </tr> <tr> <td> Profissão: </td> <td colspan="3"> <select name="ddlProfUpdate" style="width: 100%;"> <option value="0">"Escolha uma Opção"</option> <option value="1">Área da Informática</option> <option value="2">Área da Restauração</option> <option value="3">Área da Construção</option> <option value="4">Área do Ensino</option> <option value="5">Outra</option> <option value="6">Desempregado</option> </select> </td> </tr> <tr> <td> Hobbies </td> <td> <input name="chkHobbieUpdate01" type="checkbox" value="1" />Jogos PC </td> <td> <input name="chkHobbieUpdate02" type="checkbox" value="2" />Jogos Online </td> </tr> <tr> <td> </td> <td> <input name="chkHobbieUpdate03" type="checkbox" value="3" />Ouvir Música </td> <td> <input name="chkHobbieUpdate04" type="checkbox" value="4" />Passear </td> </tr> <tr> <td> </td> <td> <input name="chkHobbieUpdate05" type="checkbox" value="5" />Ler </td> <td> <input name="chkHobbieUpdate06" type="checkbox" value="6" />Desportos </td> </tr> <tr> <td> </td> <td> <input name="btnCheckAll" type="button" class="button" value="Check All" onclick="checkAll()" /> </td> <td> </td> </tr> <tr> <td colspan="4"> <input type="submit" value="Actualizar" style="width: 100%" class="button" /> </td> </tr> </tbody> </table> </form> </center> </body> </html> Obrigado por toda a ajuda 🙂
Machacaz Posted October 27, 2010 at 09:00 AM Report #352042 Posted October 27, 2010 at 09:00 AM Agora não posso ver. Estou no trabalho e agora é mvc2. logo à noite vejo isso. Mas percebeste a minha lógica? Pelo que vi, até os teus checkboxes têm o id conforme eu referi, logo tenta ir por aí. Será que estares a fazer chamadas à bd/xml no markup uma boa política?
chell515 Posted October 27, 2010 at 09:50 AM Author Report #352050 Posted October 27, 2010 at 09:50 AM Sim eu percebi a tua lógica e ja tinha pensado mais ou menos ir por aí mas ainda não consegui. Provavelmente não tou a fazer o Select correcto à BD. Não sei se é uma boa politica pq também não tenho muita experiência em programação e tenho tentado fazer as coisas com as indicações que me vão dando e com o que vou lendo pela net. Mais uma vez obrigado 🙂
Machacaz Posted October 29, 2010 at 08:57 AM Report #352330 Posted October 29, 2010 at 08:57 AM Já te safaste com isso?
chell515 Posted October 29, 2010 at 09:03 AM Author Report #352331 Posted October 29, 2010 at 09:03 AM Nem por isso... Não tou a conseguir fazer... O select que faço é assim: Set RSHobbies = myconn.Execute("SELECT LC_RelClienteHobbie.HobbieID FROM LC_RelClienteHobbie WHERE ClienteID=" & clienteID) Se eu fizer este select no SQL ele retorna o seguinte: hobbieID 1 2 E sinceramente a minha falta de experiência nestas coisas dificulta-me ainda mais as coisas... 🙂
Rechousa Posted October 29, 2010 at 10:02 AM Report #352340 Posted October 29, 2010 at 10:02 AM Olá, Em primeiro lugar, aqui vai um conselho: Não utilizes concatenação de strings para construir uma query SQL, ficas vulnerável a SQL Injection. Se não souberes o que é, procura no google. Ou seja, isto não se faz: Set RSHobbies = myconn.Execute("SELECT LC_RelClienteHobbie.HobbieID FROM LC_RelClienteHobbie WHERE ClienteID=" & clienteID) Já não me recordo exactamente como se faz em ASP, mas deve ser utilizando CommandParameters. Entretanto construí em exemplo em SQL Server 2008 que, deve ser isso que pretendes: -- Declara as tabelas temporárias (em memória, para não estar a criar tabelas na base de dados) DECLARE @Clientes TABLE (id INT IDENTITY(1,1), Cliente VARCHAR(50)) DECLARE @Hobbies TABLE (id INT IDENTITY(1,1), Hobby VARCHAR(50)) DECLARE @RelClienteHobbie TABLE (idCliente INT, idHobby INT) -- Insere os registos INSERT INTO @Clientes VALUES ('Rui Reininho'),('Rosa Lobato Faria'),('José Mourinho'),('Pedro Martins') INSERT INTO @Hobbies VALUES ('Cinema'),('Música'),('Literatura'),('Teatro'),('Televisão'),('Desporto'),('Informática') INSERT INTO @RelClienteHobbie VALUES (1, 2) INSERT INTO @RelClienteHobbie VALUES (2,3),(2,4),(2,5) INSERT INTO @RelClienteHobbie VALUES (3,6) INSERT INTO @RelClienteHobbie VALUES (4,1),(4,2),(4,7) -- Aqui podes escolher o ID do cliente DECLARE @idCliente INT = 1 -- Efectua a query em que mostra os Hobbies existentes e um campo adicional (TemHobby) que indica se tem Hobby (valor 1) ou não (valor 0) SELECT *, ISNULL((SELECT 1 FROM @RelClienteHobbie CH WHERE CH.idHobby = H.id AND idCliente = @idCliente), 0) AS TemHobby FROM @Hobbies H Isto, traduzido para o teu código deverá ser algo do género: Set RSHobbies = myconn.Execute("SELECT *, ISNULL((SELECT 1 FROM LC_RelClienteHobbie CH WHERE CH.HobbieID = H.id AND idCliente = " & clienteID & "), 0) AS TemHobby FROM LC_Hobbies H") Depois só tens de percorrer um ciclo (While Not RSHobbies.EOF) e mostrar os Hobbies do cliente Outro conselho: Estás a efectuar um acesso à base de dados para ir buscar um campo? Isto não é boa prática. Deves fazer um acesso à base de dados para ir buscar todos os campos que precises. Assim a tua aplicação fica mais eficiente. O teu código: Set RSNome = myconn.Execute("SELECT LC_Clientes.Nome FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSMorada = myconn.Execute("SELECT LC_Clientes.Morada FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSEstadoCivil = myconn.Execute("SELECT LC_Clientes.EstadoCivilID FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSProfissao = myconn.Execute("SELECT LC_Clientes.ProfissaoID FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSContacto = myconn.Execute("SELECT LC_Clientes.Contacto FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSEmail = myconn.Execute("SELECT LC_Clientes.Email FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Set RSDataNasc = myconn.Execute("SELECT LC_Clientes.DataNascimento FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Corrigido: Set RSCliente = myconn.Execute("SELECT LC_Clientes.Nome, Morada, EstadoCivilID, ProfissaoID, Contacto, Email, DataNascimento FROM LC_Clientes WHERE LC_Clientes.ClienteID=" & clienteID) Não só fica mais eficiente (menos acessos à base de dados, menos variáveis (neste caso objectos) utilizados, como é de mais fácil leitura e manutenção. Pedro Martins Sharing is Knowledge! http://www.linkedin.com/in/rechousa
chell515 Posted October 29, 2010 at 12:08 PM Author Report #352353 Posted October 29, 2010 at 12:08 PM Ola Fiz tudo o que me indicaste e obrigado pelos conselhos e segui-os à ricas 🙂 Já consigo mostrar os valores em TextBoxes assim: <% do while not RSHobbies.EOF %> <% for i = 0 to RSHobbies.EOF i = i + 1 next %> <input type="text" value="<% =RSHobbies("temhobbie") %>" name="Hobbie<% =RSHobbies("HobbiesID") %>" /> <% RSHobbies.MoveNext %> <% loop %> <input type="text" value="<% =RSHobbies("temhobbie") %>" name="Hobbie" /> <% RSHobbies.MoveNext %> <% loop %> O que não estou a conseguir fazer é esta função: function CheckHobbies() { if (Hobbie.value = 1) { chkHobbieUpdate01.checked = true; } else { chkHobbieUpdate01.checked = false; } if (Hobbie.value = 1) { chkHobbieUpdate02.checked = true; } else { chkHobbieUpdate02.checked = false; } if (Hobbie.value = 1) { chkHobbieUpdate03.checked = true; } else { chkHobbieUpdate03.checked = false; } if (Hobbie.value = 1) { chkHobbieUpdate04.checked = true; } else { chkHobbieUpdate04.checked = false; } if (Hobbie.value = 1) { chkHobbieUpdate05.checked = true; } else { chkHobbieUpdate05.checked = false; } if (Hobbie.value = 1) { chkHobbieUpdate06.checked = true; } else { chkHobbieUpdate06.checked = false; } } Pois eu estou a fazer o "onload="CheckHobbies()" mas ele está a checkar as boxes todas...
Rechousa Posted October 29, 2010 at 01:44 PM Report #352358 Posted October 29, 2010 at 01:44 PM Olá, Porque é que não fazes isso do lado do servidor? <% do while not RSHobbies.EOF %> <input type="checkbox" name="Hobby<% =RSHobbies("HobbiesID") %>" value="<% =RSHobbies("HobbiesID") %>" checked="<% =RSHobbies("temhobbie") %>" /> <% =RSHobbies("HobbiesDescription") %> <% RSHobbies.MoveNext %> <% loop %> Pedro Martins Sharing is Knowledge! http://www.linkedin.com/in/rechousa
chell515 Posted October 29, 2010 at 03:06 PM Author Report #352367 Posted October 29, 2010 at 03:06 PM Eu já fiz isso do lado do servidor... tanto o teu codigo como o meu tá a checkar todas as checkboxes... 🙂
Rechousa Posted October 29, 2010 at 03:25 PM Report #352369 Posted October 29, 2010 at 03:25 PM Pois, tens razão, my mistake! Tens duas formas de resolver isto: Método 1: Colocas um IF para escrever o atributo checked <input type="checkbox" name="Hobby<% =RSHobbies("HobbiesID") %>" value="<% =RSHobbies("HobbiesID") %>" =" <% If CInt(RSHobbies("temhobbie")) = 1 %> checked="checked" <%End If%> /><% =RSHobbies("HobbiesDescription") %> Método 2: Deixas que a query retorne NULOS para hobbies não seleccionados Set RSHobbies = myconn.Execute("SELECT *, (SELECT 1 FROM LC_RelClienteHobbie CH WHERE CH.HobbieID = H.id AND idCliente = " & clienteID & ") AS TemHobby FROM LC_Hobbies H") Deve funcionar das duas formas 🙂 Pedro Martins Sharing is Knowledge! http://www.linkedin.com/in/rechousa
chell515 Posted November 3, 2010 at 11:13 AM Author Report #352918 Posted November 3, 2010 at 11:13 AM Obrigado por toda a ajuda e pelas dicas Rechousa 🙂 Agora tou sem acesso ao projecto pis tenho outro em mãos mas penso que assim fique tudo a funcionar direitinho 😉 Cumpz
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now