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

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.

Related

How to display all oembed fields on custom page with ACF

I should create a page where you can view all videos (oembed field) of a specific custom post type.
Example:
Custom Post Type = Project
Inside Project there are 4 articles and inside each of them 4 videos are uploaded.
So my question is: how can I structure my feature so that it allows me to extract the videos of all the articles and show them in a single page?
Try this code, but change key of your custom video field
$args = [
'post_type' => 'project', // your custom post type
'post_status' => 'publish',
];
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) { $loop->the_post();
$video = get_field('video', get_the_ID()); // check custom field key
print $video;
}
wp_reset_postdata();

how to restrict Yii2 url view get request

Here I like to explain my problem clearly, How can I restrict get request through URL in Yii2
this is my url:
http://localhost/school/backend/web/index.php?r=user%2Fview&id=42
here if I change the view id = 43, it showing the data of id 43, I don't want to get data through url. I want to restrict get request through url or how can I encrypt the id value
If I change my url manager to
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
then am getting url like below
http://localhost/school/admin/user/view?id=42
here also if I change id=43 am getting the data of id 43
How can I do this. Help will be really appreciated.
Assuming the current scenario (let me know if i misunderstood something):
Company can see/add/edit People (that part you already did). Now, each Company can only do actions on your own People, not the others.
One Solution:
In your Company model you must have something like:
public function getPeoples()
{
return $this->hasMany(People::className(), ['id_people' => 'id']);
}
You can add another function just to return the Ids of the People:
public function getPeoplesIds()
{
return ArrayHelper::map($this->peoples, 'id', 'id');
}
Now in your controler you must rewrite your beforeAction function:
public function beforeAction($action){
$id = Yii::$app->request->get('id');
if($id && !Yii::$app->user->isGuest) {
$user = User::findOne(Yii::$app->user->getId());
$company = //Do the logic to get the company's user
if (! in_array($id, $company->peoplesIds) {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
return parent::beforeAction($action);
}
With that, you are checking the $id before runing each action.
first of all you should think about your purpose .
why do you want to prevent user from getting another IDs ?
if they are not authorized to see other IDs you can easily authorize their requests : Yii2-authorization
otherwise , you can use a string key for your table and generate random strings for keys using Yii built in classes .
Yii2-security

Yii appending new route to the exisitng route in url with Yii-bootstrap but working fine with CMenu

am actually having some issue with url routing while using TbMenu widget,i am using the format of /moduleId/ControllerId/ActionId in accessing module Controllers,here is an example
<?php $this->widget('bootstrap.widgets.TbNavbar', array(
'type'=>'inverse', // null or 'inverse'
'brand'=>'mysite',
'brandUrl'=>'#',
'collapse'=>true, // requires bootstrap-responsive.css
'items'=>array(
array(
'class'=>'bootstrap.widgets.TbMenu',
'items'=>array(
array('label'=>'Home','url'=>array('/site/index'), 'active'=>true),
array('label'=>'About', 'url'=>array('/site/page')),
array('label'=>'Contact us','url'=>array('/site/contact')),
),
),
'<form class="navbar-search pull-left" action=""><input type="text" class="search-query span2" placeholder="Search"></form>',
array(
'class'=>'bootstrap.widgets.TbMenu',
'htmlOptions'=>array('class'=>'pull-right'),
'items'=>array(
array('label'=>'Sign in', 'url'=>'/user/auth','visible'=>Yii::app()->user->isGuest),
'---',
[b] array('label'=>'Profile', 'url'=>'/user/user','visible'=>!Yii::app()->user->isGuest, 'items'=>array([/b]
[b]array('label'=>'Settings', 'url'=>'user/user/index'),[/b]
[b]array('label'=>'Logout', 'url'=>'user/user/logout')[/b],
)),
),
),
),
he three last line are the ones that are causing problem,when i try to access those links after clicking on home,page,contact us(using the Site controller actions that are auto-generated by the Yii) the route is appended to the existing url in stead of creating a new url to the module,for example if am on home page(after clicking home it has this as url localhost/mysite/index.php/site/index)**it gives me this url localhost/mysite/index.php/site/index/user/user/index,if i go the same link again with this as url it gives me **localhost/mysite/index/user/user/index/user/user/index if i click again it add another one again and again..but the strange in all is that it works fine with CMenu,here is snippet of CMenu that works fine,
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('//user/auth'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('//user/user/logout'), 'visible'=>!Yii::app()->user->isGuest),
array('label'=>'My profile ', 'url'=>array('/user/user/'), 'visible'=>!Yii::app()->user->isGuest),
),
)); ?>
i am assuming that it might be caused by the fact that those links are submenu but i am not sure since the first in those links is not submenu and has the same problem!thank you again
The TbMenu component is using CHtml::link to display the links...
CHtml::link(label, url, options)
CHtml::link method has one check
if url is an array ... then use controller->createUrl(...) method
if url is a string ... then just return that string.
So, I think, #dInGd0nG suggestion would work.
if not then you should be using array ...something like ( don't forget to prefix / )
array('label'=>'Settings', 'url'=> array('/user/user/index') ),
array('label'=>'Logout', 'url'=> array('/user/user/logout') )

can i type a clean url in drupal and be converted instead into a url with a query string?

i'm creating a drupal site that should include a feature that will turn a clean url into a a url with a query string.
The way it should work would be:
user would type any clean url like www.example.com/hobbies/skiing in the url bar.
here is my problem:
inside the .htaccess i've put this line of code:
RewriteRule ^hobbies/([a-zA-Z0-9-]*) /index.php?hobbies=$1 [NC]
in the drupal, i've created a page with PHP Filter enabled, then typed in
<?PHP echo $_GET['hobbies']; ?>
the RewriteRule should turn www.example.com/hobbies/skiing into www.example.com/index.php?hobbies=skiing but i guess the code doesn't work as expected, or drupal has codes running that either skips the .htaccess command or something.
3.once the url has been translated into a dirty url, the page will display what the value of hobbies is, as the code works when you actually type www.example.com/index.php?hobbies=skiing directly into the url bar.
can you help me with this one?
There's a far easier way to do it, Drupal already keeps path parts aside for later which you can access using the arg() function:
if (arg(0) == 'hobbies' && arg(1)) {
$hobby = arg(1);
}
If your path is an alias though arg() will return the original router path (node/1 etc.) so you'll have to be a bit more inventive:
$parts = explode('/', $_SERVER['REQUEST_URI']);
if ($parts[1] == 'hobbies' && isset($parts[2])) {
$hobby = $parts[2];
}
UPDATE
From your comments you'd be better off making a quick custom module for this:
// Implements hook_menu().
function mymodule_menu() {
$items['hobbies/%'] = array(
'title' => 'A title',
'access arguments' => array('access content'),
'page callback' => 'mymodule_page',
'page arguments' => array(1)
);
return $items;
}
function mymodule_page($hobby) {
return $hobby;
}
That will literally print out what ever is after hobbies/ in the content area of the page

Placeholders in symfony's url_for() helper function

I'm working on an AJAXy autocomplete widget. I'm trying to create a symfony URL with a placeholder, which I can then pass to my Javascript, so that the JS can inject the ID of records it has retrieved via AJAX. For example:
$this->widgetSchema['sons_list'] = new ynWidgetAjaxAutocomplete(
array(
'item_url' => url_for( 'person/edit?id=%' ),
// OR
'item_url' => url_for( 'person/%/edit' ),
)
);
But neither of these works - I am looking for /person/%25/edit, but the first yields /person/edit/action?id=%25 and the second yields /person/%25/action. It does work if I pass a placeholder of digits, but this seems like a narsty hack to me:
$this->widgetSchema['sons_list'] = new ynWidgetAjaxAutocomplete(
array(
'item_url' => url_for( 'person/edit?id=999999999999' ),
)
);
Anyone know a cleaner way? Thanks!
If you want to pass only one parameter, you can probably use url_for('person/edit?id=') and then just append dynamic parameter with js.
update
Another way - how about replacing %25 with js?
The main problem was that the auto-generated action was using $this->getRoute()->getObject(), but symfony wasn't able to resolve the URL to sfDoctrineRoute and was stuck with sfRoute, which doesn't have a getObject() method. I have now adjusted my action to retrieve the record based on the id parameter, and started using url_for( 'person/edit' ), appending ?id=123 in the JS, similar to Darmen. I am satisfied with this.
Good question!
Here is my solution (pass to url number and replace it it JS)
function preview_document(NODE, TREE_OBJ) {
var url_to = '<?php echo url_for(sprintf('#document_preview?id=%s', '-999999'));?>';
$.get(url_to.replace('-999999', $(NODE).attr('id').replace('phtml_', '')), function (data) {
$('#document-viewer').html(data);
});
}

Resources