Last active
August 4, 2017 00:33
-
-
Save lucianotonet/820bbe155f61549bf10e0c335126b3ee to your computer and use it in GitHub Desktop.
Análise: Checkboxes pré-selecionados
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* ANÁLISE CHECKBOX | |
* | |
* Como fazer com que a lista de checkboxes apareça devidamente checados, | |
* sendo que a relação de opcionais estão sendo salvos como sequencia de IDs separados por vírgula (string)? | |
* | |
*/ | |
// OPCIONAIS | |
$opcionais = [ | |
[ "id" => 1 , "name" => "Vidro elétrico" ], | |
[ "id" => 2 , "name" => "Trava elétrica" ], | |
[ "id" => 3 , "name" => "Direção hidráulica" ], | |
[ "id" => 4 , "name" => "Desembaçador traseiro" ], | |
[ "id" => 5 , "name" => "Alarme" ] | |
]; | |
// AUTOMÓVEL | |
$automovel = [ "id" => 1 , "opcionais" => '1,2' ]; | |
// ARRAY DE OPCIONAIS | |
$arrayOpcionais = explode( ",", $automovel["opcionais"] ); // divide a string em uma array de strings | |
// LOOP NOS OPCIONAIS | |
foreach ($opcionais as $opcional) { | |
// Checa se o ID do opcional consta no array de opcionais do automóvel | |
if ( in_array( $opcional['id'], $arrayOpcionais ) ) { | |
$checked = 'checked'; // ou 'checked="checked"' | |
} else { | |
$checked = ''; | |
}; | |
echo '<input type="checkbox" ' . $checked . ' /> ' . $opcional['name'] . ' <br />'; | |
}; | |
/** | |
* O segredo está no atributo 'checked' do input. | |
* No HTML você pode usar apenas 'checked' ao invés de 'checked="checked"'. | |
* Já no XHTML você deve usar 'checked="checked"' apenas. | |
* | |
* Se o atributo 'checked' existir, mesmo que seu valor esteja vazio ou nulo, | |
* o checkbox será considerado como CHECKED! | |
* | |
* Att. | |
* L. Tonet | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment