codeigniter, how to use url segment to direct to the view - codeigniter

I am a newbee to codeigniter
I have a website with three pages. (Home about Contact)
I want to put an anchor to each of them and
catch last segment using $this->uri->segment() in controller's index function.
Then using a switch I want to direct to exact pages.
This is one of my anchor:
<h3 id="anchor_storefront"><?php echo anchor('jstorecontroll/home', 'Home'); ?></h3>
And this is my code in index at controller:
switch( $this->uri->segment(2) )
{
case "":
case "home":
$this->load->view('public/home');
break;
}
Can an expert guide me?
Thanks

How about just having a function for each page? This follows CodeIgniter's usual URI pattern example.com/class/function/id/ - something like this:
class Jstorecontroller extends CI_Controller
{
function index()
{
//Do what you want... load the home page?
}
//Load the 'home' page
function home()
{
$this->load->view('public/home');
}
//Load the 'about' page
function about()
{
$this->load->view('public/about');
}
//Load the 'contact' page
function contact()
{
$this->load->view('public/contact');
}
}
Routing can be used to map URLs: To map jstorecontroll as the first segment and anything as the second segment to the index function in your jstorecontroll controller, you could use this route (in application/config/routes.php):
$route['jstorecontroll/(:any)'] = "jstorecontroll/index/$1";
You may want to use regex to restrict what is mapped though, for example:
$route['jstorecontroll/([a-z]+)'] = "jstorecontroll/index/$1";
You could then have a function in your controller that would filter through and load the corresponding page. However, be wary of the user input - don't trust them! Make sure you sanitise the input.
class Jstorecontroll extends CI_Controller
{
function index($page = FALSE) //Default value if a page isn't specified in the URL.
{
if($page === FALSE)
{
//Do what you want if a page isn't specified. (Load the home page?)
}
else
{
switch($page)
{
case "home":
$this->load->view('public/home');
break;
case "about":
$this->load->view('public/about');
break;
case "contact":
$this->load->view('public/contact');
break;
}
}
}
}
The use of the above route may produce undesired results if you have other function in this controller that you want to be called from a URI, they won't be called but instead mapped as a parameter to the index function. Unless you look at changing (or adding) the routes, or you could look into remapping functions. Personally, I'd just use a function for each page!

Related

How to dynamically handle Laravel routes using variable in slug

I want to have a route entry that dynamically handles requests based on the slug in the URL. I tried the code below, but the closure seems to be getting in the way. I replaced the closure with controller actions, too, and tried other options without success. The best I came up with thus far is below:
$bladeFiles = [
"about-us",
"join",
"contact",
];
foreach ($bladeFiles as $thisView) {
Route::get($thisView, function () {
global $thisView;
if (View::exists($thisView)) {
return view($thisView);
} else {
return redirect()->route('homepage');
}
})->name($thisView);
}
The issue with the above snippet is that global $thisView is always null inside the closure.
Thoughts?
Try passing the $thisView through with the use:
$bladeFiles = [
"about-us",
"join",
"contact",
];
foreach ($bladeFiles as $thisView) {
Route::get($thisView, function () use ($thisView) { // <-- here
if (View::exists($thisView)) {
return view($thisView);
} else {
return redirect()->route('homepage');
}
})->name($thisView);
}
Hello i'm doing something very similar to what you want
Route::get('pages/{pageName}',function($pageName){
if(view()->exists('pages.'.$pageName)){
return view('pages.'.$pageName);
} else {
return redirect('/');
}
});
so what i'm doing is i'm having a folder with the name pages
i write the views into that folder with the slug names like contact-us.blade.php
when i go to the route "pages/contact-us" it searches for that view in the folder
if it exists it returns the view else just redirect to the home page
the only difference in my code that you will have to call the routes like that
{{url('pages/"$pageName"')}} instead of {{rout($pageName)}}
i hope my code helps

codeigniter child function after submit parent function

In my project I have a controller call load and it has a fuction call search() that has a form, i want to submit this form in a child function of search() like this,,
localhost/ci/index.php/load/search
to
localhost/ci/index.php/load/search/something/
how can i do this after submission a form?
this is my contoller like
class Load extends CI_Controller {
function search() {
$this->load->view('search');
}
function something() {
$this->load->view('something');
}
}
This is not child function something()
You can define routes as per your requirements.
After search function call , you can use redirect() method, that will redirect to your route like 'base_url/controller/search/searchresult/'.
Routes.php
$route['Load/search/searchresult'] = 'Load/something';
Load Controller code :
class Load extends CI_Controller {
function search() {
$this->load->view('search');
// after form submission
redirect('Load/search/searchresult');
}
function something() {
$this->load->view('something');
}
}
This is not a child function of search function so you can call it like
localhost/ci/index.php/load/something/
Add this url to your form action and your form will be submitted to something() function
For clarity: localhost/ci/index.php/load/search/something/ does this...
Enters search() method of Load and provides something as a parameter e.g. search($param = 'something') (this is not correct syntax but just for show).
function search($term = null) {
if (is_null($term)) {
// user hasn't searched
} else {
// user searched for $term e.g. something
}
}
The only way you can achieve what you want is to either use the above somehow to your advantage knowing that /something will have to be the search parameter. Or you can use routing as another answerer suggested.

Passing Route Parameters to Filters when Using RESTful Controllers

I have searched around for long but nothing can quite fit my problem.
I am using RESTful controllers on my site. For some controller actions, some filters are needed and with this i do something like (i use the beforeFilter() function in the constructor):
<?php
class PostController extends BaseController {
public function __construct()
{
$this->beforeFilter('auth',array('only'=>array('getCreate','postCreate','getEdit','postEdit','postAddComment')));
$this->beforeFilter('csrf',array('only'=>array('postCreate','postEdit')));
// $this->beforeFilter('auth_post_edit', array('only'=>array('postEdit','getEdit')));
}
public function getIndex
{
$posts = Post::all();
return View::make('home')->with('posts',$posts);
}
public function getCreate()
{
return View::make('posts.create');
}
...
For the commented filter, however, it is meant to ensure that only the author of a post can edit the post, so i need to pass the post_id which is passed as a URI parameter, to the filter(or access it from the filter).
Some link showed how i can access parameters from the filter using the $route->getParameter('param') in the filter, but the problem is that because i have not even named my parameters(they are named in the controller actions), i am not able to access them from the filter using the above method.
So, how can i access route parameters from within the filter, or/and how do i name route parameters in RESTful controllers(not in their actions)?
You could use in your filter the Request::segment()
Route::filter('foo', function()
{
$param=Request::segment(2); //if the parameter is on the 2nd uri fregment.
$post=Post::find($param);
if ($post->author_id != Auth::user()->id)
{
return App::abort('404'); //or whatever
}
});

Custom Error Pages for particular controllers in CodeIgniter

If we call a method abc() within a controller named Example. Suppose abc() is not present in Example controller.
In such cases i need to display a custom error message instead of
404 Page Not Found
The page you requested was not found.
for this particular controller only.
I know we can set custom error pages, but it applies to all controller.
I need to use it with one controller only.
For Eg:
class Example extends CI_Controller
{
function index()
{
echo "index page";
}
function xyz()
{
echo "xyz page";
}
}
if i call example/xyz it displays output as 'xyz page'
but if i call example/abc it show page not found error. (i need custom message for this controller only).
Thank You...
You can do something similar to below. If the method exists call it otherwise display your own error message.
function _remap( $method )
{
// $method contains the second segment of your URI
if(method_exists($this, $method ) )
{
$this->$method();
}
else
{
//your custom coding here
}
}

CodeIgniter - dynamic pages - default controller url

edit
my solution in routes.php:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
and in my site conroller:
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
THX to YAN
question:
so i wrote a little CMS with CodeIgniter. The admin can create sites. the site opens automatically when the segment of the url is like one in the DB. eg mysite.com/sites/about will call the "About" site. this works fine.
now i got a problem with my URL. i want this url
http://www.mysite.com/sites/about
turns to this:
http://www.mysite.com/about
the problem is, that i cannot use the routes.php and set wildcards for each site. (because they are dynamic and i dont know wich site the customer will create - and i dont want to edit the routes.php file for each site he will create - this should be done automatically)
the problem is i got other fix controllers too, like news, gallery or contact:
mysite.com/news, mysite.com/gallery, ...they work fine
so here is my Site Controller:
class Sites extends Public_Controller {
public $site;
public $url_segment;
public function _remap($method)
{
$this->url_segment = $this->uri->segment(2);
$this->load->model('sites_model');
$this->site = $this->sites_model->get_site($this->url_segment);
if($this->site !== FALSE)
{
$this->show_site($this->site);
}
else
{
show_404($this->url_segment);
}
}
public function show_site($data)
{
$this->template->set('site', FALSE);
$this->template->set('site_title', $data['name']);
$this->template->set('content',$data['content']);
$this->template->load('public/template','sites/sites_view', $data);
}}
and this is the Site_model who checks the database...if the url_segment fits the title in the DB:
class Sites_model extends CI_Model {
public function get_site($site_url)
{
if($site_url != ""){
$this->db->where('name', $site_url);
$query = $this->db->get('sites', 1);
if($query->num_rows() > 0){
return $query->row_array();
}
else
{
return FALSE;
}
}else{
return FALSE;
}
} }
i think i need something who checks if the controller exists (the first segment of the url) when not call the Site controller and check if the site is in the DB and when this is false then call 404.
any suggestions how this can be solved?
btw: sry for my english
regards GN
You can handle routes.php in the following way, just keep the (:any) value last:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
In your sites controller route to the specific site using the data from the URL.
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
I am having trouble understanding the full intent of the question, but, from what I can tell, don't you simply need to add:
if ($this->uri->segment(1) != 'sites')
... // handle malformed URL

Resources