Yii2 change breadcrumb url - yii2

There are two user types in my admin application. If an admin is logged in, there should be a param in each url like this:
Home>>Property>> view property
Current url : www.example.com/property/index
Desired Url : www.example.com/property/index?agentid=5
How can I achieve this?
This param value will be dynamic and only for admin.

In the top of your view file, (I consider view.php) You can use User::can() function to check for some admin/other permissions, and look at this example code to add param to link:
if (Yii::$app->user->can('admin')) {
$this->params['breadcrumbs'][] = ['label' => 'Property', 'url' => ['index', 'agentid' => 5]];
} else {
$this->params['breadcrumbs'][] = ['label' => 'Property', 'url' => ['index']];
}
$this->params['breadcrumbs'][] = $this->title;
It adds agentid=5 param if user has admin permission, and do not otherwise

Related

Yii2 Two different way for breadcrumbs

I have a gii generated view.php page, which can be reached from two different paths, but the breadcrumbs is the same. Anyone know how to fix?
Let me explain: I have the view.php view which shows the summary of the report made and can be reached from two paths:
when I create a new report and therefore the path should be HOME / CREATION / VIEW;
and also from a section that shows the user the summary of the reports she sent and therefore the breadcrumbs should be HOME / SUMMARY / VIEW.
You have 2 options to know where it came from:
Send a query variable on each link or in the redirection to manually build the breadcumb. Like: $value = Yii::$app->request->getQueryParam('breadcumb')
Other option is to get the referrer url. And base on the value you can pass it to the switch. You can get referrer's url using: $value = Yii::$app->request->getReferrer().
Then do a switch to build the link:
switch(value) {
case 'creation':
$label = 'CREATION';
$url = 'url_of_creation';
break;
case 'summary':
$label = 'SUMMARY';
$url = 'url_of_summary';
break;
}
Then just do something like this:
$this->params['breadcrumbs'][] = ['label' => $label, 'url' => $url];
This is a short breadcrum solution using match():
$this->params['breadcrumbs'][] = match($path) {
'creation' => ['label' => 'Creation', 'url' => Url::to['creation'],
'summary' => ['label' => 'Summary', 'url' => Url::to['summary'],
};
$path should either be set in the controller or determined by Yii::$app->request->getReferrer().
Please note, that this requires PHP8.

How to make active item of SideNav in another style?

I want the items in my SideNav by Kartik in the yii2 app to change the color when it is active(was clicked and open).
Sorry, I am pretty new for PHP and Yii and the question might be seen obvious but I really stack here.
I have already tried to use the "active" option that is explained in the documentation but it doesn't work. It doesn't show any error but is not working. I have a file adminMenu.php where the SideNav is written. and the panel.php view file where I showing it.
Also, I tried to add echo
$this->render('adminMenu'['currentPage'=>'admin/personal']);
but it shows error and thus I comment it for now.
adminMenu.php:
class adminMenu extends Widget{
public function init(){
$curentpage = Yii::$app->controller->id ;
parent::init();
ob_start();
echo SideNav::widget([
'type' => SideNav::TYPE_PRIMARY,
'headingOptions' => ['class'=>'head-style'],
'items' => [
['label' => 'Personal',
'url' => ['/admin/personal'],
'active' => ($curentpage == 'admin/personal')],
['label' => 'Clients',
'url' => ['/admin/clients'],
'active' => ($curentpage == 'admin/clients')],
...
]);
panel.php:
if(\Yii::$app->user->can('Admin')){
echo adminMenu::widget();
//echo $this->render('adminMenu'['currentPage'=>'admin/personal']);
}
i think that you mistake is in this line
$curentpage = Yii::$app->controller->id;
Yii::$app->controller->id only return the name of your controller , in this casi will be "admin" then you compare "admin" equals "controller/action" ('admin/personal') this never will be equals .
To do this , you can do a concat the actual controller and the actual action like this :
$curentpage = Yii::$app->controller->id.'/'.Yii::$app->controller->action->id;
and the comparation will be success and the "active" class add to you sidebar

Displaying subdirectory name in the url in Yii2 for static pages

Iam creating static pages for a client using Yii2. I am using yii2 because the client has some other requirements to scale up the web later. I use Yii2 Basic app. The yii2 basic has default pages like about, contact etc.
The url for those pages after enabling pretty url is
www.example.com/about
etc
Now i need to create pages
"xyz.php"
under a sub directory like
"abc"
. So i need my url to be www.example.com/abc/xyz
How do i achieve this? to be informed iam a learner, I followed url rules, helpers but did not find a strong solution.
create a controller like StaticController.php and use the yii\web\ViewAction
http://www.yiiframework.com/doc-2.0/yii-web-viewaction.html
As an example:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
/**
* StaticController is only for displaying static pages.
*/
class StaticController extends Controller
{
public $defaultAction = 'page';
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['page'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
public function actions()
{
return [
'page'=>array(
'class'=>'yii\web\ViewAction',
'viewPrefix'=>null, // or set a specific directory e.g. 'static-pages' if you want to store the static pages in a subdirectory
),
];
}
}
And add this Rule to your UrlManager (where static is your controller name)
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:static>/<view:.*>' => '<controller>',
...
]
]
Now you can store your static pages in the directory /view/static/
e.g. index.php, test.php or even in subdirectories /sub/test2.php
The urls would be like /static (or /static/index), /static/test1, /static/sub/test2
The 1st pathname is of course the controller name, but you can also change the url rule to something else or rename the controller.
config/web.php
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'abc/<view:\S+>' => 'site/page',
]
]
I had a situation where I wanted the URL to indicate a sub page (like 'website/page/sub-page) but I didn't think it made sense to have a separate controller. (At the moment I just have one controller; SiteController.php.)
I am recreating the site structure of an existing site in a new Yii2 Basic site.
Client has a page called 'laptop-repair' in their existing site with a number of pages linked from it, e.g. 'laptop-overheating'. So the URI needed to look like 'laptop-repair/laptop-overheating'.
The solution:
In urlManager in config>web.php I add a new rule (Nb. the order of rules is important, the earlier rules are prioritised):
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/' => 'site/index',
[
'pattern' => 'laptop-repair/<page:.*>',
'route' => 'site/laptop-repair',
'defaults' => ['page' => 'index'],
],
...
],
],
In SiteController.php I already had an action for the page which I wanted to make into a parent page:
public function actionLaptopRepair()
{
return $this->render('laptop-repair');
}
which I replaced with:
public function actionLaptopRepair($page)
{
return $this->render("/site/laptop-repair/$page");
}
The leading slash is necessary to override the default behaviour of the Yii application, which is to look for the view in 'views>{controllerName}'. For example with render('laptop-repair'); the view file laptop-repair.php would need to be in 'views>site' since the name of the controller is SiteController, whereas render("/site/laptop-repair/$page"); corresponds to a view file ($page) in 'views>site>laptop-repair'. This allows you to organise your views in subdirectories.
I created a new folder called 'laptop-repair' in 'views>site', moved the view for the parent page (laptop-repair.php) into the new directory and renamed it index.php. I put the new sub pages' view files in that new directory ('views>site>laptop-repair'), alongside the parent view (index.php).
Everything worked except for the URL creation in my nav widget. Where the following worked fine before, the 'laptop-repair' link broke after I implemented the above:
echo Nav::widget([
'options' => ['class' => 'navbar-nav ml-auto'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
[
'label' => 'Repair Services',
'items' => [
['label' => 'Desktop PC Repairs', 'url' => ['/site/pc-repair']],
['label' => 'Laptop Repairs', 'url' => ['site/laptop-repair']],
['label' => 'Mobile Phone Repairs', 'url' => ['/site/mobile-phone-repair']],
...
The fix was simply changing the relevant line to:
['label' => 'Laptop Repairs', 'url' => ['/laptop-repair']],
Creating a link from the parent page to a sub page looks like this:
<?= Html::a('Laptop overheating?', ['laptop-repair/laptop-overheating'], ['class' => '', 'title' => 'Laptop overheating']) ?>
To add a link to the parent page to the breadcrumbs of the sub page, I replaced:
$this->title = 'Laptop Over Heating?';
$this->params['breadcrumbs'][] = $this->title;
with:
$this->title = 'Laptop Over Heating?';
$this->params['breadcrumbs'][] = ['label' => 'Laptop repair', 'url' => ['/laptop-repair']];
$this->params['breadcrumbs'][] = $this->title;
in the view file of the sub page.

Pushstate in pjax only when redirecting

In one of my pages I have a link that is handled by pjax. Basically the user clicks an item, this item becomes "checked" (and saved in the DB).
I have disabled pushState for these requests, because it makes no sense, user effectively stays in the same page, so it's counter-intuitive to change the url.
However, there is a case when this pjax request results in redirect to login page (when the user is not logged in). And this is when I really need pushState to work, and it doesn't because I disabled it in the first place.
Would it be possible to configure pjax in such a way that normal responses work without pushState, but redirect responses (done with X-Pjax-Url header) do perform pushState?
There's no way to do it using current functionality. I've added two more options to pjax and my PR has been accepted to yii2 branch of pjax. So, without further ado:
https://github.com/yiisoft/jquery-pjax
//pushRedirect - Whether to pushState the URL for redirects. Defaults to false.
//replaceRedirect - Whether to replaceState the URL for redirects. Defaults to true.
// ...
jQuery(document).pjax("#example_selector", {
"push": false,
"replace": false,
"pushRedirect": true,
"replaceRedirect": false
});
Use a linkSelector to specify which links trigger the pjax calls
<?php Pjax::begin([
'enablePushState' => false, // don't change the Browser URL
'linkSelector' => 'pjax-btn', // pjax links that
]); ?>
<?= GridView::widget([
//...
[ // no pjax, normal linl
'label' => 'link with state replace',
'format' => 'raw',
'value' => function ($model, $key, $index, $column) {
return Html::a($model->title, Url::to(['/controllet/action', 'id' => $model->id]));
}
],
[
'class' => 'yii\grid\ActionColumn',
//'class' => 'common\widgets\ActionColumn',
'template' => '{toggle} {view} {update} {delete}',
'buttons' => [
'toggle' => function ($url, $model, $key) {
$options = [
'title' => 'Privacy',
'aria-label' => 'Privacy',
'class' => 'pjax-btn', // no state replacement, load with pjax
];
$icon = Html::tag('span', '', ['class' => 'glyphicon glyphicon-check']);
return Html::a($icon, $url, $options);
},
]
]]) ?>
<?php Pjax::end(); ?>

CakePHP basic auth on API (json) request

I want to make a request to resource/index.json, but since I index is not allowed without authentication it redirects me to login page. That's the behavior I want when no username:password has been sent
The thing is how do I set AuthComponent to work with both Form and Basic and only check for basic when the request goes through api prefix.
Also, does it automatically authenticate when found username and password in the header or do I have to do it manually?
in respective controller add few lines
class NameController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("index");
}
}
This will allow index without authentication.
I decided to use Friend's of Cake TokenAuthenticate, and yes, it works along with FormAuthenticate so I am able to use both.
As a matter of fact, it automatically chooses the component it's going to use based on if there is an existing _token param or a X-MyApiTokenHeader header.
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form',
'Authenticate.Token' => array(
'parameter' => '_token',
'header' => 'X-MyApiTokenHeader',
'userModel' => 'User',
'scope' => array('User.active' => 1),
'fields' => array(
'username' => 'username',
'password' => 'password',
'token' => 'public_key',
),
'continue' => true
)
)
)
);