Posts Tagged ‘widgets’

Adding javascript to symfony form field

Tuesday, November 17th, 2009

In the users table at my company’s website there are fields for company, division, region, and location. Since each level of the company organization affects all the lower categories I have to filter out the invalid choices when a higher level choice is selected.

I’ve implemented this on some forms that I’ve created manually on the site but not in any forms that I haven’t heavily modified from the stock symfony creation.  I started googling around to find a solution but could not find a simple explanation of how to do it.  I expected to find at least some information in one of symfony’s otherwise excellent tutorials, but alas, no.

I had a minor epiphany and went digging through the forms API that symfony provides and realized that I should easily be able to do this through the sfWidgetFormPropelChoice method.  The second parameter passed is the html attributes for the form field.  I thought I had seen a form post here that said that I could add javascript code to the html attributes and not have it get converted into html entities.

I tried throwing a simple alert() inside the onchange attribute for my company box and wham! it worked!  So simple.  Code below:

new sfWidgetFormPropelChoice(
	array(
		'model' => 'Company',
		'add_empty' => true
	),
	array(
		'onchange' => "filterBy('company', 'division', this.value, 'sf_guard_user_user_division_id');" .
			"filterBy('company', 'region', this.value, 'sf_guard_user_user_region_id');" .
			"filterBy('company', 'location', this.value, 'sf_guard_user_user_location_id');"
	)
)

Till Next Time