Pjax Form

Hi All,

I have couple of Models, which are extending ActiveRecord. I wish to create a simple search form, which will be used to send the parameters to the controller and then the controller in turn returns a partial view which will contain the results in a table and this will then be displayed below the form, so that the form can be used again to re-search.

Now I am stuck. I have a 3 field inputs for simplicity, i have a seperate <a> as a button wrapped around a Pjax widget, which returns the partial view, but the button is removed once clicked. Also the form inputs are not being sent to the controller action.

How do I find by the posted values across multiple Models?

Many Thanks

Matt

You can use Model::loadMultiple and Model::validateMultiple methods. Check an example of usage for tabular form here.

Thanks Kartik,

Any help/advice on submitting a form and having the results pjax/ajax update a table?

I’d ideally like a page with only a form at the top, when submitted, a table is presented below with the results and they can re-submit the form and the data is updated in the table.

Forwarding a wiki that may be useful for tabular input handling.

Unfortunately, I do not have time to write a complete or detailed code for this. But you should use the same concept and send the html markup for the table via ajax response-

For example in your controller:




use yii\base\Model;

use yii\helpers\Json;

public function actionAjaxUpdate()

{

    // retrieve items to be updated in a batch mode

    // assuming each item is of model class 'Item'

    $items=$this->getItemsToUpdate();

    $status = 'default';

    if (Model::loadMultiple($items, Yii::$app->request->post())) {

        if (Model::validateMultiple($items)) {

            foreach ($items as $item) {

               $item->save();

            }

            $status = 'success';

        }

        else {

            $status = 'error';

        }

    }

    echo Json::encode([

        'output' => $this->renderPartial('_form', ['items'=>$items]),

        'status' => $status

    ]);

}



Possible ajax call in your view submit:




$("#idForm").submit(function() {

    $.ajax({

        type: "POST",

        url: '/site/ajax-update',

        data: $("#idForm").serialize(), // serializes the form's elements.

        success: function(data) {

            if (data.status == 'success') {

                $('#tabular-form-div').html(data.output);

            }

            else {

                alert('Error in submission. Correct the validation errors.');

            }

        }

    });

    return false; // prevent actual submit of the form.

});



You may need to build upon this for your scenario (I have not tested these code).

Many Thanks for your reply, that looks like what I want to achieve.

My only thoughts, I was hoping to achieve without adding custom js, I thought I could get this by using Pjax. But if that is the way then, thats fine, just wanted to keep in with yii as much as possible without adding to much additional code.

How do I also load multiple models into an ActiveDataProvider which is what gives my gridview the data.

Will give it a go and see the results.

I had the above set up as you suggested Kartik, it did work when the form was submitted the table was returned, but the pagination failed to work.

Just cant work it out, didnt think it was a hard task and thought it would be something Yii could do fairly simple, return a table for a form submission. Using it as a search for the database to return customers.

In my ActiveDataProvider the query is set to Customer::find(), how do i return a search based on where parameters and across multiple models.

I do not have your complete use case… probably will do so when I have time.

For writing a query to search across multiple models you may use something like below:




$query->where([

    'status' => 10,

    'type' => 2,

    'id' => [4, 8, 15, 16, 23, 42], // list of keys from your tabular data

]);



This is my current set up

View:




<div class="customer-form">

    <?php 

    $form = ActiveForm::begin([

               'id' => 'update-form',

               'enableClientValidation' => false,

    ]); ?>

         

         <div class="div col-lg-4">

             <?= $form->field($model, 'SourceBranch')->label('Branch') ?>

         </div>

         <div class="div col-lg-4">

             <?= $form->field($model, 'Name') ?>

         </div>

         <div class="div col-lg-4">

         <br>

             <?= Html::submitButton('View', ['class' => 'btn btn-primary']) ?>

         </div>


    <?php 

        ActiveForm::end(); 

    ?>


    


</div><!-- customer-form -->


     <div class="col-lg-12" id="here">

<?php

   Pjax::begin(['formSelector' => '#update-form']);

   echo GridView::widget([

           'dataProvider' => $dataProvider,

           //'summary' => '',

           'options' => ['class' => 'table-responsive'],

               ]); 

   Pjax::end();

?>

     </div>



Action:




      $params = Array();

      if(Yii::$app->request->isPost)

      {

         $params = Yii::$app->request->post();

         $params = $params['Customer'];

         $sql = Customer::find()->where(['SourceBranch' => $params['SourceBranch']]);

      }else

      {

         $sql = Customer::find();

      }

        $dataProvider = new ActiveDataProvider([

                   'query' => $sql,

                   'pagination' => [

                     'pageSize' => 30,

                    ],

                    'sort' => false,

                  ]); 


           return $this->render('form',[

                'model' => $sql,

                'dataProvider' => $dataProvider,

                 ]);



Within my Customer model I have :




    /**

     * @return \yii\db\ActiveQuery

     */

    public function getType()

    {

        return $this->hasOne(CustomerType::className(), ['ID' => 'CustomerTypeID']);

    }



But its only returning the ID not the customer type.