Codeigniter: Extract certain value from an array under controller - codeigniter

Good day!
This is pretty basic to some.
I have this code on my controller:
$data["sales_info"] = $this->The_model->get_sales_info(SELECT * FROM sales WHERE sales_id = 123);
Then get_sales_info() method under The_model stores the specific sales information into an array.
Now, I'm doing some debugging, so from the controller, I want to extract from the $data["sales_info"] and echo only the value of 'sales_date'.
How am I going to do this?
Thank you!

You can try this solution for your problem:
Change the model file to :
The_model.php
class The_model extends MY_Model {
function get_sales_info($sales_id){
$this->db->select("*.*");
if(!empty($sales_id)){
$this->db->where('sales_id', $sales_id);
$query = $this->db->get('sales');
return $query->row();
} else {
$query = $this->db->get('sales');
return $query->result();
}
}
}
and change the controller file to:
My_controller.php
$sales_id = 123;
$sales_info = $this->The_model->get_sales_info($sales_id);
echo $sales_info['sales_date'];exit; //how to get value from object
Thanks

This code may help you
$sales_info = $this->The_model->get_sales_info(SELECT * FROM sales WHERE sales_id = 123);
$data['sales_data'] = $sales_info['sales_date'];

$query = $this->db->get_where('sales', array('sales_id' => 123));
It should be like this, you cannot write the sql in to a method as best practice.

Related

Can we use Local Scopes in Symfony?

I wondering about a subject. We can use Local scopes in Laravel but i don't know if for Symfony.
Doc : Laravel Local Scopes
Well, my question is can i use it in Symfony? Is this possible ?
Have a good day
You can do the same with classical methods in your repository.
I can show you an example(using source code from the docs):
public function findAllGreaterThanPrice(int $price, bool $includeUnavailableProducts = false): array
{
// automatically knows to select Products
// the "p" is an alias you'll use in the rest of the query
$qb = $this->createQueryBuilder('p')
->where('p.price > :price')
->setParameter('price', $price)
->orderBy('p.price', 'ASC');
if (!$includeUnavailableProducts) {
$qb->andWhere('p.available = TRUE');
}
$query = $qb->getQuery();
return $query->execute();
// to get just one result:
// $product = $query->setMaxResults(1)->getOneOrNullResult();
}
Here instead of return "$query->execute()", you can return $qb and chain methods will available.
You can do something like that :
$repo->findAllActive()->findAllGreaterThan12();
Here $repo would be the repository injected in your controller.
In both method, you would have just a where and a return of querybuilder.

How to achieve this on laravel 5 eloquent

How can i achieve something like this?
public function getInformation($model) {
$result = $model::with(['province', 'city']);
if($model == 'App\Models\Business') {
$result->with(['businessProvince', 'businessCity']);
}
$result->get();
}
// call the function
$information->getInformation(\App\Models\Business::class);
i'm getting error
Object of class Illuminate\Database\Eloquent\Builder could not be
converted to string
on the sample code above. Any suggestion is really appreciated.
After taking a fourth look $model should be a string, and $result is an Eloquent Builder instance and never an instance of the model class (since a query was started when with was called).
So the $model == 'App\Models\Business' I would change to $model === \App\Models\Business::class but that should not change the outcome.
Are you sure this error comes from this part of the application? Which line specifically?
Original wrong answer.
You are trying to compare the model instance with a string (since $model::with() created a instance of the model class you passed in the $model argument).
You can use the instanceof keyword for comparing an instance with a class name (http://php.net/manual/en/language.operators.type.php).
if($model instanceof \App\Models\Business) {
$result->with(['businessProvince', 'businessCity']);
}
This solved my problem, thank you guys.
public function getInformation($model) {
$result = $model::with(['province', 'city']);
if($model == 'App\Models\Business') {
// my mistake
//$result->with(['businessProvince', 'businessCity']);
$result = $result->with(['businessProvince', 'businessCity']);
}
$result->get();
}

How to pass a view and a json from a function in laravel?

This is my function
if(isset($_POST['franchisesIds'])) {
$id_array = array();
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
return Response::json(array($id_array));
return View::make('frontend.stores')->with('franchisesAll', $results);
So I am a little bit confused on how to pass all this data. I need to pass the json just to make sure everything worked. And at the same time I need to pass a list of ids to the view.
How can I do this??
Hopefully this is what you wanted :
Please don't use directly $_POST or $_GET instead use Input
$franchisesIds = Input::get('franchisesIds');
$id_array = array();
if($franchisesIds) {
foreach( $franchisesIds as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
$jsonArray = json_encode($id_array);
return View::make('frontend.stores')->with(array('franchisesAll'=>$results,'idArrays'=>$jsonArray));
In order to pass multiple values to the view, please read more about it in the official Laravel documentation
First of all you should use Input::get('franchisesIds') instead of $_POST['franchisesIds'], also there is no reason to do this foreach loop:
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
Because this is already an array and you are bulding another array from this array, makes no sense. So you may try this instead:
if($franchisesIds = Input::get('franchisesIds')) {
$franchises = DB::table('franchises')->whereIn('id', $franchisesIds)->get();
}
Then to pass both $franchisesIds and result to your view you may use this:
return View::make('frontend.stores')
->with('franchises', $franchises)
->with('franchisesIds', $franchisesIds);
You can also use something like this (compact):
return View::make('frontend.stores', compact('franchises', 'franchisesIds'));
There is no reason to use json_encode to encode your $franchisesIds.
You could also use
$results = DB::table('franchises')
->whereIn('id', $id_array)
->get()
->toJson();

Custom Tier Price not working in checkout page magento

I have developed a custom module to meet my project requirements using Alan Storms tutorial for creating modules in magento.
I had the requirement of changing the price attribute dynamically on frontend based on a livefeed. Everysecond the feed is updated so every time the page refreshes a new price must be displayed for each product on the site.
I have override the product module and the price modules for this purpose. The issue is with tier pricing. When tier pricing comes into place I need to calculate the tier-price based on the live price.
For this also I managed to change using the price_type class override.
Now whenever an item is added to cart the tier-pricing was not working for that I wrote event_trigger ie an Observer which updates the tier_pricing on the event "checkout_cart_save_before" and here's my code
class My_Custom_Model_Observer extends Varien_Event_Observer
{
public function __construct()
{
}
public function updateCartBasedOnLiveFeed($observer)
{
foreach ($observer->getCart()->getQuote()->getAllVisibleItems() as $item /* #var $item Mage_Sales_Model_Quote_Item */)
{
$tierPrices = array();
$tierPrices = $item->getProduct()->getTierPrice();
$itemPrice = $item->getProduct()->getPrice();
$i=0;
foreach($tierPrices as $key => $tierPrice)
{
if(!is_numeric($key))
{
$updatedTierPrice = $itemPrice - ($itemPrice * ($tierPrice['price']/100));
$tierPrices[$key]['price'] = $updatedTierPrice;
$tierPrices[$key]['website_price'] = $updatedTierPrice;
}
else
{
if($tierPrice['price'] > 0)
{
$updatedTierPrice = $itemPrice - ($itemPrice * ($tierPrice['price']/100));
$tierPrice['price'] = $updatedTierPrice;
$tierPrice['website_price'] = $updatedTierPrice;
$tierPrices[$i] = $tierPrice;
$i++;
}
}
}
$item->getProduct()->setData('tier_price',$tierPrices);
}
}
}
The above code works excellently in cart page. But when it comes to checkout page. It works for a single item and when tier-pricing comes into play it does apply cart prices.
Please help me with this.
I also tried using other events along with the above event.
Event: sales_quote_save_before
public function updateQuoteLive($observer)
{
$tierPrices = array();
$quote_item = $observer->getEvent()->getQuote;
$itemPrice = $quote_item->getProduct()->getPrice();
$tierPrices = $quote_item->getProduct()->getTierPrice();
$tierPricesSize = sizeof($tierPrices);
for($i=0;$i<$tierPricesSize;$i++)
{
$updatedTierPrice = $itemPrice - ($itemPrice * ($tierPrices[$i]['price']/100));
$tierPrices[$i]['price'] = $updatedTierPrice;
$tierPrices[$i]['website_price'] = $updatedTierPrice;
}
$quote_item->getProduct()->setData('tier_price',$tierPrices);
}
When I tried to print the getQuote() function available in Quote.php I find that the tier prices there are not the ones which I updated using the first event. So I think I need to update the price before saving the quote. Please any one help me and show the correct direction.
Please help me with this I am missing some important step. Any help is greatly appreciated.
Thanks in advance.
It might be better off "saving" the new price in to the database when you update.
Try something along the lines of:
$product = $observer->getProduct();
$procuct->setPrice($updatedPrice);
This way when it comes to checkout it will be pulling in the correct price from the database (and avoids the headache of correcting it "mid-flight"
i realized such a project like you. I have no sales_quote_save_before Observer. I only use the checkout_cart_save_before. Based on the session the price will be setted.
I realized that like this way:
public function updatePrice( $observer )
{
try {
$cart = $observer->getCart();
$items = $cart->getItems();
foreach($items as $item)
{
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
}
} catch ( Exception $e )
{
Mage::log( "checkout_cart_save_before: " . $e->getMessage() );
}
}
I calcute the tierprices on the fly and with this Observer. All prices will be set up correct in the qoute.
Maybe you should try this way.
Regards boti
At last figured out the issue and got the solution.
The problem was that in cart page or checkout page when the getTierPrice() function is called, which is present in /app/code/core/Mage/Catalog/Product.php. It takes one parameter named $qty which is by default null. This function in turn calls the function getTierPrice which is present in /app/code/core/Mage/Type/Price.php file which takes two parameters $qty and $productObject. By default $qty is null and when it is null the function returns an array of tier_prices. But when the $qty value is passed then the function returns a single for that particular quantity.
So, I wrote my own custom function which calculates the tier prices based no my requirements like
I overridden both the core files with my custom module following Alan Storm's tutorials.
I've extended Mage_Catalog_Model_Product with My_CustomModule_Model_Product class and
then
Mage_Catalog_Model_Product_Type_Price with My_CustomModule_Model_Price
And then in /app/code/local/My/Custommodule/Model/Product.php
I added my custom code like
public function getTierPrice($qty=null)
{
if($qty)
{
return $this->getPriceModel()->getCustomTierPrice($qty, $this);
}
return $this->getPriceModel()->getTierPrice($qty, $this);
}
Then in /app/code/local/My/Custommodule/Model/Price.php
<?php
public function getCustomTierPrice($qty = null, $product)
{
$allGroups = Mage_Customer_Model_Group::CUST_GROUP_ALL;
$prices = $product->getData('tier_price');
if (is_null($prices)) {
$attribute = $product->getResource()->getAttribute('tier_price');
if ($attribute) {
$attribute->getBackend()->afterLoad($product);
$prices = $product->getData('tier_price');
}
}
foreach($prices as $key => $customPrices)
{
if($prices[$key]['price'] < 1)
{
$prices[$key]['price'] = abs($product->getPrice() - ($productPrice * ($customPrices['price']/100)));
$prices[$key]['website_price'] = $prices[$key]['price'];
}
}
}
which retured a customized value when $qty is passed and voila it worked.
I just posed this answer so that any one else who has similar requirement may get benefited with this.
?>

Magento online customers last URL rewrite

I'm running Magento CE 1.6.2.0.
Magento's Online Customers feature is great. Only problem is the "Last URL" column could be more helpful by displaying a rewrite (if one exists).
I changed app/code/core/Mage/Adminhtml/Block/Customer/Online/Grid/Renderer/Url.php from this:
public function render(Varien_Object $row)
{
return htmlspecialchars($row->getData($this->getColumn()->getIndex()));
}
to this:
public function render(Varien_Object $row)
{
$lastUrl = htmlspecialchars($row->getData($this->getColumn()->getIndex()));
$lastUrlRewrite = Mage::getModel('core/url_rewrite')
->setStoreId(1)
->loadByRequestPath($lastUrl);
$url = ($lastUrlRewrite) ? $lastUrlRewrite : $lastUrl;
return $url;
}
The StoreId is correct but the output remains empty.
Any help would be greatly appreciated! Thank you.
The loadByRequestPath() method returns a Mage_Core_Model_Url_Rewrite object, not a string. You probably want to do this:
$url = ($lastUrlRewrite->getId()) ? $lastUrlRewrite->getTargetPath() : $lastUrl;

Resources