Laravel - Select box - php

I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}

Related

How to access array values in laravel

This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id

PHP CODEIGNITER UPDATE issue

I can't update data in a record in CodeIgniter .
I have posted the code below:-
//CONTROLLER
//RESERVATION.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reservation_model','reservation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('manage_reservation');
}
public function reservationview()
{
$this->load->helper('url');
$this->load->view('view_reservation');
}
public function ajax_list()
{
$list = $this->reservation->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $reservation) {
$no++;
$row = array();
$row[] = $reservation->id;
$row[] = $reservation->dateReserved;
$row[] = $reservation->requestedBy;
$row[] = $reservation->facility;
$row[] = $reservation->dateFrom;
$row[] = $reservation->dateTo;
$row[] = $reservation->timeStart;
$row[] = $reservation->timeEnd;
$row[] = $reservation->status;
$row[] = $reservation->items;
$row[] = $reservation->purpose;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->reservation->count_all(),
"recordsFiltered" => $this->reservation->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->reservation->get_by_id($id);
$data->dateFrom = ($data->dateFrom == '0000-00-00') ? '' : $data->dateFrom;
$data->dateTo = ($data->dateTo == '0000-00-00') ? '' : $data->dateTo; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$insert = $this->reservation->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$this->reservation->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->reservation->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('requestedBy') == '')
{
$data['inputerror'][] = 'requestedBy';
$data['error_string'][] = 'Requested Name is required*';
$data['status'] = FALSE;
}
if($this->input->post('dateFrom') == '')
{
$data['inputerror'][] = 'dateFrom';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('dateTo') == '')
{
$data['inputerror'][] = 'dateTo';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('timeStart') == '')
{
$data['inputerror'][] = 'timeStart';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('timeEnd') == '')
{
$data['inputerror'][] = 'timeEnd';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('status') == '')
{
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Please Indicate Status*';
$data['status'] = FALSE;
}
if($this->input->post('items') == '')
{
$data['inputerror'][] = 'items';
$data['error_string'][] = 'Please select an Item*';
$data['status'] = FALSE;
}
if($this->input->post('purpose') == '')
{
$data['inputerror'][] = 'purpose';
$data['error_string'][] = 'Please indicate a Purpose*';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
//MODEL
//Reservation_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation_model extends CI_Model {
var $table = 'tblreservation';
var $column_order = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose',null); //set column field database for datatable orderable
var $column_search = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose'); //set column field database for datatable searchable just firstname , lastname , address are searchable
var $order = array('id' => 'desc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
VIEW = manage_reservation.php = save function
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('reservation/ajax_add')?>";
} else {
url = "<?php echo site_url('reservation/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
NEWBIE TO CODE IGNITER any help will be appreciated :)
try
public function update($where, $data){
$this->db->where($where);
$this->db->set($data); //array of new data
$this->db->update($this->table);
return $this->db->affected_rows();
}
Please print your query after the update statement, this will help you to know whether you query is correct or not.
$this->db->last_query();
Please check that query in model
Controller :
$update_id = array();
$update_id['id'] = $this->input->post('id');
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$result = $this->reservation->update('table_name',$update_id, $data);
Model :
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows();

How to make hyperlink from author name in Wordpress?

I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}

accessing 'blog' functionality / template in FUEL CMS

I'm having trouble getting the "stock" blog functionality / template working within FUEL CMS.
I have read that it is already there, stock with the download configuration of the CMS; I have also tried creating one from scratch and uploading a 'blog' theme from a project found in GitHub. None have worked so far.
I found the blog variable at:
_variables/global.php
I have created a 'blog' controller via interpretation of (gappy) docs.
By adding the below code within it; then making a corresponding 'blog.php' view. I get nothing but a 404 error.
<?php
class Blog extends CI_Controller {
public function view($page = 'home')
{
//you can acesse this http://example.com/blog/view/
}
public function new($page = 'home')
{
//you can acesse this http://example.com/blog/new/
}
}
Within the modules folder. I found this 'stock' blog controller file. But don't know how to use it? found at: /fuel/modules/blog/controller/blog.php
<?php
require_once(MODULES_PATH.'/blog/libraries/Blog_base_controller.php');
class Blog extends Blog_base_controller {
function __construct()
{
parent::__construct();
}
function _remap()
{
$year = ($this->uri->rsegment(2) != 'index') ? (int) $this->uri->rsegment(2) : NULL;
$month = (int) $this->uri->rsegment(3);
$day = (int) $this->uri->rsegment(4);
$slug = $this->uri->rsegment(5);
$limit = (int) $this->fuel->blog->config('per_page');
$view_by = 'page';
// we empty out year variable if it is page because we won't be querying on year'
if (preg_match('#\d{4}#', $year) && !empty($year) && empty($slug))
{
$view_by = 'date';
}
// if the first segment is id then treat the second segment as the id
else if ($this->uri->rsegment(2) === 'id' && $this->uri->rsegment(3))
{
$view_by = 'slug';
$slug = (int) $this->uri->rsegment(3);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
redirect($post->url);
}
}
else if (!empty($slug))
{
$view_by = 'slug';
}
// set this to false so that we can use segments for the limit
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache))
{
$output =& $cache;
}
else
{
$vars = $this->_common_vars();
if ($view_by == 'slug')
{
return $this->post($slug);
}
else if ($view_by == 'date')
{
$page_title_arr = array();
$posts_date = mktime(0, 0, 0, $month, $day, $year);
if (!empty($day)) $page_title_arr[] = $day;
if (!empty($month)) $page_title_arr[] = date('M', strtotime($posts_date));
if (!empty($year)) $page_title_arr[] = $year;
// run before_posts_by_date hook
$hook_params = array('year' => $year, 'month' => $month, 'day' => $day, 'slug' => $slug, 'limit' => $limit);
$this->fuel->blog->run_hook('before_posts_by_date', $hook_params);
$vars = array_merge($vars, $hook_params);
$vars['page_title'] = $page_title_arr;
$vars['posts'] = $this->fuel->blog->get_posts_by_date($year, (int) $month, $day, $slug);
$vars['pagination'] = '';
}
else
{
$limit = $this->fuel->blog->config('per_page');
$this->load->library('pagination');
$config['uri_segment'] = 3;
$offset = $this->uri->segment($config['uri_segment']);
$this->config->set_item('enable_query_strings', FALSE);
$config = $this->fuel->blog->config('pagination');
$config['base_url'] = $this->fuel->blog->url('page/');
//$config['total_rows'] = $this->fuel->blog->get_posts_count();
$config['page_query_string'] = FALSE;
$config['per_page'] = $limit;
$config['num_links'] = 2;
//$this->pagination->initialize($config);
if (!empty($offset))
{
$vars['page_title'] = lang('blog_page_num_title', $offset, $offset + $limit);
}
else
{
$vars['page_title'] = '';
}
// run before_posts_by_date hook
$hook_params = array('offset' => $offset, 'limit' => $limit, 'type' => 'posts');
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
$vars['offset'] = $offset;
$vars['limit'] = $limit;
$vars['posts'] = $this->fuel->blog->get_posts_by_page($limit, $offset);
// run hook again to get the proper count
$hook_params['type'] = 'count';
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
//$config['total_rows'] = count($this->fuel->blog->get_posts_by_page());
$config['total_rows'] = $this->fuel->blog->get_posts_count();
// create pagination
$this->pagination->initialize($config);
$vars['pagination'] = $this->pagination->create_links();
}
// show the index page if the page doesn't have any uri_segment(3)'
$view = ($this->uri->rsegment(2) == 'index' OR ($this->uri->rsegment(2) == 'page' AND !$this->uri->segment(3))) ? 'index' : 'posts';
$output = $this->_render($view, $vars, TRUE);
$this->fuel->blog->save_cache($cache_id, $output);
}
$this->output->set_output($output);
}
function post($slug = null)
{
if (empty($slug))
{
redirect_404();
}
$this->load->library('session');
$blog_config = $this->fuel->blog->config();
// run before_posts_by_date hook
$hook_params = array('slug' => $slug);
$this->fuel->blog->run_hook('before_post', $hook_params);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
$vars = $this->_common_vars();
$vars['post'] = $post;
$vars['user'] = $this->fuel->blog->logged_in_user();
$vars['page_title'] = $post->title;
$vars['next'] = $this->fuel->blog->get_next_post($post);
$vars['prev'] = $this->fuel->blog->get_prev_post($post);
$vars['slug'] = $slug;
$vars['is_home'] = $this->fuel->blog->is_home();
$antispam = md5(random_string('unique'));
$field_values = array();
// post comment
if (!empty($_POST))
{
$field_values = $_POST;
// the id of "content" is a likely ID on the front end, so we use comment_content and need to remap
$field_values['content'] = $field_values['new_comment'];
unset($field_values['antispam']);
if (!empty($_POST['new_comment']))
{
$vars['processed'] = $this->_process_comment($post);
}
else
{
add_error(lang('blog_error_blank_comment'));
}
}
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache) AND empty($_POST))
{
$output =& $cache;
}
else
{
$this->load->library('form');
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
$captcha = $this->_render_captcha();
$vars['captcha'] = $captcha;
}
$vars['thanks'] = ($this->session->flashdata('thanks')) ? blog_block('comment_thanks', $vars, TRUE) : '';
$vars['comment_form'] = '';
$this->session->set_userdata('antispam', $antispam);
if ($post->allow_comments)
{
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$this->load->library('form_builder', $blog_config['comment_form']);
$fields['author_name'] = array('label' => 'Name', 'required' => TRUE);
$fields['author_email'] = array('label' => 'Email', 'required' => TRUE);
$fields['author_website'] = array('label' => 'Website');
$fields['new_comment'] = array('label' => 'Comment', 'type' => 'textarea', 'required' => TRUE);
$fields['post_id'] = array('type' => 'hidden', 'value' => $post->id);
$fields['antispam'] = array('type' => 'hidden', 'value' => $antispam);
if (!empty($vars['captcha']))
{
$fields['captcha'] = array('required' => TRUE, 'label' => 'Security Text', 'value' => '', 'after_html' => ' <span class="captcha">'.$vars['captcha']['image'].'</span><br /><span class="captcha_text">'.lang('blog_captcha_text').'</span>');
}
// now merge with config... can't do array_merge_recursive'
foreach($blog_config['comment_form']['fields'] as $key => $field)
{
if (isset($fields[$key])) $fields[$key] = array_merge($fields[$key], $field);
}
if (!isset($blog_config['comment_form']['label_layout'])) $this->form_builder->label_layout = 'left';
if (!isset($blog_config['comment_form']['submit_value'])) $this->form_builder->submit_value = 'Submit Comment';
if (!isset($blog_config['comment_form']['use_form_tag'])) $this->form_builder->use_form_tag = TRUE;
if (!isset($blog_config['comment_form']['display_errors'])) $this->form_builder->display_errors = TRUE;
$this->form_builder->form_attrs = 'method="post" action="'.site_url($this->uri->uri_string()).'#comments_form"';
$this->form_builder->set_fields($fields);
$this->form_builder->set_field_values($field_values);
$this->form_builder->set_validator($this->blog_comments_model->get_validation());
$vars['comment_form'] = $this->form_builder->render();
$vars['fields'] = $fields;
}
$output = $this->_render('post', $vars, TRUE);
// save cache only if we are not posting data
if (!empty($_POST))
{
$this->fuel->blog->save_cache($cache_id, $output);
}
}
if (!empty($output))
{
$this->output->set_output($output);
return;
}
}
else
{
show_404();
}
}
function _process_comment($post)
{
if (!is_true_val($this->fuel->blog->config('allow_comments'))) return;
$notified = FALSE;
// check captcha
if (!$this->_is_valid_captcha())
{
add_error(lang('blog_error_captcha_mismatch'));
}
// check that the site is submitted via the websit
if (!$this->_is_site_submitted())
{
add_error(lang('blog_error_comment_site_submit'));
}
// check consecutive posts
if (!$this->_is_not_consecutive_post())
{
add_error(lang('blog_error_consecutive_comments'));
}
$this->load->module_model(BLOG_FOLDER, 'blog_users_model');
$user = $this->blog_users_model->find_one(array('fuel_users.email' => $this->input->post('author_email', TRUE)));
// create comment
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$comment = $this->blog_comments_model->create();
$comment->post_id = $post->id;
$comment->author_id = (!empty($user->id)) ? $user->id : NULL;
$comment->author_name = $this->input->post('author_name', TRUE);
$comment->author_email = $this->input->post('author_email', TRUE);
$comment->author_website = $this->input->post('author_website', TRUE);
$comment->author_ip = $_SERVER['REMOTE_ADDR'];
$comment->content = trim($this->input->post('new_comment', TRUE));
$comment->date_added = NULL; // will automatically be added
//http://googleblog.blogspot.com/2005/01/preventing-comment-spam.html
//http://en.wikipedia.org/wiki/Spam_in_blogs
// check double posts by IP address
if ($comment->is_duplicate())
{
add_error(lang('blog_error_comment_already_submitted'));
}
// if no errors from above then proceed to submit
if (!has_errors())
{
// submit to akisment for validity
$comment = $this->_process_akismet($comment);
// process links and add no follow attribute
$comment = $this->_filter_comment($comment);
// set published status
if (is_true_val($comment->is_spam) OR $this->fuel->blog->config('monitor_comments'))
{
$comment->published = 'no';
}
// save comment if saveable and redirect
if (!is_true_val($comment->is_spam) OR (is_true_val($comment->is_spam) AND $this->fuel->blog->config('save_spam')))
{
if ($comment->save())
{
$notified = $this->_notify($comment, $post);
$this->load->library('session');
$vars['post'] = $post;
$vars['comment'] = $comment;
$this->session->set_flashdata('thanks', TRUE);
$this->session->set_userdata('last_comment_ip', $_SERVER['REMOTE_ADDR']);
$this->session->set_userdata('last_comment_time', time());
redirect($post->url);
}
else
{
add_errors($comment->errors());
}
}
else
{
add_error(lang('blog_comment_is_spam'));
}
}
return $notified;
}
// check captcha validity
function _is_valid_captcha()
{
$valid = TRUE;
// check captcha
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
if (!$this->input->post('captcha'))
{
$valid = FALSE;
}
else if (!is_string($this->input->post('captcha')))
{
$valid = FALSE;
}
else
{
$post_captcha_md5 = $this->_get_encryption($this->input->post('captcha'));
$session_captcha_md5 = $this->session->userdata('comment_captcha');
if ($post_captcha_md5 != $session_captcha_md5)
{
$valid = FALSE;
}
}
}
return $valid;
}
// check to make sure the site issued a session variable to check against
function _is_site_submitted()
{
return ($this->session->userdata('antispam') AND $this->input->post('antispam') == $this->session->userdata('antispam'));
}
// disallow multiple successive submissions
function _is_not_consecutive_post()
{
$valid = TRUE;
$time_exp_secs = $this->fuel->blog->config('multiple_comment_submission_time_limit');
$last_comment_time = ($this->session->userdata('last_comment_time')) ? $this->session->userdata('last_comment_time') : 0;
$last_comment_ip = ($this->session->userdata('last_comment_ip')) ? $this->session->userdata('last_comment_ip') : 0;
if ($_SERVER['REMOTE_ADDR'] == $last_comment_ip AND !empty($time_exp_secs))
{
if (time() - $last_comment_time < $time_exp_secs)
{
$valid = FALSE;
}
}
return $valid;
}
// process through akisment
function _process_akismet($comment)
{
if ($this->fuel->blog->config('akismet_api_key'))
{
$this->load->module_library(BLOG_FOLDER, 'akismet');
$akisment_comment = array(
'author' => $comment->author_name,
'email' => $comment->author_email,
'body' => $comment->content
);
$config = array(
'blog_url' => $this->fuel->blog->url(),
'api_key' => $this->fuel->blog->config('akismet_api_key'),
'comment' => $akisment_comment
);
$this->akismet->init($config);
if ( $this->akismet->errors_exist() )
{
if ( $this->akismet->is_error('AKISMET_INVALID_KEY') )
{
log_message('error', 'AKISMET :: Theres a problem with the api key');
}
elseif ( $this->akismet->is_error('AKISMET_RESPONSE_FAILED') )
{
log_message('error', 'AKISMET :: Looks like the servers not responding');
}
elseif ( $this->akismet->is_error('AKISMET_SERVER_NOT_FOUND') )
{
log_message('error', 'AKISMET :: Wheres the server gone?');
}
}
else
{
$comment->is_spam = ($this->akismet->is_spam()) ? 'yes' : 'no';
}
}
return $comment;
}
// strip out
function _filter_comment($comment)
{
$this->load->helper('security');
$comment_attrs = array('content', 'author_name', 'author_email', 'author_website');
foreach($comment_attrs as $filter)
{
$text = $comment->$filter;
// first remove any nofollow attributes to clean up... not perfect but good enough
$text = preg_replace('/<a(.+)rel=["\'](.+)["\'](.+)>/Umi', '<a$1rel="nofollow"$3>', $text);
// $text = str_replace('<a ', '<a rel="nofollow"', $text);
$text = strip_image_tags($text);
$comment->$filter = $text;
}
return $comment;
}
function _notify($comment, $post)
{
// send email to post author
if (!empty($post->author))
{
$config['wordwrap'] = TRUE;
$this->load->library('email', $config);
$this->email->from($this->fuel->config('from_email'), $this->fuel->config('site_name'));
$this->email->to($post->author->email);
$this->email->subject(lang('blog_comment_monitor_subject', $this->fuel->blog->config('title')));
$msg = lang('blog_comment_monitor_msg');
$msg .= "\n".fuel_url('blog/comments/edit/'.$comment->id)."\n\n";
$msg .= (is_true_val($comment->is_spam)) ? lang('blog_email_flagged_as_spam')."\n" : '';
$msg .= lang('blog_email_published').": ".$comment->published."\n";
$msg .= lang('blog_email_author_name').": ".$comment->author_name."\n";
$msg .= lang('blog_email_author_email').": ".$comment->author_email."\n";
$msg .= lang('blog_email_author_website').": ".$comment->author_website."\n";
$msg .= lang('blog_email_author_ip').": ".gethostbyaddr($comment->author_ip)." (".$comment->author_ip.")\n";
$msg .= lang('blog_email_content').": ".$comment->content."\n";
$this->email->message($msg);
return $this->email->send();
}
else
{
return FALSE;
}
}
function _render_captcha()
{
$this->load->library('captcha');
$blog_config = $this->config->item('blog');
$assets_folders = $this->config->item('assets_folders');
$blog_folder = MODULES_PATH.BLOG_FOLDER.'/';
$captcha_path = $blog_folder.'assets/captchas/';
$word = strtoupper(random_string('alnum', 5));
$captcha_options = array(
'word' => $word,
'img_path' => $captcha_path, // system path to the image
'img_url' => captcha_path('', BLOG_FOLDER), // web path to the image
'font_path' => $blog_folder.'fonts/',
);
$captcha_options = array_merge($captcha_options, $blog_config['captcha']);
if (!empty($_POST['captcha']) AND $this->session->userdata('comment_captcha') == $this->input->post('captcha'))
{
$captcha_options['word'] = $this->input->post('captcha');
}
$captcha = $this->captcha->get_captcha_image($captcha_options);
$captcha_md5 = $this->_get_encryption($captcha['word']);
$this->session->set_userdata('comment_captcha', $captcha_md5);
return $captcha;
}
function _get_encryption($word)
{
$captcha_md5 = md5(strtoupper($word).$this->config->item('encryption_key'));
return $captcha_md5;
}
}
My goal is:
1.) Enable 'Blog' Module / template / functionality and understand how I did it. I find the docs lacking, I'm also new at code igniter so that could be why. I just want the most basic way to do this for now.
And 2.) I want to create a page 'from scratch' that resolves on the dashboard side as well. I have created pages in /views/ but they resolve with that whole string /fuel/application/views/page/ I want to create a normal page without all that in the URL. I have tried creating corresponding controllers even variables and haven't had much luck!!!!!!!
As of FUEL CMS 1.0 the blog module is no longer bundled with the CMS by default. You would need to do the following:
Download & setup FUEL CMS per the install instructions here: https://github.com/daylightstudio/FUEL-CMS
Next, once you've got that up and running you can download & setup the blog module per the instructions here: https://github.com/daylightstudio/FUEL-CMS-Blog-Module
Once the blog is setup, you should be able to access it at "yourdomain.com/blog". As far as creating themes, there is a views/themes folder in the blog module which contains a default theme and also where you can setup your custom theme. Additional information about the blog module & theming can be found here http://docs.getfuelcms.com/modules/blog

Codeigniter: Validate form field on edit

I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');

Categories