Call to a member function toArray() on null - laravel

I am trying to get value of meta key from table called site.management
this table
=>http://www.mediafire.com/file/pa4gs0pbwpoalqj/Homemetakey.PNG/file
public function index()
{
if (Schema::hasTable('site_managements')) {
$homepage = SiteManagement::getMetaValue('homepage');
if (!empty($homepage['home'])) {
$sections = Helper::getPageSections();
$selected_page = Page::find($homepage['home']);
$page_data = $selected_page->toArray();
$page = array();
$home = true;
$page['id'] = $page_data['id'];
$page['title'] = $page_data['title'];
$page['slug'] = $page_data['slug'];
$page['section_list'] = !empty($page_data['sections']) ? Helper::getUnserializeData($page_data['sections']) : array();
$description = $page_data['body'];
$page_meta = SiteManagement::where('meta_key', 'seo-desc-' . $homepage['home'])->select('meta_value')->pluck('meta_value')->first();
$page_banner = SiteManagement::where('meta_key', 'page-banner-' . $homepage['home'])->select('meta_value')->pluck('meta_value')->first();
$show_banner = SiteManagement::where('meta_key', 'show-banner-' . $homepage['home'])->select('meta_value')->pluck('meta_value')->first();
$breadcrumbs_settings = SiteManagement::getMetaValue('show_breadcrumb');
$show_breadcrumbs = !empty($breadcrumbs_settings) ? $breadcrumbs_settings : 'true';
$show_banner_image = false;
if ($show_banner == false) {
$show_banner_image = false;
} else {
$show_banner_image = true;
}
$banner = !empty($page_banner) ? Helper::getBannerImage('uploads/pages/' . $page_banner) : 'images/bannerimg/img-02.jpg';
$meta_desc = !empty($page_meta) ? $page_meta : '';
$type = Helper::getAccessType() == 'services' ? 'service' : Helper::getAccessType();
$slider_section = '';
$slider_style = '';
$slider_order = '';
foreach ($selected_page->meta->toArray() as $key => $meta) {
preg_match_all('!\d+!', $meta['meta_key'], $matches);
$meta_key_modify = preg_replace('/\d/', '', $meta['meta_key']);
if ($meta_key_modify == 'sliders') {
$slider_section = Helper::getUnserializeData($meta['meta_value']);
$slider_style = !empty($slider_section['style']) ? $slider_section['style'] : '';
$slider_order = !empty($slider_section['parentIndex']) ? $slider_section['parentIndex'] : '';
}
}
$categories = Category::latest()->get()->take(8);
$skills = Skill::latest()->get()->take(8);
$locations = Location::latest()->get()->take(8);
$languages = Language::latest()->get()->take(8);
$page_header = '';
$currency = SiteManagement::getMetaValue('commision');
$symbol = !empty($currency) && !empty($currency[0]['currency']) ? Helper::currencyList($currency[0]['currency']) : array();
if (file_exists(resource_path('views/extend/front-end/pages/show.blade.php'))) {
return View::make(
'extend.front-end.pages.show',
compact(
'symbol',
'page_header',
'page',
'meta_desc',
'banner',
'show_banner',
'show_banner_image',
'show_breadcrumbs',
'selected_page',
'sections',
'type',
'slider_style',
'slider_section',
'description',
'slider_order',
'home',
'categories',
'skills',
'locations',
'languages'
)
);
} else {
return View::make(
'front-end.pages.show',
compact(
'symbol',
'page_header',
'page',
'meta_desc',
'banner',
'show_banner',
'show_banner_image',
'show_breadcrumbs',
'selected_page',
'sections',
'type',
'slider_style',
'slider_section',
'description',
'slider_order',
'home',
'categories',
'skills',
'locations',
'languages'
)
);
}
} else {
if (file_exists(resource_path('views/extend/front-end/index.blade.php'))) {
return view('extend.front-end.index');
} else {
return view('front-end.index');
}
}
}
}
and am getting this error
Call to a member function toArray() on null
every thing was working fine but an interruption happened in my DB and I resorted it but home index after login gives me the mentioned error
Call to a member function toArray() on null
*(the project on laravel 5) *
what is the problem here?

Related

multiple voyager browse blade laravel

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 .

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

Prestashop shipping costs cleared after order confirmation

I'm on Prestashop 1.7.6. I made a simple test module for adding a custom carrier and manage it programmatically.
Everything works well during checkout: I see new carrier with the correct cost, if I select it the total of cart is correct! (the shipping cost is added).
After choosing the payment method and confirming the order (and I'm redirected to order confirmation page), the shipping costs disappear: is always free shipping!
I do not understand why..
I report the code of this test:
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class TxShipping extends CarrierModule
{
const PREFIX = 'tx_';
public $id_carrier;
private $loopCount = 0;
private $shipCost = 0;
protected $_hooks = array(
'actionCarrierUpdate',
'displayOrderConfirmation',
);
protected $_carriers = array(
//"Public carrier name" => "technical name",
'My new carrier' => 'txshipping',
);
public function __construct()
{
$this->name = 'txshipping';
$this->tab = 'shipping_logistics';
$this->version = '1.0.0';
$this->author = 'Gerry';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.7.1.0',
'max' => _PS_VERSION_
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Tx Shipping');
$this->description = $this->l('manage shipping costs');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
if (!Configuration::get('TXSHIPPING_NAME')) {
$this->warning = $this->l('No name provided');
}
}
public function getTemplate($area, $file)
{
return 'views/templates/' . $area . '/' . $file;
}
//-------------------------------------------------
// Hooks
//-------------------------------------------------
public function hookActionCarrierUpdate($params)
{
if ($params['carrier']->id_reference == Configuration::get(self::PREFIX . 'fcd_reference')) {
Configuration::updateValue(self::PREFIX . 'fcd', $params['carrier']->id);
}
}
public function getOrderShippingCost($params = null, $shipping_cost = 0) {
$curPage = $this->context->controller->php_self;
/* using test on which page is running cause the following code is always executed (even if is loading home page!?)
I don't understand why */
if ($curPage == "order") {
$this->loopCount++; // attempt for not to run the same code over and over.. but it doesn't work very well
if ($this->loopCount == 1) {
$this->shipCost = 77;
/*
$address = new Address($params->id_address_delivery);
$cap = $address->postcode;
$curID = $this->id_carrier; */
}
return floatval($this->shipCost);
} elseif ($curPage == "order-confirmation") {
$test = 76; // for simple test
return floatval($test);
} else {
if ($curPage != "pagenotfound") {
$this->loopCount = 0;
$this->shipCost = 0;
}
}
}
public function getOrderShippingCostExternal($params){
//return 999; costi spedizione
return $this->getOrderShippingCost($params, 0);
}
//-------------------------------------------------
// Setup
//-------------------------------------------------
public function install()
{
if (parent::install()) {
foreach ($this->_hooks as $hook) {
if (!$this->registerHook($hook)) {
return false;
}
}
if (!$this->createCarriers()) {
return false;
}
return true;
}
return false;
}
public function uninstall()
{
if (parent::uninstall()) {
foreach ($this->_hooks as $hook) {
if (!$this->unregisterHook($hook)) {
return false;
}
}
if (!$this->deleteCarriers()) {
return false;
}
return true;
}
return false;
}
//-------------------------------------------------
// Funzioni private
//-------------------------------------------------
protected function createCarriers()
{
foreach ($this->_carriers as $key => $value) {
//Create own carrier
$carrier = new Carrier();
$carrier->name = $key;
$carrier->id_tax_rules_group = 0;
$carrier->active = 1;
$carrier->deleted = 0;
foreach (Language::getLanguages(true) as $language)
$carrier->delay[(int)$language['id_lang']] = 'Delay [1-2 days]';
$carrier->shipping_handling = false;
$carrier->range_behavior = 0;
$carrier->is_module = true;
$carrier->shipping_external = true;
$carrier->external_module_name = $this->name;
$carrier->need_range = true;
if ($carrier->add()) {
$groups = Group::getGroups(true);
foreach ($groups as $group) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_group', array(
'id_carrier' => (int) $carrier->id,
'id_group' => (int) $group['id_group']
), 'INSERT');
}
$rangePrice = new RangePrice();
$rangePrice->id_carrier = $carrier->id;
$rangePrice->delimiter1 = '0';
$rangePrice->delimiter2 = '1000000';
$rangePrice->add();
$rangeWeight = new RangeWeight();
$rangeWeight->id_carrier = $carrier->id;
$rangeWeight->delimiter1 = '0';
$rangeWeight->delimiter2 = '1000000';
$rangeWeight->add();
$zones = Zone::getZones(true);
foreach ($zones as $z) {
Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_zone',
array('id_carrier' => (int) $carrier->id, 'id_zone' => (int) $z['id_zone']), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => (int) $rangePrice->id, 'id_range_weight' => NULL, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery',
array('id_carrier' => $carrier->id, 'id_range_price' => NULL, 'id_range_weight' => (int) $rangeWeight->id, 'id_zone' => (int) $z['id_zone'], 'price' => '0'), 'INSERT');
}
copy(dirname(__FILE__) . '/views/img/carrier.jpg', _PS_SHIP_IMG_DIR_ . '/' . (int) $carrier->id . '.jpg');
Configuration::updateValue(self::PREFIX . $value, $carrier->id);
Configuration::updateValue(self::PREFIX . $value . '_reference', $carrier->id);
}
}
return true;
}
protected function deleteCarriers()
{
foreach ($this->_carriers as $value) {
$tmp_carrier_id = Configuration::get(self::PREFIX . $value);
$carrier = new Carrier($tmp_carrier_id);
$carrier->delete();
}
return true;
}
}
Im my opinion it has something to do with your $curPage
I'd go for this if instead:
if ($this->context->controller instanceof CartController || $this->context->controller instanceof OrderController) {
I don't understand this part of code:
} elseif ($curPage == "order-confirmation") {
why would you do something different on real order-confirmation page where order is already placed?

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

how to use this simple acl library into codeigniter

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.

Resources