CodeIgniter - displaying view based on variable from database - database

I've been learning codeigniter recently and trying to push an application out. im running into problems with the if else statements displaying views. i am trying to pull in_party from the databaseci_admin_info and display views depending if its set to 1 or 0. its bypassing any condition and just displaying the first view set.
Model
function get_in_par(){
$this->db->select('in_party');
$this->db->from('ci_admin_info');
$query = $this->db->get();
$ret = $query->row();
return $ret->in_party;
}
Controller
public function index(){
$data['title'] = 'Party';
$data['party'] = $this->party_model->get_party();
$data['prov'] = $this->party_model->get_prov_name();
$data['info'] = $this->party_model->get_all();
$data['res'] = $this->party_model->get_party_res();
$data['rank'] = $this->party_model->get_pa_rank();
$this->load->view('admin/includes/_header', $data);
$inpar = $this->party_model->get_in_par();
if(isset($inpar['in_party'])==0){
$this->load->view('admin/party/join');
} else {
$this->load->view('admin/party/index');
}
$this->load->view('admin/includes/_footer');
}
I've tried rearranging it into the parent construct as well and it just bypassed it completely. just trying to make it load the join view if in_party = 0 . i've tried without isset bypasses it as well. i've tried switch but don't think it registered that as well. i think i'm missing something in my model

$query = $this->db->select('*')
->from('ci_admin_info')
->get();
$result = $query->result_array();
return $result[0];
$inpar = $this->party_model->get_in_par();
if(!isset($inpar['in_party']) || $inpar['in_party']=="0"){....

Related

How to get customer_id from different table and avoid duplications with correct method in laravel?

Hi I am trying to get customer _id from different tables Purchase order ,Sale Order and Consignments
Then I am looping through these Ids . Method I am using for this purpose is working perfectly but . I am afraid if there is a lot of data this method may get failed. Here is my method .
$consignmentCustomerIds = Consignment::select('customer_id')->where('is_repeat', 0)->whereDate('created_at','>',date('2021-03-06'))->whereRaw('(is_group = "parent" or is_group is null)')->where('finalize', 0)->where('invoice_id', null)->distinct()->pluck('customer_id')->toArray();
$poCustomerIds = PurchaseOrder::select('customer_id')->whereDate('created_at','>',date('2021-03-06'))->where('invoice_id', null)->distinct()->pluck('customer_id')->toArray();
$soCustomerIds = SaleOrder::select('customer_id')->whereDate('created_at','>',date('2021-03-06'))->where('invoice_id', null)->distinct()->pluck('customer_id')->toArray();
$spCustomerIds = StoragePeriod::select('customer_id')->whereDate('created_at','>',date('2021-03-06'))->where('invoice_id', null)->distinct()->pluck('customer_id')->toArray();
$ids = array_merge($consignmentCustomerIds, $poCustomerIds, $soCustomerIds, $spCustomerIds);
$customers = Customer::whereIn('id', $ids)->get();
foreach ($customers as $customer) {
CreateInvoiceOneByOne::dispatch($customer)->onQueue('invoice');
}
Is there any better way of doing so?
The main thing is to change ->get() to ->cursor() in the iteration:
// $customers = Customer::whereIn('id', $ids)->get();
$customers = Customer::whereIn('id', $ids)->cursor();
The cursor method may be used to significantly reduce your application's memory consumption when iterating through tens of thousands of Eloquent model records.
More info: https://laravel.com/docs/8.x/eloquent#cursors
IF YOUR RELATIONS ARE SET PROPERLY
I suggest to reduce database query. You can do this by chaning whereHas and orWhereHas within the customer request.
Querying Relationship Existence
$date = date('2021-03-06');
$customers = Customer::whereHas('consignment', function($query) use($date) {
$query->where('is_repeat', 0)->whereDate('created_at','>',$date)->whereRaw('(is_group = "parent" or is_group is null)')->where('finalize', 0)->where('invoice_id', null);
})->orWhereHas('purchase_order', function($query) use($date) {
$query->whereDate('created_at','>',$date)->where('invoice_id', null);
})->orWhereHas('sale_order', function($query) use($date) {
$query->whereDate('created_at','>',$date)->where('invoice_id', null);
})->orWhereHas('storage_period', function($query) use($date) {
$query->whereDate('created_at','>',$date)->where('invoice_id', null);
})->get();
foreach ($customers as $customer) {
CreateInvoiceOneByOne::dispatch($customer)->onQueue('invoice');
}
I set the $date variable before the query, so this way you can manipulate it at one place.
P.S. I am currently assuming the name of the relations.

Indirect modification of overloaded element of Illuminate\Support\Collection has no effect

im quite new in laravel framework, and im from codeigniter.
I would like to add new key and value from database
static function m_get_promotion_banner(){
$query = DB::table("promotion_banner")
->select('promotion_banner_id','promotion_link','about_promotion')
->where('promotion_active','1')
->get();
if($query != null){
foreach ($query as $key => $row){
$query[$key]['promotion_image'] = URL::to('home/image/banner/'.$row['promotion_banner_id']);
}
}
return $query;
}
that code was just changed from codeigniter to laravel, since in codeigniter there are no problem in passing a new key and value in foreach statement
but when i tried it in laravel i got this following error :
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
at HandleExceptions->handleError(8, 'Indirect modification of overloaded element of Illuminate\Support\Collection has no effect', 'C:\xampp\htdocs\laravel-site\application\app\models\main\Main_home_m.php', 653, array('query' => object(Collection), 'row' => array('promotion_banner_id' => 1, 'promotion_link' => 'http://localhost/deal/home/voucher', 'about_promotion' => ''), 'key' => 0))
please guide me how to fix this
thank you (:
The result of a Laravel query will always be a Collection. To add a property to all the objects in this collection, you can use the map function.
$query = $query->map(function ($object) {
// Add the new property
$object->promotion_image = URL::to('home/image/banner/' . $object->promotion_banner_id);
// Return the new object
return $object;
});
Also, you can get and set the properties using actual object properties and not array keys. This makes the code much more readable in my opinion.
For others who needs a solution you can use jsonserialize method to modify the collection.
Such as:
$data = $data->jsonserialize();
//do your changes here now.
The problem is the get is returning a collection of stdObject
Instead of adding the new field to the result of your query, modify the model of what you are returning.
So, assuming you have a PromotionBanner.php model file in your app directory, edit it and then add these 2 blocks of code:
protected $appends = array('promotionImage');
here you just added the custom field. Now you tell the model how to fill it:
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
Now, you get your banners through your model:
static function m_get_promotion_banner(){
return \App\PromotionBanner::where('promotion_active','1')->get();
}
Now you can access your promotionImage propierty in your result
P.D:
In the case you are NOT using a model... Well, just create the file app\PromotionImage.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PromotionImage extends Model
{
protected $appends = array('imageAttribute');
protected $table = 'promotion_banner';
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'promotion_banner_id','promotion_link','about_promotion','promotion_active'
];
just improving, in case you need to pass data inside the query
$url = 'home/image/banner/';
$query = $query->map(function ($object) use ($url) {
// Add the new property
$object->promotion_image = URL::to( $url . $object->promotion_banner_id);
// Return the new object
return $object;
});
I've been struggling with this all evening, and I'm still not sure what my problem is.
I've used ->get() to actually execute the query, and I've tried by ->toArray() and ->jsonserialize() on the data and it didn't fix the problem.
In the end, the work-around I found was this:
$task = Tasks::where("user_id", $userId)->first()->toArray();
$task = json_decode(json_encode($task), true);
$task["foo"] = "bar";
Using json_encode and then json_decode on it again freed it up from whatever was keeping me from editing it.
That's a hacky work-around at best, but if anyone else just needs to push past this problem and get on with their work, this might solve the problem for you.

joomla - Storing user parameters in custom component issue

Hi for my custom component I need to set some custom parameters for joomla user for membership for checking if the user ni trial period or not and it can be change from the component admin panel for specific user.
The problem arises while retrieving the parameter. I think it is stored in cookie and it isn^t updated. I wrote the code like that to check it.
$user = JFactory::getUser(JRequest::getVar('id','0'));
echo $user->getParam('trialPeriod','0');
to save the value I am useing JHTML booleanlist.
$user->setParam('trialPeriod',$data['trialPeriod']);
$user->save();
Then is stores the value in joomla users table in the row of that user with column of params as;
{"trialPeriod":"0"}
in this situation it echoes the value as 0. Then I am changin the state of trialPeriod var as 1 and storing in db it updates the db as;
{"trialPeriod":"1"}
After all I am refreshing the page where the value is prompt the the screen the the value remains still the same as 0;
To clarify;
First of all there is no problem with saving the param it is changed properly. The problem is retrieving the changed one. The releated piece of code is following;
$user = JFactory::getUser();
$doc = JFactory::getDocument();
if($user->getParam('trialPeriod',0) == 0){
$ed = JFactory::getDate($obj->expirationDate);//obj is user from custom table and there is no problem with getting it.
$isTrialEnd = FALSE;
}else{
$ed = JFactory::getDate($user->getParam('trialExp',0));
$isTrialEnd = TRUE;
}
if($isTrialEnd){
//do something else
}else{
echo $user->getParam('trialPeriod','0');
}
actually big part of the code is unneccessary to explain it but you will get the idea.
What is the solution for this?
Editted.
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$db = $this->getDbo();
$isNew = empty($data['uid']) ? true : false;
$params = JComponentHelper::getParams('com_dratransport');
if($isNew){
// Initialise the table with JUser.
$user = new JUser;
// Prepare the data for the user object.
$username = self::getCreatedUserName($data['type']);
$data['username'] = !empty($data['username']) ? $data['username'] : $username;
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2)) {
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
}else{
$user = JFactory::getUser($data['uid']);
$data['password'] = $data['password1'];
}
$membership = DraTransportHelperArrays::membershipCFG();
$membership = $membership[$data['membership']];
if($data['membership'] == 4)
$data['groups'] = array($params->get('new_usertype',2),$params->get($membership,2));
else
$data['groups'] = array($params->get($membership,2));
$data['name'] = $data['companyName'];
$user->setParam('trialPeriod',$data['trialPeriod']);
// Bind the data.
if (!$user->bind($data)) {
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED', $user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save()) {
$app->enqueuemessage($user->getError());
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $user->getError()));
return false;
}
this piece of code is for storing the data releated with the users table.
Turns out this was the fact that Joomla stores the JUser instance in the session that caused the problem.
When changing a user's parameters from the back-end, the changes are not reflected in that user's session, until she logs out and back in again.
We could not find an easy option to modify anther user's active session, so we resorted to the use of a plugin that refreshes the JUser instance in the logged-in users' session, something like the following:
$user = JFactory::getUser();
$session = JFactory::getSession();
if(!$user->guest) {
$session->set('user', new JUser($user->id));
}
(reference: here).

CakePHP save field to associated table

I have my 'PatientCase' model with a hasOne relationship to my 'PatientCaseOrder' model. (This table simply stored the patientCase id along with an integer position)
I am using an ajax function to update the position fields in 'PatientCaseOrder' using the function below in my PatientCase controller
public function update_position(){
Configure::write('debug', 0);
$this->autoRender = false;
$this->loadModel('PatientCaseOrder');
$list = $_POST['list'];
$errs = false;
if($list){
foreach($list as $position){
$id = $position[0];
$pos = $position[1];
$this->PatientCase->id = $id;
if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
}
}
echo json_encode ($errs);
}
I am passing to it an array containing the PatientCaseId and position.
The code produces a 500 server error, where am i going wrong, or am i taking the wrong approach to this?
NOTE: I previously had the position field in the PatientCase model, and this line of code worked with the above segment of code
$this->PatientCase->saveField('position', $pos)
You need to change your controller function for better debugging:
change to Configure::write('debug', 2);
add $this->layout = 'ajax';
and change : if(! $this->PatientCase->PatientCaseOrder->saveField('position', $pos))
$errs = true;
to:
pr($this->PatientCase->PatientCaseOrder->saveField('position', $pos)); die;
and then in your ajax function log the callback
console.log(returned_data);
and check for errors.

Eager load, ArrayResult & Doctrine 2

I need to provide a webservice which returns articles.
I want to include the user relationship in that result to avoid my clients to call another method to load the user object.
I use an Array Result because I want a collection of array (I think it's better to work with) so I wish I could eager load my user.
I tried:
* #ManyToOne(targetEntity="\My\Model\User\User", fetch="EAGER")
But it doesn't look to work.`
Edit, some code:
public function getPublishedArticles($page, $count, $useArrayResult = false) {
$qb = $this->createQueryBuilder('a');
$qb->where('a.status = :status')
->orderBy('a.published_date', 'DESC')
->addOrderBy('a.creation_date', 'DESC')
->setParameter('status', Article::STATUS_PUBLISHED )
->andWhere('a.published_date <= :date')
->setParameter('date', date('Y-m-d'));
}
$adapter = new PaginationAdapter($qb->getQuery());
$adapter->useArrayResult($useArrayResult);
$paginator = new \Zend_Paginator($adapter);
$paginator->setItemCountPerPage($itemCount)
->setCurrentPageNumber($page);
return $paginator;
}
And I call this method with the $useArrayResult flag sets to TRUE
When you're using DQL query you have add JOIN clause to join related entities:
$qb->createQueryBuilder('a')
->addSelect('u')
->join('a.user', 'u')
...
fetch="EAGER" and fetch="LAZY" are being used when you're fetching entities using EntityManager, ie:
$article = $em->find('Entity\Article', 123);

Resources