AJAX-dependent drop-down list

Often, you'll need a form with two dropdowns, and one dropdown's values will be dependent on the value of the other dropdown. Using Yii's built-in AJAX functionality, you can create such a dropdown.

Getting ready

  1. Create a new application by using composer, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
  2. Create an @app/model/Product.php model as follows:
    <?php namespace app\models; use yii\db\ActiveRecord; class Product extends ActiveRecord { public function rules() { return [ ['title', 'string'], [['title', 'category_id', 'sub_category_id'], 'required'], ['category_id', 'exist', 'targetAttribute' => 'id', 'targetClass' => 'app\models\Category'], ['sub_category_id', ...

Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.