i am having 3-4 for each in my code which all use Eloquent and in all of them i get the same error
Trying to get property of non-object
when i dd the first argument of foreach which is an eloquent it returns an array of json with all the data in database of that table so its not returning null though i know it may break or bring null while in a foreach loop but i dont know where place one of them with model and controller here so here is the loop it self
<?php foreach(\App\Menu::all()->where('slug','main')->first()->items as $top_menu): ?>
<li class="dropdown">
<a href="<?php echo e(URL($top_menu->link)); ?>" <?php if($top_menu->link_blank): ?> target="_blank" <?php endif; ?>>
<?php echo e($top_menu->title); ?>
</a>
</li>
<?php endforeach; ?>
and here is my controller
class MenuItemsController extends AdminController
{
var $object = 'menu_items';
var $route_name = 'menu_items';
var $object_title = 'item';
var $object_titles = 'items';
var $attachments_config = [
'main_image' => [],
'default_thumb_sizes' => [],
'require' => ['main_image']
];
var $dt_fields_db = [];
var $dt_fields_heading = ['شناسه','منو','عنوان','موقعیت','نمایش','ثبت','عملیات'];
var $dt_fields_full = [
'id' => ['menu_items.id'],
'menu_title' => ['menus.title'],
'title' => ['menu_items.title'],
'position' => ['menu_items.position'],
'display' => ['menu_items.display'],
'created_at' => ['menu_items.created_at'],
'actions' => ['actions']
];
var $messages = array();
public function __construct() {
parent::__construct();
view()->share(['attachments_config' => $this->attachments_config]);
}
function index() {
$data['extra_assets'] = array(
array('type' => 'css','path' => 'datatables/datatables.bootstrap.css'),
array('type' => 'js','path' => 'datatables/jquery.dataTables.min.js'),
array('type' => 'js','path' => 'datatables/datatables.bootstrap.js'),
array('type' => 'script','path' => 'pagescripts/shared/datatables_script.php'),
);
$data['dt_fields_heading'] = $this->dt_fields_heading;
$data['dt_fields'] = $this->dt_fields_full;
$data['heading'] = $this->object_titles;
return view('admin.shared.datatable',$data);
}
function datatable() {
$this->dt_filtered_actions = dt_actions_filter($this->route_name,['edit','delete']);
$objects = DB::table('menu_items')
->join('menus', 'menu_items.menu_id','=', 'menus.id')
->select([
'menu_items.id',
'menus.title as menu_title',
'menu_items.title',
'menu_items.display',
'menu_items.position',
'menu_items.created_at'
]);
return Datatables::of($objects)
->editColumn('display', function($model) {return label_status($model->display);})
->editColumn('created_at', function($model) {return ($date = jDate::forge($model->created_at)->format('%H:%M:%S - %y/%m/%d'))?$date:"";})
->addColumn('actions', function($model) {
return dt_actions($this->route,$model->id,$this->dt_filtered_actions);
})
->make(true);
}
function add() {
$data['extra_assets'] = array(
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'add'.$this->object_title;
return view('admin.'.$this->route_name.'.add',$data);
}
function create(\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$menu = Menu::find($input['menu_id']);
if($menu->items->count() == $menu->capacity) {
$this->messages[] = array('type' => 'danger', 'text' => 'menu is full');
Session::flash('messages', $this->messages);
return back();
}
MenuItem::create($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->route('admin.'.$this->route_name.'.index');
}
function edit(MenuItem $MenuItem) {
$data['object'] = $MenuItem;
$data['extra_assets'] = array(
array('type' => 'script','path' => 'pagescripts/shared/image_preview_script.php'),
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
array('type' => 'js','path' => 'ckeditor/ckeditor.js'),
array('type' => 'js','path' => 'ckeditor/config.js'),
array('type' => 'js','path' => 'ckfinder/ckfinder.js'),
array('type' => 'js','path' => 'ckfinder/config.js'),
array('type' => 'script','path' => 'pagescripts/shared/ckeditor_script.php'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'edit'.$this->object_title;
return view('admin.'.$this->route_name.'.edit',$data);
}
function update(MenuItem $MenuItem,\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$MenuItem->update($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->back();
}
function delete(\Illuminate\Http\Request $requests,MenuItem $MenuItem) {
if($requests->ajax() && $MenuItem->delete()) {
return "OK";
} else {
return "ERROR";
}
}
function deleteall(\Illuminate\Http\Request $requests) {
$ids = $requests->get('ids');
if($requests->ajax()) {
foreach (explode(',',$ids) as $id) {
if(intval($id)) MenuItem::find($id)->delete();
}
return "OK";
} else {
return "ERROR";
}
}
}
the problem was because my database table didn't got any row by the slug of menu and the query returned null and that error happens that error generally happens when your query returns null thanks all for help
Related
I'm new with Codeigniter. I got error on my code using Codeigniter. My index doesn't show the row of my datatable, even my datatable had data in it. Anyone can find my error or typo text on my code? Please help me :(.
btw I have 2 controllers.
Here's my first controller (modules->api->controller->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Auth.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Tower extends MY_Auth
{
protected $ruleMsg;
function __construct()
{
parent::__construct();
$this->load->model('Model_tower');
$this->load->library('Pagingmeta');
$this->load->library('Validate');
$this->ruleMsg = '%s must be filled';
}
public function index_get($id = '') {
if (!empty($id)) {
return $this->get_detail($id);
}
$keyword = $this->get('search', true);
$except = $this->get('excepth', true);
$type = $this->get('type', true)??'list';
$page = $this->get('page', true)??1;
$limit = $this->get('limit', true)??10;
$data = $this->Model_tower->get_list($keyword, $this->role, $this->regional, $page, $limit);
$this->response([
'message' => 'Get tower success',
'data' => $data['data'],
'meta' => $this->pagingmeta->get_meta($data['total'], $limit, $page)
], REST_Controller::HTTP_OK);
}
private function get_detail($id) {
$data = $this->Model_tower->get_detail($id);
if (empty($data)) {
return $this->response([
'message' => 'Data not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->regional != $data->regional && $this->role != 'ADMN' && $id != $this->userId) {
return $this->response([
'message' => "You didn't have right to access this data"
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->role == 'ADMN') {
$data->is_editable = true;
}
return $this->response([
'message' => 'Get tower success',
'data' => $data
], REST_Controller::HTTP_OK);
}
public function tower_post() {
$this->validate_role();
$rules = $this->rules_post($this->post(null, true));
$params = $this->validate->validation($this->post(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'])) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$id = $this->Model_tower->tower_action($params, $this->userId);
$this->response([
'message' => 'Create tower success',
'data' => $id
], REST_Controller::HTTP_CREATED);
}
public function tower_put($id = '') {
$this->validate_role();
$rules = $this->rules_post($this->put(null, true));
$params = $this->validate->validation($this->put(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'], $id)) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$this->Model_tower->tower_action($params, $this->userId, $id);
$this->response([
'message' => 'Update tower success',
'data' => $id
], REST_Controller::HTTP_OK);
}
public function upload_post() {
$this->validate_role();
$this->load->library('Uuid');
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($_FILES['data']['tmp_name']);
$sheet = $spreadsheet->getActiveSheet();
// Store data from the activeSheet to the varibale in the form of Array
$data = array_values($sheet->toArray(null,true,true,true));
$oldData = $this->Model_tower->get_all_data();
$oldData = array_column($oldData, 'site_id');
$insertData = [];
$now = date('Y-m-d H:i:s');
foreach($data as $index => $d) {
if ($index == 0) {
continue;
}
$code = $this->uuid->generate();
$type = '';
$regional = '';
$inputedType = $d['D'];
if ($inputedType == 'MTEL') {
$type = 'mtel';
} else {
$type = 'reseller';
}
$inputedRegional = $d['G'];
if ($inputedRegional == 'Jawa Timur') {
$regional = 'JATIM';
} else if ($inputedRegional == 'Jawa Tengah') {
$regional = 'JATENG';
} else {
$regional = 'BALNUS';
}
if (empty($d['A']) || empty($d['B']) || in_array($d['A'], $oldData)) {
break;
}
$insertData[] = [
'site_id' => $d['A'],
'project_id' => $d['B'],
'site_name' => $d['C'],
'type' => $type,
'company' => $d['E'],
'address' => $d['F'],
'regional_code' => $regional,
'active_status' => 1,
'created_at' => $now,
'updated_at' => $now,
'code' => $code,
'created_by' => $this->userId,
'updated_by' => $this->userId
];
}
if (!empty($insertData)) {
$this->Model_tower->insert_batch($insertData);
}
$this->response([
'message' => 'Bulk insert success',
], REST_Controller::HTTP_CREATED);
}
private function validate_role() {
if ($this->role != 'ADMN') {
return $this->response([
'message' => "You didn't have right to access this action"
], REST_Controller::HTTP_BAD_REQUEST);
}
}
private function rules_post() {
return [
[
'field' => 'site_id',
'label' => 'Site id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'project_id',
'label' => 'Project id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'type',
'label' => 'Type',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'regional',
'label' => 'Regional',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'address',
'label' => 'Address',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'company',
'label' => 'Company',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
];
}
}
and this is my second Controller (Controllers->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Cont.php';
class Tower extends MY_Cont
{
public function __construct()
{
parent::__construct();
}
public function index() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'List Tower',
'nav_target' => 'tower_list',
);
$this->view('tower/index', $opts);
}
public function detail($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Tower Detail',
'tower' => $fetch_detail['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/detail', $opts);
}
public function new() {
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Add New Tower',
'list_region' => $regional['response']->data,
'nav_target' => 'tower_new',
);
$this->view('tower/new', $opts);
}
public function bulk() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Upload Tower',
'nav_target' => 'tower_bulk',
);
$this->view('tower/bulk', $opts);
}
public function edit($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Edit Tower Detail',
'tower' => $fetch_detail['response']->data,
'list_region' => $regional['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/edit', $opts);
}
private function render_invalid() {
header('HTTP/1.0 404');
$opts = array(
'content_only' => true,
'cfg_mainclass' => 'fullpage',
'private_routing' => false,
);
$this->view('layouts/404', $opts);
exit();
}
private function get_data_tower($id = '') {
if (empty($id)) {
$curl = curl_init(base_url() . 'api/tower');
} else {
$curl = curl_init(base_url() . 'api/tower/' . $id);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(
'code' => $httpcode,
'response' => $result,
);
}
private function get_regional() {
$curl = curl_init(base_url() . 'api/master/regional');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = array(
'code' => $httpcode,
'response' => $result,
);
return $response;
}
}
and this is my index.php
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="mainpanel">
<div class="mainpanel-header">
<div class="row align-items-end">
<div class="col-9">
<h3>List Tower</h3>
<h5>Click on tower to view detail</h5>
</div>
<div class="col text-right">
<a href="{{ base_url }}tower/new" class="panel-cta">
Add new tower
</a>
</div>
</div>
</div>
<form method="post" action="" id="form-filter-data" autocomplete="off">
<div class="digi-tablefilter">
<div class="filter-inputholder">
<label>Search</label>
<input type="text" name="search" placeholder="Search keyword" id="filter-search" />
</div>
<div class="filter-inputholder">
<input type="submit" value="Apply filter" />
</div>
</div>
</form>
<span class="table-information" id="t-info"></span>
<div class="digi-tableholder">
<table>
<thead>
<tr>
<th>Name</th>
<th>Project ID</th>
<th>Site ID</th>
<th>Regional</th>
<th>Company</th>
</tr>
</thead>
<tbody id="tower-table-value"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div id="test-pag"></div>
</div>
</div>
</div>
</section>
<script>
$(document).ready(function() {
const payload = {
page: 1,
limit: 10,
search: '',
}
fetchListData(payload);
});
function fetchListData(payload) {
var apiURL = "{{ api_server ~ 'tower' }}";
var userToken = getUserToken();
$.ajax({
url: apiURL,
type: "GET",
data: payload,
headers: {
Authorization: userToken,
},
success: function(response) {
const { data, message, meta } = response;
buildDataTable(data, meta);
},
error: function(response) {
const { responseJSON } = response;
addNotification({
type: 'error',
title: 'Fetching data tower gagal',
message: responseJSON.message,
});
return;
}
});
}
function buildDataTable(data, metadata) {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
$("#tower-table-value").empty();
target.innerHTML = "";
txtResult.innerHTML = "";
if (data.length == 0) {
buildEmptyRows();
return;
}
$.each(data, function(idx, item) {
const { id, name, project_id, site_id, regional, company } = item;
const tr = document.createElement('tr');
const nameHolder = document.createElement('td');
const projectHolder = document.createElement('td');
const siteHolder = document.createElement('td');
const regionalHolder = document.createElement('td');
const companyHolder = document.createElement('td');
nameHolder.innerHTML = name;
projectHolder.innerHTML = project_id;
siteHolder.innerHTML = site_id;
regionalHolder.innerHTML = regional;
companyHolder.innerHTML = company;
tr.appendChild(nameHolder);
tr.appendChild(projectHolder);
tr.appendChild(siteHolder);
tr.appendChild(regionalHolder);
tr.appendChild(companyHolder);
tr.onclick = function(e) {
window.location.href = `{{ base_url }}tower/detail/${item.id}`;
}
target.appendChild(tr);
});
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> ${metadata.total} row(s) found.`;
txtResult.innerHTML = $resultText;
if (metadata.last_page > 1) {
buildPagination(metadata);
} else {
hideLoader();
}
}
function buildEmptyRows() {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> • 0 row(s) found.`;
txtResult.innerHTML = $resultText;
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colspan = 5;
td.innerHTML = 'No Rows Found.';
tr.appendChild(td);
target.appendChild(tr);
hideLoader();
}
function buildPagination(metadata) {
const { from, to, last_page, current_page, per_page, total } = metadata;
$("#test-pag").pagination({
items: total,
itemsOnPage: per_page,
currentPage: current_page,
onPageClick: function(pageNumber, event) {
event.preventDefault();
const payload = {
page: pageNumber,
limit: per_page,
search: '',
}
fetchListData(payload);
}
});
}
$("#form-filter-data").submit(function(e) {
e.preventDefault();
const $payload = {
page: 1,
limit: 10,
search: $("#filter-search").val()
}
fetchListData($payload);
})
</script>
I'll very thankful if u can solve my problem :D
I am using Laravel Tastyigniter system in which I want to show the locations name in dropdown in Menus module according to locations added by admin which is currently logged in.
For Example, If admin A added two locations such as location A and location B and
admin B added two locations such as location C and location D resp.
Note - The locations are getting saved in database with created_by column which is id of admin adding the location.
A) What supposed to happen -
If I logged in as admin A then in location dropdown Location A and Location B should get display
If I logged in as admin B then in location dropdown Location C and Location D should get display.
B) What is happening currently -
For both the admins all the 4 locations are getting displayed.
C) Following is the Code -
Here is Menus_model.php
<?php namespace Admin\Models;
use Admin\Traits\Locationable;
use Igniter\Flame\Database\Traits\Purgeable;
class Menus_model extends Model
{
use Purgeable;
use Locationable;
const LOCATIONABLE_RELATION = 'locations';
public $relation = [
'morphToMany' => [
'locations' => ['Admin\Models\Locations_model', 'name' =>
'locationable'],
],
];
protected $purgeable = ['locations'];
}
Here is menus_model.php which is present under models->config
<?php
$config['form']['tabs'] = [
'fields' => [
'locations' => [
'label' => 'Location',
'type' => 'relation',
'span' => 'right',
'valueFrom' => 'locations',
'nameFrom' => 'location_name',
'locationAware' => 'hide',
],
],
];
return $config;
Here is the Locations_model.php file code under models folder
<?php namespace Admin\Models;
use Admin\Traits\HasDeliveryAreas;
use Admin\Traits\HasWorkingHours;
use Igniter\Flame\Database\Attach\HasMedia;
use Igniter\Flame\Database\Traits\HasPermalink;
use Igniter\Flame\Database\Traits\Purgeable;
use Igniter\Flame\Location\Models\AbstractLocation;
use DB;
/**
* Locations Model Class
*
* #package Admin
*/
class Locations_model extends AbstractLocation
{
use HasWorkingHours;
use HasDeliveryAreas;
use HasPermalink;
use Purgeable;
use HasMedia;
const LOCATION_CONTEXT_SINGLE = 'single';
const LOCATION_CONTEXT_MULTIPLE = 'multiple';
protected $appends = ['location_thumb'];
protected $hidden = ['options'];
public $casts = [
'location_country_id' => 'integer',
'location_lat' => 'double',
'location_lng' => 'double',
'offer_delivery' => 'boolean',
'offer_collection' => 'boolean',
'delivery_time' => 'integer',
'collection_time' => 'integer',
'last_order_time' => 'integer',
'reservation_time_interval' => 'integer',
'reservation_stay_time' => 'integer',
'location_status' => 'boolean',
'options' => 'serialize',
'location_city' => 'integer',
'region_id'=>'integer',
];
public $relation = [
'hasMany' => [
'working_hours' => ['Admin\Models\Working_hours_model', 'delete' =>
TRUE],
'delivery_areas' => ['Admin\Models\Location_areas_model', 'delete'
=> TRUE],
'reviews' => ['Admin\Models\Reviews_model', 'delete' => TRUE],
],
'belongsTo' => [
'country' => ['System\Models\Countries_model', 'otherKey' =>
'country_id', 'foreignKey' => 'location_country_id'],
'city' => ['Admin\Models\City_model', 'otherKey' => 'city_id', 'foreignKey' => 'location_city'],
'region' => ['Admin\Models\Region_model', 'otherKey' => 'region_id', 'foreignKey' => 'region_id'],
],
'belongsToMany' => [
'tables' => ['Admin\Models\Tables_model', 'table' => 'location_tables'],
'cuisines' => ['Admin\Models\Cuisines_model', 'table' => 'location_cuisines'],
],
];
protected $purgeable = ['tables', 'delivery_areas','cuisines'];
public $permalinkable = [
'permalink_slug' => [
'source' => 'location_name',
'controller' => 'local',
],
];
public $mediable = [
'thumb',
'gallery' => ['multiple' => TRUE],
];
protected static $allowedSortingColumns = [
'distance asc', 'distance desc',
'reviews_count asc', 'reviews_count desc',
'location_id asc', 'location_id desc',
'location_name asc', 'location_name desc',
];
public $url;
protected static $defaultLocation;
public static function onboardingIsComplete()
{
if (!$defaultId = params('default_location_id'))
return FALSE;
if (!$model = self::isEnabled()->find($defaultId))
return FALSE;
return isset($model->getAddress()['location_lat'])
AND isset($model->getAddress()['location_lng'])
AND ($model->hasDelivery() OR $model->hasCollection())
AND isset($model->options['hours'])
AND $model->delivery_areas->where('is_default', 1)->count() > 0;
}
public function getWeekDaysOptions()
{
return ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
}
//
// Events
//
protected function afterFetch()
{
$this->parseOptionsValue();
}
protected function beforeSave()
{
$this->parseOptionsValue();
}
protected function afterSave()
{
$this->performAfterSave();
}
protected function beforeDelete()
{
Location_tables_model::where('location_id', $this->getKey())->delete();
Location_cuisines_model::where('location_id', $this->getKey())->delete();
}
//
// Scopes
//
/**
* Scope a query to only include enabled location
*
* #return $this
*/
public function scopeIsEnabled($query)
{
return $query->where('location_status', 1);
}
public function scopeListFrontEnd($query, array $options = [])
{
extract(array_merge([
'page' => 1,
'pageLimit' => 20,
'sort' => null,
'search' => null,
'latitude' => null,
'longitude' => null,
], $options));
if ($latitude AND $longitude)
$query->selectDistance($latitude, $longitude);
$searchableFields = ['location_name', 'location_address_1', 'location_address_2', 'location_city',
'location_state', 'location_postcode', 'description'];
if (!is_array($sort)) {
$sort = [$sort];
}
foreach ($sort as $_sort) {
if (in_array($_sort, self::$allowedSortingColumns)) {
$parts = explode(' ', $_sort);
if (count($parts) < 2) {
array_push($parts, 'desc');
}
[$sortField, $sortDirection] = $parts;
$query->orderBy($sortField, $sortDirection);
}
}
$search = trim($search);
if (strlen($search)) {
$query->search($search, $searchableFields);
}
return $query->paginate($pageLimit, $page);
}
//
// Accessors & Mutators
//
public function getLocationThumbAttribute()
{
return $this->hasMedia() ? $this->getThumb() : null;
}
public function getDeliveryTimeAttribute($value)
{
return (int)$value;
}
public function getCollectionTimeAttribute($value)
{
return (int)$value;
}
public function getFutureOrdersAttribute($value)
{
return (bool)$value;
}
public function getReservationTimeIntervalAttribute($value)
{
return (int)$value;
}
//
// Helpers
//
public function setUrl($suffix = null)
{
if (is_single_location())
$suffix = '/menus';
$this->url = site_url($this->permalink_slug.$suffix);
}
public function hasGallery()
{
return $this->hasMedia('gallery');
}
public function getGallery()
{
$gallery = array_get($this->options, 'gallery');
$gallery['images'] = $this->getMedia('gallery');
return $gallery;
}
public function parseOptionsValue()
{
$value = #unserialize($this->attributes['options']) ?: [];
$this->parseHoursFromOptions($value);
$this->parseAreasFromOptions($value);
$this->attributes['options'] = #serialize($value);
return $value;
}
public function listAvailablePayments()
{
$result = [];
$payments = array_get($this->options, 'payments', []);
$paymentGateways = Payments_model::listPayments();
foreach ($paymentGateways as $payment) {
if ($payments AND !in_array($payment->code, $payments)) continue;
$result[$payment->code] = $payment;
}
return collect($result);
}
public function performAfterSave()
{
$this->restorePurgedValues();
if (array_key_exists('hours', $this->options)) {
$this->addOpeningHours($this->options['hours']);
}
if (array_key_exists('delivery_areas', $this->attributes)) {
$this->addLocationAreas($this->attributes['delivery_areas']);
}
if (array_key_exists('tables', $this->attributes)) {
$this->addLocationTables($this->attributes['tables']);
}
if (array_key_exists('cuisines', $this->attributes)) {
$this->addLocationCuisines($this->attributes['cuisines']);
}
}
public static function getDefault()
{
if (self::$defaultLocation !== null) {
return self::$defaultLocation;
}
$defaultLocation = self::isEnabled()->where('location_id', params('default_location_id'))->first();
if (!$defaultLocation) {
$defaultLocation = self::isEnabled()->first();
if ($defaultLocation) {
params('default_location_id', $defaultLocation->getKey());
params()->save();
}
}
return self::$defaultLocation = $defaultLocation;
}
/**
* Create a new or update existing location tables
*
* #param array $tables
*
* #return bool
*/
public function addLocationTables($tables = [])
{
return $this->tables()->sync($tables);
}
public function addLocationCuisines($cuisines = [])
{
return $this->cuisines()->sync($cuisines);
}
}
Here is locations_model.php which is present under models->config folder
<?php
$config['form']['tabs'] = [
'defaultTab' => 'lang:admin::lang.locations.text_tab_general',
'fields' => [
'location_name' => [
'label' => 'lang:admin::lang.label_name',
'type' => 'text',
'span' => 'left',
],
'location_email' => [
'label' => 'lang:admin::lang.label_email',
'type' => 'text',
'span' => 'right',
],
'location_telephone' => [
'label' => 'lang:admin::lang.locations.label_telephone',
'type' => 'text',
'span' => 'left',
],
'location_status' => [
'label' => 'lang:admin::lang.label_status',
'type' => 'switch',
'default' => 1,
'span' => 'right',
],
'created_by' => [
'type' => 'hidden',
'default' => isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '',
],
],
];
return $config;
UPDATED
Basically I want to diaply locations in menus form , Currently in menus form all the locations are getting display and the code for this is mentioned below
This is Menus.php controller
<?php namespace Admin\Controllers;
use Admin\Classes\AdminController;
use Admin\Models\Menu_options_model;
use AdminMenu;
use ApplicationException;
class Menus extends AdminController
{
public $implement = [
'Admin\Actions\ListController',
'Admin\Actions\FormController',
'Admin\Actions\LocationAwareController',
];
public $listConfig = [
'list' => [
'model' => 'Admin\Models\Menus_model',
'title' => 'lang:admin::lang.menus.text_title',
'emptyMessage' => 'lang:admin::lang.menus.text_empty',
'defaultSort' => ['menu_id', 'DESC'],
'configFile' => 'menus_model',
],
];
protected $requiredPermissions = 'Admin.Menus';
public function __construct()
{
parent::__construct();
AdminMenu::setContext('menus');
}
public function edit_onChooseMenuOption($context, $recordId)
{
$menuOptionId = post('Menu._options');
if (!$menuOption = Menu_options_model::find($menuOptionId))
throw new ApplicationException('Please select a menu option to
attach');
$model = $this->asExtension('FormController')->formFindModelObject($recordId);
$menuItemOption = $model->menu_options()->create(['option_id' => $menuOptionId]);
$menuOption->option_values()->get()->each(function ($model) use ($menuItemOption) {
$menuItemOption->menu_option_values()->create([
'menu_option_id' => $menuItemOption->menu_option_id,
'option_value_id' => $model->option_value_id,
'new_price' => $model->price,
]);
});
$model->reload();
$this->asExtension('FormController')->initForm($model, $context);
flash()->success(sprintf(lang('admin::lang.alert_success'), 'Menu item option attached'))->now();
$formField = $this->widgets['form']->getField('menu_options');
return [
'#notification' => $this->makePartial('flash'),
'#'.$formField->getId('group') => $this->widgets['form']->renderField($formField, [
'useContainer' => FALSE,
]),
];
}
}
Below is Locaations.php controller
<?php namespace Admin\Controllers;
use Admin\Facades\AdminLocation;
use Admin\Models\Locations_model;
use AdminMenu;
use Exception;
use Geocoder;
class Locations extends \Admin\Classes\AdminController
{
public $implement = [
'Admin\Actions\ListController',
'Admin\Actions\FormController',
];
public $listConfig = [
'list' => [
'model' => 'Admin\Models\Locations_model',
'title' => 'lang:admin::lang.locations.text_title',
'emptyMessage' => 'lang:admin::lang.locations.text_empty',
'defaultSort' => ['location_id', 'DESC'],
'configFile' => 'locations_model',
],
];
protected $requiredPermissions = 'Admin.Locations';
public function __construct()
{
parent::__construct();
AdminMenu::setContext('locations', 'restaurant');
}
public function remap($action, $params)
{
if ($action != 'settings' AND AdminLocation::check())
return $this->redirect('locations/settings');
return parent::remap($action, $params);
}
public function settings($context = null)
{
if (!AdminLocation::check())
return $this->redirect('locations');
$this->asExtension('FormController')->edit('edit', $this-
>getLocationId());
}
public function index_onSetDefault($context = null)
{
$defaultId = post('default');
if (Locations_model::updateDefault(['location_id' => $defaultId])) {
flash()->success(sprintf(lang('admin::lang.alert_success'),
lang('admin::lang.locations.alert_set_default')));
}
return $this->refreshList('list');
}
public function settings_onSave($context = null)
{
try {
$this->asExtension('FormController')->edit_onSave('edit',
params('default_location_id'));
return $this->refresh();
}
catch (Exception $ex) {
$this->handleError($ex);
}
}
public function listOverrideColumnValue($record, $column, $alias = null)
{
if ($column->type != 'button')
return null;
if ($column->columnName != 'default')
return null;
$attributes = $column->attributes;
$column->iconCssClass = 'fa fa-star-o';
if ($record->getKey() == params('default_location_id')) {
$column->iconCssClass = 'fa fa-star';
}
return $attributes;
}
public function formExtendQuery($query)
{
if ($locationId = $this->getLocationId())
$query->where('location_id', $locationId);
}
public function formAfterSave($model)
{
if (post('Location.options.auto_lat_lng')) {
if ($logs = Geocoder::getLogs())
flash()->error(implode(PHP_EOL, $logs))->important();
}
}
}
Views
Now the n views folder there is folder names menus and under that folder there is create.php file for displaying create menu form
The code in views->menus->create.php file is below
<div class="row-fluid">
<?= form_open(current_url(),
[
'id' => 'edit-form',
'role' => 'form',
'method' => 'POST',
]
); ?>
<?= $this->renderForm(); ?>
<?= form_close(); ?>
</div>
FormController
Now the renderForm() function is present at path app/admin/actions/FormController.php which we have defined in Locations and Menus controller under public $implement = ['Admin\Actions\FormController'];
Ther renderForm() function is as follow
public function renderForm($options = [])
{
if (!$this->formWidget) {
throw new Exception(lang('admin::lang.form.not_ready'));
}
if (!is_null($this->toolbarWidget)) {
$form[] = $this->toolbarWidget->render();
}
$form[] = $this->formWidget->render($options);
return implode(PHP_EOL, $form);
}
Widgets
At last the there are widgets for input fields like select, text, radio, checkbox etc. In our case we have widget name field_selectlist, which is present at path app/admin/widgets/form/field_selectlist.php
The field_selectlist.php file has code as below
<?php
$fieldOptions = $field->options();
//print_r($fieldOptions);die; All the locations are displaying here.
$isCheckboxMode = $field->config['mode'] ?? 'checkbox';
$selectMultiple = $isCheckboxMode == 'checkbox';
$checkedValues = (array)$field->value;
$enableFilter = (count($fieldOptions) > 20);
?>
<div class="control-selectlist">
<select
data-control="selectlist"
id="<?= $field->getId() ?>"
name="<?= $field->getName() ?><?= $selectMultiple ? '[]' : '' ?>"
<?php if ($field->placeholder) { ?>data-non-selected-text="<?=
e(lang($field->placeholder)) ?>"<?php } ?>
<?= $selectMultiple ? 'multiple="multiple"' : '' ?>
data-enable-filtering="<?= $enableFilter; ?>"
data-enable-case-insensitive-filtering="<?= $enableFilter; ?>"
<?= $field->getAttributes() ?>>
<?php if ($field->placeholder) { ?>
<option value=""><?= e(lang($field->placeholder)) ?></option>
<?php } ?>
<?php
foreach ($fieldOptions as $value => $option) { ?>
<?php
if (!is_array($option)) $option = [$option];
if ($field->disabled AND !in_array($value, $checkedValues)) continue;
?>
<option
<?= in_array($value, $checkedValues) ? 'selected="selected"' : '' ?>
value="<?= $value ?>">
<?= e(is_lang_key($option[0]) ? lang($option[0]) : $option[0]) ?>
<?php if (isset($option[1])) { ?>
<span><?= e(is_lang_key($option[1]) ? lang($option[1]) :
$option[1]) ?></span>
<?php } ?>
</option>
<?php } ?>
this is the function, the error is in line 25 in
'$data = Excel::load($path)->get();' saying that None-Static méthode 'load' should not be called statically:
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'zi' => $row['zi'],
'siteId' => $row['siteId'],
'gsmId' => $row['gsmId'],
'topoCont' => $row['topoCont'],
'plannRedr' => $row['plannRedr'],
'Country' => $row['country'],
'dateReal' => $row['dateReal'],
'semReal' => $row['semReal'],
'statuts' => $row['country'],
);
}
}
if(!empty($insert_data))
{
DB::table('tbl_customer')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
}
add this in your controller :
use Maatwebsite\Excel\Facades\Excel;
I wanna show usernames in timeline index. It show error
Call to a member function getStatusesLabel() on integer
if use this code :
'status' =>$model->data['status']->getStatusesLabel(),
and
'author' => $model->data['author']->getAuthor(),
and another error
Trying to get property of non-object
if use this code :
'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
My Model
namespace common\models;
.....
class Article extends ActiveRecord
{
.....
public function getAuthor()
{
return $this->hasOne(User::className(), ['id' => 'author_id']);
}
public function getUpdater()
{
return $this->hasOne(User::className(), ['id' => 'updater_id']);
}
public function getCategory()
{
return $this->hasOne(ArticleCategory::className(), ['id' => 'category_id']);
}
public function getArticleAttachments()
{
return $this->hasMany(ArticleAttachment::className(), ['article_id' => 'id']);
}
public static function statuses()
{
return [
self::STATUS_PUBLISHED => Yii::t('common', 'Published'),
self::STATUS_DRAFT => Yii::t('common', 'Draft'),
];
}
public function afterCreate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_item',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'created_at' => $this->created_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
public function afterUpdate()
{
$this->refresh();
// use common\commands\AddToTimelineCommand;
Yii::$app->commandBus->handle(new AddToTimelineCommand([
'category' => 'articles',
'event' => '_itemU',
'data' => [
'title' => $this->title,
'published_at' => $this->published_at,
'updated_at' => $this->updated_at,
'slug' => $this->slug,
'author' => $this->author_id,
'category' => $this->category,
'status' => $this->status,
]
]));
}
}
my controller article:
public function actionCreate()
{
$model = new Article();
$transaction = Yii::$app->db->beginTransaction();
try{
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->afterCreate();
$transaction->commit();
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
'categories' => ArticleCategory::find()->active()->all(),
]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
controller timeline
public function actionIndex()
{
$searchModel = new TimelineEventSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort = [
'defaultOrder'=>['created_at'=>SORT_DESC]
];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
command timeline :
class AddToTimelineCommand extends Object implements SelfHandlingCommand
{
public $category;
public $event;
public $data;
public function handle($command)
{
$model = new TimelineEvent();
$model->application = Yii::$app->id;
$model->category = $command->category;
$model->event = $command->event;
$model->data = json_encode($command->data, JSON_UNESCAPED_UNICODE);
return $model->save(false);
}
}
index timeline:
<ul class="timeline">
<?php foreach($dataProvider->getModels() as $model): ?>
<?php if(!isset($date) || $date != Yii::$app->formatter->asDate($model->created_at)): ?>
<!-- timeline time label -->
<li class="time-label">
<span class="bg-blue">
<?php echo Yii::$app->formatter->asDate($model->created_at) ?>
</span>
</li>
<?php $date = Yii::$app->formatter->asDate($model->created_at) ?>
<?php endif; ?>
<li>
<?php
try {
$viewFile = sprintf('%s/%s', $model->category, $model->event);
echo $this->render($viewFile, ['model' => $model]);
} catch (\yii\base\InvalidParamException $e) {
echo $this->render('_item', ['model' => $model]);
}
?>
</li>
view _item for index:
<div class="timeline-body">
<?php echo Yii::t('backend', 'Updated post <b>({title})</b>, published date : {published_at} ', [
'title' => Html::a($model->data['title'],
Url::to(Yii::$app->urlManager->hostInfo.'/article'.'/') .$model->data['slug'],
['target' => '_blank']),
//'author' => ArrayHelper::map($model->data['author']->getAuthor, 'id','username'),
//'author' => $model->data['author']->getAuthor(),
'author' => $model->data['author'],
'category' => $model->data['category'],
//'status' =>$model->data['status']->getStatusesLabel(),
'published_at' => Yii::$app->formatter->asDatetime($model->data['published_at']),
'updated_at' => Yii::$app->formatter->asDatetime($model->data['updated_at'])
])//.Html::a($model->data['title'], ["/article/$model->data['title']"]) ?>
</div>
what is wrong with the above code?
i was use in GridView / detailview, there is no errors
how do I fix it?
In a simple view (not based on gridview or detailView widget) that you render using eg:
return $this->render('your_view', [
'model' => $model,
]);
you can use directly the model and the attribute (or the depending function) eg:
'author' => $model->author
If you instead use a
return $this->render('your_view', [
'dataProvider' => $dataProvider,
]);
you can refer to the model instance
'author' => $dataProvider->models[i]['author']
where i is the index for the specific instance
i have a mistake uploading some images on "multiple upload". If i try to upload the galeries without these images the widget works correctly.
The Image: http://s27.postimg.org/a6qosyctv/Esta_Imagen_Tira_Error.jpg
My form:
$form = ActiveForm::begin([
'id' => 'Item',
'layout' => 'horizontal',
'enableClientValidation' => false,
'errorSummaryCssClass' => 'error-summary alert alert-error',
'options' => ['enctype'=>'multipart/form-data']
]);
$form->field($gallery, 'images[]')->widget(\kartik\file\FileInput::classname(), [
'options' => [
'multiple' => true,
],
'pluginOptions' => [
'uploadUrl' => 'javascript:;',
'showCaption' => false,
'showUpload' => false,
'overwriteInitial' => false,
'allowedFileExtensions' => ['jpg', 'jpeg', 'png'],
'layoutTemplates' => [
'actionUpload' => '',
],
'browseIcon' => '',
'browseLabel' => Yii::t('app', 'Select Files'),
'browseClass' => 'btn btn-block',
'removeLabel' => Yii::t('app', 'Remove All File'),
'removeClass' => 'btn btn-block',
],
]);
My controller:
public function actionCreate()
{
$model = new Hotel();
$model->setCurrentLanguage();
$model->itemType = IElement::ITEM_TYPE_HOTEL;
if ($model->load($_POST)) {
$model->coverPhoto = UploadedFile::getInstance($model, 'coverPhoto');
if ($model->save()) {
if (isset($_POST['Gallery'])) {
$gallery = new Gallery();
$gallery->setAttributes($_POST['Gallery']);
$gallery->idElement = $model->idItem;
$gallery->itemType = IElement::ITEM_TYPE_HOTEL;
$gallery->images = UploadedFile::getInstances($gallery, 'images');
$gallery->save();
}
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
'gallery' => new Gallery(),
]);
}
Gallery Model:
public $images = [];
public function rules()
{
return array_merge(parent::rules(), [
[['images', 'removedImages'], 'safe']
]);
}
public function save($runValidation = true, $attributeNames = null)
{
$transaction = $this->getDb()->beginTransaction();
if(parent::save($runValidation, $attributeNames)){
foreach($this->images as $image){
/* #var UploadedFile $image */
if(!GalleryItem::generateFromImage($image, $this)){
$transaction->rollBack();
return false;
}
}
if(strlen($this->removedImages) > 0){
foreach(explode(',', $this->removedImages) as $itemId){
$albumItem = GalleryItem::findOne($itemId);
if($albumItem instanceof GalleryItem && !$albumItem->delete()){
$transaction->rollBack();
return false;
}
}
}
$transaction->commit();
return true;
}
$transaction->rollBack();
return false;
}
Gallery Item Model:
public static function generateFromImage($imageFile, $gallery)
{
$image = new self;
$image->idGallery = $gallery->primaryKey;
$image->galleryItemOrder = time();
$path = $image->getBasePath();
if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$name = uniqid().'_'.strtr($imageFile->name, [' '=>'_']);
$imageFile->saveAs($path.DIRECTORY_SEPARATOR.$name);
$image->picture = $name;
// var_dump($image->attributes);die();
if(!$image->save()){
#unlink($path.DIRECTORY_SEPARATOR.$name);
return false;
}
return true;
}