Search of the CRUD is not working

Hi, i have a problem with my Yii2 application in the CRUD Application. The search of the CRUD is not working and it not show to me any result if i type anything on the fields between the heading and the starting row . The CRUD code is autogenerated by GII.Here are the code:

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\CRUDSearch;
use app\models\CRUDSearchCommesse;
use app\models\MElettrico;
use Da\QrCode\QrCode;
use app\models\Commesse;
use yii\db\Query;
use yii\data\ActiveDataProvider;
use yii\helpers\Url;
use app\models\AzioniUtente;

class SiteController extends Controller
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public static function UserPermissions(){
      return [
        'admin' => '100,103',
        'normal' => '101',
        'only_view' =>'102'
      ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
      Yii::$app->session->set('permessi', $this->UserPermissions());
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);

      return $this->render('commesse', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
      ]);
      //  return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
      if ($model->load(Yii::$app->request->post()) && $model->login()) {

        return $this->goBack();
        }

        $model->password = '';
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionCrud(){
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);

      return $this->render('commesse', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
      ]);
    }

    public function actionCreate(){
      $model = new MElettrico();
      $model_Utente = new AzioniUtente();
      $searchModel = new CRUDSearch();

          if ($model->load($this->request->post())){
          /*  if($this->request->post('QE_QB') == 1)
              $model->QE_QB = 'QE';
            else
              $model->QE_QB = 'QB';
*/
          //  $model->StringaToDate(Yii::$app->request->post('Tempi_Consegna'));
          $model_Utente -> username = Yii::$app->user->identity->username;
          $model_Utente -> Lettura_QRCode_At  = date('Y-m-d H:i:s');
          $model_Utente -> Stato_Oggetti = $model->Stato;
          $model_Utente -> Azione = 'CREATE';
          $model_Utente -> save();
          $qrCode = (new QrCode('http://192.168.0.47:8080/index.php?r=site%2Fobject&Codice_Interno='.$model->Codice_Interno))
              ->setSize(75)
              ->setMargin(5)
              ->useForegroundColor(51, 153, 255);
          $qrCode->writeFile('C:/Users/carlo.lazzari/Desktop/prova/QRCodes/' .$model->Nome_Sullo_Schema. '.jpg');
          $model->save();

          $query = (new Query())->from('m_elettrico')
          ->where(['ID_Commessa' =>   Yii::$app->session->get('Commessa')])
          ->orderBy('Stazione_Appartenenza');
          $dataProvider = new ActiveDataProvider([
              'query' => $query
            ]);


          return $this->render('magazzinoElettrico', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
          ]);
        }
      return $this->render('create', [
          'model' => $model,
      ]);
    }

    public function actionCreazione(){
      $model = new Commesse();
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);
     if ($this->request->isPost && $model->load($this->request->post())) {
            $model->save();
            return $this->render('commesse', [
              'searchModel' => $searchModel,
              'dataProvider'=> $dataProvider,
            ]);
          }
      return $this->render('creazione', [
          'model' => $model,
      ]);
    }

    public function actionMagazzino($ID_Commessa){
      $searchModel = new CRUDSearch();
      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $ID_Commessa])
      ->orderBy('Stazione_Appartenenza');
      Yii::$app->session->set('Commessa', $ID_Commessa);
      $dataProvider = new ActiveDataProvider([
        'query' => $query
      ]);
      return $this->render('magazzinoElettrico', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
      ]);
    }



    public function actionObject($Codice_Interno){

      $model = new MElettrico();
      $model = $this->findModel($Codice_Interno);

      Yii::$app->session->set('Codice_Interno',$Codice_Interno);
      Yii::$app->user->setReturnUrl(Yii::$app->request->url);

    return $this->render('viewObject', [
      'model'=> $model
    ]);
    }

    public function actionArrivato(){
      $model_Utente = new AzioniUtente();
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model_Utente -> Azione = $model->Stato;
      $model->Stato = 'Arrivato';
      $model_Utente -> username = Yii::$app->user->identity->username;
      $model_Utente -> Lettura_QRCode_At  = date('Y-m-d H:i:s');
      $model_Utente -> Stato_Oggetti = $model->Stato;
      $model_Utente -> Azione = $model_Utente -> Azione.' to '.$model->Stato;
      var_dump($model_Utente -> save());
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa])
      ->orderBy('Stazione_Appartenenza');
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }
    public function actionScaffale(){
      $model_Utente = new AzioniUtente();
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model_Utente -> Azione = $model->Stato;
      $model->Stato = 'Scaffale';
      $model_Utente -> username = Yii::$app->user->identity->username;
      $model_Utente -> Lettura_QRCode_At  = date('Y-m-d H:i:s');
      $model_Utente -> Stato_Oggetti = $model->Stato;
      $model_Utente -> Azione = $model_Utente -> Azione.' to '.$model->Stato;
      var_dump($model_Utente -> save());
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa])
      ->orderBy('Stazione_Appartenenza');
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }

    public function actionMontato(){
      $model_Utente = new AzioniUtente();
      $model = $this->findModel(Yii::$app->session->get('Codice_Interno'));
      $model_Utente -> Azione = $model->Stato;
      $model->Stato = 'Montato';
      $model_Utente -> username = Yii::$app->user->identity->username;
      $model_Utente -> Lettura_QRCode_At  = date('Y-m-d H:i:s');
      $model_Utente -> Stato_Oggetti = $model->Stato;
      $model_Utente -> Azione = $model_Utente -> Azione.' to '.$model->Stato;
      var_dump($model_Utente -> save());
      $model->save();

      $query = (new Query())->from('m_elettrico')
      ->where(['ID_Commessa' => $model->ID_Commessa])
      ->orderBy('Stazione_Appartenenza');
        $dataProvider = new ActiveDataProvider([
          'query'=> $query
        ]);
        $searchModel = new CRUDSearch();

        return $this->render('magazzinoElettrico', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
        ]);
    }

    public function actionLogs(){
      $query = (new Query())->from('azioni_utente_qr')
      ->orderBy([
        'Lettura_QRCode_At' => SORT_DESC
      ]);
      $activeDataProvider = new ActiveDataProvider([
        'query' => $query
      ]);
      return $this->render('logUtenti', [
        'dataProvider' => $activeDataProvider
      ]);
    }

    public function actionBack(){
      $searchModel = new CRUDSearchCommesse();
      $dataProvider = $searchModel->search($this->request->queryParams);
      return $this->render('commesse',[
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider
      ]);
    }
    /**
     * Finds the Commesse model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $ID_Commessa Id Commessa
     * @return Commesse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($Codice_Interno)
    {
        if (($model = MElettrico::findOne(['Codice_Interno' => $Codice_Interno])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

view

<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\ActionColumn;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\data\ActiveDataProvider;
use app\controllers\SiteController;
use app\models\MElettrico;
/* @var $this yii\web\View */
/* @var $model app\models\MElettrico*/
/* @var $searchModel app\models\CRUDSearch */
/* @var $dataProvider yii\data\ActiveDataProvider*/

$this->title = 'Magazzino Elettrico per '.Yii::$app->session->get('Commessa');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="melettrico-index" align="left">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?php
        $model = new MElettrico();
        $admin= false;
        $normal= false;
        $onlyView = false;
        $user_logged = Yii::$app->session->get('__id');
        $permessi = SiteController::UserPermissions();
      //  $permessi =Yii::$app->session->get('permessi');
        $adminPermissions = $permessi['admin'];
        $normalPermissions = $permessi['normal'];
        $onlyViewPermissions = $permessi['only_view'];
        $adminUsers = explode(',',$adminPermissions);
        $normalUSers = explode(',',$normalPermissions);
        $onlyViewUsers = explode(',',$onlyViewPermissions);
        for ($i=0; $i <count($adminUsers); $i++) {
          if ($adminUsers[$i] == $user_logged) {
             $admin = true;
          }
        }
        if(! $admin){
        for ($i=0; $i <count($normalUSers); $i++) {
          if ($normalUSers[$i] == $user_logged) {
             $normal = true;
          }
        }
        if(!$normal){
              for ($i=0; $i <count($onlyViewUsers); $i++) {
                    if ($onlyViewUsers[$i] == $user_logged) {
                    $onlyView = true;
                  }
                }
              }
        }
        if(!$onlyView){
        ?>
        <?= Html::a('Crea Elemento per '.Yii::$app->session->get('Commessa'), ['create'], ['class' => 'btn btn-success']) ?>
      <?php } ?>
    </p>

    <?php Pjax::begin(); ?>
    <?php // echo $this->render('_search', ['model' => $searchModel]);

        if($admin){
    ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'id' => 'elementiMagazzino',
       'tableOptions' => [
          'id' => 'MTable',
          'class'=>"table table-striped table-bordered"
        ],
        'columns' => [

            //'QRCode',
          /*  [
              'class' => 'yii\grid\DataColumn',
              'value' => function(){
                echo '<img src="' $dataProvider-> '">';
              }
            ],*/

            [
              'attribute' => 'Stato',
              'contentOptions' => function ($model, $key, $index){
                  if($model['Stato'] == 'Da Ordinare'){
                        return ['style' => 'background-color:Red'];
                } else if ($model['Stato'] =='Arrivato'){
                        return ['style' => 'background-color:Orange'];
                } else if ($model['Stato'] =='Scaffale'){
                        return ['style' => 'background-color:Yellow'];
                } else if ($model['Stato']=='Montato'){
                        return ['style' => 'background-color:Green'];
          }
                return ['style' => 'background-color:White'];
    }

            ],
            'Codice_Interno',
            'ID_Commessa',
            'Quantita',
            'Codice_Fornitore:ntext',
            'Descrizione:ntext',
            'Fornitore:ntext',
            'Marca:ntext',
            'QE_QB:ntext',
            'Costo',
            'Sconto_Base',
            'Sconto_Extra_1',
            'Sconto_Extra_2',
            'Costo_TotaleXQty_and_Sconto',
            'Tempi_Consegna',
            'Nome_Sullo_Schema:ntext',
            'Stazione_Appartenenza:ntext'


        ],
    ]); ?>

  <?php }
  else {?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [

            //'QRCode',
          /*  [
              'class' => 'yii\grid\DataColumn',
              'value' => function(){
                echo '<img src="' $dataProvider-> '">';
              }
            ],*/

            [
              'attribute' => 'Stato',
              'contentOptions' => function ($model, $key, $index){
                  if($model['Stato'] == 'Da Ordinare'){
                        return ['style' => 'background-color:Red'];
                } else if ($model['Stato'] =='Arrivato'){
                        return ['style' => 'background-color:Orange'];
                } else if ($model['Stato'] =='Scaffale'){
                        return ['style' => 'background-color:Yellow'];
                } else if ($model['Stato']=='Montato'){
                        return ['style' => 'background-color:Green'];
          }
                return ['style' => 'background-color:White'];
    }

            ],
            'Codice_Interno',
            'ID_Commessa',
            'Quantita',
            'Codice_Fornitore:ntext',
            'Descrizione:ntext',
            'Fornitore:ntext',
            'Marca:ntext',
            'QE_QB:ntext',
            'Tempi_Consegna',
            'Nome_Sullo_Schema:ntext',
            'Stazione_Appartenenza:ntext'


        ],
    ]); ?>
<?php  }
  Pjax::end(); ?>

</div>

Thanks in advance to everyone who’s gonna look my code and help me finding a solution.

First, do not paste every code in the controller. Just post codes relevant to your question. Not many people can waste time to try to figure out which code relates to your problem. Secondly do not create models in views. that code should be in controllers.

Your code is such a mess that it is hard to understand what you are actually trying to do!

Is actionIndex or actionCrud the one that you have some trouble with?
If so, please show us what you are doing in CRUDSearchCommesse::search().
Probably you fail to filter the result by the attributes of the search model.

1 Like

Thanks for the advice next time i will!

The action that i am in trouble with is the actionMagazzino and the filters are not working in the view related that is the view posted here.
The CRUDSearchCommesse::search() is autogenerated code with GII that is in the following space

public function search($params)
    {
        $query = MElettrico::find();

        // add conditions that should always apply here

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

        $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;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'Quantita' => $this->Quantita,
            'Costo' => $this->Costo,
            'Sconto_Base' => $this->Sconto_Base,
            'Sconto_Extra_1' => $this->Sconto_Extra_1,
            'Sconto_Extra_2' => $this->Sconto_Extra_2,
            'Costo_TotaleXQty_and_Sconto' => $this->Costo_TotaleXQty_and_Sconto,
            'Tempi_Consegna' => $this->Tempi_Consegna,
        ]);

        $query->andFilterWhere(['like', 'Stato', $this->Stato])
            ->andFilterWhere(['like', 'Codice_Interno', $this->Codice_Interno])
            ->andFilterWhere(['like', 'ID_Commessa', $this->ID_Commessa])
            ->andFilterWhere(['like', 'Codice_Fornitore', $this->Codice_Fornitore])
            ->andFilterWhere(['like', 'Descrizione', $this->Descrizione])
            ->andFilterWhere(['like', 'Fornitore', $this->Fornitore])
            ->andFilterWhere(['like', 'Marca', $this->Marca])
            ->andFilterWhere(['like', 'QE_QB', $this->QE_QB])
            ->andFilterWhere(['like', 'Nome_Sullo_Schema', $this->Nome_Sullo_Schema])
            ->andFilterWhere(['like', 'Stazione_Appartenenza', $this->Stazione_Appartenenza])
            ->andFilterWhere(['like', 'PercorsoQRCode', $this->PercorsoQRCode]);

        return $dataProvider;
    }

I assume all those fields are text and that whetever you type have something like it in the database.
My Advice is, comment all fields but one and start testing which field is the offender and try to find out why

1 Like

In actionMagazzino, you are not using the gii-generated search() function and you are trying to generate a data provider on your own. Your code has no filtering functionality because you are setting a fixed where clause using ID_Commessa.

You are doing the same kind of things in many of the actions, but that’s not an effective way.

Try to consider making use of the gii-generated search().

actionMagazzino could be written like the following, I guess

    public function actionMagazzino($ID_Commessa)
    {
      $searchModel = new CRUDSearchCommesse();
      $searchModel->ID_Commessa = $ID_Commessa;
      $dataProvider = $searchModel->search($this->request->queryParams);

      return $this->render('commesse', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
      ]);
    }
2 Likes

Thank so much it works perfectly!