Just wondering whether is it possible to show and hide a subform within a zend form on either a radio check event or button onclick event. As I have a form with user field elements and now I want a sub form with password elements which will give the user the ability to optionally change their password. However I only want to show the password elements on request (ie: click a radio button 'Change Password' and the change password elements appear).
Is this possible with Zend\Form or would I need to use client side javascript to show and hide the elements?
It is possible but that kind of thing is client side so you need to use javascript in order to do it. Personnaly, I like to use jQuery for that kind of stuff, it makes it a lot easier. Here is an example on how you could do it.
class My_Form extends Zend_Form {
$field = $this->createElement('select', 'myselect');
$field->setLabel('Choose to display the form or not');
$field->setMultiOptions(array('1'='Display', '2'=>'Do not display'));
$this->addElement($field);
$field = $this->createElement('text', 'optionaltext');
$field->setLabel('This is an optional field');
$this->addElement($fiel);
}
Now, in your layout, you should include jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
And finally, you should include another .js file (or simply embed the code in <script> tags on your page).
$(document).ready(function() {
$(function() {
//Function triggered when changing the value in the drop down
$('#myselect').change(function(event) {
if($('#myselect').val() == 1) {
//Show elements
$('#optionaltext').show();
//The following line shows/hides all the dd/dt wrappers as well
$('[id*=optionaltext]).show();
} else {
//Hide elements
$('#optionaltext').hide();
//The following line shows/hides all the dd/dt wrappers as well
$('[id*=optionaltext]).hide();
}
});
});
});
Now please keep in mind that I haven't tested the code and I just wrote that on top of my head before I actually finished my first coffee of the day so... it might have a few bugs. This being said, it should be a good start for what you want to do. Please just ask your questions here if there is something missing or if there is a bug you can't find. Hope this helps !