Reputation: 913
I would like to create a form in Symfony2 which displays a set of radio buttons depending on the selected value in a combo-box belonging to the same form.
I have not been able to find a suitable solution in Symfony2 that would allow me to have this functionality.
Is there any way to use the Symfony2 framework at least for part of the implementation or should I generate the form manually?
Upvotes: 1
Views: 965
Reputation: 31
You could try using the symfony2 form builder, which permits to construct forms programmatically.
This would be possible if you could determine the entity before the construction of the form...
Upvotes: 1
Reputation: 7040
What you're looking for is AJAX. This can be implemented with straight javascript or jQuery (jQuery is much cleaner and easier to use).
Here's a jQuery stub for you to get an idea of what has to happen:
<script language="javascript">
$('#mySelect').change(function() {
$.post('backgroundScript.php', {
val: $(this).val()
}, function(data) {
$('#radioDiv').html(data);
});
});
</script>
If you're not familiar with AJAX & jQuery, I'll explain what's going on. $('#mySelect')
is almost the equivalent of javascript's getElementById()
function. They are NOT the same functionality (jQuery uses the same notations as css to find the elements you're looking for), but this will return the element with mySelect
as its id attribute.
.change()
sets the onChange event handler to the function()
defined within the brackets. $.post
is jQuery shorthand for performing an AJAX post
(as opposed to a get
), that is sent to backgroundScript.php without a page load. When backgroundScript.php returns with a 200 status (i.e. "everything's OK, here's my output") it will perform the callback function function(data)
.
backgroundScript.php will receive val
as a $_POST variable and do "something" to determine which radio buttons should be displayed, then will write output to the screen.
EDIT (more info):
backgroundScript.php should look something like this if you're determining the radio buttons based on a database. Keep in mind that this is not written with security or consideration of deprecated functions in mind (e.g. mysql_*
), just functionality:
<?php
// backgroundScript.php
$masterVal = $_POST['val'];
$output = "";
$query = "SELECT bt.button_value, bt.button_label
FROM button_table as bt
WHERE bt.button_master_id = " . $masterVal;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$output .= "<input type='radio' name='radioGroup' value='" .
$row['button_value'] . "' /> " . $row['button_label'];
}
echo $output;
Upvotes: 4