kartik-v/yii2 select2-widget not working with render partial - yii2

I am trying to add dynamic drop downs, which will added from javascript on clicking add new button.
view file
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use kartik\select2\Select2Asset;
use yii\helpers\ArrayHelper;
Select2Asset::register($this);
?>
<div class='row'>
<div class='form-group'>
<?=
Select2::widget([
'name' => 'coupons',
'value' => $model->coupon_id,
'data' => ArrayHelper::map($coupons, 'id', 'name'),
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
controller
public function actionNewCoupon()
{
$coupon = new DealCoupon();
$deal = Yii::$app->request->get('deal');
$order = Yii::$app->request->get('order');
$coupon->deal_id = $deal;
$coupon->order = $order;
$coupon->save();
$coupons = Coupon::find('id','name')->all();
return $this->renderPartial('_form', [
'model' => $coupon,
'coupons' => $coupons
],true, true);
}
js file
.get(BASE_URL + '/coupon/new-coupon', { deal: dealId, order: order }, function(data) {
var dealWidget = newStep.find('.coupon-panel');
$(newStep).find('.coupon-panel').html(data);
});
What I am getting
Any help to resolve this issue is appreciable, as I am totaly lost.
Thanks in advance.

yii\web\Controller::renderPartial() doesn't include registered JS or CSS files. Try using yii\web\Controller::renderAjax() instead. It's similar but it injects registered JS/CSS files into rendered html code.

Related

Yii2 UploadedFile::getInstance() returns null

When my form is sent UploadedFile::getInstance($model, 'images') returns null. I also tried UploadedFile::getInstanceByName('images'). In the $_POST array the images key is empty e.g. 'images' => ['']. The file exists in $_FILES array.
My code is pretty simple. My view:
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle floating-labels',
'enctype'=>'multipart/form-data'
],
]); ?>
<?= $form->field($model, 'images[]')->fileInput([
'id' => 'image_0',
'class' => 'dropify',
'data-default-file' => ''
]) ?>
<?php ActiveForm::end() ?>
In my model I have:
public $images;
public function rules()
{
return [
['images', 'each', 'rule' => ['file']],
];
}
If you want to access an array of files, you need to use UploadedFile::getInstances() instead of UploadedFile::getInstance().
$files = UploadedFile::getInstances($model, 'images');
Good example of handling multiple files can be found in guide in Uploading Multiple Files section.

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 Basic sql query in view

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

Yii2: Override global pdf orientation settings for mpdf in controller action

I am using the mpdf extension to generate pdf files. I have set global settings for the mpdf in the config file, hence I am able to call the function every time I want to generate a pdf from my controller action. However, I am finding it hard to change the orientation for the pdf with data that requires landscape orientation since the default orientation set in the global settings is portrait. Here are the codes:
main.pdf code for the global setting
'pdf' => [
'class' => Pdf::classname(),
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => [
'shrink_tables_to_fit' => 0
],
// refer settings section for all configuration options
],
Controller Action calling the global settings:
public function actionReservationsList()
{
$searchModel = new ReservationsSearch();
$dataProvider = $searchModel->search(Yii::$app->session->get('repquery'));
$dataProvider->pagination = false;
$pdf = Yii::$app->pdf;
$pdf->content = $this->renderPartial('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
$pdf->methods = [
'SetHeader' => [Yii::$app->user->identity->company->name.'||Date: ' . date("r")],
'SetFooter' => ['User: '.Yii::$app->user->identity->username.'||Page {PAGENO}'],
];
return $pdf->render();
}
So I need help in overriding the 'orientation' => Pdf::ORIENT_PORTRAIT, setting that is in the global settings main.php file from the controller action.
This work for me:
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use kartik\mpdf\Pdf;
class InformesController extends Controller
{
...
public function actionImprimirInforme($id,$key)
{
$html = $this->renderPartial('informe-pdf', [
'title' => 'Informe'
]);
$pdf = new Pdf([
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_LANDSCAPE,
'destination' => Pdf::DEST_BROWSER,
'options' => [
'showImageErrors' => true,
]
]);
$pdf->configure([
'title' => 'Informe ',
]);
$pdf->content = $html;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;
$pdf->execute('SetFooter', ['{PAGENO} de {nbpg}']);
$pdf->filename = "Informe.pdf";
return $pdf->render();
}
}
My first answer was wrong, i have been setting the property 'orientation' into pdf component, so the dynamically assign does not work properly.
Here you have the documentation example
You need to add the contents via addPage. So if you build a array of pages, with the contents etc - you should be able to specify the orientation per page.
<?php
$mpdf = new mPDF('', 'Legal');
$mpdf->WriteHTML('
Hello World
');
$mpdf->AddPage('L'); // Adds a new page in Landscape orientation
$mpdf->WriteHTML('
Hello World
');
$mpdf->Output();
?>
Try add this line this :
$pdf = Yii::$app->pdf;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;

Dynamic Multilevel Drop-down menu in Yii2

I want to create a dynamic menu with my table (db). I have followed some instructions which are given below:
Table : "menupanal"
Step 01: I just create a super controller in app\components\Controller.php
Here is the code:
namespace app\components;
use app\models\MenuPanal;
class Controller extends \yii\web\Controller
{
public $menuItems = [];
public function init(){
$items = MenuPanal::find()
->where(['c_type' => 'MENU'])
->orderBy('id')
->all();
$menuItems = [];
foreach ($items as $key => $value) {
$this->menuItems[] =
['label' => $value['c_name'],
'items'=> [
['label' => $value['c_redirect'], 'url' => ['#']],
],
];
}
parent::init();
}
Step 02: Changed n main layout page:
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => Yii::$app->controller->menuItems,
]);
It is working in only one level. My question::
Question : how can I add multilevel menu using Super controller ?
I am new in Yii2. Helps are highly appreciated.
Create New MenuHelper in Component folder. There is no default component folder. Please create by yourself.
<?php
namespace app\components;
use app\models\MenuPanel;
use app\models\Zuser;
use app\models\Vwrole;
use app\assets\AppAsset;
class MenuHelper
{
public static function getMenu()
{
$role_id = 1;
$result = static::getMenuRecrusive($role_id);
return $result;
}
private static function getMenuRecrusive($parent)
{
$items = MenuPanel::find()
->where(['c_parentid' => $parent])
->orderBy('c_sortord')
->asArray()
->all();
$result = [];
foreach ($items as $item) {
$result[] = [
'label' => $item['c_name'],
'url' => ['#'],
'items' => static::getMenuRecrusive($item['id']),
'<li class="divider"></li>',
];
}
return $result;
}
}
in Main Layout Page put the following code
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => app\components\MenuHelper::getMenu(),
Enjoy Coding!!
You may use nested sets. Look at this extension for Yii: http://www.yiiframework.com/extension/nestedsetbehavior/ and its documentation. All you need to do is component with dynamic creation of menu items array for nested sets.
I found that there is a Yii2 extension version: http://www.yiiframework.com/extension/yii2-nestedsetbehavior/
Good luck
You may use this extension for multilevel dropdownMulti level Dropdown