I have several links in my Magento template file. If a user is currently viewing a page that is one of the links I would like that link to display the CSS class "active". How could I achieve this?
$routeName = Mage::app()->getRequest()->getRouteName();
$identifier = Mage::getSingleton('cms/page')->getIdentifier();
The above variable $routeName can be used to check whether the current page is a CMS page. The other variable $identifier will output the page identifier.
Magento assigns classes to each page individually
The easiest way to get active states was to to assign each link a class and then write a CSS role for the specific body class and link class.
body.page-a a.class-a {
color:red}
body.page-b a.class-b {
color:red}
<body class="page-b">
<a class="class-a">page a</a>
<a class="class-b">page b</a>
</body>
Create an array that contains all the links (or pages)
$urls = array('home.php', 'about.php', 'contact.php');
Then compare the current url with the one in the array:
<li><a href="about.php" <?php if(in_array($current_url, $urls))
{ echo 'class="active"'; } ?>>About Us</a></li>;
Related
I have created a script that allows admin to set Site title and site email for his CMS, which gets stored in database.
I my views folder I have _main_layout.php file which is the basic layout of my webiste, I want to fetch that site title from database in main_layout in my nav bar.
Below is the code where I want that title:
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="<?php echo site_url('admin/dashboard'); ?>"><?php echo $meta_title; ?></a>
</div>
The meta title here is fetched statically but I want instead site_title to be fetched dynamically from database.
So that admin of CMS can set the site title.
Dont worry from where ever u r setting ur title its not an issue solution is you have title in your database now go to application/helper/ create a helper file like functions_helper.php add it in autoload like
$autoload['helper'] = array('url','functions');
in helper file creat a function like
function get_site_title()
{
$CI =& get_instance();
$CI->load->model("your_model");
return $result = $CI->your_model->getSiteTitle();
}
then call this function from anyfile in your project either its controller/model or view like get_site_title()
and thats it
function add_meta_title ($string)
{
$CI =& get_instance();
$CI->data['meta_title'] = e($string) . ' - ' . $CI->data['meta_title'];
}
currently this is the way i fetch my title from cms helper
and this is done statically from admin controller by this :
$this->data['meta_title'] = '';
in view i write echo $meta_title.
if i load the setting_m , which is my model in cms helper its shows error also i am confused how does the site title gets fetched.
Is it possible to have some sort of pagination within the URL in Concrete 5. I see many CMS's such as Wordpress and Drupal etc that have such a feature.
At the moment my blogs are the following:
/blog?ccm_paging_p_b348=2
and the way I want it to be is:
/blog/page/1 ... /blog/page/2 etc (or something similar)
Any tips or advice would be appreciated
Your only choice is to create a custom page type for your blog page and then a custom controller for that which handles the pagination.
Please see this page:
http://www.concrete5.org/documentation/developers/pages/mvc-approach
And particularly the "Page Types" section under "Controllers". It explains how to create your page type controllers. For them, you can create similar functions that you would for normal single pages, so you can paginate the results there according to the parameters you get from the URL.
This example is for 5.6 and earlier:
<?php
class BlogPageTypeController extends Controller {
public function view($page=1) {
$pageIndex = intval($page)-1;
if ($pageIndex < 0) {
$pageIndex = 0;
}
$pageList = new PageList();
$pageList->setItemsPerPage(25);
$this->set('pages', $pageList->getPage($pageIndex));
}
}
And then you would use the $pages variable in your view to go through the pages:
<?php foreach($pages as $page) : ?>
<h2><?php echo $page->getCollectionName()</h2>
<?php endforeach; ?>
I really wonder how can I do this, I have 3 pages that has the same link going to 1 page, now what I want to do is to have 1 button that is intelligently enough to get which of the 3 pages was used to go to that page and used it as it's link going back to that previous page.
Please if anyone who knows how to do this, help me to get out to this chaos. post some code how to do it in codeigniter. Thank you in advance.
By using a simple javascript to achieve previous button like,
Previous
With the url helper loaded, set the current_url in a hidden field say 'refer_from'.
<input type="hidden" name="refer_from" value="<?php echo current_url(); ?>" />
Get this using Input Class and set this on the anchor link
Previous
NOTE: using window.history.go(-1) will fail and throw a js error, if the user some how lands
directly on the "1" last page. window.history will be empty in that case.
In my case jquery back methods means window.history etc,were not working so,I tried this hope this helps you guys.call this method on click. cheers
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
In controller add:
$data['back'] = $_SERVER['HTTP_REFERER'];
In view add a button and link to $back.
//to get previous url $_SERVER['HTTP_REFERER'];
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
//to redirected to this link
location.assign(redirect_to);
//you can pass static link also to redirected to this link
location.assign('facebook.com');
I don't know the older version, I guess there was such funcionallity but know there is and you should avoid use the accepted answer it may break in many ways.
Know you can use method previous_url.
Just add it where you need and is all done
<div class="container">
<a href="<?= previous_url();?>" class="btn btn-info">
<i class="bi bi-arrow-return-left"></i>
</a>
</div>
Returns the full URL (including segments) of the page the user was previously on.
Due to security issues of blindly trusting the HTTP_REFERER system variable, CodeIgniter will store previously visited pages in the session if it’s available. This ensures that we always use a known and trusted source. If the session hasn’t been loaded, or is otherwise unavailable, then a sanitized version of HTTP_REFERER will be used.
EDIT
Improvements Issue fix
I noticed that the previous_url alone may suit for all scenarios, especially if we have a form which redirects back to the same page; that's because the previous page would be the one that the user was currently, hence will not come back in the desire place (and others solutions would have same issue anyway), a simple solution, and by all means improvable, is the following:
In /app/Controllers/BaseController.php
/// Use this as base redirect
public static $baseRedirect = '/index';
/** #public
* Will check the User position and avoid and URL which aren't desired
* - #example
* Current Page: /news
* Previus : /index
*
* if the user update a form in the current page, which is a POST or GET and the user is
* /news/update and then will go back to the current page now previous_url() will be /news and
* NOT /index , if the user presses back will go to /news again and not /index.
*
* #var array $skip An array with url slugs to check the previous url, if the previous url containts any then skip to fallback
* #var string $baseRedirect : base redirec if fallback is not provided
* #param string|null $fallback use a target url as the desired 'Go Back' URL
*/
public function getPreviousURL(?string $fallback=null)
{
// NOTE: We need the current_url also inside, to check that we don't go back in the same page ;)
$skip = [current_url(), "create", "udate", "delete", "post"];
$prev = previous_url();
foreach($skip as $s) {
if (str_contains($prev, $s)) {
return site_url($fallback ? $fallback : self::$baseRedirect);
}
}
return $prev;
}
Now , in any controller which extends BaseController
class MyController extends BaseController
// ... code
public function view($slug=null)
{
// code
$data = [
// data
'prev' => $this->getPreviousURL(), // this will be available in any Controller
];
echo view('templates/header', $data);
echo view('news/view', $data);
echo view('templates/footer', $data);
}
Additionally you can pass any fallback into the url ;)
$data = [
// data
'prev' => $this->getPreviousURL(fallback: '/home'), // this will be available in any Controller
];
In a view news/view.php
<?php $prev = $prev ??= site_url('/index'); ?>
<div class="container">
<a href="<?= $prev ?>" class="btn btn-info">
G Back <i class="bi bi-arrow-return-left"></i>
</a>
</div>
/*Back button in codeigniter project using jquery */
<button type="button" class="btn btn-primary btn-sm" id= "back">Back</button>
//JQuery of back button
<script type="text/javascript">
$(document).ready(function(){
$('#back').on('click', function(){
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location.href = redirect_to;
});
});
</script>
Is this facebook link populated fully from the DB? Or, is it a physical file with PHP in it? Just, how is this page called?
http://www.facebook.com/profile.php?id=49300915&sk=photos
They probably do something like:
if(isset($_GET['id'], $_GET['sk'])) {
mysql_query("SELECT info, photos FROM users WHERE id = '$id'");
}
I'm trying to ask, how do they include this page? Is it like Drupal / any CMS where the PHP and page is stored in the DB, or is it a physical file on the server? If the latter, what's the best way to get the file (case insensitive URL)?
I would have a class with a single method, which reads 'sk' and runs another method, depending on what it's value is.
One method would be 'photos' which would read 'id' and fetch a photo from the database. It would then run another method, displayPage, which will display a page from that data.
The displayPage method takes a "template" filename and an array of variables to provide to the template. It sets up a smarty object, provides the variables, and instructs it to display the template.
Inside the template, I'd include another template for the global header that's on every page in the site, then i'd have the html page content, using smarty to insert dynamic values, then include a global footer.
Note that i've simplified this system a lot. A real page like that would take me a week to write all the code, since a big website does a lot of stuff just to display a simple page (for example: find out if the logged in user actually has access to the page... i don't have access to the example one you gave).
<?php
// profile.php
class ProfileController
{
public function run()
{
if ($_GET['sk'] == 'photos')
return $this->photosPage();
}
protected function photosPage()
{
$id = (int)$_GET['id'];
$result = mysql_query("select * from photo where id = $id");
$photo = mysql_fetch_object($photo);
$this->displayPage('view-photo.tpl', array('photo' => $photo);
}
protected function displayPage($templateFile, $templateVariables)
{
$smarty = new Smarty();
foreach ($templateVariables as $variableName => $variableValue) {
$smarty->assign($variableName, $variableValue);
}
$smarty->display($templateFile);
}
}
$conntroller = new ProfileController();
$controller->run();
And the smarty code:
<!-- view-photo.tpl -->
{include file='head.tpl'}
<h1>View Photo {$photo->name|escape}</h1>
<img src="{$photo->src|escape}" width="{$photo->width|escape} height="{$photo->height|escape}>
{include file='foot.tpl'}
in the controller i have :
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$this->view->posts = $paginator;
in the view's i have some thing like this :
if ($this->posts != null) {?>
<div id="cities_accord" class="news">
<?php echo $this->partialLoop('partials/post-min.phtml', $this->posts); ?>
</div>
<?php echo $this->paginationControl($this->posts,
'Sliding',
'public/pagination_cont.phtml');
}
the partial/post-min.phtml
<?php
$color = array(1=>'spring',2=>'summer',3=>'autumn',4=>'winter');
?>
<div id='<?php echo $color[$this->partialCounter] ?>' class="accordion_post">
<?php
$link = Digitalus_Uri::get(false, false, array('openCity' =>
$this->id));//$color[$this->partialCounter]));
?>
<h1 class="accordion_post_title"><?php echo $this->title ?></h1>
<p><?php echo $this->teaser ?> <i>read more</i></p>
</div>
the pagination_cont.phtml taken from this link zend ( http://framework.zend.com/manual/en/zend.paginator.usage.html )
will show links that will pass params to the controller to fetch the corresponding whole page which is working alright for now
but i want to change this so that i will be able ajaxify the returned ( i.e. only a single paginated value rather than reloading the whole page ) results how can i do that using jquery and what should i change ..
** EDIT: it would be nice to have a fail-save ,if possible, for browsers(users) that disabled javascript to see the same thing by reloading the page (i.e. keeping the current status for if(javascript_not_enabled ))**
This is what I've done in the past.
First, setup the AjaxContext action helper to enable the html context on your controller action.
Add a .ajax.phtml view that just contains the section of markup that may be replaced via AJAX as well as the pagination control links. You can probably just copy this out of your normal view. Replace that section in your normal view with something like
<div id="reloadable-content">
<?php echo $this->render('controller/action.ajax.phtml') ?>
</div>
This will ensure that your initial and any non-AJAX requests will still include the right content. The <div> id is purely for referencing the loadable block in JavaScript.
Also make sure you include your JS file (using headScript) in the normal view only.
Now, in your JS file, unobtrusively add the appropriate event binding to the paginator links. As you'll be replacing the pagination control section in order to reflect the correct current page and other links, it's probably best to do this using the jQuery live binding. I'm also assuming you'll wrap the pagination control with some kind of identifiable element (<div class="pagination-control"> for example)
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#reloadable-content').load(link.attr('href'), { format: 'html' });
return false;
});
Keep in mind that in using this method, you will lose the ability to navigate the paged requests using the normal back / forward browser buttons. You will also lose the ability to bookmark pages directly (though you could always provide a permanent link to the current page as part of the AJAX loaded content).
You can use something like the jQuery history plugin if you're really concerned but that will require more client-side work.
Another caveat is that the above will only work with pagination links. If you want to use a form with dropdown page selection, you need to add another event handler for the submission.
GOT IT and big Thanks to #Phil Brown :
in the controller int() change the response type to json
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'JSON')
->initContext();
}
// ...
}
public listAtcion() {
// .............
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$post = array();
foreach($paginator as $post ) {
$post[] = $post;
}
$this->view->post = $paginator;
#TODO //add a check here for non-ajax requests (#improvment)
$this->view->posts = $paginator;
}
in one of the views (most probably in the pagination_cont.phtml) on the pagination controller add the ajax links
<?= $this->ajaxLink (
$this->url('cities'=>$this->page_num),array('id'=>'div_id','complete'=>'js_method(json_data)','method'=>post) ,array('format'=>'JSON'));
and add a JavaScript function of js_method(json_data) to modify the div with id = 'div_id' with a json data
function js_method(json_data) {
var content = parse.JSON(json_data);
$('#div_id').html('');
//fill it with the reposnse content some thing like $('#div_id').append(content);
}