Yii2 Basic sql query in view - yii2

I'm trying to get the user profile image of the author of the content inside the view , my view is channel I created but I get this error on my view
Undefined variable: queryAvatar
on my view I did
//Yii2 View code
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Channel */
$this->title = $model->Channel_name;
?>
<div class="channel-view">
<h1><?= Html::encode($this->title) ?></h1>
<div><?php echo $queryAvatar; ?></div> // THE LINE I ADD
<?php if($model->uid == Yii::$app->user->id):?>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Channel_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Channel_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?php endif;?>
</div>
and on my controller I created this function
//function on my controller
public function actionChannel($id)
{
$cchannel = new Channel();
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
}

in your controller you define an empty model so your $cchannel->uid is empty.
You must define first your model like this
public function actionChannel($id)
{
$cchannel = $this->findModel($id);
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $cchannel ,
'queryAvatar '=> $queryAvatar ,
]);
}

The problem can be caused by space when you created array of variable before giving to view.
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
remove space from 'queryAvatar '
Like this:
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar'=> $queryAvatar ,
]);
Another problem can be caused by partial view in side view. For example when you call view:channel from controller inside it may be you view called like this.
<?=$this->render('your_view')?>
So, you should pass your variable to this view also like this.
<?=$this->render('your_view',['queryAvatar'=>$queryAvatar])?>
And finally you cannot echo the varable $queryAvatar beacuse it is array of objects. Therefore use the function print_r();
Like this.
<div><?php print_r($queryAvatar); ?></div> // THE LINE I ADD

Related

Why does it give an error "missing required parameters: id"?

I understand that the error occurred due to the confusion of variables, although these are my assumptions .. The fact is that this error occurred in the update and in the view: update and view. I have already tried everything .. Please poke your nose where I went wrong?
My controller in which I pass two actions view and update:
public function actionView($id)
{
return $this->render('view', [
'faq' => $this->findModel($id),
]);
}
public function actionUpdate($id)
{
$faq = FaqLang::findOne($id);
$faqLang = Faq::findOne($faq->faq_id);
if ($faq->load(Yii::$app->request->post()) && $faqLang->load(Yii::$app->request->post()) && Model::validateMultiple([$faq, $faqLang]))
{
$faqLang->save(false);
$faq->save(false);
return $this->redirect(['view', 'id' => $faq->id]);
}
return $this->render('update', [
'faq' => $faq,
'faqLang' => $faqLang,
]);
}
protected function findModel($id)
{
if (($faq = FaqLang::findOne($id)) !== null) {
return $faq;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
view.php in which I am trying to display data using DetailView
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $faqLang app\modules\admin\models\Faq */
/* #var $faq app\modules\admin\models\FaqLang */
//$this->title = $faq->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="faq-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $faq->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $faq->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'faq' => $faq,
'attributes' => [
'id',
['attribute' => 'name', 'value' => 'faqLang.name'],
['attribute' => 'body', 'value' => 'faqLang.body:ntext'],
'put_date',
[
'attribute' => 'hide',
'format' => 'html',
'value' => function($model) {
if($model->hide == 'show')
return 'Нет';
else
return 'Да';
}
],
],
]) ?>
update.php through which the records are updated
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $faqLang app\modules\admin\models\Faq */
/* #var $faq app\modules\admin\models\FaqLang */
$this->title = Yii::t('app', 'Update Faq: ' . $faq->id, [
'nameAttribute' => '' . $faq->id,
]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $faq->id, 'url' => ['view', 'id' => $faq->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="faq-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'faq' => $faq,
'faqLang' => $faqLang,
]) ?>
</div>
And 2 related Faq and FaqLang models
Faq.php
public function getFaqLang()
{
return $this->hasMany(FaqLang::className(), ['faq_id' => 'id']);
}
FaqLang.php
public function getFaq()
{
return $this->hasOne(Faq::className(), ['id' => 'faq_id']);
}
You may be seeing this error because the request path/query string you're using to run your controller actions does not include the $id parameter.
If you specify a method parameter in a controller action, that parameter must be defined in your routes, and passed in the request
Your action methods are as follows:
public function actionView($id)
{
....
}
Which expects a route like
'/view/<id:\d+>' => 'admin/faqs/view'
and
public function actionUpdate($id)
{
...
}
Which expects a route like
'/update/<id:\d+>' => 'admin/faqs/update'
So for example, for the request /view/123 , the value 123 is passed as the value of $id into the actionView($id) method.
If you have a route set up like
'/view' => 'admin/faqs/view'
There's no id parameter defined, and the controller will throw the error missing required parameters: id

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']);

One search form to 3 Gridview in same page

Friends,
I have an INDEX page with 3 GRIDVIEW components (model Keys, model Products, model Indicators). And on that same page I have a search form with a dropdownlist (company).
I need to: When you select for example company 02 the 3 GRIDVIEW are filtered only company records 02.
_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
?>
<div class="ideas-search">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-inline',
],
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'pa')->dropdownList([..])?>
...
index.php
<?php echo $this->render('_search', ['model' => $searchBase]); ?>
<?php Pjax::begin(['id' => '1']) ?>
<?= GridView::widget([
'id' => 'grid1',
'dataProvider' => $dataProviderKey,
'columns' => [
...
],
]); ?>
<?php Pjax::end() ?>
<?php Pjax::begin(['id' => '2']) ?>
<?= GridView::widget([
'id' => 'grid2',
'dataProvider' => $dataProviderProduct,
'columns' => [
...
],
]); ?>
<?php Pjax::end() ?>
<?= GridView::widget([
'dataProvider' => $dataProviderIndicators,
'summary' => false,
'columns' => [
...
],
]); ?>
== UPDATE==
BaseController
public function actionIndex()
{
$searchBase = new BaseSearch();
$searchBase->pa = 0;
$searchBase->data = date("Y-m-d");
$dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);
$searchMobilizadores = new MobilizadoresSearch();
$dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);
$searchIndicadores = new IndicadoresSearch();
$dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchBase' => $searchBase,
'dataProviderBase' => $dataProviderBase,
'searchMobilizadores' => $searchMobilizadores,
'dataProviderMobilizadores' => $dataProviderMobilizadores,
'searchIndicadores' => $searchIndicadores,
'dataProviderIndicadores' => $dataProviderIndicadores,
]);
}
dont forget define filterModel in your Gridview Widget
view file
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
1st Approach :
You may use a single model that extend from model that joint all 3 table and create a search model for it. If u insist on separating all 3 table in the view, you may just declare different column for each grid.
a tip to achieve this, you may create a view and use gii tool to generate view file.
the tricky part is that 1 model can only hold one table except you joint. But, by joining table, you may get extra rows that are not necessarily needed for lets say your $dataProviderKey grid.
2nd Approach :
manually check for params from Yii::$app->request->get() add filter for each $dataprovider.
controller file
if(isset($id = Yii::$app->request->get('company_id'))) {
$dataProviderKey->query->andFilterWhere(['company.id' => $id]);
$dataProviderProduct->query->andFilterWhere(['company.id' => $id]);
$dataProviderIndicators->query->andFilterWhere(['company.id' => $id]);
}
== UPDATE ==
to answer your update question, you may assign your base search attributes to the respective attributes from others searchModel like this :
public function actionIndex()
{
$searchBase = new BaseSearch();
$searchBase->pa = 0;
$searchBase->data = date("Y-m-d");
$dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);
$searchMobilizadores = new MobilizadoresSearch();
$searchMobilizadores->company = $searchBase->company; -->add this
$dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);
$searchIndicadores = new IndicadoresSearch();
$searchIndicadores->company = $searchBase->company; -->add this
$dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);

Yii2 - Search exact value and return result in detailview

I need to put on the page to search by protocol number, and display only one result when the entered protocol number is exactly the same. If possible the results to be shown, it is a DetailView
My model OccurrenceSearch:
public function searchprotocol($params)
{
$query = Occurrence::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'protocol' => $this->protocol,
]);
return $dataProvider;
}
}
My view search:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="occurrence-search">
<?php $form = ActiveForm::begin([
'action' => ['search'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'protocol') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My controller actionSearch() :
public function actionSearch()
{
$searchModel = new OccurrenceSearch();
$dataProvider = $searchModel->searchprotocol(Yii::$app->request->queryParams);
return $this->render('search', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
The guest user can see only the record for its protocol number
The a detailView use model (and not dataProvider) for show the data instance ..
then in you controller you should obtain the model
public function actionSearch()
{
$searchModel = new OccurrenceSearch();
$dataProvider = $searchModel->searchprotocol(Yii::$app->request->queryParams);
$model = $dataProvider->query->one();
return $this->render('search', [
'searchModel' => $searchModel,
//'dataProvider' => $dataProvider,
'model' => $model,
]);
}
But in you view the code proposed don't show a detailView widget .. you should probably add
I decided to use the GRIDVIEW, and so changed the MymodelSearch
if (isset($_GET['AuthorSearch']) && !($this->load($params) && $this->validate())) {
return $dataProvider;
}

select2 and Pjax not work together in yii2

when i use pjax in yii2. selec2 widget stops working. while select2 working alone. (not working together)
im using select2 widgets and pjax together. but when submit form with pjax. in new form, select2 not work. (just show loading img). pls help me
what is problem?
I want to use both at the same time.
select2 extention page
in view:
<?php
use yii\helpers\Hrml;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model app\models\Vitrin */
?>
<?php Pjax::begin(); ?>
<?php
if($model->getProductTypeSetting()=='both')
{
echo $this->render('_form', [
'model' => $model,
]);
}
?>
<?php Pjax::end(); ?>
in _form:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post'['data-pjax' => '']); ?>
<?= Html::activeInput('text', $model, 'name', ['class' => $username]) ?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
in controller:
if(Yii::$app->request->post('productType'))
{
$model->productType = $_POST['productType'];
if($model->productType=='physical')
{
return $this->renderAjax('_formProduct', ['products' => $this->getProductName()]);
}
else
throw new \yii\web\HttpException(406, Yii::t('app', 'Your request is invalid.'));
}
in _formProduct:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post', ['data-pjax' => '']); ?>
<?php
echo Select2::widget([
'name' => 'name',
'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
'options' => [
'placeholder' => 'Select a type ...',
],
]);
?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
and AppAssets class:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot/themes/backend';
public $baseUrl = '#web/themes/backend/assets_t';
public $css = [
'bootstrap-rtl/css/bootstrap-rtl.min.css',
'bootstrap-rtl/css/bootstrap-responsive-rtl.min.css',
'font-awesome/css/font-awesome.css',
'fancybox/source/jquery.fancybox.css',
'uniform/css/uniform.default.css',
];
public $js = [
'bootstrap-rtl/js/bootstrap.min.js',
'js/jquery.blockui.js',
'uniform/jquery.uniform.min.js',
];
when submit _form with pjax. in _formProduct, select2 not work. (just show loading img).
Generally, when I use Pjax, other Js codes are deactivated.
In your view header:
use kartik\select2\Select2Asset;
Select2Asset::register($this);
Also make sure you have the latest Select2 widget.