codeigniter admin panel automatic page creation - php

I want to create one controller file which is creating automatically a function if i create a menu dynamically and also want to create view page which is connencted to this main controller.. how to do that?
Current code:
public function our_history()
{
$data['category']= $this->menu_model->getCategory('$lang');
$data['subcategory']= $this->menu_model->getSubCategory('$lang');
$this->load->view('vwMain',$data);//Left Menu }
}

Follow below steps Hope that makes sense.
-- Admin section --
/*content.php -- controller starts here */
class Content extends VCI_Controller {
# Class constructor
function __construct()
{
parent::__construct();
$this->load->model('content_model');
}
/*
Add page logic
*/
function edit_page($id = null)
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
//Set the view caption
$view_data['caption'] = "Edit Content";
//Set the validation rules for server side validation
// rule name editcontent should be defined
if($this->form_validation->run('editcontent')) {
//Everything is ok lets update the page data
if($this->content_model->update(trim($id))) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
/*
Edit page logic
*/
function add_page()
{
$this->_vci_layout('your_layoutname');
$this->load->library('form_validation');
$view_data = array();
$view_data['caption'] = "Edit Content";
if($this->form_validation->run('editcontent')) {
// after passing validation rule data to be saved
// editcontent rule must be defined in formvalidations file
//Everything is ok lets update the page data
if($this->content_model->add()) {
$this->session->set_flashdata('success', "<li>Page has been edited successfully.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
} else {
$this->session->set_flashdata('error', "<li>Unknown Error: Unable to edit page.</li>");
$this->output->set_header('location:' . base_url() . 'content/manage_content');
}
} else {
$page = $this->content_model->get_content_page(trim($id));
$view_data["id"] = $page->id;
$view_data["page_title"] = $page->page_title;
$view_data["page_menu_slug"] = $page->page_menu_slug;
$view_data["page_name"] = $page->page_name;
$view_data["page_content"] = $page->page_content;
$view_data["status"] = $page->status;
$this->_vci_view('content_editpage', $view_data);
}
}
}
/**
* content.php -- controller ends here
*/
/*
Content_model starts here
*/
class Content_model extends CI_Model {
// update logic goes here
function update($id = null) {
if(is_null($id)) {
return false;
}
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->update('content', $data);
return true;
}
// Add logic goes here
function add() {
$data = array(
'page_title' => htmlspecialchars($this->input->post('page_title',true)),
'page_name' => htmlspecialchars($this->input->post('page_name',true)),
'page_content' => $this->input->post('page_content',true),
'page_menu_slug' => htmlspecialchars($this->input->post('page_menu_slug',true)),
'status' => htmlspecialchars($this->input->post('status',true))
);
$this->db->where('id', $id);
$this->db->insert('content', $data);
return true ;
}
}
/*
Content_model ends here # Admin section changes ends here
*/
-- Add view files also to admin section content_editpage.php
Now go to your routes.php file for front section --
add below line at last --
$route['(:any)'] = 'page/view_usingslug/$1';
This will be for all urls like --- http://yourdomainname/your_slug_name
// create again a controller in front section page.php --
class page extends VCI_Controller {
function __construct()
{
parent::__construct();
}
function view_usingslug($slug='')
{
// retrieve the data by slug from content table using any model class and assign result to $view_dat
$this->_vci_view('page',$view_data);
//page.php will be your view file
}
}

Suppose Your URL is
www.example.com/controllername/methodname/menutitle1
or
www.example.com/controllername/methodname/menutitle2
So this is how you handle these pages.
public function method()
{
$menutitle = $this->uri->segment(3);
$query = $this->db->get_where('TableName',array('Menutitle'=>$menutitle))
$data['content'] = $query->row()->page_content;
$this->load->view('common_page',$data);
}

Related

Pass the value from a Controller to the view

I created a form and passed the values for name and picture from the form. The value is accessed from the Upload controller as follows:
$data = array(
'title' => $this->input->post('title', true),
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
return $data;
I need to pass these values to the view so, I modified the above code as:
class Upload extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function input_values(){
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data); }
function add(){
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
//logo image upload
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
}
But I am able to get only the value of title. Following error occurs for both name and title:
Message: Undefined variable: name
I have accessed the variables from the view as follows:
<?php var_dump($title)?>
<?php var_dump($name)?
<?php var_dump($picture)?>
so, this part is where you get the post data and load view (contain the upload form)
public function input_values() {
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data);
}
then this part is handle the post request from the upload form:
function add() {
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
and this part is where you upload the file
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
when you call add() function, it call input_values() function then load views then the next line of codes won't be executed (cmiiw).
so, maybe you want to change with this :
public function index() {
if ($this->input->post()) {
// then handle the post data and files tobe upload here
// save the post data to $data, so you will able to display them in view
} else {
// set the default data for the form
// or just an empty array()
$data = array();
}
// if the request was not a post, render view that contain form to upload file
$this->load->view('nameOfTheView', $data);
}

Cannot use custom library in CodeIgniter 3

I want to use https://www.verot.net/php_class_upload_download.htm library in my project for resizing images. However, when I submit form it gives this error
I have loaded the library in the autoloader and I renamed library to "my_upload" and gave the same class name.
However, I do not know why this error occurs.
And here is my controller:
<?php
class Blog extends CI_Controller{
function __construct() {
parent::__construct();
}
public function add() {
if(!$this->session->userdata('logged_in')) {
$this->session->set_flashdata('not_loggedin','<div class="alert alert-success text-center">Please Login</div>');
redirect('login');
}
$data['title'] = 'Ədd nyus';
$data['author'] = $this->Blog_model->get_author();
$data['category'] = $this->Blog_model->get_category();
$this->load->view('templates/header');
$this->load->view('blog/add', $data);
$this->load->view('templates/footer');
}
public function create() {
if(!$this->session->userdata('logged_in')) {
$this->session->set_flashdata('not_loggedin','<div class="alert alert-success text-center">Please Login</div>');
redirect('login');
}
//insert image
$now = date("YmdHis");
$this->my_upload->upload($_FILES["userfile"]);
if ( $this->my_upload->uploaded == true ) {
$this->my_upload->allowed = array('jpg|png');
$this->my_upload->file_new_name_body = 'image_resized' . $now;
$this->my_upload->image_resize = true;
$this->my_upload->image_ratio_fill = true;
$this->my_upload->image_x = 360;
$this->my_upload->image_y = 236;
// $this->my_upload->image_ratio_y = true;
$this->my_upload->process('C:\xampp\htdocs\edu-center\assets\img\blog');
if ( $this->my_upload->processed == true ) {
$this->my_upload->clean();
$post_image = $_FILES["userfile"]["name"];
}
} else {
$post_image = '';
}
//insert the user registration details into database
$randnum = mt_rand(100000,999999);
$slugtitle = mb_strtolower($this->input->post('title_az'), 'UTF-8') . '-' .$randnum;
$slug = url_title($slugtitle);
$post_image = str_replace(' ', '_', $post_image);
$post_image = preg_replace('/_+/', '_', $post_image);
date_default_timezone_set('Asia/Baku');
$data = array(
'title_az' => strip_tags($this->input->post('title_az')),
'title_rus' => strip_tags($this->input->post('title_rus')),
'author_id' => $this->input->post('author_id'),
'category_id' => strip_tags($this->input->post('category')),
'body_az' => $this->input->post('body_az'),
'body_rus' => $this->input->post('body_rus'),
'date' => date("d-m-Y"),
'news_slug' => $slug,
'img' => $post_image
);
$this->Blog_model->add_news($data);
$this->session->set_flashdata('changed_msg','<div class="alert alert-success text-center">Ваши изменения были сохранены!</div>');
redirect('blog');
}
Where can be the problem?
imho the best way is to create a third party library for that
copy your class into your folder application/third_party/upload/
and in your controller you simply inlcude this file like:
require_once(APPPATH."third_party/upload/my_upload.php");
$objUpload = new my_upload($_FILES);
If you really want a library for that try the following:
The problem is your library gets instantiated by CI - you don't really have control over the constructor
the only way you could do is to include a "wrapper" library
e.g.
<?php
require_once(APPPATH."libraries/my_upload.php");
class Uploadwrapper_library
{
public function get($files)
{
return new my_upload($files);
}
}
in your controller you could do
$this->load->library("uploadwrapper_library");
$objMyUpload = $this->uploadwrapper_library->get($_FILES);
Well if you look at the file - system/libraries/Upload.php it's constructor requires a parameter...
public function __construct($config = array())
So with your MY_Upload class which is CI's way to allow you to override core classes, you need to follow suit with the class you are extending.
You've not shown your constructor so I don't know what you have attempted with your constructor...

Role base access control system for admin and super_admin

I am trying to get this result -> Use access control logic for two user types: administrators and super administrators.
Administrators will have read access to all records within the system however they will have edit/delete access to only those records that are created by them.
Super administrators will have read/edit/delete access to all records. In this case what should i use? if any one know how to give Roll back accessing control in simple manner in above case then please tell me how to do this?
after login from admin_login.php my page comes here...
this is my controller page..
listing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Listing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('student');
$this->load->helper('url');
$this->load->helper('form');
$s = $this->session->userdata('admin_id');
log_message('error', 'Some variable did not contain a value.');
}
public function index()
{
$s = $this->session->userdata('admin_id');
$this->load->model('student',$s);
//$data['result'] = $this->student->listing();
$students = $this->student->listing();/////new line delete [resulet]time 5:42 29/03/16
//$this->load->view('list_view',$data); //// change here time 5:52 29/03/16
$this->load->view('list_view',array('students'=>$students)); /////listing->list_view name change
}
public function delete($id)
{
$result = $this->student->delete_operation($id);
$s = $this->session->userdata('admin_id');// session data call.
//$data['result'] = $this->student->listing();
$students = $this->student->listing();///new line 30/03 1230pm// change for list_view
$this->load->view('list_view',array('students'=>$students));///same as above//change for list_view
//$this->load->view('list_view',$data); ////////////////////////listing->list_view name change
}
public function edit($id)
{
if($id)
{
$s = $this->session->userdata('admin_id');
$result = $this->student->edit_record($id);
$data['action'] = 'edit';
$data['student_id'] = $result[0]->student_id;
$data['student_name'] = $result[0]->student_name;
$data['student_email'] = $result[0]->student_email;
$data['student_address'] = $result[0]->student_address;
$data['subject'] = $result[0]->subject;
$data['marks'] = $result[0]->marks;
}
$this->load->view('edit_student',$data);
}
public function add_student()
{
//$s['user'] = $this->session->userdata('admin_id');//get session data // new line30/03/16
$data['student_id'] = '';
$data['student_name'] = '';
$data['student_email'] = '';
$data['student_address'] ='';
$data['subject'] = '';
$data['marks'] = '';
//$data['admin_id']=''; //new line 12:39 30/03/16
$this->load->view('edit_student',$data);
}
public function add()
{
$data = array(
'student_name' => $this->input->post('txt_name'),
'student_email' => $this->input->post('txt_email'),
'student_address' => $this->input->post('txt_address'),
'subject' => $this->input->post('subject'),
'marks' => $this->input->post('marks'),
'admin_id' => $this->input->post('admin_id')//new line 12:39 31/03
);
$result = $this->student->add_record($id,$data);
header('location:'.base_url().'index.php/listing');
}
}
Probably the best way would be to use some roles in your system, for instance you can use the Ion auth library:
http://benedmunds.com/ion_auth/
With this you can define user groups (e.g.: user,administrator,superadministrator)
you can check the in_group() part of the manual to see how it works.
An example function to let you get some idea how can you check the record deleting:
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->ion_auth->in_group('administrator', $logged_in_user_id)) {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->ion_auth->in_group('superadministrator', $logged_in_user_id)) {
return true;
}
// other users cannot delete the record
return false;
}
You still can use this example as base of functions.
usage in your code:
public function delete($id)
{
$logged_user_id = $this->session->userdata('admin_id');
if(!hasDeleteRight($id, $logged_user_id))
{
return false;
}
//....your delete record code
update:
permission check without ion auth, only with session data and separated login (not preferred way):
in the super admin login code you can put the permission into session:
function super_admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'superadministrator');
}
}
similar for normal administrator login:
function admin_login() {
//your log in code
if($login_success) {
$this->session->set_userdata('permission', 'administrator');
}
}
function hasDeleteRight($record_author_id, $logged_in_user_id) {
// if the user has administrator role we check if he is the author of the record he can delete it
if ($this->session->userdata('permission') == 'administrator') {
if($record_author_id == $logged_in_user_id) {
return true;
}
// if the user has superadministrator role he anyway can delete the record
} elseif ($this->session->userdata('permission') == 'superadministrator') {
return true;
}
// other users cannot delete the record
return false;
}

Codeigniter How to redirect back to previous page without losing data

here is my items controller, it displays list of items, and view it from items_view.php.
class Items extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('crud');
}
function index(){
$data['items'] = $this->crud->read('items');
$data['header_info'] = $this->crud->header_info('items');
#$data['single_row'] = $this->crud->read_single('items','ID', 1);
$this->load->view('items_view', $data);
}
function edit($id){
$data['single_row'] = $this->crud->read_single('items','ID', $id);
$this->load->view('items_view', $data);
}
function insert(){
if($_POST){
$data = array(
'Desc' => $_POST['Desc'],
'Cost' => $_POST['Cost']
);
if($_POST['status']=='update'){
$this->crud->update('items', $data, 'ID',$_POST['id']);
echo "Updated...";
}elseif ($_POST['status']=='new'){
$last_row = $this->crud->insert('items', $data);
if($last_row){
#Data insertion completed.....
#now ready to get back my items list page.....!
}
}
}
}
}
in the items_view.php also have form that can user add some more items to the list, so that i would like, when user submit the form the insert method will execute, so how to get back to my previous page without losing data.
In insert() take the id if inserted row or updated row Then redirect to index() like this
redirect("items/index/".$last_row);
In index()
function index($id = ""){
if($id) {
// fetch data from db and pass it to view
} else {
// pass empty value to view
}
$data['items'] = $this->crud->read('items');
$data['header_info'] = $this->crud->header_info('items');
$this->load->view('items_view', $data);
}

Adding custom callback to Codeigniter Form Validation

I want to limit my registration to emails with #mywork.com I made the following in My_Form_validation.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
I use it as follows. I use CI rules for username and password and it works, for email it accepts any email address. Any I appreciate any help.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
The problem with creating a callback directly in the controller is that it is now accessible in the url by calling http://localhost/yourapp/yourcontroller/yourcallback which isn't desirable. There is a more modular approach that tucks your validation rules away into configuration files. I recommend:
Your controller:
<?php
class Your_Controller extends CI_Controller{
function submit_signup(){
$this->load->library('form_validation');
if(!$this->form_validation->run('submit_signup')){
//error
}
else{
$p = $this->input->post();
//insert $p into database....
}
}
}
application/config/form_validation.php:
<?php
$config = array
(
//this array key matches what you passed into run()
'submit_signup' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[255]|valid_email|belongstowork'
)
/*
,
array(
...
)
*/
)
//you would add more run() routines here, for separate form submissions.
);
application/libraries/MY_Form_validation.php:
<?php
class MY_Form_validation extends CI_Form_validation{
function __construct($config = array()){
parent::__construct($config);
}
function belongstowork($email){
$endsWith = "#mywork.com";
//see: http://stackoverflow.com/a/619725/568884
return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
}
}
application/language/english/form_validation_lang.php:
Add: $lang['belongstowork'] = "Sorry, the email must belong to work.";
Are you need validation something like this in a Codeigniter callback function?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '#mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
A correction to Jordan's answer, the language file that you need to edit should be located in
system/language/english/form_validation_lang.php
not application/.../form_validation_lang.php. If you create the new file under the application path with the same name, it will overwrite the original in the system path. Thus you will lose all the usage of the original filters.

Categories