Yii CWidget - Dependent Dropdown

726 Views Asked by At

I am trying to create a widget with a dependent dropdown box.

Following tutorial: http://www.yiiframework.com/wiki/24, I am faced with the following problem with the ajax part:

echo CHtml::dropDownList('metal_id', 'id', $metals, array(
    'ajax' => array(
        'type' => 'POST', //request type
        'url' => CController::createUrl('currentController/dynamiccities'),
        'update' => '#product_id',
    )
));

using CController is not possible, because I am inside a CWidget, not CController.

I can however use something like:

'url' => $this->getController()->createUrl('currentController/dynamicProducts')

However it still does not solve my problem because it does not refer to widget location, but the controllers folder.

Question 1: How can I get my ajax to call a method from within my CWidget?

Question 2: I am using a widget because I want this form to be available on several pages. Should I be creating a partial view instead??? If so, how do I pass the data required from another controller into the partial view?

POOR Solution / workaround: I have got the widget working by creating an AjaxController within the Controllers Folder. Not too happy with this solution because it is not very neat.

Is there a better solution for this?

3

There are 3 best solutions below

1
On

Try this:

'url' => Yii::app()->createAbsoluteUrl('currentController/dynamiccities'),
0
On

I would recommend taking a look at how the CCaptcha widget works.

If you create a new Yii application, it will be setup in the site/contact.php view by default.

Here are the general steps I would follow:

  1. Create a class DependentDropDownAction that extends CAction. It should handle processing your AJAX requests.
  2. Configure the actions() method in your controller to utilize that action class as dependentdropdown
  3. Within your DependentDropdownWidget class, configure a public $action='dependentdropdown' attribute
  4. When you render the CHtml::dropDownList() within your widget for your ajax configuration, do something like 'url' => $this->getController()->createUrl($this->action)
  5. Fill in those classes with your implementation logic, and then call your widget from within your view
0
On

Try using absolute url as shown

$this->createAbsoluteUrl('currentController/dynamicProducts');