I have a problem that I have not been able to solve, I need the associated products of my code to be shown in the index, that is to say, they are shown for each client that products took, as I did in the View, in the View it is shown as it should be: order1 with all the data and data of the client and the products that I carry that are the associated products. In the index, it shows all the orders and all the information of the client and the order but it does not show the products is what I want to do.
In the view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\Pjax;
use kartik\grid\GridView;
/* @var $this yii\web\View */
/* @var $model app\models\Pedidos */
//$this->title = $model->Id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Pedidos'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="pedidos-view">
<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i>LISTAR PEDIDO</h3>
<p><p><p><?//= Html::a('<i class="glyphicon glyphicon-plus"></i> Crear', ['create'], ['class' => 'btn btn-success'])?></p></p></p>
<h1><?= Html::encode($this->title) ?></h1>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'estado.Nombre',
'Id',
'RemitoNro',
'Fecha',
'encabezados.Cliente',
'cliente.DNI',
'cliente.fullTodo',
'cliente.Direccion',
'cliente.fullTels',
'apodo',
'encabezados.DetallesVenta',
'canalventa.Nombre',
'medipago.Nombre',
'Idcompra',
'IdPago',
'Valorenvio',
'TotalPedido',
'TotalProducto2',
'encabezados.Otros',
'Observaciones',
'encabezados.DetallesEntrega',
'agencia.Nombre',
'FechaEntrega',
'Lugarentrega',
'encabezados.Vendedores',
'vendedores.fullTodov',
],
]) ?>
<hr>
<h1>Productos asociados al pedido</h1>
<?php
Pjax::begin();
echo GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => '\kartik\grid\SerialColumn'],
[
'attribute' => 'producto_id',
'format' => 'raw',
'value' => 'producto.ProductosNombre',
'enableSorting' => false,
],
[
'attribute' => 'cantidad',
'format' => 'raw',
'contentOptions' => ['style'=>'text-align: right;'],
'enableSorting' => false,
],
[
'attribute' => 'valor_unitario',
'format' => 'raw',
'contentOptions' => ['style'=>'text-align: right;'],
'enableSorting' => false,
],
[
'attribute' => 'valor_total',
'format' => 'raw',
'contentOptions' => ['style'=>'text-align: right;'],
'enableSorting' => false,
],
[
'attribute' => 'fecha_registro',
'format' => 'raw',
'contentOptions' => ['style'=>'text-align: center;'],
'enableSorting' => false,
'value' => function($model)
{
return date('Y-m-d h:i a', strtotime($model->fecha_registro));
}
]
],
]);
Pjax::end();
?>
</div>
In the index:
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\ActiveForm;
//use yii\grid\GridView;
use yii\widgets\Pjax;
//use kartik\select2\Select2;
use kartik\datecontrol\DateControl;
use kartik\date\DatePicker;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use app\models\Estadosp;
use app\models\Agencias;
use app\models\Mediopago;
use app\models\Canales;
use app\models\Pagosp;
use app\models\Vendedores;
use kartik\editable\Editable;
use yii\helpers\Json;
use app\models\PedidoProducto;
/* @var $this yii\web\View */
/* @var $searchModel app\models\PedidosSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
//$this->title = Yii::t('app', 'Pedidos');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="pedidos-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'options' => [ 'style' => 'table-layout:fixed;' ],
'rowOptions' => function ($model) {
/*if ($model->EstadoId == 1) {
return ['style' => 'background-color: #99FF33'];
}*/
if ($model->EstadoId == 1) {
return ['class' => 'info'];
}
if ($model->EstadoId == 2) {
return ['style' => 'background-color: #CCFF66' ];
}
if ($model->EstadoId == 3) {
return ['style' => 'background-color: #FFFF66' ];
}
if ($model->EstadoId == 4) {
return ['class' => 'danger'];
}
},
'filterModel' => $searchModel,
'floatHeader'=>true,
'perfectScrollbar' => true,
'resizableColumns'=>false,
'hover'=>true,
'showPageSummary' => true,
'summary'=>'Mostrar todo / Exportar',
'panel' => [
'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-globe"></i>TRANSACCIONES PEDIDO</h3>',
'type'=>'success',
'before'=>Html::a('<i class="glyphicon glyphicon-plus"></i> Crear', ['create'], ['class' => 'btn btn-success']),
'after'=>Html::a('<i class="glyphicon glyphicon-repeat"></i> Resetear Grid', ['index'], ['class' => 'btn btn-info']),
'footer'=>true
],
'columns' => [
[
'class' => '\kartik\grid\SerialColumn',
],
['class' => '\kartik\grid\ActionColumn'],
[
'class'=>'kartik\grid\EditableColumn',
'attribute'=>'EstadoId',
'editableOptions'=>[
'header'=>'Estado',
'asPopover' => true,
'format' => \kartik\editable\Editable::FORMAT_BUTTON,
'inputType'=>\kartik\editable\Editable::INPUT_DROPDOWN_LIST,
'data' => ArrayHelper::map(Estadosp::find()->all(), 'Id','Nombre'),
'options' => ['class'=>'form-control', 'prompt'=>'Seleccione estado'],
],
'value' => function($searchModel){
return $searchModel->EstadoId;
},
'value' => 'estado.Nombre',
'filter'=>ArrayHelper::map(Estadosp::find()->joinWith('pedidos')->orderBy('Id')->all(), 'Nombre', 'Nombre'),
'filterType' => GridView::FILTER_SELECT2,
'filter' => ArrayHelper::map(Estadosp::find()->orderBy('Id')->asArray()->all(), 'Nombre', 'Nombre'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Filtrar...'],
'format' => 'raw'
],
[
'class'=>'kartik\grid\EditableColumn',
'attribute'=>'Idcompra',
'editableOptions'=>[
'header'=>'Factura',
'asPopover' => true,
'format' => \kartik\editable\Editable::FORMAT_BUTTON,
'inputType' => \kartik\editable\Editable::INPUT_TEXT,
],
'width' => '500px',
],
[
'attribute' => 'PagoId',
'value' => 'pagosped.Nombre',
'filter'=>ArrayHelper::map(Pagosp::find()->joinWith('pedidos')->orderBy('Id')->all(), 'Nombre', 'Nombre'),
],
'IdPago',
[
'attribute' => 'AgenciaId',
'value' => 'agenciacombo.Nombre',
'filterType' => GridView::FILTER_SELECT2,
'filter' => ArrayHelper::map(Agencias::find()->orderBy('Id')->asArray()->all(), 'Nombre', 'Nombre'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Filtrar...'],
'format' => 'raw'
],
[
'attribute' => 'FechaEntrega',
'value' => 'FechaEntrega',
'filterType' => GridView::FILTER_DATE,
'filterWidgetOptions' =>([
'pluginOptions'=>[
'format'=>'yyyy-m-d',
'opens'=>'bottom',
'autoclose' => true,
]
])
],
'Lugarentrega',
[
'class'=>'kartik\grid\EditableColumn',
'attribute'=>'RemitoNro',
'editableOptions'=>[
'header'=>'RemitoNro',
'asPopover' => true,
'format' => \kartik\editable\Editable::FORMAT_BUTTON,
'inputType' => \kartik\editable\Editable::INPUT_TEXT,
],
'width' => '500px',
],
[
'attribute' => 'ClienteId',
'value' => 'cliente.DNI',
],
[
'attribute' => ' ',
'value' => 'cliente.fullTodo',
],
'Fecha',
'Id',
'apodo',
[
'attribute' => 'VendedoresId',
'value' => 'vendedores.DNI',
],
[
'attribute' => '',
'value' => 'vendedores.fullTodov',
],
[
'attribute' => 'CanalventaId',
'value' => 'canalventa.Nombre',
// 'contentOptions'=>['style'=>'max-width: 800px;'],
//'contentOptions'=>['width' => '200px'],
//'filter'=>ArrayHelper::map(Agencias::find()->joinWith('pedidos')->orderBy('Id')->all(), 'Nombre', 'Nombre'),
'filterType' => GridView::FILTER_SELECT2,
'filter' => ArrayHelper::map(Canales::find()->orderBy('Id')->asArray()->all(), 'Nombre', 'Nombre'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Filtrar...'],
'format' => 'raw'
],
[
'attribute' => 'MedipagoId',
'value' => 'medipago.Nombre',
// 'contentOptions'=>['style'=>'max-width: 800px;'],
//'contentOptions'=>['width' => '200px'],
//'filter'=>ArrayHelper::map(Agencias::find()->joinWith('pedidos')->orderBy('Id')->all(), 'Nombre', 'Nombre'),
'filterType' => GridView::FILTER_SELECT2,
'filter' => ArrayHelper::map(Mediopago::find()->orderBy('Id')->asArray()->all(), 'Nombre', 'Nombre'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Filtrar...'],
'format' => 'raw'
],
'TotalProducto',
'TotalProducto2',
'Valorenvio',
'TotalPedido',
'Observaciones',
],
]); ?>
<?php Pjax::end(); ?>
</div>
On the controller:
<?php
namespace app\controllers;
use app\models\PedidoProducto;
use Yii;
use app\models\Pedidos;
use app\models\PedidosSearch;
use yii\base\Model;
use yii\base\ModelEvent;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
//use app\models\Modelo;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
/**
* PedidosController implements the CRUD actions for Pedidos model.
*/
class PedidosController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Pedidos models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new PedidosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Pedidos model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
$modelo = $this->findModel($id);
$searchModel = new PedidoProducto();
$searchModel->pedido_id = $modelo->Id;
$dataProvider = $searchModel->searchProductos(Yii::$app->request->queryParams, $modelo->Id);
return $this->render('view', [
'model' => $modelo,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Creates a new Pedidos model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Pedidos;
$productos = [new PedidoProducto];
if ($model->load(Yii::$app->request->post())) {
$productos = Pedidos::createMultiple(PedidoProducto::classname());
Model::loadMultiple($productos, Yii::$app->request->post());
// ajax validation
/*if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validateMultiple($productos);
}*/
$valido = $model->validate();
$valido = Model::validateMultiple($productos) && $valido;
if ($valido) {
$transaction = \Yii::$app->db->beginTransaction();
try {
$totalProducto = 0;
if($model->save())
{
foreach ($productos as $k=>$producto)
{
$mPro = $producto->producto;
//Calcular total producto
$valorProducto = ($producto->cantidad * $mPro->ProductosPrecioVenta);
$totalProducto = ($totalProducto + $valorProducto);
$producto->pedido_id = $model->Id;
$producto->valor_unitario = $mPro->ProductosPrecioVenta;
$producto->valor_total = $valorProducto;
$producto->fecha_registro = date('Y-m-d H:i:s');
$producto->save();
//Actualizar el stock del producto
//Productos::actualizarStockProducto($model->ProductosId);
$mPro->actualizarStockProducto();
}
}
if($model->Id <> '')
{
//Calcular total pedido;
$totalPedido = ($totalProducto + $model->Valorenvio);
//Actualizar total producto y total pedido
$model->TotalProducto = $totalProducto;
$model->TotalPedido = $totalPedido;
$model->save();
$transaction->commit();
return $this->redirect(['view', 'id' => $model->Id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('create', [
'model' => $model,
'productos' => (empty($productos)) ? [new PedidoProducto] : $productos,
]);
}
public function actionCreate_old()
{
$model = new Pedidos();
if ($model->load(Yii::$app->request->post())) {
$producto = $model->productos;
//Calcular total producto
$totalProducto = $model->Cantidad * $producto->ProductosPrecioVenta;
//Calcular total pedido;
$totalPedido = $totalProducto + $model->Valorenvio;
$model->TotalProducto = $totalProducto;
$model->TotalPedido = $totalPedido;
$model->save();
//Actualizar el stock del producto
//Productos::actualizarStockProducto($model->ProductosId);
$producto->actualizarStockProducto();
return $this->redirect(['view', 'id' => $model->Id]);
}
return $this->render('create', [
'model' => $model,
'productos' => false,
]);
}
/**
* Updates an existing Pedidos model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$productos = $model->pedidoProductos;
if ($model->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($productos, 'id', 'id');
$productos = Pedidos::createMultiple(PedidoProducto::classname(), $productos);
Model::loadMultiple($productos, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($productos, 'id', 'id')));
// ajax validation
/*if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validateMultiple($productos);
}*/
$valido = $model->validate();
$valido = Model::validateMultiple($productos) && $valido;
if ($valido) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if($model->save())
{
if (! empty($deletedIDs)) {
PedidoProducto::deleteAll(['id' => $deletedIDs]);
}
$totalProducto = 0;
foreach ($productos as $k=>$producto)
{
$mPro = $producto->producto;
//Calcular total producto
$valorProducto = ($producto->cantidad * $mPro->ProductosPrecioVenta);
$totalProducto = ($totalProducto + $valorProducto);
$producto->pedido_id = $model->Id;
$producto->valor_unitario = $mPro->ProductosPrecioVenta;
$producto->valor_total = $valorProducto;
if($producto->id == '')
{
$producto->fecha_registro = date('Y-m-d H:i:s');
}
$producto->save();
//Actualizar el stock del producto
//Productos::actualizarStockProducto($model->ProductosId);
$mPro->actualizarStockProducto();
}
//Calcular total pedido;
$totalPedido = ($totalProducto + $model->Valorenvio);
//Actualizar total producto y total pedido
$model->TotalProducto = $totalProducto;
$model->TotalPedido = $totalPedido;
$model->save();
}
if($model->Id <> '')
{
$transaction->commit();
return $this->redirect(['view', 'id' => $model->Id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update', [
'model' => $model,
'productos' => (empty($productos)) ? [new PedidoProducto] : $productos,
]);
}
public function actionUpdate_old($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$producto = $model->productos;
//Calcular total producto
$totalProducto = $model->Cantidad * $producto->ProductosPrecioVenta;
//Calcular total pedido;
$totalPedido = $totalProducto + $model->Valorenvio;
$model->TotalProducto = $totalProducto;
$model->TotalPedido = $totalPedido;
$model->save();
//Actualizar el stock del producto
//Productos::actualizarStockProducto($model->ProductosId);
$producto->actualizarStockProducto();
return $this->redirect(['view', 'id' => $model->Id]);
}
return $this->render('update', [
'model' => $model,
'productos' => false,
]);
}
/**
* Deletes an existing Pedidos model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$productos = $model->pedidoProductos;
if($productos)
{
foreach($productos as $pr)
{
$producto = $pr->producto;
$pr->delete();
$producto->actualizarStockProducto();
}
}
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the Pedidos model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Pedidos the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Pedidos::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
Image of what I need to do (Only the column: Associated products, what you see in the image of associated products is done with the editor is not showing it, this is how I want it to look and show in addition to the product name as is the quantity and value of each product What I need is just that in the index):
Notice that in the view, you see all the data included in the products, but it does not work because it is at the level of 1 single order, and I want that same information to be seen in the index at the level of all the records, to use the filtering and export options offered by the index.
No more characters were included, then attach file with model content: see model
The row options option does not affect the associated product grid.