URI Routing for codeigniter - php

I'm trying to figure out how I should do this. The following controller is for a bio page for each wrestler. Here's an example.
http://kansasoutlawwrestling.com/bio/kid-wonder
Now if you notice there's three links Biography, Wrestling, Appearances.
One question I have is should all three be different functions inside this controller?
If the answer is yes are the links actually correct on the page link?
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Bio extends CI_Controller
{
function index($character = "jfkdlsjl")
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$activeTemplate = $this->sitemodel->getTemplate();
$footerLinks = $this->sitemodel->getFooterNav();
$bodyContent = "bio";//which view file
$bodyType = "main";//type of template
$this->data['activeTemplate'] = $activeTemplate;
$this->data['footerLinks']= $footerLinks;
$this->load->model('biomodel');
if($character !== "jfkdlsjl")
{
if((!empty($character))||(!isset($character))||(trim($character) !== '')||($character !== NULL))
{
$bioArray = $this->biomodel->getCharacterBio($character);
if ($bioArray == "empty")
{
$this->data['bioArray']= array();
}
else
{
if (($bioArray[0]->characters_statuses_id == 2)||($bioArray[0]->characters_statuses_id == 3)||($bioArray[0]->characters_statuses_id == 5))
{
$this->data['bioArray']= array();
}
else
{
$this->data['bioArray']= $bioArray;
$bioPagesArray = $this->biomodel->getBioPages();
$alliesArray = $this->biomodel->getCharacterAllies($bioArray[0]->id);
$rivalsArray = $this->biomodel->getCharacterRivals($bioArray[0]->id);
$quotesArray = $this->biomodel->getCharacterQuotes($bioArray[0]->id);
$this->data['bioPagesArray']= $bioPagesArray;
$this->data['alliesArray']= $alliesArray;
$this->data['rivalsArray']= $rivalsArray;
$this->data['quotesArray']= $quotesArray;
}
}
}
}
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view($activeTemplate[0]->short_name.'/index', $this->data);
}
}
/* End of file bio.php */
/* Location: ./application/controllers/bio.php */
EDIT: I'm really concerned with the biography page link when I'm on the bio page like the link above.
Here's what I have currently for my route: $route['bio/(:any)'] = "bio/index/$1";

It would be the best to have separate controllers for each of the 3 links.
But if you don't want to, and still want the links /appearances/whatever, here's the routing you need to keep it all within the Bio controller:
UPDATE - this is still a bad approach, but it should do.
if ($this->uri->segment(1) == 'bio') {
$route['bio/(:any)'] = "bio/index/$1";
} else {
$route['wrestling/(:any)'] = "bio/wrestling/$1";
$route['appearances/(:any)'] = "bio/appearances/$1";
}
UPDATE 2: you got me confused, but the first solution HAS to work, even the order doesn't matter:
$route['bio/(:any)'] = "bio/index/$1";
$route['wrestling/(:any)'] = "bio/wrestling/$1";
$route['appearances/(:any)'] = "bio/appearances/$1";
bio/kid goes to bio/index/kid
wrestling/kid goes to bio/wrestling/kid
appearances/kid goes to bio/appearances/kid

You currently have this setup:
The functions
function index($wrestlerName = null){ }
function wrestling($wrestlerName = null){ }
function appearances($wrestlerName = null){ }
The links
bio/kid-wonder
bio/wrestling/kid-wonder
bio/appearances/kid-wonder
If you wanted to have the wrestling/kid-wonder and appearances/kid-wonder without the bio at the beginning of the url, you are going to need to create new controllers for wrestling and appearances.
class wrestler extends CI_Controller {
function index($wrestlerId = NULL){
if($wrestlerId != NULL){
}
}
}
class appearances extends CI_Controller {
function index($wrestlerId = NULL){
if($wrestlerId != NULL){
}
}
}

Related

PHP variable usage in different file

here I am again, had before more complicated issue, but now got another (smaller I think).
In template file there's variables in use as "author_id", "authlink", but in controller file doesn't getting author url (but it should).
In template file there's defined variables as authlink and author_id.
Also, in controller file I've included file path where is these variables in use.
<?php
set_include_path(".:/domains/example.com/public_html/.../single-2.php"); //destination to file where's author_id variables either.
function ajax_rental_add_to_cart()
{
if ( STInput::request( 'action' ) == 'rental_add_cart' ) {
$response = array();
$response['status'] = 0;
$response['message'] = "";
$response['redirect'] = '';
$author_id = get_post_field( 'post_author', get_the_ID() );
$authlink = get_author_posts_url($author_id);
if ( $this->do_add_to_cart() ) {
$response['redirect'] = $authlink;
$response['status'] = 1;
wp_send_json($response, 200);
} else {
$message = STTemplate::message();
$response['message'] = $message;
wp_send_json($response, 200);
}
}
}
static function inst()
{
if (!self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
}
STRental::inst()->init();
}
?>
Not sure is that static function inst() related, but pasting anyway. Problem is, on variable $response['redirect'] = $authlink; I should be redirected to https://example.com/author/author_id , but I'm getting redirected only into https://example.com/author/
It seems like controller file doesn't getting anyway author_id, maybe because after redirect it loosing author_id and that's why I'm not redirected to right way? Should I store author_id somehow and use it again in this file?
P.S. If I'm using same redirection in template file (not controller) - works perfectly, but then bypassing all date checks, so that's why I'm still messing up with controller file.

How can I use callback functions in groceryCrud for the view record page?

I do not know how to set a callback function for the view record page in codeigniter.
I use the callback_column function and it does what I need in the grid view, but on the view record page it does not work.
I searched their site and forum and did not found anything that could help me.
My code looks like:
$zeus = new grocery_CRUD();
$zeus->set_theme('bootstrap');
// $zeus->set_language('romanian');
$zeus->set_table('programari');
$zeus->columns(array('id_client', 'id_sala', 'denumire', 'numar_persoane', 'observatii'));
$zeus->callback_column('id_sala',array($this,'_test_function'));
$cod = $zeus->render();
$this->_afiseaza_panou($cod);
public function _test_function($row, $value)
{
return '0';
}
write this lines in \libraries\Grocery_CRUD.php
at line number 3530
protected $callback_read_field = array();
than put this function after constructor call
public function callback_read_field($field, $callback = null)
{
$this->callback_read_field[$field] = $callback;
return $this;
}
//Now update this function to manage the field outputs using callbacks if they are defined for the same
protected function get_read_input_fields($field_values = null)
{
$read_fields = $this->get_read_fields();
$this->field_types = null;
$this->required_fields = null;
$read_inputs = array();
foreach ($read_fields as $field) {
if (!empty($this->change_field_type)
&& isset($this->change_field_type[$field->field_name])
&& $this->change_field_type[$field->field_name]->type == 'hidden') {
continue;
}
$this->field_type($field->field_name, 'readonly');
}
$fields = $this->get_read_fields();
$types = $this->get_field_types();
$input_fields = array();
foreach($fields as $field_num => $field)
{
$field_info = $types[$field->field_name];
if(isset($field_info->db_type) && ($field_info->db_type == 'tinyint' || ($field_info->db_type == 'int' && $field_info->db_max_length == 1))) {
$field_value = $this->get_true_false_readonly_input($field_info, $field_values->{$field->field_name});
} else {
$field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
}
if(!isset($this->callback_read_field[$field->field_name]))
{
$field_input = $this->get_field_input($field_info, $field_value);
}
else
{
$primary_key = $this->getStateInfo()->primary_key;
$field_input = $field_info;
$field_input->input = call_user_func($this->callback_read_field[$field->field_name], $field_value, $primary_key, $field_info, $field_values);
}
switch ($field_info->crud_type) {
case 'invisible':
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
case 'hidden':
$this->read_hidden_fields[] = $field_input;
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
}
$input_fields[$field->field_name] = $field_input;
}
return $input_fields;
}
than call same as other callback functions
As far as I'm aware GroceryCRUD doesn't provide callbacks or another means of overriding the default output in the view state.
The solution to customising this would be to create a custom view to which you will insert the data from your record. This way you can customise the layout and other presentation.
What you would then do is unset the default read view with:
$crud->unset_read();
And add a new action where there are details on how to do this here.
What to do with the new action is point it to a URL that you map in routes.php if necessary and handle it with a new function in your controller. You'll either have to write a model function to retrieve the data since this isn't passed from GC or you can use the action to target a callback and feed $row to it via POST or something so that the data for the record is accessible in the view. (Look at the example in the link above).

View Not Rendered Codeigniter HMVC

I am trying to make a CRUD Module in Codeigniter HMVC but I seem to be missing something in the process. Here is what I am facing.
I have a News Module which has a Manage function
function manage(){
$grid = Modules::run('Crud/renderGrid', 'News' , 'News management');
}
Render Grid Function
function renderGrid($module , $page_title){
$data['page_title'] = $page_title; //Dynamic
$data['module'] = $module;
$data['view_module'] = 'Crud';
$data['displayfields'] = Modules::run($module.'/get_displayfields');
$data['key'] = Modules::run($module.'/get_key');
$data['rows'] = Modules::run($module.'/get' , $data['key']);
$data['view_file'] = 'manage';
$this->load->module('dashboard');
$this->dashboard->show_dashboard($data);
}
Here, the show_dashboard function just loads up a template layout with a desired view in it.
function show_dashboard($data = NULL){
if($data == NULL){
$data['view_file'] = "manage";
$data['page_title'] = 'Sigma Web Solutions';
}
$this->load->module('templates');
$this->templates->admin($data);
}
Templates->admin
function admin($data){
$this->load->view('admin' , $data);
}
The View (omitting the header n Footer)
<?php
if (!isset($view_file)) {
$view_file = "";
}
if (!isset($view_module)) {
$module = $this->uri->segment(1);
}
if (($view_module!="") && ($view_file!="")) {
$path = $view_module."/".$view_file;
$this->load->view($path);
}
?>
Now, when I try the url news/manage, it gives me a blank page with no source code in it. But when I try something like
crud/renderGrid/news/sometitle/ it works just fine.
Kindly point out what did I miss here. Thanks.
Working Solution:
Thanks to wolf I added a route
$route['managenews']= 'crud/renderGrid/news/News';
And it works like charm. But why do I need a route here? Shouldn't it just work. And this means for every module I need to have 4 entries in my route file for the CRUD system to work. can anyone suggest a better method?

Activation Routes and controller

What I'm trying to do is figure out IF I am going to need a route for this situation. After the user registers for my site they are sent a verification email in which they click a link and sent to the activate controller where it verifies that the first parameter is numeric and the second is a string and then if they match together with a record in the db then the user was successfully activated.
Here's what I have for my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Activate extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('auth');
}
public function index()
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$x = 0;
if(($param1 !== NULL)&&($param2 !== NULL))
{
//params not null yay..
if((isset($param1))&&((trim($param1) !== '')||(!empty($param1))))
{
if(!is_numeric($param1))
{
$x++;
}
}
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
if(!preg_match('/^[A-Za-z0-9]+$/', $param2))
{
$x++;
}
}
if($x !== 0)
{
$bodyContent = $this->config->item('defaultTemplate') ."error_page";
}
else
{
$bodyContent = $this->config->item('defaultTemplate') ."/usermanagement/forms/activate";//which view file
}
}
else
{
$bodyContent = "error_page";
}
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view($this->config->item('defaultTemplate') .'/usermanagement/index', $this->data);
}
}
/* End of file register.php */
/* Location: ./application/controllers/register.php */
My urls look like siteurl.com/activate/10000/7dfdao87fda8f7
if your URL will be http://example.com/activate/account/12345/abcde then you won't need a route.
if it will be http://example.com/activate/12345/abcde then you will need a route like so:
$route["activate/(:num)/(:any)"] = "activate/account/$1/$2";
that is taking for granted that the activate controller has a method called account which you use to activate accounts.
what this does is takes the first bracketed value (which is a number) and inserts it into the place of $1, then takes the second bracketed value (which is any character) and inserts it in the place of $2
you then need to use the following controller / method:
class Activate extends CI_Controller {
public function account ($var1, $var2) {
// ...process vars etc
}
}
if you use the index method, you'd need to pass the variables to it and then call it in the route :
class Activate extends CI_Controller {
public function index ($var1, $var2) {
// ...process vars etc
}
}
$route["activate/(:num)/(:any)"] = "activate/index/$1/$2";
this is because by changing it to activate/$1/$2you are telling it to look for the method in $1, not the index method.

Parameters for activation page

I am just completely stumped at this and so is my buddy who created this template system.
I have a registration page that sends the user an email with a link to the account activation page in which they must fill out there password to confirm. Inside the link is their user_id and a random string for a registration key.
Here's what I normal url would look like :
kansasoutlawwrestling.com/kowmanager/activate/10000/da54d6fad5fa5fadf
What I want to do is if either of these statements are true then it shows my 404 error page:
Doesn't have the user_id in the url
Doesn't have the registration key in the url
Doesn't have either the two parameters in the url
Activate Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Activate extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('kow_auth');
}
public function index($param1 = NULL, $param2 = NULL)
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '<script src="http://www.kansasoutlawwrestling.com/kowmanager/assets/js/activatevalidate.js"></script>';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
$x = 0;
if(($param1 !== NULL)&&($param2 !== NULL))
{
//params not null yay..
if((isset($param1))&&((trim($param1) !== '')||(!empty($param1))))
{
if(!is_numeric($param1))
{
$x++;
}
}
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
if(!is_string($param2))
{
$x++;
}
}
}
else
{
$x++;
}
if($x !== 0)
{
$bodyContent = "error_page";
}
else
{
$bodyContent = "activate_form";
}
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->load->view('usermanagement/index', $this->data);
}
function activate_submit()
{
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|alpha_numeric');
$user_id = $this->uri->segment(3);
$registration_key = $this->uri->segment(4);
if (($registration_key == '') OR ($user_id == ''))
{
echo json_encode(array('error' => 'yes', 'message' => 'URL was not complete!'));
}
else
{
if (!$this->form_validation->run())
{
echo json_encode(array('error' => 'yes', 'message' => 'There was a problem submitting the form! Please refresh the window and try again!'));
}
else
{
if ($this->kow_auth->activate_user($user_id, $registration_key, $this->input->post('password')))
{
echo json_encode(array('sucess' => 'yes', 'message' => 'Your account has been successfully activated!'));
}
else
{
echo json_encode(array('error' => 'yes', 'message' => 'The activation code you entered is incorrect or expired!'));
}
}
}
}
}
/* End of file activate.php */
/* Location: ./application/controllers/activate.php */
Routes:
$route['activate/:num/:any'] = 'activate/index/$1/$2';
$route['404_override'] = 'error';
Here's what I'm getting for each of those instances:
kansasoutlawwrestling.com/kowmanager/activate - correct
kansasoutlawwrestling.com/kowmanager/activate/10000/ - correct
kansasoutlawwrestling.com/kowmanager/activate/10000/271cce33ab11ced5fd10aeca41323a3c - incorrect should be showing the activate form
EDIT : Anybody have any ideas because it just seems like nothing is working.
I'll start by simplifying a bit the params checking:
$this->error = FALSE;
if(NULL != $param1 AND NULL != $param2)
{
if(!is_numeric($param1) OR (string)trim($param2)!= '')
{
$this->error = TRUE;
}
}
else
{
$this->error = TRUE;
}
$this->data['bodyContent'] = $this->error? 'error_page' : 'activate_form';
It's late here so I might messed up something, but basically:
if both params are null, set $error to TRUE (they don't have to be null);
if at least one isn't null:
- if param1 isn't numeric (userid) or
- if param2 isn't a string (nor even an empty one), $error is again TRUE.
In the end, if error is FALSE (as initialized), we pass the "activate_form" value to the view, else (i.e. if any of the above condition caused the error to be set to TRUE), we pass the "error_page" value.
Also, as per documentation, custom routes should go after fixed ones:
$route['404_override'] = 'error';
$route['activate/(:num)/(:any)'] = 'activate/index/$1/$2';
Out of curiosity...what happens if you remove the following line?
if(!is_string($param2))
And you just have:
if((isset($param2))&&((trim($param2) !== '')||(!empty($param2))))
{
$x++;
}
You dont need to create a new controlller/module for account activation, simply add a new method inside your existing auth controller/module.
IF you setup a route with conditions and they fail, your shown an error or 404.
class Auth extends CI_Controller
{
public function __construct(){parent::__construct();}
/**
* Activate user account
* $route['activate/(:num)/(:any)'] = 'auth/activate/$1/$2';
*/
public function activate($uid, $code)
{
//if need be, double check
if(!$uid OR !$code){show_404();} //BOTH need to exists
//if $route['activate/(:num)/(:any)'] = 'auth/activate/$1/$2'; FAILS CI will show error or 404
//grab $code and $uid and seek a match from DB, if failure do your own errors.
}
}
I would suggest removing the user id from the uri segment and make the activation code a UNIQUE db constraint so you only have to query for that.
Take a look at Tank Auth
It is a CI library that already does this, but with a key difference, you don't want to pass more than you have to. So just generate a HASH (encrypted for instance), that lets you find the userid & activate at the same time.
It is less checking and less issues with copy & pasting URL. Also eliminates having to do all this extra checking of ID validity + hash validity.
But as I said, look at the tank auth code, and pull out what you need for the activation part, it's fairly straight forward, and already for CI.

Categories