Related
i have Product Model and it have bread in voyager and everything is ok.
Products have publisher_id column if null == main else int(id of publisher).
i want create multiple browse blade but one of those is default voyager blade
and another where('publisher_id','!=',null)
to show .
how to created it with route ?
thanks .
fixed with resource route
Route::resource('products/index/publisher', VoyagerProductPublisherController::class);
Route::resource('products/index/notaccept', VoyagerProductPublisherNotAcceptController::class);
and then in controllers index function write query
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('publisher_id','!=',null),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('publisher_id','!=',null), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('publisher_id','!=',null), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('publisher_id','!=',null), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.publisher';
if (view()->exists("voyager::$slug.publisher")) {
$view = "voyager::$slug.publisher";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// in controller two
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('accept',0),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('accept',0), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('accept',0), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('accept',0), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.notaccept';
if (view()->exists("voyager::$slug.notaccept")) {
$view = "voyager::$slug.notaccept";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
thanks for view .
I've tried doing:
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
but when testing it in postman returned me 0.
enter image description here
Here's my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ShowSummaryResultsController extends Controller
{
public function show(Request $request)
{
$usuario = $request->input('usuario');
$results = DB::table('tests')
->where('usuario_id', '=', $usuario)
->where('id_evento_test', '=', '0')
->get();
$resultsOkPROTANOPIA = 0;
$resultsNokPROTANOPIA = 0;
$resultsOkDEUTERANOPIA = 0;
$resultsNokDEUTERANOPIA = 0;
$resultsOkTRITANOPIA = 0;
$resultsNokTRITANOPIA = 0;
foreach ($results as $rows)
{
$image_id = $rows->image_id;
$resultado = $rows->resultado;
//$tipo = DB::table('images')
//->where('id', '=', $image_id)
//->get();
$image = 'App\Models\Image'::findOrFail($image_id);
$tipo_discromatopsia = $image->tipo_discromatopsia;
if ($tipo_discromatopsia == 'PROTANOPIA') {
if($resultado) {
$resultsOkPROTANOPIA +=1;
}else{
$resultsNokPROTANOPIA +=1;
}
}
elseif ($tipo_discromatopsia == 'DEUTERANOPIA') {
if($resultado) {
$resultsOkDEUTERANOPIA +=1;
}else{
$resultsNokDEUTERANOPIA +=1;
}
}
else {
if($resultado) {
$resultsOkTRITANOPIA +=1;
}else{
$resultsNokTRITANOPIA +=1;
}
}
//update event_id with a unique key
//$uniquekey = 202208271116;
//$results->id_evento_test = $uniquekey;
//$results->save();
}
$porc=0;
if (($resultsOkPROTANOPIA + $resultsNokPROTANOPIA) >0)
{ $porc=$resultsOkPROTANOPIA / ($resultsOkPROTANOPIA + $resultsNokPROTANOPIA ) * 100; }
$result[0] = array("tipo" =>'PROTANOPIA',"ResOK" =>$resultsOkPROTANOPIA,"ResNOK" =>$resultsNokPROTANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) >0)
{$porc=$resultsOkDEUTERANOPIA / ($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) * 100;}
$result[1] = array("tipo" =>'DEUTERANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )>0)
{$porc=$resultsOkTRITANOPIA/ ($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )* 100;}
$result[2] = array("tipo" =>'TRITANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$min = min($result[0]['Porc'],$result[1]['Porc'],$result[2]['Porc']);
$result[3] = array("tipo" =>'RESULTADOS',"index"=>$min,"Tipo"=>$result[$min]['tipo'], );
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
//return response()->json($result, 201);
}
}
If you need value of column after successful updating then read this example please:
$uniquekey = '202208271120';
try {
DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', 0)
->update(['id_evento_test' => $uniquekey]);
$results2 = $uniquekey;
return response()->json($results2, 201);
} catch (\Illuminate\Database\QueryExeption $e) {
return response()->json(['error' => 'Unsuccessful Update']);
}
You can use first or get to retrieve all the data from table test or only column id_evento_test. So $results2 could have all data or only part of data as you need.
in this code $results2 =DB::table('tests') you are storing the result of the database query to $result2 which is 0 or 1 and 0 means that nothing was updated and 1 means that the update was done successfully.
if you want to return the $uniquekey then assign it to $result2:
$results2 = $uniquekey;
return response()->json($results2, 201);
or just return $uniquekey:
return response()->json($uniquekey, 201);
There is a table foo and it has a column called fooPos. I ned to update the fooPos column with respect to id.
I have the following data
$id = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
How can I update this without using loops?
It's like 21(id) => 1(fooPos), 23 => 2, 34 =>3 etc.,
You have a solution with INSERT INTO ... ON DUPLICATE KEY UPDATE..., more details in here Multiple update
That solution can trigger an error if the ID doesn't exist and you have some other required fields. In that cas you ca use this solution:
$updateSets = [];
$ids = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
foreach ($ids as $key => $id) {
$updateSets[] = 'SELECT '.$id.' as set_id, '.$fooPos[$key].' as pos ';
}
$updateSetsString = implode(' UNION ALL ', $updateSets);
\DB::statement('UPDATE your_table JOIN ('.$updateSetsString.') up_set ON your_table.id = up_set.set_id SET your_table.pos = up_set.pos');
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));
i used cakephp before and now use codeigniter but Unfortunately hasn't any authentication or ACL built-in library ..after more search i have found a good library, but I do not know how to use it..it is no example to use it..any one have create controller and model as sample...thanks for helping
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class acl {
/* Actions::::
* Create 1
* Read 2
* Update 4
* Delete 8
* The allowance is made by a sum of the actions allowed.
* Ex.: user can read and update (2+4)=6 … so ill put 6 instead of 1 or 0.
*
* if(!$this->acl->hasPermission(‘entries_complete_access')) {
echo “No no”;
} else
* echo “yeah”;
}
*
*
*/
var $perms = array(); //Array : Stores the permissions for the user
var $userID; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
var $ci;
function __construct($config = array()) {
$this->ci = &get_instance();
$this->userID = floatval($this->ci->session->userdata('account_id'));
$this->userRoles = $this->getUserRoles();
$this->buildACL();
}
function buildACL() {
//first, get the rules for the user's role
if (count($this->userRoles) > 0) {
$this->perms = array_merge($this->perms, $this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms, $this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID) {
//$strSQL = “SELECT `permKey` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permKey');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permKey;
}
function getPermNameFromID($permID) {
//$strSQL = “SELECT `permName` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permName');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permName;
}
function getRoleNameFromID($roleID) {
//$strSQL = “SELECT `roleName` FROM `”.DB_PREFIX.”roles` WHERE `ID` = ” . floatval($roleID) . ” LIMIT 1″;
$this->ci->db->select('roleName');
$this->ci->db->where('id', floatval($roleID), 1);
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
return $data[0]->roleName;
}
function getUserRoles() {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_roles` WHERE `userID` = ” . floatval($this->userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where(array('userID' => floatval($this->userID)));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_roles');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
$resp[] = $row->roleID;
}
return $resp;
}
function getAllRoles($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”roles` ORDER BY `roleName` ASC”;
$this->ci->db->order_by('roleName', 'asc');
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[] = array('id' => $row->ID, 'name' => $row->roleName);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getAllPerms($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”permissions` ORDER BY `permKey` ASC”;
$this->ci->db->order_by('permKey', 'asc');
$sql = $this->ci->db->get('perm_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[$row->permKey] = array('id' => $row->ID, 'name' => $row->permName, 'key' => $row->permKey);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getRolePerms($role) {
if (is_array($role)) {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` IN (” . implode(“,”,$role) . “) ORDER BY `ID` ASC”;
$this->ci->db->where_in('roleID', $role);
} else {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` = ” . floatval($role) . ” ORDER BY `ID` ASC”;
$this->ci->db->where(array('roleID' => floatval($role)));
}
$this->ci->db->order_by('id', 'asc');
$sql = $this->ci->db->get('role_perms'); //$this->db->select($roleSQL);
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '1inheritted' => true, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function getUserPerms($userID) {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_perms` WHERE `userID` = ” . floatval($userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where('userID', floatval($userID));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_perms');
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '2inheritted' => false, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function hasRole($roleID) {
foreach ($this->userRoles as $k => $v) {
if (floatval($v) === floatval($roleID)) {
return true;
}
}
return false;
}
function actionPerm($value, $wanted) {
/* Actions::::
* Create 1
* Read, 2
* Update, 4
* Delete 8
*/
$action['create'] = array('1', '3', '5', '9', '11', '13', '15'); //1
$action['read'] = array('2', '3', '6', '10', '14', '15'); //2
$action['update'] = array('4', '5', '6', '7', '12', '13', '14', '15'); //4
$action['delete'] = array('8', '9', '10', '11', '12', '13', '14', '15'); //8
$action['all'] = array('15');
if (in_array($value, $action[$wanted], true)) {
return true;
} else {
return false;
}
}
function hasPermission($permKey, $action = 'all') {
$permKey = strtolower($permKey);
if (array_key_exists($permKey, $this->perms)) {
if ($this->actionPerm($this->perms[$permKey]['value'], $action)) {
return true;
} else {
return false;
}
} else {
return false;
}
/* OLD METHOD
if ($this->perms[$permKey]['value'] === '1′ || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
*/
}
}
and this is the url
sample ACL Class for codeigniter
This is simple
Load it first in your controller
$this->load->library('acl');
Now call its method
$this->acl->buildACL();
EDIT
Use these for menuall assigning
$this->acl->perms = array('your values');
$this->acl->userID= 'user id';
$this->acl->userRoles = array('your values');
Note that you should have db table userRoles which will be invoked when the library is initialized getUserRoles method will be called and $userRoles parameter will have values.
I'm Brian from Tastybytes. My best solution would be to step through the tutorial that the code igniter ACL library is based on. It is a 100% straight port from the base php files to CI Library.
http://net.tutsplus.com/tutorials/php/a-better-login-system/
And possibly look at the very bottom of the page where I go through "Installation" and what not.