1

Edito(22/08/2018): El problema ya se soluciono agrego el código corregido y funcionando para que pueda ser usado de guía por quien lo necesite, muchas gracias al usuario Sr1871 que fue quien dio la respuesta

Bueno se que tal vez mi consulta puede ser algo tonta pero ya tengo rato intentando y no mas no lo logro. Bueno estoy desarrollando un inventario para una biblioteca con el framework yii2 para todo su manejo, bueno entonces ya hice lo que creo yo son todas las tablas y datos a usar pero en este caso me enfocare libros y adq(asi identifican a los libros en la biblioteca ya que es un dato irrepetible).

Lo que necesito es lo siguiente en mi view de libros yo puedo ver todos los datos del libro y abajo de esos datos quiero que se muestren los datos de adq estos los obtengo de otra tabla, en fin logre traer esos datos pero me muestra todos los adq en general no solo los del libro que quiero revisar

Asi se ve mi view actual: introducir la descripción de la imagen aquí

Asi quiero que se vea: introducir la descripción de la imagen aquí EDITO(21/08/2018): Como puedo hacer que me muestre solo los ADQ de ese libro y en caso de que aun no tenga ninguno registrado me muestre la lista en blanco, si me pueden ayudar para lograr esto, se los agradecería mucho.

introducir la descripción de la imagen aquí

Funcionando:

introducir la descripción de la imagen aquí

View:

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $model app\models\Libros */
/* @var $searchModel app\models\LibrosSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">

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

    <p>
        <?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?>
    </p>
<div class="row" align="center">
     <?php
       if ($model->lib_image_web_filename!='') {
         echo '<br /><p><img width="500" src="'.Url::to('@web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
       }    
    ?>
    </div>
<div class="row" style="
text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'lib_id',
            'lib_titulo',
            'lib_autor',
            //'lib_edicion',
            'editorialNombre',
            'ubicacionNombre',
            'lib_isbn',
            'lib_clasificacion',
            'lib_seccion',
            //'lib_image_src_filename',
            //'lib_image_web_filename',
        ],
    ]) ?>
</div>
<?php
$this->title = 'Libros Disponibles';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="adq-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>


    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $model,
        'columns' => [
            //['class' => 'yii\grid\SerialColumn'],

            'adq_id',
            'adq_adq',
            'adq_libro_id',
            'adq_edicion',
            'adq_status',
            'adq_eti_roja',

            ['class' => 'yii\grid\ActionColumn'

        ],
        ],
    ]); ?>
</div>


</div>

Model(Libros.php):

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "libros".
 *
 * @property int $lib_id
 * @property string $lib_titulo
 * @property string $lib_autor
 * @property string $lib_edicion
 * @property int $lib_ubi
 * @property int $lib_editorial_id
 * @property string $lib_isbn
 * @property string $lib_clasificacion
 * @property string $lib_seccion
 * @property string $lib_image_src_filename
 * @property string $lib_image_web_filename
 *
 * @property Adq[] $adqs
 * @property Editorial $libEditorial
 * @property Ubicacion $libUbi
 * @property LibrosCarreras[] $librosCarreras
 * @property Carreras[] $licCarreras
 */
class Libros extends \yii\db\ActiveRecord
{
    const PERMISSIONS_PRIVATE = 10;
      const PERMISSIONS_PUBLIC = 20;  
      public $image;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'libros';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
            [['lib_ubi', 'lib_editorial_id'], 'integer'],
            [['lib_titulo'], 'string', 'max' => 120],
            [['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
            //[['lib_edicion'], 'string', 'max' => 3],
            [['lib_isbn'], 'string', 'max' => 32],
            [['lib_seccion'], 'string', 'max' => 2],
            [['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
            [['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
            [['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
            [['image'], 'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png'],
            [['image'], 'file', 'maxSize'=>'1000000'],
             [['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255],        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
             'lib_id' => 'lib_id',
            'lib_titulo' => 'lib_titulo',
            'lib_autor' => 'lib_autor',
            //'lib_edicion' => 'Edicion',
            'lib_editorial_id' => 'lib_editorial_id',
            'lib_isbn' => 'lib_isbn',
            'lib_clasificacion' => 'lib_clasificacion',
            'lib_ubi' => 'lib_ubi',
            'lib_seccion' => 'lib_seccion',
            'image' => 'Captura',
            'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
            'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
            'editorialNombre' => 'Editorial',
            'ubicacionNombre' => 'Ubicacion',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAdqs()
{
    return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id'])->where(['<>', 'lib_id', $this->id]);
}

    /**
     * @return \yii\db\ActiveQuery
     */


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLibrosCarreras()
    {
        return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */

    public function getEditorial0()
    {
        return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
    }
    public function getEditorialNombre()
    {
        return $this->editorial0->edi_nombre;
    }

    public function getLibUbi()
    {
        return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
    }

        public function getUbicacionNombre()
    {
        return $this->libUbi->ubil_nombre;    }
}

Controller(LibrosController):

<?php

namespace backend\controllers;

use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use app\models\Adq;
use app\models\AdqSearch;
use yii\data\ActiveDataProvider;

/**
 * LibrosController implements the CRUD actions for Libros model.
 */
class LibrosController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Libros models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new LibrosSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Libros model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
    $model = $this->findModel($id);
$dataProvider = new ActiveDataProvider([
        'query' => Adq::find()->where(['adq_libro_id' => $model->lib_id])
]);

return $this->render('view', [
    'dataProvider' => $dataProvider,
    'model' => $model
]);
}
    /**
     * Creates a new Libros model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Libros();

        if ($model->load(Yii::$app->request->post())) {
          $image = UploadedFile::getInstance($model, 'image');
           if (!is_null($image)) {
             $model->lib_image_src_filename = $image->name;
             $ext = end((explode(".", $image->name)));
              // generate a unique file name to prevent duplicate filenames
              $model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
              // the path to save file, you can set an uploadPath
              // in Yii::$app->params (as used in example below)                       
              Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
              $path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
               $image->saveAs($path);
            }
            if ($model->save()) {             
                return $this->redirect(['view', 'id' => $model->lib_id]);             
            }  else {
                var_dump ($model->getErrors()); die();
             }
              }
              return $this->render('create', [
                  'model' => $model,
              ]);     
    }

    /**
     * Updates an existing Libros 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);

        if ($model->load(Yii::$app->request->post())) {
          $image = UploadedFile::getInstance($model, 'image');
           if (!is_null($image)) {
             $model->lib_image_src_filename = $image->name;
             $ext = explode(".", $image->name);
             $ext_final = end($ext);
              // generate a unique file name to prevent duplicate filenames
              $model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
              // the path to save file, you can set an uploadPath
              // in Yii::$app->params (as used in example below)                       
              Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
              $path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
               $image->saveAs($path);
            }
            if ($model->save()) {             
                return $this->redirect(['view', 'id' => $model->lib_id]);             
            }  else {
                var_dump ($model->getErrors()); die();
             }
              }
              return $this->render('create', [
                  'model' => $model,
              ]);     
    }

    /**
     * Deletes an existing Libros 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)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Libros model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Libros the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Libros::findOne($id)) !== null) {
            return $model;
        }

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

Search(LibroSearch.php):

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Libros;

/**
 * LibrosSearch represents the model behind the search form of `app\models\Libros`.
 */
class LibrosSearch extends Libros
{
    public $editorialNombre;
    public $ubicacionNombre;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
            [['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
              [['editorialNombre'],'safe'],
              [['ubicacionNombre'],'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Libros::find();

        // add conditions that should always apply here

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

        $dataProvider->setSort([
            'attributes'=>[
                'editorialNombre'=>[
                    'asc'=>['editorial.edi_nombre'=>SORT_ASC],
                    'desc'=>['editorial.edi_nombre'=>SORT_DESC],
                    'label'=>'Editorial Nombre'
                ]
            ]
        ]);

        $dataProvider->setSort([
            'attributes'=>[
                'ubicacionNombre'=>[
                    'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
                    'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
                    'label'=>'Ubicacion Nombre'
                ]
            ]
        ]);

        $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([
            'lib_id' => $this->lib_id,
            'lib_ubi' => $this->lib_ubi,
            'lib_editorial_id' => $this->lib_editorial_id,
        ]);

        $query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
            ->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
            //->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
            ->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
            ->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
            ->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
            ->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
            ->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);

            $query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
        {
            $q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
        }]);

            $query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
        {
            $q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
        }]);

        return $dataProvider;
    }
}
7
  • muestra como inicias la variable $dataprovider
    – Sr1871
    el 14 ago. 2018 a las 23:13
  • @Sr1871 amigo perdon espero puedas ayudarme ya actualiza la pregunta y agrege todo lo que corresponde podrias ayudarme?
    – genesis96
    el 21 ago. 2018 a las 19:33
  • @genesis96 no deberías publicar dos veces la misma pregunta. Cuando tengas mas información que añadir a la pregunta, siempre puedes editarla. el 21 ago. 2018 a las 21:49
  • Podrías poner un ejemplo, de como esta actualmente tu vista y de como quieres que se vea (aunque sea con paint o algo pintar el resultado deseado) ya que no logro entender bien lo que quieres, y por favor no repitas las preguntas, simplemente edítala
    – Sr1871
    el 21 ago. 2018 a las 22:36
  • @Sr1871 Ahi agregue un ejemplo que edite en paint(los datos los agregue en paint), ya no me interesa que sea dentro de un gridview solo quiero lograr que los muestre aun si es solo texto plano o como creas tu que pueda ser mas facil
    – genesis96
    el 21 ago. 2018 a las 23:17

2 respuestas 2

0

EDITO

Si los vas a meter en un gridView necesitas generar el dataProvider en el controller, el que intentas meter es un provider de Libros y no de Adq, cambia esa parte a esta en el action de View

$model = $this->findModel($id);
$dataProvider = new ActiveDataProvider([
        'query' => Adq::find()->where(['adq_libro_id' => $model->id])
]);

return $this->render('view', [
    'dataProvider' => $dataProvider,
    'model' => $model
]);
5
  • actualiza mi view y los meti dentro de un gridview como puedes ver en la imagen, igual actualize mi codigo para ver que me puedes decir
    – genesis96
    el 22 ago. 2018 a las 17:39
  • actualicé mi respuesta
    – Sr1871
    el 22 ago. 2018 a las 18:37
  • listo puse tu codigo y me tira el sig error: Getting unknown property: app\models\Libros::id en la linea 'query' => Adq::find()->where(['adq_libro_id' => $model->id])
    – genesis96
    el 22 ago. 2018 a las 19:41
  • cambia ->id por ->lib_id
    – Sr1871
    el 22 ago. 2018 a las 23:02
  • si ya lo habia arreglado pero no tenia conexion solo era eso y ya quedo, la verdad muchisimas gracias por tu ayuda y no dejarme varado te lo agradezco infinitamente
    – genesis96
    el 23 ago. 2018 a las 2:35
0

Para mostrar solo ciertos datos en un GridView necesitas configurar el parametro columns https://www.yiiframework.com/doc/guide/2.0/en/output-data-widgets introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.