i want to create scope , but dont know how to create it because my code kinda kinky :d, code will be below. Can you show me example for my 1-2 sort requests which will work with search too? (i want to get this). Basic functional is like this -> i have searching form, which is searching between countries, also i can sort this countries by arrow buttons, by desc or asc, (first one is by country names sorting, and others is only numbers), im able now to sort correctly, and also search and then sort.
CONTROLLER :
$countries = Country::latest()->filter(request(['search']))->get();
$infos = Info::all();
$page = request('page');
$confirmed = Info::sum('confirmed');
$recovered = Info::sum('recovered');
$deaths = Info::sum('deaths');
//for by country name sorting
if (request()->get('sort') === 'country_desc')
{
$countries = Country::orderByDesc(Info::select('country')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderByDesc(Info::select('country')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
if (request()->get('sort') === 'country_asc')
{
$countries = Country::orderBy(Info::select('country')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderBy(Info::select('country')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
// for new cases sorting
if (request()->get('sort') === 'cases_desc')
{
$countries = Country::orderByDesc(Info::select('confirmed')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderByDesc(Info::select('confirmed')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
if (request()->get('sort') === 'cases_asc')
{
$countries = Country::orderBy(Info::select('confirmed')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderBy(Info::select('confirmed')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
// for deaths sorting
if (request()->get('sort') === 'deaths_desc')
{
$countries = Country::orderByDesc(Info::select('deaths')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderByDesc(Info::select('deaths')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
if (request()->get('sort') === 'deaths_asc')
{
$countries = Country::orderBy(Info::select('deaths')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderBy(Info::select('deaths')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
//for recovered sorting
if (request()->get('sort') === 'recovered_desc')
{
$countries = Country::orderByDesc(Info::select('recovered')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderByDesc(Info::select('recovered')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
if (request()->get('sort') === 'recovered_asc')
{
$countries = Country::orderBy(Info::select('recovered')->whereColumn('infos.country_id', 'countries.id'))->get();
if (request()->get('search'))
{
$countries = Country::orderBy(Info::select('recovered')->whereColumn('infos.country_id', 'countries.id'))
->latest()->filter(request(['search']))->get();
}
}
COUNTRY MODEL SCOPE :
public function scopeFilter($query, array $filters)
{
$query->when($filters['search'] ?? false, fn ($query, $search) => $query
->where('name', 'like', '%' . $search . '%'));
}
as you can see its kinda big code, so i want to create scopes or etc.. what is the best way to reduce this code
Related
I'm trying to get the shipping available methods by country code that giving in the request, in the above code I'm facing an issue/conflict
That the available locations can be both a country or a continent so I need to check if this country code is a part of some continent.
the problem is with the first zone I get all methods in all zones not just within the first ( the callback return ).
The second zone which has the continents/countries ( rest of the world ) I get no issues with it but as far I guess that's because its the end of the loop. ( as I have two zones for now )
add_action("rest_api_init", function () {
register_rest_route(
"test-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$quantity = $req->get_param('quantity');
$shipping_cost = 0;
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
}
}
}
}
}
}
}
return $methodes;
}
)
);
});
Here's the answer: ( adding break with the number of the array want it to be stop )
Register_rest_route(
"kefan-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
break 2;
}
}
}
}
}
}
}
return $methodes;
}
)
);
I have a function for userDashboard() and I have to call updateUserlocation() function inside this userDashboard() function.
Please tell me how to do that.
I have tried to add updateUserLocation() inside userDashboard() but it is not working.
This error is coming:
Call to undefined function App\Http\Controllers\userUpdateLocation()
This is the userDashboard function:-
public function userDashboard()
{
$user = Session::get('user_account');
$commonModel = new CommonModel();
$userModel = new User();
$data = $commonModel->commonFunction();
$login = GlobalData::isLoggedIn();
if ($login) {
return redirect(url('/'));
}
$data['user_session'] = Session::get('user_account');
// Get the groups joined by the user
$user_id = $data['user_session']['id'];
$get_groups = DB::table('trans_group_users')
->where('user_id_fk', $user_id)
->get();
// if user's group count is zero, redirect to signup2 to choose groups first
if (count($get_groups) == 0) {
Session::flash('error_msg', 'Please select atleast one group to proceed further.');
return redirect()->guest('/signup2');
}
$lang_id = 14;
$arr_user_data = array();
$user_id = $data['user_session']['id'];
/* Differciate date for get record for perticuler month */
$today_date = date("Y-m-d");
$first_date = date("Y-m-01");
$date1 = date_create($today_date);
$date2 = date_create($first_date);
$diff = date_diff($date1, $date2);
$remain_days = $diff->days;
$today_with_minus_days = date('Y-m-d', strtotime("-$remain_days days"));
/* Ends here */
/* notification count */
$arr_user_data = $userModel->find($user_id);
$arr_user_data = $arr_user_data;
$get_events = DB::table('mst_event as e')
->join('trans_event_rsvp_status as r', 'r.event_id_fk', '=', 'e.id')
->where('r.user_id_fk', $user_id)
->where('r.status', 1)
->where('e.start_date', '>', $today_with_minus_days)
->where('e.end_date', '<', $today_date)
->select('e.start_date')
->groupBy('e.id')
->get();
$get_e = array();
if (count($get_events) > 0) {
foreach ($get_events as $object) {
$get_e[] = (array) $object;
}
}
$get_meetups = DB::table('mst_meetup as m')
->join('trans_meetup_rsvp_status as r', 'r.meetup_id_fk', '=', 'm.id')
->where('r.user_id_fk', $user_id)
->where('m.start_date', '>', $today_with_minus_days)
->where('m.start_date', '<', $today_date)
->where('r.status', 1)
->select('m.start_date')
->groupBy('m.id')
->get();
$get_m = array();
if (count($get_meetups) > 0) {
foreach ($get_meetups as $object) {
$get_m[] = (array) $object;
}
}
$arr = array();
$arr = array_merge($get_e, $get_m);
$upcoming_going_event_count = count($arr);
if ($upcoming_going_event_count > 0) {
Session::put('going_count', $upcoming_going_event_count);
} else {
Session::forget('going_count');
}
/* Ends here */
$data['header'] = array(
"title" => 'My Home | ATG',
"keywords" => '',
"description" => ''
);
return view('Frontend.user.dashboard')
->with('title', 'Profile')
->with('finalData', $data)
->with('arr_user_data', $arr_user_data);
}
This is the updateUserlocation function:-
public function updateUserLocation()
{
/* Update User Location based on input from the browser, else from IP */
$all = Input::all();
$latitude = (isset($all['latitude']) ? $all['latitude'] : '');
$longitude = (isset($all['longitude']) ? $all['longitude'] : '');
$agent = (isset($all['agent']) ? $all['agent'] : '');
$commonModel = new CommonModel();
$data = $commonModel->commonFunction();
$data['user_session'] = Session::get('user_account');
$user_id = $data['user_session']['id'];
if ($latitude == '' && $longitude == '') {
try {
$ip = Request::ip();
$data = \Location::get($ip);
$latitude = $data->latitude;
$longitude = $data->longitude;
$agent = $_SERVER['HTTP_USER_AGENT'];
} catch (\Exception $e) {
\Log::alert($e->getMessage());
\Log::debug($e);
}
}
$this->UpdateUserLocationfx($user_id, 'web', $latitude, $longitude, $agent);
}
Laravel / PHP thinks you are calling a class or controller instead of a method.
If the userUpadateLocation() method is within the same controller as userDashboard(), use the $this variable to call the method from within the same controller:
$this->userUpadateLocation();
$this translates to 'use this controller's method'.
I am trying to create an API using CakePHP that allows searching. For example:
http://localhost:8765/users/index/?username=admin
Which should return users with usernames equal to 'admin':
users: [
{
id: 3,
username: "admin",
image: "",
firstName: "Jeremy",
lastName: "Quick",
userTypeId: 1,
email: "jrquick#test.com",
groupId: 2
}
]
So far, I have been able to accomplish this with a custom get() in the AppController which checks the $_GET and $_POST array for fields on the model. But the function is getting more and more complicated and verging on hackiness as I add more functionality (range search, collection search, and child table filtering). Is there a better, more CakePHP friendly way of accomplishing this? Whether through pure cakephp or a plugin?
I think you want to use the Cakephp Search plugin. It has good documentation and uses a PRG method similar to what you are currently using. It will function just fine through an API. Here's a link to that plugin: github.com/FriendsOfCake/search
If You want to create API, You should create a MiddleWare at first, which will filter tokens, keys etc. to make Your API more protected.
Also, You should use Plugins and RESTful Routes, which will be very helpful.
To create plugin:
bin/cake bake plugin Api
Create Model:
bin/cake bake model Users
For example, You want to have UsersController in Api plugin:
<?php
namespace Api\Controller;
/* This controller will be extending like parent */
use Api\Controller\AppController;
use Api\Model\Table\UsersTable;
/**
* Class UsersController
* #package Api\Controller
* #property UsersTable $Users
*
*/
class UsersController extends AppController{
public function initialize(){
parent::initialize();
$this->loadModel('Api.Users');
}
public function getUser($field ='username', $username = false){
return $this->_jsonResponse(
[
'users' => $this->Users->findBy{ucfirst($field)}($username)
];
)
}
public function _jsonResponse($data, $code = 200){
$this->response->type('json');
$this->response->statusCode($code);
$this->response->body(
json_encode((array)$data)
);
return $this->response;
}
}
Route will be descripbed in plugins/config/routes.php. You need to create Route Map for API in /api path:
function (RouteBuilder $routes) {
$routes->resources('Users', [
'map' => [
'get-user' => [
'action' => 'getUser',
'method' => 'GET' /* Can be also as array ['GET', 'PUT', 'DELETE'] */
]
]
]);
$routes->fallbacks('DashedRoute');
}
If You have frequent calls, You should use Cache that calls and save them for some amount of time. For example - 10 minutes. Cache can be configured in config/app.php. You should create separate Cache prefix and use it in this way:
<?php
use Cake\Cache\Cache;
$data = [];
Cache::write('some_key', $data, 'prefix')
dump(Cache::read('some_key', 'prefix'));
It's just examples. If You will face some problems - just tell in comments :)
Also, use Migrations and Seeds instead dumping sql files
If You want to filter data from Middleware - You should have Event as argument, that will contain request data ($_POST) and request query($_GET) variables that You will be able to easily handle with.
From controllers You need to use $this->request->data to get POST data array or $this->request->query to get GET data array.
I haven't found an answer that seems to work exactly how I am wanting, so here is my current get command. It does allow searching by fields, join tables, greater/less than, in array, and like.
If anyone has recommendations to improve I will update my answer.
public function get() {
$response = new Response();
$model = $this->loadModel();
$fields = $this->getFields();
$joins = $this->getJoins();
$order = $this->getOrder();
$params = $this->getParams();
$limit = $this->getLimit();
$offset = $this->getOffset();
$query = $model->find('all', ['fields' => $fields]);
if (!is_null($joins)) {
$query->contain($joins);
}
if (sizeof($params['equals']) > 0) {
foreach ($params['equals'] as $equalsKey=>$equalsValue) {
$query->andWhere([$equalsKey => $equalsValue]);
}
}
if (sizeof($params['or']) > 0) {
foreach ($params['or'] as $orKey=>$orValue) {
$query->orWhere([$orKey => $orValue]);
}
}
if (!is_null($order)) {
$query->order([$order]);
}
if (!is_null($limit)) {
$query->limit($limit);
if (!is_null($offset)) {
$query->offset($offset);
}
}
$response->addMessage($model->table(), $query->toArray());
$response->respond($this);
}
private function getFields() {
$fields = [];
if (array_key_exists('fields', $_GET)) {
$fields = explode(',', $_GET['fields']);
}
return $fields;
}
private function getLimit() {
$limit = null;
if (array_key_exists('limit', $_GET)) {
$limit = $_GET['limit'];
}
return $limit;
}
private function getJoins() {
$joins = null;
if (array_key_exists('joins', $_GET)) {
$joins = explode(',', $_GET['joins']);
}
return $joins;
}
private function getOffset() {
$offset = null;
if (array_key_exists('offset', $_GET)) {
$offset = $_GET['limit'];
}
return $offset;
}
private function getOrder() {
$results = [];
if (array_key_exists('order', $_GET)) {
$orders = explode(',', $_GET['order']);
foreach ($orders as $order) {
$sign = substr($order, 0, 1);
$direction = 'ASC';
if (in_array($sign, ['+', '-'])) {
if ($sign === '-') {
$direction = 'DESC';
}
$order = substr($order, 1);
}
$result = $order;
if (strpos($result, '.') === false) {
$result = $this->loadModel()->alias() . '.' . $order;
}
$result = $result . ' ' . $direction;
$results[] = $result;
}
}
return (sizeof($results) == 0) ? null : implode(',', $results);
}
private function getParams() {
$params = [
'equals' => [],
'or' => []
];
$parentModel = $this->loadModel();
$array = array_merge($_GET, $_POST);
foreach ($array as $field=>$value) {
$comparisonType = 'equals';
$operator = substr($field, strlen($field) - 1);
if (in_array($operator, ['!', '>', '<'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator .= '=';
} else if (in_array($operator, ['|'])) {
$field = substr($field, 0, strlen($field) - 1);
$comparisonType = 'or';
$operator = '=';
} else if (in_array($operator, ['%'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator = 'LIKE';
$value = '%'.$value.'%';
} else {
$operator = '=';
}
if ($value == 'null') {
$operator = (strpos($operator, '!') === false) ? 'IS' : 'IS NOT';
$value = null;
}
$field = str_replace('_', '.', $field);
if (strpos($field, '.') === false) {
$alias = $parentModel->alias();
} else {
$fieldExplosion = explode('.', $field);
$alias = $fieldExplosion[0];
$field = $fieldExplosion[1];
}
$model = null;
if ($parentModel->alias() !== $alias) {
$association = $parentModel->associations()->get($alias);
if (!is_null($association)) {
$model = $this->loadModel($association->className());
}
} else {
$model = $parentModel;
}
if (!is_null($model)) {
if ($model->hasField(rtrim($field, 's')) && !$model->hasField($field)) {
$field = rtrim($field, 's');
$value = '(' . $value . ')';
$operator = ' IN';
}
if ($model->hasField($field)) {
$params[$comparisonType][$alias.'.'.$field . ' ' . $operator] = $value;
}
}
}
return $params;
}
Here is the scenario, and let me start off saying any help would be a god-send, I have cloned the Article Category module inside Joomla! Basically changed all the articles_category to breed_articles (for my purpose). This worked fine, where I am stuck at is where in the module code can I define a specific category to pull articles from.
I know I can do this in the backend but I am working on a dynamic way to pull articles by categories and need to define the category in the module code. That being said, I will also need to pull the categoies by the slug not id.
Where I have been looking is the helper.php file in the module and I believe that I am on the right path there. I have tried replacing a few things and tracing the code but I am not very familiar with Joomla!
helper.php
$com_path = JPATH_SITE.'/components/com_content/';
require_once $com_path.'router.php';
require_once $com_path.'helpers/route.php';
JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel');
abstract class modBreedArticlesHelper
{
public static function getList(&$params)
{
// Get an instance of the generic articles model
$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$articles->setState('params', $appParams);
// Set the filters based on the module params
$articles->setState('list.start', 0);
$articles->setState('list.limit', (int) $params->get('count', 0));
$articles->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$articles->setState('filter.access', $access);
// Prep for Normal or Dynamic Modes
$mode = $params->get('mode', 'normal');
switch ($mode)
{
case 'dynamic':
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content') {
switch($view)
{
case 'category':
$catids = array($app->input->getInt('id'));
break;
case 'categories':
$catids = array($app->input->getInt('id'));
break;
case 'article':
if ($params->get('show_on_article_page', 1)) {
$article_id = $app->input->getInt('id');
$catid = $app->input->getInt('catid');
if (!$catid) {
// Get an instance of the generic article model
$article = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article->setState('params', $appParams);
$article->setState('filter.published', 1);
$article->setState('article.id', (int) $article_id);
$item = $article->getItem();
$catids = array($item->catid);
}
else {
$catids = array($catid);
}
}
else {
// Return right away if show_on_article_page option is off
return;
}
break;
case 'featured':
default:
// Return right away if not on the category or article views
return;
}
}
else {
// Return right away if not on a com_content page
return;
}
break;
case 'normal':
default:
$catids = $params->get('catid');
$articles->setState('filter.category_id.include', (bool) $params->get('category_filtering_type', 1));
break;
}
// Category filter
if ($catids) {
if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) {
// Get an instance of the generic categories model
$categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true));
$categories->setState('params', $appParams);
$levels = $params->get('levels', 1) ? $params->get('levels', 1) : 9999;
$categories->setState('filter.get_children', $levels);
$categories->setState('filter.published', 1);
$categories->setState('filter.access', $access);
$additional_catids = array();
foreach($catids as $catid)
{
$categories->setState('filter.parentId', $catid);
$recursive = true;
$items = $categories->getItems($recursive);
if ($items)
{
foreach($items as $category)
{
$condition = (($category->level - $categories->getParent()->level) <= $levels);
if ($condition) {
$additional_catids[] = $category->id;
}
}
}
}
$catids = array_unique(array_merge($catids, $additional_catids));
}
$articles->setState('filter.category_id', $catids);
}
// Ordering
$articles->setState('list.ordering', $params->get('article_ordering', 'a.ordering'));
$articles->setState('list.direction', $params->get('article_ordering_direction', 'ASC'));
// New Parameters
$articles->setState('filter.featured', $params->get('show_front', 'show'));
$articles->setState('filter.author_id', $params->get('created_by', ""));
$articles->setState('filter.author_id.include', $params->get('author_filtering_type', 1));
$articles->setState('filter.author_alias', $params->get('created_by_alias', ""));
$articles->setState('filter.author_alias.include', $params->get('author_alias_filtering_type', 1));
$excluded_articles = $params->get('excluded_articles', '');
if ($excluded_articles) {
$excluded_articles = explode("\r\n", $excluded_articles);
$articles->setState('filter.article_id', $excluded_articles);
$articles->setState('filter.article_id.include', false); // Exclude
}
$date_filtering = $params->get('date_filtering', 'off');
if ($date_filtering !== 'off') {
$articles->setState('filter.date_filtering', $date_filtering);
$articles->setState('filter.date_field', $params->get('date_field', 'a.created'));
$articles->setState('filter.start_date_range', $params->get('start_date_range', '1000-01-01 00:00:00'));
$articles->setState('filter.end_date_range', $params->get('end_date_range', '9999-12-31 23:59:59'));
$articles->setState('filter.relative_date', $params->get('relative_date', 30));
}
// Filter by language
$articles->setState('filter.language', $app->getLanguageFilter());
$items = $articles->getItems();
// Display options
$show_date = $params->get('show_date', 0);
$show_date_field = $params->get('show_date_field', 'created');
$show_date_format = $params->get('show_date_format', 'Y-m-d H:i:s');
$show_category = $params->get('show_category', 0);
$show_hits = $params->get('show_hits', 0);
$show_author = $params->get('show_author', 0);
$show_introtext = $params->get('show_introtext', 0);
$introtext_limit = $params->get('introtext_limit', 100);
// Find current Article ID if on an article page
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content' && $view === 'article') {
$active_article_id = $app->input->getInt('id');
}
else {
$active_article_id = 0;
}
// Prepare data for display using display options
foreach ($items as &$item)
{
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
if (isset($menuitems[0]))
{
$Itemid = $menuitems[0]->id;
}
elseif ($app->input->getInt('Itemid') > 0)
{
// Use Itemid from requesting page only if there is no existing menu
$Itemid = $app->input->getInt('Itemid');
}
$item->link = JRoute::_('index.php?option=com_users&view=login&Itemid='.$Itemid);
}
// Used for styling the active article
$item->active = $item->id == $active_article_id ? 'active' : '';
$item->displayDate = '';
if ($show_date) {
$item->displayDate = JHTML::_('date', $item->$show_date_field, $show_date_format);
}
if ($item->catid) {
$item->displayCategoryLink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
$item->displayCategoryTitle = $show_category ? ''.$item->category_title.'' : '';
}
else {
$item->displayCategoryTitle = $show_category ? $item->category_title : '';
}
$item->displayHits = $show_hits ? $item->hits : '';
$item->displayAuthorName = $show_author ? $item->author : '';
if ($show_introtext) {
$item->introtext = JHtml::_('content.prepare', $item->introtext, '', 'mod_articles_category.content');
$item->introtext = self::_cleanIntrotext($item->introtext);
}
$item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit) : '';
$item->displayReadmore = $item->alternative_readmore;
}
return $items;
}
public static function _cleanIntrotext($introtext)
{
$introtext = str_replace('<p>', ' ', $introtext);
$introtext = str_replace('</p>', ' ', $introtext);
$introtext = strip_tags($introtext, '<a><em><strong>');
$introtext = trim($introtext);
return $introtext;
}
/**
* Method to truncate introtext
*
* The goal is to get the proper length plain text string with as much of
* the html intact as possible with all tags properly closed.
*
* #param string $html The content of the introtext to be truncated
* #param integer $maxLength The maximum number of charactes to render
*
* #return string The truncated string
*/
public static function truncate($html, $maxLength = 0)
{
$baseLength = strlen($html);
$diffLength = 0;
// First get the plain text string. This is the rendered text we want to end up with.
$ptString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = false);
for ($maxLength; $maxLength < $baseLength;)
{
// Now get the string if we allow html.
$htmlString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = true);
// Now get the plain text from the html string.
$htmlStringToPtString = JHtml::_('string.truncate', $htmlString, $maxLength, $noSplit = true, $allowHtml = false);
// If the new plain text string matches the original plain text string we are done.
if ($ptString == $htmlStringToPtString)
{
return $htmlString;
}
// Get the number of html tag characters in the first $maxlength characters
$diffLength = strlen($ptString) - strlen($htmlStringToPtString);
// Set new $maxlength that adjusts for the html tags
$maxLength += $diffLength;
if ($baseLength <= $maxLength || $diffLength <= 0)
{
return $htmlString;
}
}
return $html;
}
public static function groupBy($list, $fieldName, $article_grouping_direction, $fieldNameToKeep = null)
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
if (!isset($grouped[$item->$fieldName])) {
$grouped[$item->$fieldName] = array();
}
if (is_null($fieldNameToKeep)) {
$grouped[$item->$fieldName][$key] = $item;
}
else {
$grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
return $grouped;
}
public static function groupByDate($list, $type = 'year', $article_grouping_direction, $month_year_format = 'F Y')
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
switch($type)
{
case 'month_year':
$month_year = JString::substr($item->created, 0, 7);
if (!isset($grouped[$month_year])) {
$grouped[$month_year] = array();
}
$grouped[$month_year][$key] = $item;
break;
case 'year':
default:
$year = JString::substr($item->created, 0, 4);
if (!isset($grouped[$year])) {
$grouped[$year] = array();
}
$grouped[$year][$key] = $item;
break;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
if ($type === 'month_year') {
foreach($grouped as $group => $items)
{
$date = new JDate($group);
$formatted_group = $date->format($month_year_format);
$grouped[$formatted_group] = $items;
unset($grouped[$group]);
}
}
return $grouped;
}
}
It looks like my issue was really specific to the project I am working on. If anyone happens to find this or wants to accomplish something similar, read on.
Decided to accomplish what I was doing using a JDatabase query. To retrieve the articles using the category alias, I queried the DB to match the alias I was giving the query to the category ID. Then joined the content table to get the article information.
All the information you need to make a proper JDatabase query can be found here: http://docs.joomla.org/Accessing_the_database_using_JDatabase
I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players