How to send model id to ActiveFrom field - yii2

I have a view team/view where I have details for the team (from the model Team).
views/team/view.php:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\grid\GridView;
use yii\data\ActiveDataProvider;
use app\models\Pt;
/* #var $this yii\web\View */
/* #var $model app\models\Team */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Teams', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="team-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'tournament.name',
'teamindex',
'region.name',
'rank',
],
]) ?>
<?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
</div>
Last link is a link button to add players to the team: <?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
In views/pt/create I have an ActiveForm with fields: team (dropdown list), player (dropdown list). So, if I want to add a player to the team I should choose the team's name from a looong dropdown list and then choose a player (and some player options..).
Here is views/pt/create.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
/* #var $this yii\web\View */
/* #var $model app\models\Pt */
$this->title = 'Add players to the team';
$this->params['breadcrumbs'][] = ['label' => 'Players in teams', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="pt-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
Here is views/pt/_form.php:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use app\models\Player;
use yii\helpers\ArrayHelper;
/* #var $this yii\web\View */
/* #var $model app\models\Pt */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="pt-form">
<?php $form = ActiveForm::begin(['id'=>'owner-form']); ?>
<?= $form->field($model, 'team_id')->dropDownList($model->teamList) ?>
<?= $form->field($model, 'player_id')
->dropDownList(ArrayHelper::map(Player::find()->joinWith('category')
->orderBy(['lastname'=>SORT_ASC])->all(), 'id', 'lastname'));
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Add' : 'Update', ['class' => $model
->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I want like this: when I am on http://localhost/myproject/web/team/100 I click on that button <?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
and go to pt/create where in the field team already defined team_id =100 and so I need to input only player.
How can I do that? I know this is simple but I'm still learning.
PS: Models Team and Pt have relations,
models/Team.php
public function getPt()
{
return $this->hasMany(Pt::className(), ['team_id' => 'id']);
}

You should create a proper cation for create the player with the id_team already assigned (or you can modify the original create)
/**
* Creates a new Palyer model assigning the id_team.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreateForTeam(id_team)
{
$model = new Player();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->id_team = $id_team
return $this->render('create', [
'model' => $model,
]);
}
}
Then send the proper id_team
Html::a('add players to the team', ['pt/create-for-teaam', 'id_team'=> $model->team_id],
['class'=> 'btn btn-success']) ?>

Related

Yii2 execute controller and show view from package in vendor

In my case I am trying to execute slide(controller)/index(action) and render the corresponding view ( index ). They are both in my vendor folder like this way:
vendor/
tomaivanovtomov/
yii2-revolution/
controllers/
models/
views/
slide/
index.php
How should I construct my url to reach them ? Before this it was simply www.example.com\backend\web\slide\index. Now it gave me an expected error but I realized that I don't know how to reach them. Is there any way or I should override the controller at least in my backend\controllers\ directory and the call it ? Thank you in advance!
EDIT Now I did it this way:
1. Override the `SlideController.php` to my `backend\controllers\` directroy
2. Extend the `vendor/tomaivanovtomov/revolution/controllers/SlideController.php`
3. In action index set the layout to `$this->layout = '#vendor/tomaivanovtomov/yii2-revolution/views/slide/index';`
4. And the return to `return $this->render('#vendor/tomaivanovtomov/yii2-revolution/views/slide/index', [
'dataProvider' => $dataProvider,
'hidden' => $hidden
]);`
This is my slide/index action:
public function actionIndex()
{
$this->layout = '#vendor/tomaivanovtomov/yii2-revolution/views/slide/index';
$searchModel = new SlideSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$hidden = new Slide();
return $this->render('#vendor/tomaivanovtomov/yii2-revolution/views/slide/index', [
'dataProvider' => $dataProvider,
'hidden' => $hidden
]);
}
This way it properly renders the view but error Undefined variable: hidden occures. Any sugestions why is that ? Thank you!
EDIT
Index file:
<?php
use yii\widgets\ListView;
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use backend\components\BackendPrefix;
\kartik\file\FileInputAsset::register($this);
/* #var $this yii\web\View */
/* #var $searchModel backend\models\SlideSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Slides');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<button type="button" class="btn btn-primary" onclick="addSlideModel('<?= BackendPrefix::PREFIX ?>')"><?= Yii::t('app', 'Add slide') ?></button>
</div>
</div>
<?php
$form = ActiveForm::begin([
'options' => [
'multipart/form-data'
],
'action' => [
'slide/create'
],
'id' => 'slides'
]);
//Hidden model to enable UploadFile class
echo $form->field($hidden, 'image[]')->fileInput(['class' => 'display-n'])->label(false);
echo ListView::widget([
'dataProvider' => $dataProvider,
'layout' => "{items}",
'itemView' => function( $model, $key, $index, $widget ){
return $this->render("_slideImage", [
'model' => $model,
'index' => $index
]);
},
]);
?>
<div class="col-sm-12">
<div class="form-group mt20">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
</div>
<?php
ActiveForm::end();
?>
</div>

Yii2 Basic call action from different controller

Is it possible to call action from a controller in different view ?
example
I have 2 controllers : Post and Blog , so I want to call actionCreate from post but inside blog view not in post view. I have 2 views and 2 controllers :
view :
1. views/blog/view
2. views/post/view
controller
1. controllers/blogController.php
2. controllers/postController.php
controllers/PostController.php :
public function actionCreate()
{
$model_Post = new Post();
if ($model_Post->load(Yii::$app->request->post()) && $model_Post->save()) {
return $this->redirect(['view', 'id' => $model_Post->Post_id]);
} else {
return $this->render('/blog/view', [
'model_Post' => $model_Post,
]);
}
}
views/blog/view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Likectt */
$this->title = $model->Blog_id;
?>
<div class="blog-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Blog_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Blog_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'Blog_id',
'Blog_title',
'Blog_text',
'User_id',
'Category_id',
],
]) ?>
<?= Yii::$app->runAction('PostController/actionCreate', ['model_Post'=>$model_Post]);?>
</div>
Yes you can do that :
In you blog view :
Yii::$app->runAction('postController/actionCreate', ['param1'=>'value1', 'param2'=>'value2']);

Multiply of two columns in yii2

I have two tables -
1. rmtemplate
id, productname, rmname, qty
2. rmname
rmid,rmname,min,unitcost
The query I want to run is -
SELECT id,productname,rmtemplate.rmname,qty,rmtemplate.qty * rmname.unitcost as cost
FROM `rmtemplate`
left join rmname on rmtemplate.rmname = rmname.rmname
In Yii2 I've joined two tables with no problem. The unitcost is showing without any trouble. But when I try to multiply rmtemplate.rmname to rmname.unitcost it returns error - 'Getting unknown property: frontend\models\Rmtemplate::cost'
RmtemplateSearch.php -
public $cost;
public function rules()
{
return [
[['id'], 'integer'],
[['productname', 'rmname', 'qty', 'unitcost','cost'], 'safe'],
];
}
$query = Rmtemplate::find()
->joinWith(['unitcost'])
->select(['id','productname','rmtemplate.rmname','qty', '(rmtemplate.qty * rmname.unitcost) as cost']);
Rmtemplate Model
public function getUnitcost()
{
return $this->hasOne(Rmname::className(), ['rmname' => 'rmname']);
}
Rmtemplate index.php
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\rmprod\models\RmtemplateSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Rmtemplates';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="rmtemplate-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Rmtemplate', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'kartik\grid\CheckboxColumn'],
'id',
//'productname',
[
'attribute'=>'productname',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Charge Name'],
],
'rmname',
'qty',
[
'attribute' => 'unitcost',
'value' => 'unitcost.unitcost',
],
'cost',
['class' => 'kartik\grid\ActionColumn'],
],
]); ?>
</div>
Please let me know if any further input required.

How to select data from gridview to form in yii2

I have to insert data into 'production' table. The productid, productname, batchno is stored in a table 'productbatch'. I want to select these fields from gridview to the form on clicking on the gridview. How can I do that?
index.php of producbatch -
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\production\models\ProductbatchSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productbatches';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productbatch-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Productbatch', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn'],
'itemid',
'productname',
'batchno:ntext',
//'mfgdate',
//'expdate',
// 'mrp',
// 'rate',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
_form of production
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'productiondate')->textInput() ?>
<?= $form->field($model, 'itemid')->textInput() ?>
<?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'batchno')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$this->RegisterJs ( "
$('document').ready(function(){
// $('#".Html::getInputId($model, 'mrp')."').keyup(function(){
// var total = this.value;
// var percent = 10;
// var discount_value = this.value - ((total / 100) * percent);
// $('#".Html::getInputId($model, 'rate')."').val(discount_value);
// });
var keys = $('#grid').yiiGridView('getSelectedRows');
});
", View::POS_END);
?>
The simplest way is base on check columns and obtaining the reldated rows in an array
this is from yii guide http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#checkbox-column
echo GridView::widget([
'dataProvider' => $dataProvider,
'id' => 'my_gridview_id',
'columns' => [
// ...
[
'class' => 'yii\grid\CheckboxColumn',
// you may configure additional properties here
],
],
Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the following JavaScript
var keys = $('#my_gridview_id').yiiGridView('getSelectedRows');

Yii2: How to save form data in two tables from one form?

public function actionCreate()
{
$model = new CreateClient1();
$employee = new Employee();
if ($model->load(Yii::$app->request->post()) && $employee->load(Yii::$app->request->post()))
{
$model->save();
/*add same field in employee table*/
$employee->client_code = $model->client_code;
$employee->company_name = $model->company_name;
$employee->emp_first_name = $model->emp_first_name;
$employee->emp_last_name = $model->emp_last_name;
$employee->emp_email = $model->emp_email;
$employee->emp_mobile = $model->emp_mobile;
$employee->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
'employee' => $employee,
]);
}
}
My form looks like this do i need to add something in it?
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model backend\models\CreateClient1 */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="create-client1-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= Html::activeHiddenInput($model, 'client_code', ['value' => rand(1,100000000000000)]) ?>
<?= $form->field($model, 'company_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_mobile')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_first_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_last_name')->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Trying to insert same data in two tables.
Table CreateClient1 and Employee has to be same data, how do I insert in to Employee table in Yii2.
Any thing needs to add in form? my form form is not submitting
Try this:
public function actionCreate()
{
$model = new CreateClient1();
$employee = new Employee();
if ($model->load(Yii::$app->request->post()))
{
$model->save();
/*add same field in employee table*/
$employee->attributes = $model->attributes;
$employee->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
'employee' => $employee,
]);
}
}