ZF2: Zend Framework 2 Full URL including host name - zend-framework2

In my view I need to draw full URL. Like this:
http://hostename.com/default/url
When I try to use $this->url('default', array(1,2,3)) I get only /index/get/. Is there any Zend method to het host name or I have to use $_SERVER['HTTP_HOST'] instead?

You can use the option force_canonical on the router. All router options go into the third parameter of the url helper:
url($route, $params, $options)
So you can so something like this:
$this->url('myroute', array('id' => 123), array('force_canonical' => true))

I found this article with some interesting ways:
1) without parameters use an empty array:
// Using a route with the name "register" and the route "/register"
echo $this->url('register', array(), array('force_canonical' => true));
// Output: http://mydomain.com/register
2) note the differences between:
echo $this->serverUrl();
// Output: http://mydomain.com
and
// Current URL: http://mydomain.com/register
echo $this->serverUrl(true);
// Output: http://mydomain.com/register
3) starting from the route
// The "register" route has the following route: /register
echo $this->serverUrl($this->url('register'));
// Output: http://mydomain.com/register

There is a Zend\View\Helper\ServerUrl to create full url in zend view.
Try below code in your view template.
<?php echo $this->serverUrl()?>

If you want to set base URL globally, you can do it using onBootstrap method:
$e->getApplication()->getMvcEvent()->getRouter()->setBaseUrl($baseUrl);
In this case Navigation helpers would also use it.
To fetch current base URL use ServerUrl helper as described in this thread:
$serverUrl = $e->getApplication()->getServiceManager()->get('ViewHelperManager')->get('ServerUrl');
$baseUrl = $serverUrl->__invoke();

Related

What is the exact method to set the url in Kartik Sidenav in Yii2

In my computer I've set the link as following in kartik sidenav
'url' => 'http://localhost:8080/advanced/frontend/web/index.php?r=batchno/productbatch/create',
'label' => 'New Batch',
'icon' => 'glyphicon glyphicon-plus-sign',
'visible'=>Yii::$app->user->can('c_billing-person'),
It Works Fine. But in other computer with same database setup it's not working as I need to give the URL as below
http://localhost/advanced/frontend/web/index.php?r=batchno/productbatch/create
So the difference is in the port.
My question is that how can I set the URL dynamically?
A correct method for setting the url with yii2 (included kartik sidenav) is base on Url Helper
use yii\helpers\Url;
$menuItems[] = ['label' => 'my_label', 'url'=>Url::to(['/your-controller/your-action'])];
in you case
'url'=>Url::to(['/batchno/productbatch/create'])
The Url Helper Url::to function provide the corretc routing for controller action in every environment ..

Displaying page Name in the URL instead of page ID in yii?

How to display Page Name in the url instead of Page ID
For example, It Should be
localhost/mysite/index.php/page/about
Instead of
localhost/mysite/index.php/page/1
I have tired from edit actionview()
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
You can create links to ANY url that you like. The issue is how you deal with the data that is passed.
So in your view, create a link.
About Us
This will call the controller action actionView(). You can then handle the page in there.
public function actionView($page)
{
// Load the model with the required page tag.
$pageDetails = Article::model()->findByAttributes(
array('page_name' => $page)
);
// Display the page
$this->render('view',array(
'model'=>$pageDetails
));
}
Updated Answer
Hope you are making your website SEO friendly with pretty URL. If your pages are static web pages such as about, faq, privacy..., you can implement the above answer provided by crafter. In this case page names should unique.
Another way (but not exactly what you want) is url rewriting with native yii feature urlManager. In this case page id will appear in URL like bellow.
localhost/mysite/index.php/page/1/about
localhost/mysite/index.php/page/2/britain-to-support-italys-intelligence-effort-on-migrants
If you observe, most of the News website following the same url structure.
Ex: http://www.telegraph.co.uk/finance/economics/11682277/Greeks-admit-they-will-default-at-the-end-of-the-month-as-central-bank-turns-on-government.html
To do this this in application, you have to write urlManager rules.
'urlManager' => array(
'urlFormat'=>'path',
'showScriptName'=>true,
'rules' => array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
//We are adding pretty url for article
'page/<id:\d+>/<title:[a-zA-Z0-9\-_]>' => 'page/view',
),
I am assuming bellow is you Article database table
id title description keywords status
-------------------------------------------------------
1 about some big text some keys active
Now i am making the URl dynamically
<?php
//In Controller
//Fetch articles and send them to view
$articles=Articles::model()->findAll();
?>
<?php
//In View
//Iterate articles
foreach($articles as $article)
{
$id=$article->id;
$title=$article->title;
//Make structured Url.
// Replaces all spaces with hyphens and change text to lowercase .
$titleInUrl= strtolower(str_replace(' ', '-', $title));
// Removes special chars.
$titleInUrl=preg_replace('/[^A-Za-z0-9\-]/', '', $titleInUrl);
?>
$title
<?php
}
?>
You can also change URL pattern as you want. Ex i need url like
localhost/mysite/index.php/page/about-1
For this i have write/change rule in urlManager as
'page/<title:[a-zA-Z0-9\-_]>-<id:\d+>' => 'page/view',
Hope it will help you for your problem.

Kohana 3.3 get url parameters

My question can look stupid but I need to get in touch and get a decision. I want to pass parameters to url without the parameters being seen in the url. this is to secure my server. Because the url looks like this
controller/edit/123
and the '123' is the user ID in the database.
I can simple do this
public function action_edit($id) {
get_db_info($id);
}
Is it possible to hide the parameter while redirecting to this url from a view? ie in the view file
// Do something to set the ID
<?php Kohana_Request::post("user_id", $id); ?>
Click
and get the ID like this
public function action_edit() {
$id = $this->request->post("user_id");
get_db_info($id);
}
But the problem I can't access the KOhana_Request instance and get this error
*Non-static method Kohana_Request::post() should not be called statically*
Can someone gives a secured approach to this ?
I think I found a solution by encoding and decoding the parameters.
Since Kohana 3.3 do not allow parameters in controller functions see .
I do this in my view
$user_id = Encrypt::instance()->encode($liste->user_id);
$encode_id = base64_encode($user_id);
$encode_ure_id = urlencode($encode_id);
And from the controller,
$encoded_id = urldecode($this->request->param('uri_id'));
$encode_base_url = base64_decode($encoded_id);
$user_id = Encrypt::instance()->decode($encode_base_url);
If this can help others.

Yii url route with parameters

At the moment i have a glossar controller with an actionAnzeige()-method.
For this action i need GET-paramter named item.
Now i could use this url: www.xy.de/glossar/anzeigen?item=programming
But i want to use this: www.xy.de/glossar/programming
I've added this route to the rules:
'glossar/<item:\d+>'=>'glossar/anzeigen',
and now i can generate the url i want to use:
<?php echo Yii::app()->createUrl('glossar/anzeigen', array('item' => $glossarItem->Url)); ?>
But if i visit the created url, i get a 404 error.
You can use this, which accepts characters or numbers:
'glossar/<item:.+>'=>'glossar/anzeigen',
You have to use w+ instead of d+ since item takes letters instead of digits
'glossar/<item:\w+>'=>'glossar/anzeigen',

Using the Symfony admin generator to let a user manage a subset of record

My first post here, hopefully It will be right! =)
I am creating a site to manage web application development using symfony 1.4 and doctrine.
My records consist for this problem of Project and ProjectFeatures
Now what I want to do is use the admin generator to let users manage the features for one project thru a link constraining all the returned features by project_id, that would look like: http://mysite/member/project/:project_id/features
in my routing.yml configuration, I have:
member_project_feature:
class: sfDoctrineRouteCollection
options:
model: ProjectFeature
module: memberProjectFeature
prefix_path: /member/project/:project_id/features
with_show: true
column: id
with_wildcard_routes: true
project_id is an existing column in the model ProjectFeature,
I will use a custom query to retrieve features only by that project_id.
Now I can generate a url to link to that admin generator module without error using:
url_for('member_project_feature', array('project_id' => $project['id']))
And the routing system does recognise the url:
May 04 14:30:59 symfony [info] {sfPatternRouting} Match route "member_project_feature" (/member/project/:project_id/features.:sf_format) for /member/project/1/features with parameters array ( 'module' => 'memberProjectFeature', 'action' => 'index', 'sf_format' => 'html', 'project_id' => '1',)
But the admin generator can't generate it's links inside it's templates with that prefix_path and returns error InvalidArgumentException with message The "/member/project/:project_id/features/:action/action.:sf_format" route has some missing mandatory parameters (:project_id).
Any idea?
Well I found my answer at this url: http://www.blogs.uni-osnabrueck.de/rotapken/?s=symfony
But I will give it here and shorten it because, stackoverflow is awesome and it should be there for a long time =)
1st - The routing configuration I used in my question is valid.
2nd - You need to add a method in the action file generated by the admin
public function execute($sfRequest)
{
// taken from http://www.blogs.uni-osnabrueck.de/rotapken/?s=symfony
$this->forward404Unless(
$project_id = $sfRequest->getUrlParameter('project_id'));
$this->forward404Unless(
$this->project = Doctrine::getTable('ttcWebProject')->find($project_id));
$this->getContext()->getRouting()
->setDefaultParameter('project_id', $project_id);
if ($id = $sfRequest->getUrlParameter('id'))
{
$this->getContext()->getRouting()->setDefaultParameter('id', $id);
}
$result = parent::execute($sfRequest);
return $result;
}
At this point the url gets generated correctly but here is the last step to get to the end result you most probably want to achieve:
3rd - To get the list by project_id I can either provide a table method in the generator.yml, a default value to the getFilterDefaults or this method in the action file:
protected function buildQuery ()
{
$q = parent::buildQuery();
$rootAlias = $q->getRootAlias();
$q->andWhere("{$rootAlias}.project_id = ?",
$this->getRequest()->getUrlParameter('project_id'));
return $q;
}
I'm not 100% certain about what you're trying to do here, but it sounds like you need the ProjectFeature::toParams method return the project_id.

Resources