yii2 dynamic form for single model - php

I am working yii2 advanced of dynamic form using webraganca for a single model. but i am unable to precede further due to the following error. Any help is appreciated to much.
my code is as follows:
controller.php
namespace frontend\controllers;
use Yii;
use frontend\models\Ireturn;
use frontend\models\IreturnSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use frontend\models\Model;
/**
* IreturnController implements the CRUD actions for Ireturn model.
*/
class IreturnController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Ireturn models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new IreturnSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if(Yii::$app->request->post('hasEditable'))
{
$ireturnId = Yii::$app->request->post('editableKey');
$ireturn = Ireturn::findOne($ireturnId);
$out = Json::encode(['output'=>'','message'=>'']);
$post = [];
$posted = current($_POST['Ireturns']);
$post['Ireturns']= $posted;
if($ireturn->load($post))
{
$ireturn->save();
$output ='my values';
$out = Json::encode(['output'=>$output,'message'=>'']);
}
return;
}
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Ireturn model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$modelsItem = $model->ireturn;
return $this->render('view', [
'model' => $this->findModel($id),
'modelsItem'=>$modelsItem,
]);
}
/**
* Creates a new Ireturn model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Ireturn();
$modelsAddress = [new Ireturn];
if ($model->load(Yii::$app->request->post())) {
$modelsAddress = Model::createMultiple(Ireturn::classname());
Model::loadMultiple($modelsAddress, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAddress) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsAddress as $modelAddress) {
$modelAddress->id = $model->id;
if (! ($flag = $modelAddress->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('create', [
'model' => $model,
'modelsAddress' => (empty($modelsAddress)) ? [new Ireturn] : $modelsAddress
]);
/*$model = new Ireturn();
$modelsAddress = [new Ireturn];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'modelsAddress' => (empty($modelsAddress)) ? [new Ireturn] : $modelsAddress
]);
}*/
}
/**
* Updates an existing Ireturn model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Ireturn model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Ireturn model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Ireturn the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Ireturn::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
/*public function actionEditableDemo() {
$model = new Ireturn(); // your model can be loaded here
// Check if there is an Editable ajax request
if (isset($_POST['hasEditable'])) {
// use Yii's response format to encode output as JSON
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// read your posted model attributes
if ($model->load($_POST[])) {
// read or convert your posted information
$value = $model->functional;
// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>''];
// alternatively you can return a validation error
// return ['output'=>'', 'message'=>'Validation error'];
}
// else if nothing to do always return an empty JSON encoded output
else {
return ['output'=>'', 'message'=>''];
}
}
// Else return to rendering a normal view
return $this->render('view', ['model'=>$model]);
}*/
}
_form.php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use backend\models\Items;
use backend\models\Departments;
use kartik\select2\Select2;
use dosamigos\datepicker\DatePicker;
use yii\web\View;
use wbraganca\dynamicform\DynamicFormWidget;
use common\models\User;
/* #var $this yii\web\View */
/* #var $model backend\models\Ireturn */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="ireturn-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form','options'=>['class'=>'well'],]); ?>
<div class="panel panel-default" >
<!--<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Items
</h4>
</div>-->
<div class="panel-body">
<div class="row">
<div class="col-xs-4">
<?= $form->field($model, 'dept_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Departments::find()->all(),'id','dept_name'),
'language' => 'en',
'options' => ['placeholder' => 'Select departments ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-3">
<?= $form->field($model, 'voucher_no')->textInput(['maxlength' => true])?>
</div>
</div>
<!-- <div class="panel panel-default">-->
<!-- <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Items</h4></div>-->
<!-- <div class="panel-body">-->
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'items_id',
'unit',
'amount',
'functional',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left"> <i class="glyphicon glyphicon-envelope"></i>Item</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($model, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-3">
<?= $form->field($modelAddress, "[{$i}]items_id")->dropDownList(
ArrayHelper::map(Items::find()->all(),'id','item_name'),
['prompt'=>'select items']) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelAddress, "[{$i}]unit")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelAddress, "[{$i}]amount")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-3">
<?= $form->field($modelAddress, "[{$i}]functional")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
<?php endforeach; ?>
</div>
</div>
<?php DynamicFormWidget::end(); ?>
<!-- </div>-->
<!-- </div>-->
<div class="padding-v-md">
<div class="line line-dashed"></div>
</div>
<div class="row">
<div class="col-xs-4">
<?= $form->field($model,'user_id')->dropDownList(
ArrayHelper::map(User::find()->all(),'id','full_name'),
['prompt'=>'select employees'])
?>
<?= $form->field($model,'head_id')->dropDownList(
ArrayHelper::map(User::find()->all(),'id','full_name'),
['prompt'=>'select dept heads'])
?>
<?= $form->field($model,'man_id')->dropDownList(
ArrayHelper::map(User::find()->all(),'id','full_name'),
['prompt'=>'select stoke managers'])
?>
<?= $form->field($model,'keeper_id')->dropDownList(
ArrayHelper::map(User::find()->all(),'id','full_name'),
['prompt'=>'select stoke keepers'])
?>
</div>
<div class="col-xs-4">
<?=$form->field($model, 'emp_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'head_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'man_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'keeper_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<<EOD
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
console.log("beforeInsert");
});
$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
console.log("afterInsert");
});
$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
if (! confirm("Are you sure you want to delete this item?")) {
return false;
}
return true;
});
$(".dynamicform_wrapper").on("afterDelete", function(e) {
console.log("Deleted item!");
});
$(".dynamicform_wrapper").on("limitReached", function(e, item) {
alert("Limit reached");
});
EOD;
$this->registerJs($script, View::POS_END);
?>

it is not clear why you want to save the child item into the same table as the parent items.
please review your code,
$modelAddress->id = $model->id;
you cannot assign the same id to both parent and child if you are saving it in the same table with unique constrain on the id attribute
alternative, u may create a new column [refference_id] to refer to parent id
$modelAddress->refference_id = $model->id;

Related

Yii2 Dynamic Form Error on Create - The 'model' property must be set and must extend from '\yii\base\Model'

In Yii2, I have been trying to create a dynamic form using the below tutorials.
Yii2-dynamicForm - GitHub and Youtube Tutorial.
I followed the same step as mentioned in tutorials, unfortunately I am held up with an error(screenshot attached)
And I am not able to resolve this error, can any one help me to find what I am missing.
For the reference I am attaching my Models here, rest the controllers and views are same as the tutorials.
Request Model
<?php
namespace app\models;
use Yii;
class Request extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'request';
}
public function rules()
{
return [
[['req_date', 'req_on', 'req_updated_on'], 'safe'],
[['req_job', 'req_type', 'material_type', 'req_status'], 'required'],
[['req_by'], 'integer'],
[['req_status'], 'string'],
[['req_job', 'req_type'], 'string', 'max' => 100],
[['material_type'], 'string', 'max' => 150],
];
}
public function attributeLabels()
{
return [
'req_id' => 'Req ID',
'req_date' => 'Req Date',
'req_job' => 'Job No',
'req_type' => 'Type of Request',
'req_on' => 'Required On',
'material_type' => 'Material Type',
'req_by' => 'Req By',
'req_updated_on' => 'Req Updated On',
'req_status' => 'Request Status',
];
}
}
RequestItems Model
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* This is the model class for table "request_items".
*
* #property int $req_item_id
* #property int $req_id
* #property string $item_name
* #property string $item_qty
* #property string $item_unit
*/
class RequestItems extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'request_items';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['req_id', 'item_name', 'item_qty', 'item_unit'], 'required'],
[['req_id'], 'integer'],
[['item_name'], 'string', 'max' => 100],
[['item_qty', 'item_unit'], 'string', 'max' => 25],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'req_item_id' => 'Req Item ID',
'req_id' => 'Req ID',
'item_name' => 'Item Name',
'item_qty' => 'Item Qty',
'item_unit' => 'Item Unit',
];
}
}
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use kartik\select2\Select2;
use kartik\checkbox\CheckboxX;
/* #var $this yii\web\View */
/* #var $model app\models\Request */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="request-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'req_date')->hiddenInput()->label(false) ?>
<div class="row">
<div class="col-sm-6">
<?php
$data = ['1001' => '1001/Sample Job 1', '1002' => '1002/Sample Job 2', '1003' => '1003/Sample Job 3'];
echo $form->field($model, 'req_job')->widget(Select2::classname(), [
'data' => $data,
'class'=>'form-control',
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'req_type')->radioList(array('Urgent'=>'Urgent','Normal'=>'Normal')); ?>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'req_on')->input('date') ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'material_type')->radioList(array('Civil'=>'Civil','Mechanical'=>'Mechanical', 'Manpower'=>'Manpower')); ?>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'req_by')->hiddenInput()->label(false) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'req_updated_on')->hiddenInput()->label(false) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress,
'formId' => 'dynamic-form',
'formFields' => [
'item_name',
'item_qty',
'item_unit',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Requested Items</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]id");
}
?>
<?= $form->field($modelAddress, "[{$i}]item_name")->textInput(['maxlength' => true]) ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelAddress, "[{$i}]item_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelAddress, "[{$i}]item_unit")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<?= $form->field($requestModel, 'req_status')->dropDownList(['Requested' => 'Requested', 'Approved' => 'Approved', 'Rejected' => 'Rejected', 'Hold' => 'Hold',], ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
You need to change the
'model'=>$modelsAddress
to
'model'=>$modelsAddress[0]
As stated in the basic example, its an array of models and the way you passing, it will be detected as array rather than a model.

Form doesn't get submitted in yii2

I'm using yii2 advanced app and im stuck at a point where my form doesn't get submitted. It refreshes and stays on the same page. There are no errors shown too.
Here is the model code Countries.php
<?php
namespace backend\models\base;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use mootensai\behaviors\UUIDBehavior;
/**
* This is the base model class for table "countries".
*
* #property integer $id
* #property string $sortname
* #property string $name
* #property integer $phonecode
* #property integer $created_at
* #property integer $updated_at
* #property integer $created_by
* #property integer $updated_by
* #property integer $deleted_at
* #property integer $deleted_by
*
* #property \backend\models\States[] $states
*/
class Countries extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
private $_rt_softdelete;
private $_rt_softrestore;
public function __construct(){
parent::__construct();
$this->_rt_softdelete = [
'deleted_by' => \Yii::$app->user->id,
'deleted_at' => date('Y-m-d H:i:s'),
];
$this->_rt_softrestore = [
'deleted_by' => 0,
'deleted_at' => date('Y-m-d H:i:s'),
];
}
/**
* This function helps \mootensai\relation\RelationTrait runs faster
* #return array relation names of this model
*/
public function relationNames()
{
return [
'states'
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['sortname', 'name', 'phonecode'], 'required'],
[['phonecode', 'created_at', 'updated_at', 'created_by', 'updated_by', 'deleted_at', 'deleted_by'], 'integer'],
[['sortname'], 'string', 'max' => 3],
[['name'], 'string', 'max' => 150],
[['lock'], 'default', 'value' => '0'],
[['lock'], 'mootensai\components\OptimisticLockValidator']
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'countries';
}
/**
*
* #return string
* overwrite function optimisticLock
* return string name of field are used to stored optimistic lock
*
*/
public function optimisticLock() {
return 'lock';
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'sortname' => Yii::t('app', 'Sortname'),
'name' => Yii::t('app', 'Name'),
'phonecode' => Yii::t('app', 'Phonecode'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getStates()
{
return $this->hasMany(\backend\models\States::className(), ['country_id' => 'id']);
}
/**
* #inheritdoc
* #return array mixed
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new \yii\db\Expression('NOW()'),
],
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
/**
* #inheritdoc
* #return \backend\models\query\CountriesQuery the active query used by this AR class.
*/
public static function find()
{
$query = new \backend\models\query\CountriesQuery(get_called_class());
return $query->where(['countries.deleted_by' => 0]);
}
}
And the controller CountriesController.php
<?php
namespace backend\controllers;
use Yii;
use backend\models\Countries;
use backend\models\search\CountriesSearch;
use backend\controllers\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CountriesController implements the CRUD actions for Countries model.
*/
class CountriesController extends BackendController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
'roles' => ['admin']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Countries models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CountriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Countries model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerStates' => $providerStates,
]);
}
/**
* Creates a new Countries model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Countries();
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Countries model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Countries();
}else{
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Countries model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Countries information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerStates' => $providerStates,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Countries model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param mixed $id
* #return mixed
*/
public function actionSaveAsNew($id) {
$model = new Countries();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Countries model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Countries the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Countries::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for States
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddStates()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('States');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formStates', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
and the view file create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Apps */
$this->title = Yii::t('app', 'Create Apps');
?>
<div class="uk-container uk-container-small uk-position-relative">
<div><!----> <div>
<h1 id="navbar" class="uk-h2 tm-heading-fragment">
Apps
</h1>
<!-- Start Breadcrumb -->
<ul class="uk-breadcrumb">
<li><?= Html::a('Admin', ['/'])?></li>
<li><?= Html::a('Apps', ['/apps'])?></li>
<li>Create</li>
</ul>
<!-- End Breadcrumb -->
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
and view _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use alexeevdv\widget\SluggableInputWidget;
use dosamigos\ckeditor\CKEditor;
/* #var $this yii\web\View */
/* #var $model backend\models\Apps */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="uk-margin-auto">
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true, 'placeholder' => 'Title']) ?>
<?= $form->field($model, 'slug')->widget(SluggableInputWidget::className(), [
'dependsOn' => 'title',
]); ?>
<?= $form->field($model, 'content')->widget(CKEditor::className(), [
'options' => ['rows' => 6],
'preset' => 'basic',
'clientOptions' => [
'filebrowserImageBrowseUrl' => yii\helpers\Url::to(['imagemanager/manager', 'view-mode'=>'iframe', 'select-type'=>'ckeditor']),
]
]);?>
<?= $form->field($model, 'video')->textInput(['maxlength' => true, 'placeholder' => 'Video']) ?>
<?= $form->field($model, 'category')->widget(\kartik\widgets\Select2::classname(), [
'data' => \yii\helpers\ArrayHelper::map(\backend\models\Categories::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
'options' => ['placeholder' => Yii::t('app', 'Choose a category')],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'status')->textInput(['placeholder' => 'Status']) ?>
<div class="form-group">
<?php if(Yii::$app->controller->action->id != 'save-as-new'): ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn uk-button uk-button-primary' : 'btn uk-button uk-button-primary']) ?>
<?php endif; ?>
<?php if(Yii::$app->controller->action->id != 'create'): ?>
<?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn uk-button uk-button-default', 'value' => '1', 'name' => '_asnew']) ?>
<?php endif; ?>
<?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer , ['class'=> 'btn uk-button uk-button-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I've browsed few articles, but of no help. My form has a <?php ActiveForm::end(); ?> at the end of the form. I also tried to remove the select2 widget but i still get the same issue. Could someone help me out why this is happening?
Html output rendered of create.php
<div class="uk-container uk-container-small uk-position-relative">
<div><!----> <div>
<h1 id="navbar" class="uk-h2 tm-heading-fragment">
Countries
</h1>
<!-- Start Breadcrumb -->
<ul class="uk-breadcrumb">
<li>Admin</li>
<li>Countries</li>
<li>Create</li>
</ul>
<!-- End Breadcrumb -->
<div class="uk-margin-auto">
<form id="w0" action="/final/backend/en-us/countries/create" method="post">
<input type="hidden" name="_csrf" value="zIvM0awWY3XpcrF1kY6gFY00ghnL1cgwTYhaEqF7RO2hch4x5AznMwtfWxWp4D-YW9yJy5aiNupb0JnMSbi5qQ==">
<div class="error-summary" style="display:none"><p>Please fix the following errors:</p><ul></ul></div>
<div class="form-group field-countries-id">
<input type="text" id="countries-id" class="form-control" name="Countries[id]" style="display:none">
</div>
<div class="form-group field-countries-sortname required">
<label class="control-label" for="countries-sortname">Sortname</label>
<input type="text" id="countries-sortname" class="form-control" name="Countries[sortname]" maxlength="3" placeholder="Sortname" aria-required="true">
<div class="help-block"></div>
</div>
<div class="form-group field-countries-name required">
<label class="control-label" for="countries-name">Name</label>
<input type="text" id="countries-name" class="form-control" name="Countries[name]" maxlength="150" placeholder="Name" aria-required="true">
<div class="help-block"></div>
</div>
<div class="form-group field-countries-phonecode required">
<label class="control-label" for="countries-phonecode">Phonecode</label>
<input type="text" id="countries-phonecode" class="form-control" name="Countries[phonecode]" placeholder="Phonecode" aria-required="true">
<div class="help-block"></div>
</div>
<div id="w3-container" class=" tabs-above tab-align-left tabs-krajee"><ul id="w3" class="nav nav-tabs nav nav-tabs hidden-print" data-krajee-tabsx="tabsX_0b4b2adf" role="tablist"><li class="active"><i class="glyphicon glyphicon-book"></i> States</li></ul>
<div class="tab-content printable"><div class="h3 visible-print-block"><i class="glyphicon glyphicon-book"></i> States</div>
<div id="w3-tab0" class="tab-pane fade in active"><div class="form-group" id="add-states">
<div id="w1" class="grid-view hide-resize" data-krajee-grid="kvGridInit_7fee31f2"><div class="panel panel-default">
<div class="rc-handle-container" style="width: 628px;"><div class="rc-handle" style="left: 50px; height: 37px;"></div><div class="rc-handle" style="left: 496px; height: 37px;"></div></div><div id="w1-container" class="table-responsive kv-grid-container"><table class="kv-grid-table table table-hover kv-table-wrap"><thead>
<tr><th class="kv-align-center kv-align-middle" style="width: 7.96%;" data-col-seq="0">#</th><th class="kv-align-top kv-grid-hide" data-col-seq="1">Id</th><th class="kv-align-top" data-col-seq="2" style="width: 71.02%;">Name</th><th class="kv-align-middle" data-col-seq="3" style="width: 21.02%;"></th></tr>
</thead>
<tbody>
<tr><td colspan="4"><div class="empty">No results found.</div></td></tr>
</tbody></table></div>
<div class="kv-panel-after"><button type="button" class="btn btn-success kv-batch-create" onclick="addRowStates()"><i class="fa fa-plus"></i>Add States</button></div>
</div></div> </div>
</div>
</div></div> <div class="form-group">
<button type="submit" class="uk-button uk-button-primary">Create</button> <a class="uk-button uk-button-danger">Cancel</a> </div>
</form>
</div>
</div>
</div>
</div>
Changing loadAll() and saveAll() to load() and save() has solved the issue
<?php
namespace backend\controllers;
use Yii;
use backend\models\Countries;
use backend\models\search\CountriesSearch;
use backend\controllers\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CountriesController implements the CRUD actions for Countries model.
*/
class CountriesController extends BackendController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
'roles' => ['admin']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Countries models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CountriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Countries model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerStates' => $providerStates,
]);
}
/**
* Creates a new Countries model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Countries();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Countries model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Countries();
}else{
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Countries model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Countries information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerStates' => $providerStates,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Countries model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param mixed $id
* #return mixed
*/
public function actionSaveAsNew($id) {
$model = new Countries();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Countries model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Countries the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Countries::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for States
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddStates()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('States');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formStates', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
Thank you #aendeerei for the quick help!

Yii2: Config global template for all forms fields

I have this:
<?php
use app\models\Location;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Role;
?>
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'roleId', Yii::$app->formtemplate->fieldTemplate())->dropDownList(ArrayHelper::map(Role::find()->all(), 'id', 'name'), array('prompt' => '-- Select a role --', 'class' => 'form-control select2')); ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'published')->checkbox(['label' => ''], true)->label($model->getAttributeLabel('published'), ['class' => 'form-label semibold']); ?>
</div>
</div>
I think this is unefficient since I have to add the template to each field (I know I can add it per form, but checkbox has a different one, any ideas how to set it globally, for all forms? not only for one form?
So far what I have done is to create a component called FormTemplate to avoid writing the template directly in the view, which is good, but I want to set it globally.
<?php
namespace app\components;
use Yii;
use yii\base\Component;
class FormTemplate extends Component {
public function fieldTemplate($option = []) {
$template = [
'template' => '',
'labelOptions' => [ 'class' => 'form-label semibold']
];
$icon = '';
$position = 'right';
if(!empty($option['position'])) {
$position = $option['position'];
}
if(!empty($option['icon'])) {
$icon = $this->_setFieldIcon($option['icon']);
}
$template['template'] = '<div class="form-group">{label}<div class="form-control-wrapper form-control-icon-'.$position.'">{input}'.$icon.'<div class="error">{error}{hint}</div></div></div>';
return $template;
}
private function _setFieldIcon($option) {
switch($option) {
case 'text':
$icon = '<i class="fa fa-text-width"></i>';
break;
case 'password':
$icon = '<i class="fa fa-key" aria-hidden="true"></i>';
break;
default:
$icon = '';
break;
}
return $icon;
}
}
Any ideas?
UPDATE
I have noticed ActiveField is a component, so maybe I could do it on global config? someone has done something like that?
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'activeField' => [
'template' => '...'
]
If you want to customize ActiveField objects for all your application, you should use Yii2 dependency injection container, e.g. :
\Yii::$container->set('yii\bootstrap\ActiveField', [
'template' => '...',
]);
Or for ActiveForm :
\Yii::$container->set('yii\bootstrap\ActiveForm', [
'inputTemplate' => '...',
]);
Read more about practical usage of DI container.
You can create
your ActiveField class as :-
<?php
namespace frontend\widgets;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveField;
class MyActiveField extends ActiveField
{
public $labelOptions = [ 'class' => 'form-label semibold'];
public function init()
{
$position = ArrayHelper::remove($this->options, 'right');
$icon = $this->_setFieldIcon($this->options);
$this->template ='
<div class="form-group">{label}
<div class="form-control-wrapper form-control-icon-'.
$position.'">
{input}'.$icon.
'<div class="error">{error}{hint}
</div>
</div>
</div>';
parent::init();
}
/**
* #param $option array
* #return string HTML
*/
private function _setFieldIcon($option) {
$icon ='';
switch(ArrayHelper::getValue($option ,'icon' ,'')) {
case 'text':
$icon = '<i class="fa fa-text-width"></i>';
break;
case 'password':
$icon = '<i class="fa fa-key" aria-hidden="true"></i>';
break;
}
return $icon;
}
}
And In ActiveForm use your class as : -
<?php $form = ActiveForm::begin([
//change this with your active field class
'fieldClass' => 'frontend\widgets\MyActiveField'
]); ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'roleId',[
'options' => ['icon' => '' ,'position' => '']]
)->dropDownList(ArrayHelper::map(Role::find()->all(), 'id', 'name'), [
'prompt' => '-- Select a role --', 'class' => 'form-control select2'
]); ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'published' ,['icon' => '' ,'position' => ''])->checkbox(['label' => ''], true)
->label($model->getAttributeLabel('published'), ['class' => 'form-label semibold']); ?>
</div>
</div>
<?php ActiveForm::end(); ?>

Provide validation for minimum number inserted in Yii2

i am having trouble with this validation,
how can i validate minimum number to be inserted in
$form->field($modeldetails, "[{$i}]qty")->textInput()
based on sum of table quantity field with parameter to filter from $form->field($model, 'tgl') because i cannot simply add range validation in models rule.
I need a function to get paramater from two models ($model,$modeldetails), and process summary of quantity, if user inserted more than minimum sum then show an error in quantity field.
View activeform field for header ( using dynamic form )
<?php $form = ActiveForm::begin(['id' => 'dynamic-form')]); ?>
<?= $form->field($model, 'tgl')->widget(DatePicker::classname(), [
'options' => ['placeholder' => 'Enter Transaction Date ...'],
'type' => DatePicker::TYPE_COMPONENT_APPEND,
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd',
'todayHighlight' => true
],
]); ?>
View activeform field for detail
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 15, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modeldetail[0],
'formId' => 'dynamic-form',
'formFields' => [
'id_brg',
'qty',
],
]); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h4>
Detail
<button type="button" class="add-item btn btn-success btn-sm pull-right"><i class="glyphicon glyphicon-plus"></i> Add</button>
</h4>
</div>
<div class="panel-body">
<div class="container-items"><!-- widgetBody -->
<?php foreach ($modeldetail as $i => $modeldetails): ?>
<div class="item panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left"></h3>
<div class="pull-right">
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modeldetails->isNewRecord) {
echo Html::activeHiddenInput($modeldetails, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modeldetails, "[{$i}]id_brg")->label('Nama')->widget(Select2::classname(), [
'data' => $brg,
'language' => 'en',
'options' => ['placeholder' => 'Select an item ...'],
'pluginOptions' => [
'allowClear' => true
],
]);?>
</div>
<div class="col-sm-6">
<?= $form->field($modeldetails, "[{$i}]qty")->textInput() ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div><!-- .panel -->
<?php DynamicFormWidget::end(); ?>
my models for details
class Detail extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'detail';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id_brg', 'qty'], 'required'],
[['kode', 'id_brg', 'qty'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'kode' => 'Kode',
'id_brg' => 'ID Barang',
'qty' => 'Qty',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getLinkheader()
{
return $this->hasOne(Transaksi::className(), ['kode' => 'kode']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getItems()
{
return $this->hasOne(Barang::className(), ['id' => 'id_brg']);
}
}
Core Validators integer
[['qty'], 'integer', 'min' => 123],
Use custom validator. Simple example is inline validator:
public function rules()
{
return [
[['id_brg', 'qty'], 'required'],
[['kode', 'id_brg', 'qty'], 'integer'],
['qty', function ($attribute, $params) {
/* calculate min value */
$min = 123;
if ($this->$attribute > $min) {
$this->addError($attribute, "Qty must be less than {$min}.");
}
}],
];
}

yii 2.0 framework trying to show search results

I have a submit form with one field called case_no, when I enter in the case_no it should then populate the table with that specific information that matched the case_no.
Controller:
public function actionSearch()
{
$model = new LegalCase();
$category = new Category();
/*$categories = Category::findAll();*/
if ($model->load(Yii::$app->request->post())) {
Yii::$app->session->setFlash('searchFormSubmitted');
$case = $model->findByCaseNo($case_no);
return $this->render('search', [
'model' => $model,
'dataProvider' => $model->findAll(),
'results' => $case
]);
return $this->refresh();
} else {
return $this->render('search', [
'model' => $model,
]);
}
}
Model:
class LegalCase extends Model
{
public $id;
public $case_no;
public $name;
public $judgement_date;
public $year;
public $neutral_citation;
private static $cases = [
'100' => [
'id' => '1',
'case_no' => '3',
'name' => 'first case'
],
'101' => [
'id' => '1',
'case_no' => '125',
'name' => 'second case'
],
];
/**
* #inheritdoc
*/
public static function findAll()
{
//$query = new Query();
$provider = new ArrayDataProvider([
'allModels' => self::$cases,
'sort' => [
'attributes' => ['id', 'case_no', 'name'],
],
'pagination' => [
'pageSize' => 10,
],
]);
return $provider->getModels();
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$cases[$id]) ? new static(self::$cases[$id]) : null;
}
/**
* Finds case by name
*
* #param string $name
* #return static|null
*/
/**
* Finds case by number
*
* #param string $case_no
* #return static|null
*/
public static function findByCaseNo($case_no)
{
foreach (self::$cases as $case) {
if (strcasecmp($case['case_no'], $case_no) === 0) {
return new static($case);
}
}
return null;
}
View:
<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\ListView;
use app\models\LegalCase;
use backend\models\Standard;
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model app\models\LegalCase */
$this->title = 'Search';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-login">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to login:</p>
<?php $form = ActiveForm::begin([
'id' => 'search-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-3\">{input} </div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?= $form->field($model, 'case_no') ?>
<?= $form->field($model, 'name') ?>
<?php /*= Html::activeDropDownList($model, 's_id',
ArrayHelper::map(Standard::find()->all(), 's_id', 'name'))*/ ?>
<?php
?>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary', 'name' => 'search-button']) ?>
</div>
</div>
<?php if (Yii::$app->session->hasFlash('searchFormSubmitted')) { ?>
<table class="table table-striped">
<tr>
<th>ID</th>
<th>case_no</th>
<th>name</th>
</tr>
</table>
<?php //$posts = $results->getModels();
foreach($results as $case){
echo '<tr>';
//print_r($case);
echo $case;
//echo $case->id;
/*echo '<td>' . $post['id'] . '</td>';
echo '<td>' . $post['case_no'] . '</td>';
echo '<td>' . $post['name'] . '</td>';*/
echo '</tr>';
} ?>
Any idea why this is not working?
Use $_POST['LegalCase']['case_no'] instead of $case_no.
EDIT: note: I'm using an older version of Yii so things might have changed.
You need to do this:
$case = $model->findByCaseNo($model->case_no);
But your attribute $case_no will be empty after the form submit. This happened because attribute is not safe. Function load() set only safe model attributes. If you want to load model attributes after submit you need to add validation to the LegalCase model. For example:
public function rules()
{
return [
['case_no', 'trim'],
];
}

Categories