Yii2 foreach loop inside $menuItems - yii2

I have a menu like this
<?php
NavBar::begin([
'brandLabel' => Html::img('#web/images/cennos1.png', ['alt'=>Yii::$app->name]),
'brandUrl' => Yii::$app->homeUrl,
'brandOptions' => ['style' => 'margin-top:-7px;'],
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = [
'label' => 'Teams',
'items' => [
foreach ($teams as $team) {
['label' => '' . $team->name .'', 'url' => ['team/preview','id' => $team->id]],
}
],
];
I tried to use foreach loop like that to list all teams as a dropdown menu for guest users to see but it didn't work.
Please help me with this. Sorry for my bad English.
Thank you.

This may not be the best way, but it works for me.
function items($teams)
{
$items = [];
foreach ($teams as $team) {
array_push($items, ['label' => '' . $team->name .'', 'url' => Url::to(['team/preview', 'id' => $team->id])]);
}
return $items;
}
NavBar::begin([
'brandLabel' => Html::img('#web/images/cennos1.png', ['alt'=>Yii::$app->name]),
'brandUrl' => Yii::$app->homeUrl,
'brandOptions' => ['style' => 'margin-top:-7px;'],
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = [
'label' => 'Teams',
'items' => items($teams)
];
Hope it helps,

Related

Add Custom Button in Kartik Yii2 Kartik DetailView

I already search and try every forum and example.
I am using the Kartik\DetailViwew in Yii2 and I can´t manage to put a single custom button in the buttons1 option.
The code I am working on:
echo DetailView::widget([
'model' => $model,
'attributes' => $attributes,
'mode'=>Yii::$app->request->get('edit')=='t' ? DetailView::MODE_EDIT : DetailView::MODE_VIEW,
'panel'=>[
'heading'=>$this->title,
'type'=>DetailView::TYPE_INFO,
],
'buttons1' => '{update}',
'bordered' => 'true',
'striped' => $striped,
'condensed' => $condensed,
'responsive' => $responsive,
'hover' => $hover,
'hAlign'=>$hAlign,
'vAlign'=>$vAlign,
'fadeDelay'=>$fadeDelay,
'deleteOptions'=>[ // your ajax delete parameters
'params' => ['id' => $model->p_id, 'custom_param' => true],
'url'=>['delete', 'id' => $model->p_id],
]
]);
In the
'buttons1' => '{update}',
According to the example http://demos.krajee.com/detail-view, there is a way to customize.
But there is no example. And the documentation not explain how to do this.
Can anyone help?
After research and some tryings, I did it by this way, you have to enable the edit mode (to show buttons), and modify the defatul template ({buttons}{title}), as this template is replaced if the template exists in vender grideview constants, just inject your code to add any button u want. Is not the rigth solution, but is a workaround that works well
<?php
$button1 = Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]);
$button2 = Html::a('<i class="glyphicon glyphicon-pencil"></i>', Url::to(['actualizar', 'id' => $model->id]), [
'title' => 'Actualizar',
'class' => 'pull-right detail-button',
]);
?>
<?=
DetailView::widget([
'model' => $model,
'hover' => true,
'hideAlerts' => true,
'enableEditMode' => true,
'mode' => DetailView::MODE_VIEW,
'hAlign' => 'left',
'panel' => [
'heading' => '&nbsp',
'type' => DetailView::TYPE_DEFAULT,
'headingOptions' => [
'template' => "$button1 $button2 {title}"
]
],
'attributes' => [
'id',
'identificacion',
'nombre',
],
])
?>
Try it like this:
'buttons1' => Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]),
If you have more than one button, try it like this:
$button1 = Html::a('<i class="glyphicon glyphicon-trash"></i>', Url::to(['delete', 'id' => $model->id]), [
'title' => 'Eliminar',
'class' => 'pull-right detail-button',
'data' => [
'confirm' => '¿Realmente deseas eliminar este elemento?',
'method' => 'post',
]
]);
$button2 = Html::a('<i class="glyphicon glyphicon-pencil"></i>', Url::to(['actualizar', 'id' => $model->id]), [
'title' => 'Actualizar',
'class' => 'pull-right detail-button',
]);
'buttons1' => "{$button1} {$button2}",

Kartik export widget not export search result Yii2

Fighting form last 3 days not able to find what exactly problem is. When after search I export data it export all data, expected to export search result.Please help!
My Controller
public function actionAdvancesearch()
{
$searchModel = new CandidateSearch();
$model = new Candidate();
$dataProvider1 = $searchModel->search(Yii::$app->request->queryParams);
if(Yii::$app->request->post()){
$postedData=Yii::$app->request->post();
$searchModel = new CandidateSearch();
$dataProvider1 = $searchModel->searchAdvanced();
return $this->render('candidateAdvSearch', ['dataProvider1' => $dataProvider1,
'model' => $model ,
'searchModel' => $searchModel,
'posted'=>"posted",
'postedData'=>$postedData]);
}else{
return $this->render('candidateAdvSearch', ['searchModel' => $searchModel, 'model' => $model, 'dataProvider1' => $dataProvider1]);
}
}
View
Pjax::begin();
if($dataProvider1){
$gridColumns = [
[
'attribute'=>'HRMS_candidateID',
'label'=>'Candidate ID',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateID;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateFirstName',
'label'=>'Candidate FirstName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateFirstName;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateLastName',
'label'=>'Candidate LastName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateLastName; },
'format'=>'raw'
],
];
$fullExportMenu = ExportMenu::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'target' => ExportMenu::TARGET_POPUP,
'fontAwesome' => true,
'pjaxContainerId' => 'kv-pjax-container',
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]);
// Generate a bootstrap responsive striped table with row highlighted on hover
echo GridView::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container']],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Candidate Advanced Search</h3>',
],
'toolbar' => [
$fullExportMenu,
],
'striped'=>true,
'hover'=>true,
'responsive'=>true,
'hover'=>true,
'resizableColumns'=>true,
'persistResize'=>false,
'columns' => $gridColumns,
]);
}
Pjax::end();

Control of active menu items

I'm setting up a small page, so i removed /site/ from the URL. Most pages will be static pages on the site controller, so this looks cleaner.
The menu widget is configured as follows:
$menuItems = [
['label' => 'Home', 'url' => ['/']],
['label' => 'About', 'url' => ['/about']],
['label' => 'Projects', 'url' => ['/projects']],
];
And the config rule is
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<action:\w+>' => 'site/<action>',
],
Now my problem is that my menu item links are no longer marked as active (css .active). What controlls this, and how can I change it?
Solved.
Change the menuItems like this
$menuItems = [
['label' => 'Home', 'url' => ['/'], 'active' => $this->context->route == 'site/index'],
['label' => 'About', 'url' => ['/about'], 'active' => $this->context->route == 'site/about'],
['label' => 'Projects', 'url' => ['/projects'], 'active' => $this->context->route == 'site/projects'],
];
You should to use 'url' => [controller/action] to get this thing done. And this config will be overwrited by you rules. So, and then class .active will be added automatically.
You can use in_array method to check current URL. In array we need add all urls in which menu is in active state.
'active' => in_array($this->context->route,['items/index','items/create','items/update']),
If we open List page, create page or update page, Item menu will be active.
We can use Controller id to check current controller
'active' => Yii::$app->controller->id == 'items',
I use this code in yii2 for best menu:
\yii\widgets\Menu::widget([
'submenuTemplate' => "\n<ul class='top-nav-menu'>\n{items}\n</ul>\n",
'activateParents' => false,
'activeCssClass' => 'active',
'id' => 'sandwich-menu',
['label' => Yii::t('app', 'Education'), 'url' => ['/site/education'] ],
[
'label' => Yii::t('app', 'Entertainment'),
'url' => '#',
'items' => [
['label' => Yii::t('app', 'Games'), 'url' => ['/site/games']],
['label' => Yii::t('app', 'Music'), 'url' => ['/site/music'] ],
['label' => Yii::t('app', 'Videos'), 'url' => ['/site/videos'] ],
['label' => Yii::t('app', 'Chat & Forum'), 'url' => ['/site/forum'] ],
['label' => Yii::t('app', 'Clubs'), 'url' => ['/site/clubs'] ]
]
],
['label' => Yii::t('app', 'News'), 'url' => ['/site/news']],
['label' => Yii::t('app', 'Contact'), 'url' => ['/site/gencol'] ]
]
])
Actually, as soovorow suggested, it should work with
$menuItems = [
['label' => 'Home', 'url' => ['/']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Projects', 'url' => ['/site/projects']],
];
the problem was that the controlled name was not explicit in
$menuItems = [
['label' => 'Home', 'url' => ['/']],
['label' => 'About', 'url' => ['/about']],
['label' => 'Projects', 'url' => ['/projects']],
];

Yii2 Link FrontEnd To BackEnd

How to link from frontend page to backend in Yii2 using advanced template.... I want to link the login button from frondend to backend...when I click on login button in frontend it can redirect to login page in backend that I already created...
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
`
You can try a relative path
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' =>'Login','url' =>'../../../backend/site/login'];
} else {
add this in common/config/main.php
under the section components
'components' => [
.....
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => false,
'showScriptName' => true,
],
.......
add to section components after urlManager in frontend/config/main.php
'urlManagerBackend' => [
'class' => 'yii\web\UrlManager',
'baseUrl' => 'http://backend.site.local',
'hostInfo' => 'http://backend.site.local',
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
],
in frontend/views/layout
add something like this
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'Admin panel', 'url' => Yii::$app->urlManagerBackend->createUrl([''])],
];

Yii2: Select2, How to set initValueText in Gridview or Tabularform?

I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each.
<?= TabularForm::widget([
'dataProvider' => $dataProvider,
'form' => $form,
'actionColumn' => false,
'checkboxColumn' => false,
'attributeDefaults' => [
'type' => TabularForm::INPUT_RAW,
],
'attributes' => [
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform?
],
],
]
]) ?>
Of course this is not working,
'initValueText' => function($model){
retur $model->textValue;
}
Any help would be appreciated.
Into tabularform if you want dynamic initValueText, you can use options closure in this manner:
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => function($model, $key, $index, $widget) {
$initValueText = empty($model['textValue']) ? '' : $model['textValue'];
return [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'initValueText' => $initValueText,
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
];
}
],
If for example attribute for city, so try this..
$cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description;
'initValueText' => $cityDesc, // set the initial display text
For init value first assign value to $model attribute, if you should not assign so this attribute can take value.
Set the data parameter with the array including the option you want to show. For example for cities:
'options' => [
'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
]
try to put inside the options instead ouside
'widgetClass' => Select2::className(),
'options' => [
'initValueText' => 'Selected Text'
Don't use isset it return error if more the one filter are use there.
[
'attribute' => 'ad_partner_id',
'value' => function ($model, $key, $index, $widget) {
return $model->partner->name;
},
'filter' => Select2::widget([
'model' => $searchModel,
'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "",
'attribute' => 'ad_partner_id',
'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')],
'pluginOptions' => ['allowClear' => true, 'autocomplete' => true,
'ajax' => ['url' => Url::base() . '/partner/get-partners',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
]),
],