How to give active class to clicked button in Yii2 - yii2

I am a new member in Yii2. I integrated new template with by default Yii2 advanced template. I need to use active class to clicked menu from side bar. Below my code. How can I do it? Please help me
<li class="">
<?= Html::a('<i class="glyphicon glyphicon-education"></i><span>Суд жараёни</span>', ['law1/']) ?>
</li>
<li class="">
<?= Html::a('<i class="glyphicon glyphicon-check"></i><span>МИБ</span>', ['law2/']) ?>
</li>
<li class="">
<?= Html::a('<i class="glyphicon glyphicon-ruble"></i><span>Прократура</span>', ['law3/']) ?>
</li>
<li class="">
<?= Html::a('<i class="glyphicon glyphicon-bitcoin"></i><span>Банк</span>', ['law4/']) ?>
</li>

Some Simple Approaches
You can compare the controller/route/action to the URL and if they match add an active class with a yii2 helper:
Simple add class to html link:
<?php
use yii\helpers\Html;
$controller = Yii::$app->controller->id;
$options = ['class' => ['btn btn-md btn-default']];
if ($controller == 'batch') {
Html::addCssClass($options, ['active']);
}
echo $link = Html::a('SomeLink', ['batch/view'], $options);
echo $link = Html::a('SomeLink', ['batch/view'],);
?>
If using a nav widget, you can leverage the active and visible properties:
<?php
use mdm\admin\components\Helper;
$controller = Yii::$app->controller->id;
echo kartik\sidenav\SideNav::widget([
'type' => SideNav::TYPE_DEFAULT,
'items' => [
[
'url' => ['supplier/index'],
'label' => 'Suppliers',
//'icon' => 'th-list',
'active' => $controller == 'supplier',
'visible' => Helper::checkRoute('supplier/index'),
],
[
'url' => ['site/index'],
'label' => 'Sites',
//'icon' => 'th-list',
'active' => $controller == 'site',
'visible' => Helper::checkRoute('site/index'),
],
],
]);
?>

Related

yii2 - two modal in one active form

I have 2 modals in one active form. Let's say first one is modal-ticket and second one is contract-ticket. First time, I click button to show modal-ticket, and it was fine, but when I click button to show modal-contract, it also call script modal-ticket or otherwise. why?
this is my code.
<?php $form = ActiveForm::begin(); ?>
<div id="BtnSearchTicket">
<?= Html::button('Search Ticket', [
'value' => Url::to('../ticket-timbangan/list'),
'class' => 'btn btn-primary',
'id' => 'BtnModalTicketList',
'data-toggle'=>"modal",
'data-target'=>"#modalTicketList",
]) ?>
</div>
<div id="BtnSearchContract">
<?= Html::button('Search Contract', [
'value' => Url::to('../contract/list'),
'class' => 'btn btn-primary',
'id' => 'BtnModalContractList',
'data-toggle'=>"modal",
'data-target'=>"#modalContractList",
]) ?>
</div>
<?php ActiveForm::end(); ?>
<?php
Modal::begin([
'header' => 'Ticket List',
'id' => 'modalTicketList',
'size' => 'modal-lg',
'class' => 'style=width:auto'
]);
echo "<div id='modalContentTicket'></div>";
Modal::end();
?>
<?php
Modal::begin([
'header' => 'Contract List',
'id' => 'modalContractList',
'size' => 'modal-lg',
'class' => 'style=width:auto'
]);
echo "<div id='modalContentContract'></div>";
Modal::end();
?>
<?php
$script = <<< JS
$('#BtnModalTicketList').click(function(e){
e.preventDefault();
$('#modalTicketList').modal('show')
.find('#modalContentTicket')
.load($(this).attr('value'));
return false;
});
$('#BtnModalContractList').click(function(e){
e.preventDefault();
$('#modalContractList').modal('show')
.find('#modalContentContract')
.load($(this).attr('value'));
return false;
});
JS;
$this->registerJs($script);
?>
this are the error found in console web browser
GET http://localhost/pks/web/ticket-timbangan/get-ticket?id=1 404 (Not Found)
GET http://localhost/pks/web/contract/get-contract?id=2 404 (Not Found)
please help.
Try This: using one modal on your form:
<?php $form = ActiveForm::begin(); ?>
<div id="BtnSearchTicket">
<?= Html::button('Search Ticket', [
'value' => Url::to('../ticket-timbangan/list'),
'class' => 'btn btn-primary showModal',
'id' => 'BtnModalTicketList',
'title' => 'Search Ticket',
]) ?>
</div>
<div id="BtnSearchContract">
<?= Html::button('Search Contract', [
'value' => Url::to('../contract/list'),
'class' => 'btn btn-primary showModal',
'title' => 'Search Contract',
'id' => 'BtnModalContractList',
]) ?>
</div>
<?php ActiveForm::end(); ?>
<?php
Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
'closeButton' => [
'id'=>'close-button',
'class'=>'close',
'data-dismiss' =>'modal',
],
'class' => 'style=width:auto',
'clientOptions' => [
'backdrop' => false, 'keyboard' => true
]
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php
$script = <<< JS
$(document).on('click', '.showModal', function(){
if ($('#modal').hasClass('in')) {
$('#modal').find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
} else {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
}
});
JS;
$this->registerJs($script);
?>
From viewing your code what calls my attention is how you use the Url::to() function. Not sure why you use ../. I have fiddled with using more than one modal in a form and the code is similar to what your are doing. I suggest you try changing your Url::to() function as follows:
Url::to('/ticket-timbangan/list')
and
Url::to('/contract/list')
Another suggestion would be to try with
Yii::$app->urlManager->createUrl('/ticket-timbangan/list')
and
Yii::$app->urlManager->createUrl('/contract/list')
Let me know if this helps.
First, many thanks to kalu who has helped me 2 days to solve my problem. Two modals which contains grid need to define different classes to prevent execute previous script.
'value' => Url::to('../ticket-timbangan/list') and 'value' => Url::to('../contract/list'), both has two gridview and same select-row class. This class is root cause of the problem, because it's same class and execute both script.
Thanks Kalu, you save my day.

Yii2 - checkbox change commit ActiveForm

in the index.php there is a checkbox within a active form
<div class="form-group pull-right" style="margin-right: 10px">
<?php Pjax::begin(['id' => 'options']); ?>
<?php $form = ActiveForm::begin(['method' => 'get', 'action' => ['ensemble/index'], 'options' => ['data-pjax' => true]]); ?>
<?= $form->field($searchModel, 'completed')->checkbox(); ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
also there is kartik gridview in the index.php
<?= GridView::widget($gridConfig); ?>
with the following configuration
$gridConfig['pjax'] = true;
$gridConfig['pjaxSettings'] = ['options' => ['id' => 'pjaxGrid']];
the ensemble controller with the index action looks like this
public function actionIndex()
{
$searchModel = new EnsembleSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
This does work every thing just fine. I can check / uncheck the checkbox field and hit the submit button; which then reloads the gridview. Just cool.
Now i was wondering if it is possible, to just make this with only by clicking the checkbox? So if i check / uncheck the checkbox the gridview will be reloaded (pjax'd).
cheers,
Luc
Assign id to your form as well as class to your checkbox.
<div class="form-group pull-right" style="margin-right: 10px">
<?php Pjax::begin(['id' => 'options']); ?>
<?php $form = ActiveForm::begin([
'id' => 'filter-form',
'method' => 'get',
'action' => ['ensemble/index'],
'options' => ['data-pjax' => true]
]); ?>
<?= $form->field($searchModel, 'completed',['class'=>'status_chk'])->checkbox(); ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
Add this script to your index.php file.
<?php
$this->registerJs(
'$("document").ready(function(){
$(document).on("change",".status_chk", function() {
$("#filter-form").submit();
});
});'
);
?>
I would say that you could do that with JavaScript. You could do something like this:
You must know how to identify the Form and the Checkbox (you could assign them so ids..)
In a JavaScript you could do something like this:
var form = document.getElementById("form-id");
document.getElementById("your-checkbox-id").addEventListener("click", function () {
form.submit();
});
As explain in this answer:
submit form with javaScript

YII2 how to use pjax to submit a form without refresh the page

I use a yii2 to create a website, trying to use a form to submit some data.
Can some body give me a example. Tell me how to use pjax to submit a form without reload the page.
There's an example of Yii2 Pjax submit form in this link
views\site\form-submission.php:
<?php Pjax::begin(); ?>
<?= Html::beginForm(['site/form-submission'], 'post', ['data-pjax' => '', 'class' => 'form-inline']); ?>
<?= Html::input('text', 'string', Yii::$app->request->post('string'), ['class' => 'form-control']) ?>
<?= Html::submitButton('Hash String', ['class' => 'btn btn-lg btn-primary', 'name' => 'hash-button']) ?>
<?= Html::endForm() ?>
<h3><?= $stringHash ?></h3>
<?php Pjax::end(); ?>
controllers\SiteController.php:
public function actionFormSubmission()
{
$security = new Security();
$string = Yii::$app->request->post('string');
$stringHash = '';
if (!is_null($string)) {
$stringHash = $security->generatePasswordHash($string);
}
return $this->render('form-submission', [
'stringHash' => $stringHash,
]);
}

Yii2- Multiple Bootstrap Modal Items on Same Page

I am creating a page which would hold some buttons for creating different model items loaded via modal.
I'm using this code in a view file: create-all that belongs to the controller: ProductsController
Modal::begin([
'toggleButton' => [
'label' => '<i class="glyphicon glyphicon-plus"></i> Add Product',
'class' => 'btn btn-success'
],
'closeButton' => [
'label' => 'Close',
'class' => 'btn btn-danger btn-sm pull-right',
],
'size' => 'modal-lg',
]);
$class_products = 'app\models\Products';
$productModel = new $class_products();
echo $this->render('/products/create', ['model' => $productModel]);
Modal::end();
Modal::begin([
'toggleButton' => [
'label' => '<i class="glyphicon glyphicon-plus"></i> Add branch',
'class' => 'btn btn-success'
],
'closeButton' => [
'label' => 'Close',
'class' => 'btn btn-danger btn-sm pull-right',
],
'size' => 'modal-lg',
]);
$class_branch = 'app\models\Branch';
$branchModel = new $class_branch();
echo $this->render('/branch/create', ['model' => $branchModel]);
Modal::end();
branch/create code:
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Branch */
$this->title = Yii::t('app', 'Create {modelClass}', [
'modelClass' => 'Branch',
]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Branches'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="branch-create">
<?php
//echo Yii::$app->request->getReferrer();
$route = parse_url(Yii::$app->request->getReferrer(), PHP_URL_QUERY);
if ($route == urldecode('r=products%2Fcreate-all'))
print_r ($route);
?>
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
The buttons work just fine and a modal loads for both of the buttons
Problem
Add Product modal adds a new product successfully, but Add Branch doesn't. It just refreshes the page.
An attempt to solve your issue:
As far as I know, simply rendering view file inside the view, will not post data to the controller, unless you specify the action inside the form which you are rendering.
So inside the _form.php
<?php $form = ActiveForm::begin([
'action'=>'your_path_to_the_url',
]); ?>
You can also make an ajax submission from the form and handle the ajax data using Yii::$app->request->isAjax
This is just an idea. I have not seen your controller code nor your forms. Still a wild guess of the problem. See this will help you or not.

Split ActiveForm fields into different tabs with Tabs widget

I'm creating a form view and I want to organize the form fields with tabs structure, using the official Tabs widget.
Is it possible init the Tabs widget with the id (or class) of the div elements that contains the active form fields?
One example of how you can manage it is doing like this:
First, divide your contact-form into one view-file for each tab.
Place the ActiveForm::begin() and ActiveForm::end() around the Tabs::widget()
Render the contact-form pages into content, with parameters $model and $form
Example code:
views/site/contact.php
<?php
/* #var $this yii\web\View */
$this->title = 'Contact';
use yii\bootstrap\Tabs;
use yii\bootstrap\ActiveForm;
?>
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= Tabs::widget([
'items' => [
[
'label' => 'One',
'content' => $this->render('contact_form1', ['model' => $model, 'form' => $form]),
'active' => true
],
[
'label' => 'Two',
'content' => $this->render('contact_form2', ['model' => $model, 'form' => $form]),
],
]]);
?>
<?php ActiveForm::end(); ?>
views/site/contact_form1.php
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
views/site/contact_form2.php
<?php
use yii\helpers\Html;
use yii\captcha\Captcha;
?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
Hope this helps!
Just add at the top of your contact.php global $form; and all works fine.
I have another solution:
When we call $form->field($model, 'name')->textInput(), it will return the model of class yii\widgets\ActiveField, so just continue calling a method of this class as $form->field($model, 'name')->textInput()->render(). It will return a string then you can use it for the tab's content.
I have an example code in my application for translating multi languages as the following code:
<?php
$items = [];
foreach ($translateModels as $translateModel) {
$tabContent = $form->field($translateModel, "[{$translateModel->code}]name")->textInput()->render();
$items[] = [
'label' => $translateModel->language->name,
'content' => $tabContent,
];
}
?>
<?= Tabs::widget([
'options' => [
'class' => 'nav-tabs',
'style' => 'margin-bottom: 15px',
],
'items' => $items,
]) ?>
Maybe it's help.