Categories followed by their subcategories in dropdown – Yii2.0

For Example


Create category table.

`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`description` text NOT NULL,
`image` varchar(250) NOT NULL,
`order` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0' COMMENT '0=> inactive, 1=>active',

Open models/Category.php. Then add below code,

public function getCategories($parent_id = 0, $exclude = '', $space = '', $categories='')
if($parent_id == 0){
$space = '';
$categories = array();
$space .='- ';

$model = Category::findAll([
'parent_id' => $parent_id,
foreach ($model as $key) {
if($key->id == $exclude) continue;
$categories[] = array('id'=>$key->id, 'name'=>$space.$key->name);
$categories = $this->getCategories($key->id, $exclude, $space, $categories);

return $categories;

Open views/category/_form.php


use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Category;

 $category = new Category;
 $categories = $category->getCategories(0, $model->id);
 $items = ArrayHelper::map($categories, 'id', 'name');
<?php echo $form->field($model, 'parent_id')->dropDownList($items,['prompt'=>'--None--']); ?>
'btn btn-success']) ?>
<?php ActiveForm::end(); ?> </div>


Yii2 advanced – Hide frontend/web and backend/web from url

Step 1
Create .htaccess file in root folder, i.e advanced/.htaccess and write below code.

Options +FollowSymlinks
RewriteEngine On

# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} ^/(assets|css) <------
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php


Note : if you are trying in local server then replace ^/ with ^/project_name/ where you see arrow sign.
Remove those arrow sign

Step 2
Now create a components/Request.php file in common directory and write below code in this file.

namespace common\components;

class Request extends \yii\web\Request {
    public $web;
    public $adminUrl;

    public function getBaseUrl(){
        return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;

        If you don't have this function, the admin site will 404 if you leave off 
        the trailing slash.


        Wouldn't work:

        Would work:

        Using this function, both will work.
    public function resolvePathInfo(){
        if($this->getUrl() === $this->adminUrl){
            return "";
            return parent::resolvePathInfo();


Step 3
Installing component. Write below code in frontend/config/main.php and backend/config/main.php files respectively.

//frontend, under components array
    'class' => 'common\components\Request',
    'web'=> '/frontend/web'
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,

// backend, under components array
    'class' => 'common\components\Request',
    'web'=> '/backend/web',
    'adminUrl' => '/admin'
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,


Step 4 (Optional, if doesn’t work till step three)

create .htaccess file in frontend/web and backend/web directories

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]


Note: make sure you have enabled your mod rewrite in apache

Thats it! You can try your project with,

in local server
localhost/project_name/admin, localhost/project_name

Copy from:

Install Yii2 advanced in Ubuntu

Step 1. Create an advanced project with composer

root@manager:/var/www/html# composer create-project --prefer-dist yiisoft/yii2-app-advanced yii2advanced

Step 2. Change to the yii2advanced folder and run the init command

root@manager:/var/www/html# cd yii2advanced
root@manager:/var/www/html/yii2advanced# php init
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?
[0] Development
[1] Production

Your choice [0-1, or “q” to quit] 0

Initialize the application under ‘Development’ environment? [yes|no] y

Start initialization …

generate backend/config/main-local.php
generate backend/config/params-local.php
generate backend/web/index-test.php
generate backend/web/index.php
generate common/config/main-local.php
generate common/config/params-local.php
generate console/config/main-local.php
generate console/config/params-local.php
generate frontend/config/main-local.php
generate frontend/config/params-local.php
generate frontend/web/index-test.php
generate frontend/web/index.php
generate yii
generate cookie validation key in backend/config/main-local.php
generate cookie validation key in frontend/config/main-local.php
chmod 0777 backend/runtime
chmod 0777 backend/web/assets
chmod 0777 frontend/runtime
chmod 0777 frontend/web/assets
chmod 0755 yii

… initialization completed.

Step 3. Create the database

mysql> create database yii2advanced;

Open common/config/main-local.php set your mysql connection.

 'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => 'redhat',
'charset' => 'utf8',
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,

Step 4. Run the Yii Migration Tool

root@manager:/var/www/html/yii2advanced# php yii migrate

Yii Migration Tool (based on Yii v2.0.11.1)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:

Apply the above migration? (yes|no) [no]:y
*** applying m130524_201442_init
> create table {{%user}} ... done (time: 0.140s)
*** applied m130524_201442_init (time: 0.186s)
1 migration was applied.

Migrated up successfully.