How to pass variable from controller to the view joomla mvc - model-view-controller

How do I pass my variable from joomla sub-controller to the view according to this example
class MYControllerControllerParser extends JController{
public function __construct($default = array()) {
parent::__construct($default);
}
protected function _import($file, $type) {
$layout = '';
switch ($type) {
case 'importcsv':
$contains_headers = false;
$field_separator = JRequest::getVar('separator');
$field_separator = empty($field_separator) ? ',' : $field_separator;
$field_enclosure = JRequest::getVar('enclosure');;
$field_enclosure = empty($field_enclosure) ? '"' : $field_enclosure;
//this variable should be passed to the view
$this->info = $this->getImportInfoCSV($file, contains_headers, $field_separator, $field_enclosure);
//This variable should go to view
$this->file = basename($file);
$layout = 'importcsv';
break;
}
$this->getView('import','html')->display();
}
}

In Controller:
$view = $this->getView('import','html');
$view->myVariable = 'hello';
$view->display();
In View:
class MycomponentViewItem extends JViewLegacy
{
/** #var string my variable */
public $myVariable;
public function display($tpl = null)
{
$myVariable = $this->myVariable;
//...
}
}

Related

Attempt to read property "ref_department_id" on null in laravel 8

My problem is its hard to get the data from relationship field. There is no null value in table but the error shows attempt to read null value.The data connected with api.Its work when i put if and else but i cant figure out the correct solution for this problem.
Here is my function.php line
function getUnitClerk($unit_id){
$unit = Unit::where('id', $unit_id)->first();
$division = Division::where('id', $unit->ref_division_id)->first();
$department = Department::where('id', $division->ref_department_id)->first();
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Platform\Bpms;
use Session;
use Illuminate\Support\Facades\DB;
use App\User;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function dashboard()
{
if(!auth()->check())
{
return redirect('login')->with('message', 'Please log in!');
}else{
$roleOfUser = DB::table('role_of_user')->where('user_id','=',auth()->user()->id)->get();
$tasklist = Bpms::queryForTaskListByAssignee(auth()->user()->id);
$list_role = '';
if(count($roleOfUser) > 0){
foreach($roleOfUser AS $roleUser){
if($roleUser != ''){
$grouptasklist = Bpms::queryForTaskList($roleUser->role_name);
$tasklist = array_merge($tasklist, $grouptasklist);
$list_role .= $roleUser->role_name;
$list_role .= ",";
}else{
$tasklist = array();
}
}
}
if(count($tasklist) > 0){
foreach ($tasklist as $i => $task) {
$taskname = $task['taskDefinitionKey'];
$overdue = 'overdue';
if((stripos($taskname, $overdue) !== FALSE)){
$overdue_task2[] = 1;
}else{
$overdue_task2[] = 0;
}
}
$overdue_task = array_sum($overdue_task2);
}else{
$overdue_task = 0;
}
$new = DB::table('history')->where('history_status', '=', 2)->where('history_sender_id','=',auth()->user()->id)->get();
$newtask = count($new);
$inprogress = count($tasklist);
$closed = DB::table('history')
->whereRaw('(history_status = 6)')
->where('created_by','=',auth()->user()->id)
->get();
$closedtask = count($closed);
$lastlogin = DB::table('audit_trail')
->where('adt_action_name', '=', 1)
->where('adt_created_by','=',auth()->user()->id)
->orderBy('adt_created_date', 'desc')
->skip(1)
->take(1)
->first();
// echo '<pre>';
// print_r($tasklist);
// $historyCheck = DB::table('history')->where('history_taskid','=',88989)->exists();
// if($historyCheck)
// {
// $history = DB::table('history')->where('history_taskid','=',88989)->first();
// print_r($history);
// $recordrequest = DB::table('ddms_record_request')->where('ddms_request_id','=',$history->history_request_id)->first();
// print_r($recordrequest);
// exit;
// $requestnumber = DB::table('ddms_request')->where('id','=',$recordrequest->ddms_request_id)->first();
// } else {
// $history = array();
// $recordrequest = array();
// $requestnumber = array();
// }
return view('main.dashboard',compact('tasklist','newtask','inprogress','closedtask', 'overdue_task', 'lastlogin'));
}
}
}
?>
unit model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Unit extends Model
{
protected $table = 'ref_unit';
public function division() {
return $this->belongsTo(division::class,'ref_division_id','id');
}
public function section() {
return $this->hasMany(section::class,'ref_unit_id','id');
}
}
Division Model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Division extends Model
{
protected $table = 'ref_division';
public function department() {
return $this->belongsTo(department::class,'ref_department_id','id');
}
public function unit() {
return $this->hasMany(unit::class,'ref_division_id','id');
}
}
Department Model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $table = 'ref_department';
public function tenant() {
return $this->belongsTo('App\Models\References\Tenant','ref_tenant_id','id');
}
public function departmentdetail() {
return $this->hasMany(departmentdetail::class,'ref_department_id','id');
}
public function division() {
return $this->hasMany(division::class,'ref_department_id','id');
}}

Too few arguments to function App\Awe\JsonUtility::addNewProduct(),

i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.

Codeigniter $this->load->database not returning results

For some weird reason when i attempt to load the database no results are being returned.
class Customer_model extends CI_Model {
public function fetch_email_list() {
$DB1 = $this->load->database('orders', TRUE);
if ( $this->load->database('orders') === FALSE ){
echo 'no database';
}
$results = $DB1->query("SELECT * FROM email_list");
return $results->result_array();
}
}
I've checked my database config
$db['orders']['hostname'] = 'localhost';
$db['orders']['username'] = 'db_user';
$db['orders']['password'] = 'password';
$db['orders']['database'] = 'db_name';
$db['orders']['dbdriver'] = 'mysql';
$db['orders']['dbprefix'] = '';
$db['orders']['pconnect'] = FALSE;
$db['orders']['db_debug'] = TRUE;
$db['orders']['cache_on'] = FALSE;
$db['orders']['cachedir'] = '';
$db['orders']['char_set'] = 'utf8';
$db['orders']['dbcollat'] = 'utf8_general_ci';
$db['orders']['swap_pre'] = '';
$db['orders']['autoinit'] = TRUE;
$db['orders']['stricton'] = FALSE;
How do i solve?
No database is added in database.php. And this use $DB1 = $this->load->database('orders', TRUE); for if we have multiple Databases only.
Set default DB
$db['orders']['database'] = 'orders';
In Code
public function fetch_email_list() {
$this->load->database();
$query = $this->db->query("SELECT * FROM email_list");
$result = $query->result_array();
return $result
}
Codeigniter - multiple database connections
You may define the database instance globally in a model so you can access it across methods as follows:
class Some_model extends CI_Model {
// Our 2nd database
protected $DB2;
public function __construct () {
parent::__construct();
$this->DB2 = $this->load->database('orders', TRUE);
}
public function some_method () {
$q = $this->DB2->query('...');
}
public function some_other_method () {
$q = $this->DB2->query('...');
}
}
Try this
$query = $this->db->get('email_list');
return $query->result_array();

Laravel library to handle messages

I have just created a library class in laravel.
class Message {
public static $data = array();
public function __construct() {
// If session has flash data then set it to the data property
if (Session::has('_messages')) {
self::$data = Session::flash('_messages');
}
}
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}
I can use this class in my views calling Message::get(). In the controllers, I can set the message as Message::set('info', 'success message here.'); and it works perfectly fine.
However, I can not use this class for flash messages redirects using Message::set('info', 'success message here.', true). Any idea, whats wrong in this code?
First problem is the constructor function is not called when using the above get and set methods, with minor modification the code is now working. :)
class Message {
public static $data = array();
public static function set($type, $message, $flash = false) {
$data = array();
// Set the message properties to array
$data['type'] = $type;
$data['message'] = $message;
// If the message is a flash message
if ($flash == true) {
Session::flash('_messages', $data);
} else {
self::$data = $data;
}
}
public static function get() {
// Check the session if message is available in session
if (Session::has('_messages')) {
self::$data = Session::get('_messages');
}
// If the data property is set
if (count(self::$data)) {
$data = self::$data;
// Get the correct view for the message type
if ($data['type'] == 'success') {
$view = 'success';
} elseif ($data['type'] == 'info') {
$view = 'info';
} elseif ($data['type'] == 'warning') {
$view = 'warning';
} elseif ($data['type'] == 'danger') {
$view = 'danger';
} else {
// Default view
$view = 'info';
}
// Return the view
$content['body'] = $data['message'];
return View::make("alerts.{$view}", $content);
}
}
}

Codeigniter load model in controller - 500 erorr

This is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Order extends CI_Controller {
public function index($id=-1) {
$this->load->model('order');
}
}
When i try to open the corresponding url i get Error 500. The strange thing is that i load the model the same way on another controller without a problem.
Here goes the route and the model just in case:
Route:
$route['order/(:num)'] = "order/index/$1";
Model:
<?php
class Order extends CI_Model {
var $fullname = '';
var $email = '';
var $address = '';
var $phone = '';
var $notes = '';
var $facebook = '';
//var $canvases = '';
var $admin_notes = '';
var $status = '';
var $id = '';
var $date = '';
var $price = '';
//var $emailStatus_recivedOrder = '';
//var $emailStatus_sendedOrder = '';
//var $emailStatus_askFeedback = '';
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get($search_query='', $per_page=5, $skip=0) {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$query = $this->db->get('entries', $per_page, $skip);
return $query->result();
}
function count_all($search_query='') {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$this->db->from('entries');
return $this->db->count_all_results();
}
function get_by_id($id) {
return $this->db->get_where('entries', array('id' => $id), 1);
}
function get_active_orders_count() {
$this->db->where('status', '1');
$this->db->from('entries');
return $this->db->count_all_results();
}
function insert_entry() {
$this->fullname = $this->input->post('fullname');
$this->email = $this->input->post('email');
$this->address = $this->input->post('address');
$this->phone = $this->input->post('phone');
$this->facebook = $this->input->post('facebook');
$this->notes = $this->input->post('notes');
$this->admin_notes = $this->input->post('admin_notes');
$this->status = $this->input->post('status');
$this->date = date('Y-m-d H:i:s');
$this->db->insert('entries', $this);
}
function update_entry() {
$this->admin_notes = $this->input->post('admin_notes');
$this->db->update('entries', $this, array('id' => $this->input->post('admin_notes')));
}
}
The error is:
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346
You can't name your controller and model the same.
give them a different name and the problem should be fixed. So something like
Controller
class Order extends CI_Controller{ ... }
Model
class Order_model extends CI_Model{ ... }
In Objected oriented programming no two class can have the same name. As of codeigniter Controllers, Models are all classes. So, it is good practice to name your controller as ABC_Controller and model as ABC_Model to avoid class name conflict.
Controller
class ABC_Controller extends CI_Controller { .. }
Model
class ABC_Model extends CI_Model { .. }

Resources