symfony setting value of specific checkbox widgets in form
I ha开发者_StackOverflow社区ve a widget defined with a series of checkboxes that is essentially used to build up a bit flag. So I have a DB column 'access_bits', and I have several checkboxes generated on in the form class, in the format of 'access_bits[]', with the appropriate values (i.e. 1,2,16,1024 etc)
following the solution on this post (Symfony: How to change a form field attribute in an action?) - which is simple and sensible - I am able to magically set the attribute for all the checkboxes. But how can I target specific ones (preferably by value)?
TO CLARIFY:
HTML:
<input name="user[access_bit][]" value="1" /> Level 1
<input name="user[access_bit][]" value="2" /> Level 2
<input name="user[access_bit][]" value="4" /> Level 3
<input name="user[access_bit][]" value="8" /> Level 4
In the DB I have a column that has a bitwise integer. So for example, to have Level 1 and Level 2 checked, the value in the column would be 3. To have them all checked, the value would be 15.
"What I Want" PHP in action.class.php
$exampleValue = 4;
foreach ($form->getWidget('access_bit') as $thisWidget)
{
if ($thisWidget->getValue() == $exampleValue)
{
$thisWidget->setAttribute('checked','checked');
}
}
... which would cunningly set the checkbox next to Level 3 as ticked.
I do not want to use jQuery to do this.
you can try this....on your form save you can use this
$samplevar = $this->your_form->save();
$samplevar->setYOURFORMFIELDNAME(array of values(1,2,3));
$this->sample = YOURFORM($samplevar);
or,
on showing the form in first you can also pass the value in form while setting
$this->samplevariable = YOURFORM($this->getYOURMODEL->setYOURFORMFIELDNAME(array of values(1,2,3) which u get form db getYOURFORMFIELDNAME);
if you have values in comma seperated you cane use explode directly
$samplevar = $this->YOURFORMNAME->save();
$samplevar->setYOURFORMFIELDNAME(explode(',', $samplevar ->getYOURFORMFIELDNAME()));
$this->YOURFORMNAME = new YOURFORMForm($samplevar);
Try using the setDefault method :
$thisWidget->setDefault(array($examplevalue));
精彩评论