PHP code example of lav45 / yii2-target-behavior

1. Go to this page and download the library: Download lav45/yii2-target-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lav45 / yii2-target-behavior example snippets


use lav45\behavior\Target;

class Post extends ActiveRecord
{
    public function behaviors() {
        return [
            [
                'class' => Target::className(),
                'targetAttribute' => 'tagNames',
//                'targetRelation' => 'tags',
//                'targetRelationAttribute' => 'name',
//                'delimiter' => ',',
            ],
        ];
    }
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getTags()
{
    return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
        ->viaTable('tbl_tour_tag_assn', ['tour_id' => 'id']);
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        // ...
        [['tagNames'], 'safe'],
        // ...
    ];
}

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        // for different configurations, please see the code
        // we have created tables and relationship in order to
        // use defaults settings
        'class' => Target::className(),
        'targetAttribute' => 'tagNames',
    ];
}


// On TagController (example)
// actionList to return matched tags
public function actionList($query)
{
    // We know we can use ContentNegotiator filter
    // this way is easier to show you here :)
    Yii::$app->response->format = Response::FORMAT_JSON;

    return Tag::find()
       ->select(['name'])
       ->where(['like', 'name', $query])
       ->asArray()
       ->limit(10)
       ->all();
}


// On our form
<?= $form->field($model, 'tagNames')->widget(SelectizeTextInput::className(), [
    // calls an action that returns a JSON object with matched
    // tags
    'loadUrl' => ['tag/list'],
    'options' => ['class' => 'form-control'],
    'clientOptions' => [
        'plugins' => ['remove_button'],
        'valueField' => 'name',
        'labelField' => 'name',
        'searchField' => ['name'],
        'create' => true,
    ],
])->hint('Use commas to separate tags')