Yii2 CRUD generated manually

828 Views Asked by At

I would like to have a CRUD table, and to be specific I don't need to edit/delete records, only the part with filtering results, which appears at the top of the CRUD generated table, is the part that I want to have. My table contains data from 1 table in database, but I have one column that is not connected to this or any other table in database (it's a comment, that is auto-generated, based on one column from the table). I generate my table manually, but I'd like to add the part with filtering. I have no idea how to do it though. Is it possible in Yii2 to do it manually, or do I have to use CRUD generator?

2

There are 2 best solutions below

1
On BEST ANSWER

I don't use CRUD generator as it doesn't generate the code I want (and I think it also doesn't generate filters?). I use a basic template which fits to nearly all gridviews I need to display. Here's one example that can give you a filter:

use yii\grid\GridView;

/** @var array $userTypes All user types (classes) */ 
// ...

echo GridView::widget([
    'dataProvider' => $modelProvider,
    'filterModel' => $model,
    'columns' => [
        [
            'attribute' => 'id',
            'format' => 'raw',
            'filter' => Html::input('text', 'User[id]', $model->id, ['class' => 'form-control', 'placeholder' => 'Filter ID']),
        [
            'attribute' => 'type',
            'format' => 'raw',
            'filter' => Html::activeDropDownList($model, 'type', $userTypes, ['class' => 'form-control', 'prompt' => 'All types']),
        ],
]);

In here I use 2 different input field types (text and dropdown).

For Html::input, first is type (text), then full attribute name (model name + attribute name), then default value and finally other options.

For Html::activeDropDownList we have model first, then attribute name (only), that items list (array) and finally other options.

0
On

I guess you are talking about GridView, if yes then you can have your own columns in it, no problem. lets call that column comment as you mentioned

If you use basic template, generated by Gii, and you also generate search class for that model, then you comment to safe attributes and add code for that code to be able to filter it.

If you could be more detailed about mentioned column, possible values or algorythm you might get more suitable answers...

Also take look at Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView

Lets say your model is called Xyz as you did not provided any. Also I named column from your table as column_from_your_table and your virtual column as comment

In your model Xyz you will add relation (method with specific name to define it)

public function getComment()
{
    $column_from_your_table = $this->column_from_your_table;
    $comment = '';

    // your code to specify the relation
    // ...

    // this is value dislpayed in column grid
    return $comment;
}

and in file XyzSearch.php in \app\models\

you will have something like this (edit to your needs ofcourse)

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\Expression;

/**
 * XyzSearch represents the model behind the search form about `app\models\Xyz`.
 */
class XyzSearch extends Xyz
{
    public $comment; // your virtual column

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            // add it to safe attributes
            [['comment'], 'safe'],
            // you will have more rules for your other columns from DB probably
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Xyz::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        // I dont know your how it is your comment column autogenerated
        // or what is the relation, so I give you just basic idea
        // your algorythm needs to be able to be rewritten in SQL
        // otherwise I dont know how you could possibly sort it
        $dataProvider->sort->attributes['comment'] = [
            'asc' => [Xyz::tableName().'.column_from_your_table' => SORT_ASC],
            'desc' => [Xyz::tableName().'.column_from_your_table' => SORT_DESC],
            'default' => SORT_ASC,
        ];

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // again, you will have more filtering conditions from your generated code

        // then you will add your custom filtering condition
        // I dont know your how it is your comment column autogenerated 
        // or what is the relation, so I give you just basic idea
        $query->andFilterWhere(['like', Xyz::tableName().'.column_from_your_table', $this->comment]);


        return $dataProvider;
    }
}

finaly in your view file add your virutal column

<?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        // other columns from database
        // ...

        'comment',

        ['class' => 'yii\grid\ActionColumn'],
    ]
]); ?>