Using observe_field to update an input

Saturday, April 19th, 2008

Had an issue on Acme Video Website where I want to prepopulate some content on a form element after making an ajax call to a 3rd party API.

Problems comes, in that observe_field (part of the prototype javascript library), is designed to update a div, so I was incorrectly trying to do this:

echo observe_field('hint', array(
'update' => "tags",
'url' => '@embargo_helper',
'with' => "'hint=' + $('hint').value",
'loading' => "'Loading...'"
));

So it should take the value of the hints input element, go off to the 3rd party api, grab the info I need then pop it into the input that has an id of tags … only that doesn’t work, of course.

So what’s the solution?
Ok, a 3 step process, firstly we need to add script = true in our observe_field parameters, letting the observe_field know that it’s going to have script returned that it will need to execute

echo observe_field('hint', array(
'update' => "tags",
'url' => '@embargo_helper',
'with' => "'hint=' + $('hint').value",
'loading' => "'Loading...'",
'script' => true
));

note: true without quotes.

Next, here’s a look at my action, of course it’s not really that important, you do whatever you need to do here:

Action

  public function executeHelper(){
  	$this->description = myTools::getDescriptionFromHint($this->getRequestParameter('hint'));
  }

Then you need to edit the view to execute some javascript:

View

<?php $sf_context->getResponse()->setContentType('text/javascript') ?>
$('tags').value = '<?php echo $description;?>';

And there we go…

…now, I’m not entirely happy with this for 2 reasons. Firstly, the update parameter of the observe_field call is now redundant, and secondly, the id of the input we want to update is now harded in the view, so to at least get around that, we can add an extra parameter in the with part of observe_field like this:

echo observe_field('hint', array(
'update' => "tags",
'url' => '@embargo_helper',
'with' => "'hint=' + $('hint').value+ '&updateid=tags'",
'loading' => "'Loading...'",
'script' => true
));

…so now we are letting our symfony code know what ID we want to update, so lets re-edit the action to take this into account:

Action

  public function executeHelper(){
  	$this->description = myTools::getDescriptionFromHint($this->getRequestParameter('hint'));
        $this->updateid = $this->getRequestParameter('updateid');
  }

and then let the view know which id it needs to update:

View

<?php $sf_context->getResponse()->setContentType('text/javascript') ?>
$('<?php echo $updateid;?>').value = '<?php echo $description;?>';

I’m sure there’s a neater way of doing this, but hell, got it working anyway.

Written by baj | Posted on April 19th, 2008 in symfony |