Pages

Wednesday, April 13, 2011

Calling ajax function when using form Widgets in doctrine and symfony1.4

Suppose you want to call a ajax function for a dropwon value changes
first define a dropdown in TblNameForm.class.php

$this->widgetSchema('myDropdown',array('label'=>'Drop Down','choices'=>array('Cars'=>'Cars','Bikes'='Bikes'),'onchange'=>'callajax(this.value,'automobileDiv')'));

In your template action class
$this->form = new TblNameForm();

In your template
<tr>
 <td>
  <?php echo $form['myDropdown']->renderLabel(); ?>
 </td>
 <td><?php echo $form['myDropdown']->render(); ?>
 <div id='automobileDiv'></div></td>
</tr>

<script type="text/javascript">
function createInstance()
{
  if (window.XMLHttpRequest)
  {
   req = new XMLHttpRequest();
  } 
  else 
   alert("XHR not created");
 return(req);
};

function callajax(val,div)
{
  var req = createInstance();
  req.onreadystatechange = function()
  { 
   document.getElementById(div).value="Wait server...";
   if(req.readyState == 4)
   {
    if(req.status == 200)
    {
     document.getElementById(div).innerHTML=req.responseText; 
    } 
   else 
   {
    document.ajax.dyn.value="Error: returned status code " + req.status + " " + req.statusText;
   } 
} 
}; 
req.open("GET", "formWidgets/automobiles?type="+val, true); 
req.send(null);
}
</script>
In automobiles function in action class
$this->type = $this->requestParameter('type');
In automobilesSuccess.php
<?php if($type=="Cars") { ?>
<select>
 <option>BMW</option>
 <option>RR</option>
 <option>Benz</option>
</select>
<?php } else { ?>
<select>
 <option>Pulsar</option>
 <option>RR</option>
 <option>BR</option>
</select>
<?php } ?>
Please double check the path to the ajax file in fresh page and after submitting the page with required error.
Because the url might change so that you need to change the path to the ajax file to work perfectly.

Hope this helps someone........

No comments:

Post a Comment