Prestashop 1.7: product-prices.TPL: where is defined {$product.price_amount}? - prestashop

I am looking at the file themes/my_theme/templates/catalog/_partials/product-prices.tpl. There, an attempt to show the real price with taxes is made: <span class="price-ttc">{Tools::displayPrice($product.price_amount*$prix_ttc)} TTC </span>.
However, I don't find the property named price_amount in web/controllers/front/ProductController.php:
public function getTemplateVarProduct()
{
$productSettings = $this->getProductPresentationSettings();
// Hook displayProductExtraContent
$extraContentFinder = new ProductExtraContentFinder();
$product = $this->objectPresenter->present($this->product);
$product['id_product'] = (int) $this->product->id;
$product['out_of_stock'] = (int) $this->product->out_of_stock;
$product['new'] = (int) $this->product->new;
$product['id_product_attribute'] = $this->getIdProductAttributeByRequestOrGroup();
$product['minimal_quantity'] = $this->getProductMinimalQuantity($product);
$product['quantity_wanted'] = $this->getRequiredQuantity($product);
$product['extraContent'] = $extraContentFinder->addParams(array('product' => $this->product))->present();
$product['ecotax'] = Tools::convertPrice((float) $product['ecotax'], $this->context->currency, true, $this->context);
$product_full = Product::getProductProperties($this->context->language->id, $product, $this->context);
$product_full = $this->addProductCustomizationData($product_full);
$product_full['show_quantities'] = (bool) (
Configuration::get('PS_DISPLAY_QTIES')
&& Configuration::get('PS_STOCK_MANAGEMENT')
&& $this->product->quantity > 0
&& $this->product->available_for_order
&& !Configuration::isCatalogMode()
);
$product_full['quantity_label'] = ($this->product->quantity > 1) ? $this->trans('Items', array(), 'Shop.Theme.Catalog') : $this->trans('Item', array(), 'Shop.Theme.Catalog');
$product_full['quantity_discounts'] = $this->quantity_discounts;
if ($product_full['unit_price_ratio'] > 0) {
$unitPrice = ($productSettings->include_taxes) ? $product_full['price'] : $product_full['price_tax_exc'];
$product_full['unit_price'] = $unitPrice / $product_full['unit_price_ratio'];
}
$group_reduction = GroupReduction::getValueForProduct($this->product->id, (int) Group::getCurrent()->id);
if ($group_reduction === false) {
$group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
}
$product_full['customer_group_discount'] = $group_reduction;
$product_full['title'] = $this->getProductPageTitle();
$presenter = $this->getProductPresenter();
return $presenter->present(
$productSettings,
$product_full,
$this->context->language
);
}
Could you please tell me where is it located?

PrestaShop 1.7 uses Presenters
Your property is defined here:
/src/Adapter/Presenter/Product/ProductLazyArray.php in addPriceInformation method

Related

How Can I Add Website Decimal Quantity in Odoo

I Have a custom module website_decimal_quantity. after installing this module, In the website shop cart, when the user clicks on the + or - button to adjust quantity, It should add or deduct .1 value from it. i find out that a function onclickaddcartjson in the sale.variantmixin is responsible for the button click.i tried to extend the onclickaddcartjson function that present in the website_sale.website_sale. but it does not work.
Thanks For the Attention
My code is like :
publicWidget.registry.WebsiteSale.include({
onClickAddCartJSON: function (ev) {
ev.preventDefault();
var $link = $(ev.currentTarget);
var $input = $link.closest('.input-group').find("input");
var min = parseFloat($input.data("min") || 0);
var max = parseFloat($input.data("max") || Infinity);
var previousQty = parseFloat($input.val() || 0, 10);
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) + previousQty;
var newQty = quantity > min ? (quantity < max ? quantity : max) : min;
if (newQty !== previousQty) {
$input.val(newQty).trigger('change');
}
return false;
},
_changeCartQuantity: function ($input, value, $dom_optional, line_id, productIDs) {
_.each($dom_optional, function (elem) {
$(elem).find('.js_quantity').text(value);
productIDs.push($(elem).find('span[data-product-id]').data('product-id'));
});
$input.data('update_change', true);
this._rpc({
route: "/shop/cart/update_json",
params: {
line_id: line_id,
product_id: parseInt($input.data('product-id'), 10),
set_qty: value
},
}).then(function (data) {
$input.data('update_change', false);
var check_value = parseFloat($input.val());
if (isNaN(check_value)) {
check_value = 1;
}
if (value !== check_value) {
$input.trigger('change');
return;
}
if (!data.cart_quantity) {
return window.location = '/shop/cart';
}
wSaleUtils.updateCartNavBar(data);
$input.val(data.quantity);
$('.js_quantity[data-line-id='+line_id+']').val(data.quantity).text(data.quantity);
if (data.warning) {
var cart_alert = $('.oe_cart').parent().find('#data_warning');
if (cart_alert.length === 0) {
$('.oe_cart').prepend('<div class="alert alert-danger alert-dismissable" role="alert" id="data_warning">'+
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' + data.warning + '</div>');
}
else {
cart_alert.html('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' + data.warning);
}
$input.val(data.quantity);
}
});
},
_onChangeCartQuantity: function (ev) {
var $input = $(ev.currentTarget);
if ($input.data('update_change')) {
return;
}
var value = parseFloat($input.val());
if (isNaN(value)) {
value = 1;
}
var $dom = $input.closest('tr');
// var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
var line_id = parseInt($input.data('line-id'), 10);
var productIDs = [parseInt($input.data('product-id'), 10)];
this._changeCartQuantity($input, value, $dom_optional, line_id, productIDs);
},
})
The change that I made is in _onclickaddcartjson; change the line
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) + previousQty;
and in _changeCartQuantity, change the check_value into:
var check_value = parseFloat($input.val())
And in _onChangeCartQuantity, change the value into:
var value = parseFloat($input.val()).
Even if I made these changes in source file without my custom module, the quantity increase or decrease by .1. But it automatically turns into an integer value. That means when I click on the + button, the value changes to 1.1, but it immediately changes to 1. Also, if I click on the - button, it will changes to 2.9 from 3, then it changes to 2 as its value. If anybody has an idea about this please share. Thanks for the attention.
Yes, it 's possible as the type of the underlying field in model SaleOrderLine is Float. And in website_sale/models/sale_order.py : int(sum(order.mapped('website_order_line.product_uom_qty'))) needs to be reülaced by: sum(order.mapped('website_order_line.product_uom_qty')):
class SaleOrderLine(models.Model):
_name = 'sale.order.line'
product_uom_qty = fields.Float(string='Quantity', digits='Product Unit of Measure', required=True, default=1.0)
#api.depends('order_line.product_uom_qty', 'order_line.product_id')
def _compute_cart_info(self):
for order in self:
order.cart_quantity = sum(order.mapped('website_order_line.product_uom_qty'))
order.only_services = all(l.product_id.type in ('service', 'digital') for l in order.website_order_line)
The underlying python method to add quantity is located in addons module website_sale/models/sale_oder.py :
def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, **kwargs):
""" Add or set product quantity, add_qty can be negative """
self.ensure_one()
product_context = dict(self.env.context)
product_context.setdefault('lang', self.sudo().partner_id.lang)
SaleOrderLineSudo = self.env['sale.order.line'].sudo().with_context(product_context)
...
...which is called by 2 methods in website_sale/controllers/main.py :
#http.route(['/shop/cart/update'], type='http', auth="public", methods=['GET', 'POST'], website=True, csrf=False)
def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):
AND
#http.route(['/shop/cart/update_json'], type='json', auth="public", methods=['POST'], website=True, csrf=False)
def cart_update_json(self, product_id, line_id=None, add_qty=None, set_qty=None, display=True):
"""This route is called when changing quantity from the cart or adding
a product from the wishlist."""
"""This route is called when adding a product to cart (no options)."""
This controller method cart_update_json is called in sale/.../js/variant_mixin.js by:
onClickAddCartJSON: function (ev) {
ev.preventDefault();
var $link = $(ev.currentTarget);
var $input = $link.closest('.input-group').find("input");
var min = parseFloat($input.data("min") || 0);
var max = parseFloat($input.data("max") || Infinity);
var previousQty = parseFloat($input.val() || 0, 10);
var quantity = ($link.has(".fa-minus").length ? -1 : 1) + previousQty;
var newQty = quantity > min ? (quantity < max ? quantity : max) : min;
if (newQty !== previousQty) {
$input.val(newQty).trigger('change');
}
return false;
},
...where: var quantity = ($link.has(".fa-minus").length ? -1 : 1) + previousQty; shows us that is incremented +1 oder -1
That s why you need to override this function in website_sale/.../website_sale.js to integrate:
var $parent = $(ev.target).closest('.js_product');
var product_id = this._getProductId($parent);
if product_id == yourspecificproductid
var quantity = ($link.has(".fa-minus").length ? -0.1 : 0.1) +
previousQty;
else
var quantity = ($link.has(".fa-minus").length ? -1 : 1) +
previousQty;
When quantity input value is changed automatically, it might be caused by parseInt($input.val()) in _onChangeCartQuantity in the file: website_sale.js:
_onChangeCartQuantity: function (ev) {
var $input = $(ev.currentTarget);
if ($input.data('update_change')) {
return;
}
var value = parseFloat($input.val() || 0, 10);
if (isNaN(value)) {
value = 1;
}
var $dom = $input.closest('tr');
// var default_price = parseFloat($dom.find('.text-danger > span.oe_currency_value').text());
var $dom_optional = $dom.nextUntil(':not(.optional_product.info)');
var line_id = parseInt($input.data('line-id'), 10);
var productIDs = [parseInt($input.data('product-id'), 10)];
this._changeCartQuantity($input, value, $dom_optional, line_id, productIDs);
},

Create Order in prestashop programmatically

I am trying to create an order in prestashop programmatically,
Here are the steps I am following:
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
if (empty($billingAddress)) {
continue;
}
$id_customer = $this->createPrestashopCustomer($billingAddress, $order->getEmail());
$lines = $order->getLines();
$AddressObject = new AddressCore();
$AddressObject->id_customer = $id_customer;
$AddressObject->firstname = $billingAddress->getfirstName();
$AddressObject->lastname = $billingAddress->getlastName();
$AddressObject->address1 = " " . $billingAddress->getHouseNr();
$AddressObject->address1.= " " . $billingAddress->getHouseNrAddition();
$AddressObject->address1.= " " . $billingAddress->getStreetName();
$AddressObject->address1.= " " . $billingAddress->getZipCode();
$AddressObject->address1.= " " . $billingAddress->getCity();
$AddressObject->city = $billingAddress->getCity();
$AddressObject->id_customer = $id_customer;
$AddressObject->id_country = CountryCore::getByIso($billingAddress->getCountryIso());
$AddressObject->alias = ($billingAddress->getcompanyName() != "") ? "Company" : "Home";
$AddressObject->add();
$currency_object = new CurrencyCore();
$default_currency_object = $currency_object->getDefaultCurrency();
$id_currency = $default_currency_object->id;
$id_address = $AddressObject->id;
$cart = new Cart();
$cart->id_customer = (int) $id_customer;
$cart->id_address_delivery = $id_address;
$cart->id_address_invoice = $id_address;
$cart->id_lang = 1;
$cart->id_currency = (int) $id_address;
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
if (!empty($lines)) {
foreach ($lines as $item) {
$cart->updateQty(1, 5, 19);
}
}
$cart->update();
$order_object = new OrderCore();
$order_object->id_address_delivery = $id_address;
$order_object->id_address_invoice = $id_address;
$order_object->id_cart = $cart->id;
$order_object->id_currency = $id_currency;
$order_object->id_customer = $id_customer;
$CarrierObject = new CarrierCore();
$CarrierObject->delay[1] = "2-4";
$CarrierObject->active = 1;
$CarrierObject->name = "ChannelEngine Order2";
$CarrierObject->add();
$id_carrier = $CarrierObject->id;
$order_object->id_carrier = $id_carrier;
$order_object->payment = "Channel Engine Order";
$order_object->module = "1";
echo $order->getTotalInclVat();
$order_object->valid = 1;
$order_object->total_paid_tax_excl = $order->getTotalInclVat();
$order_object->total_discounts_tax_incl = $order->getTotalInclVat();
$order_object->total_paid = $order->getTotalInclVat();
$order_object->total_paid_real = $order->getTotalInclVat();
$order_object->total_products = $order->getSubTotalInclVat() - $order->getSubTotalVat();
$order_object->total_products_wt = $order->getSubTotalInclVat();
$order_object->conversion_rate = 1;
$order_object->id_shop = 1;
$order_object->id_lang = 1;
$order_object->secure_key = md5(uniqid(rand(), true));
$order_id = $order_object->add();
The Order is getting added to admin But somehow I can not see products in the order, Can anyone check and let me know what I am doing wrong here.
Also order total is also 0.
You should also create OrderDetail Objects for each product of this order.
Have a look at validateOrder() method of PaymentModule Class.
Here is an extract from this method:
$order = new Order();
$order->product_list = $package['product_list'];
if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
$address = new Address((int)$id_address);
$this->context->country = new Country((int)$address->id_country, (int)$this->context->cart->id_lang);
if (!$this->context->country->active) {
throw new PrestaShopException('The delivery address country is not active.');
}
}
$carrier = null;
if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
$carrier = new Carrier((int)$package['id_carrier'], (int)$this->context->cart->id_lang);
$order->id_carrier = (int)$carrier->id;
$id_carrier = (int)$carrier->id;
} else {
$order->id_carrier = 0;
$id_carrier = 0;
}
$order->id_customer = (int)$this->context->cart->id_customer;
$order->id_address_invoice = (int)$this->context->cart->id_address_invoice;
$order->id_address_delivery = (int)$id_address;
$order->id_currency = $this->context->currency->id;
$order->id_lang = (int)$this->context->cart->id_lang;
$order->id_cart = (int)$this->context->cart->id;
$order->reference = $reference;
$order->id_shop = (int)$this->context->shop->id;
$order->id_shop_group = (int)$this->context->shop->id_shop_group;
$order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key));
$order->payment = $payment_method;
if (isset($this->name)) {
$order->module = $this->name;
}
$order->recyclable = $this->context->cart->recyclable;
$order->gift = (int)$this->context->cart->gift;
$order->gift_message = $this->context->cart->gift_message;
$order->mobile_theme = $this->context->cart->mobile_theme;
$order->conversion_rate = $this->context->currency->conversion_rate;
$amount_paid = !$dont_touch_amount ? Tools::ps_round((float)$amount_paid, 2) : $amount_paid;
$order->total_paid_real = 0;
$order->total_products = (float)$this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_products_wt = (float)$this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
$order->total_discounts_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
$order->total_discounts = $order->total_discounts_tax_incl;
$order->total_shipping_tax_excl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, false, null, $order->product_list);
$order->total_shipping_tax_incl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, true, null, $order->product_list);
$order->total_shipping = $order->total_shipping_tax_incl;
if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
$order->carrier_tax_rate = $carrier->getTaxesRate(new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
}
$order->total_wrapping_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
$order->total_wrapping = $order->total_wrapping_tax_incl;
$order->total_paid_tax_excl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_incl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid = $order->total_paid_tax_incl;
$order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
$order->round_type = Configuration::get('PS_ROUND_TYPE');
$order->invoice_date = '0000-00-00 00:00:00';
$order->delivery_date = '0000-00-00 00:00:00';
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Creating order
$result = $order->add();
if (!$result) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int)$id_cart, true);
throw new PrestaShopException('Can\'t save Order');
}
// Amount paid by customer is not the right one -> Status = payment error
// We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
// if ($order->total_paid != $order->total_paid_real)
// We use number_format in order to compare two string
if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
$id_order_state = Configuration::get('PS_OS_ERROR');
}
$order_list[] = $order;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Insert new Order detail list using cart for the current order
$order_detail = new OrderDetail(null, null, $this->context);
$order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
$order_detail_list[] = $order_detail;
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
// Adding an entry in order_carrier table
if (!is_null($carrier)) {
$order_carrier = new OrderCarrier();
$order_carrier->id_order = (int)$order->id;
$order_carrier->id_carrier = (int)$id_carrier;
$order_carrier->weight = (float)$order->getTotalWeight();
$order_carrier->shipping_cost_tax_excl = (float)$order->total_shipping_tax_excl;
$order_carrier->shipping_cost_tax_incl = (float)$order->total_shipping_tax_incl;
$order_carrier->add();
}
Create Order Programatically in prestashop, we need to use validate order function to create order manually in prestashop.
<?php
$cart = new Cart(Context::getContext()->cart);
$summary = $cart->getSummaryDetails($id_lang,true);
$total = (string) $summary['total_price'];
$cashondelivery = new CashOnDelivery();
if($cashondelivery->validateOrder((int) $cart->id,2, $total, $cashondelivery->displayName, null, array(),$id_currency, false, false)) {
$result['orderid']=(string)$cashondelivery->currentOrder;
return $result;
}

Image not resizing when added programmatically prestashop

I am abel to add image programmatically. But images are not getting resized. In other words resized images are not generating. Attaching the code I use:
$image = new Image();
$image_url = 'http://i.imgur.com/0zSw2gl.jpg';
$id_image = Product::getCover($id_product);
$shops = Shop::getShops(true, null, true);
$image->id_product = $id_product;
$image->position = Image::getHighestPosition($id_product) + 1;
$image->cover = true; // or false;
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (!AdminImportControllerExtended::copyImgCustom($id_product, $image->id, $image_url, 'products', false))
{
$image->delete();
}
}
Images should be resized programatically
I use this code
$image = new Image();
$image->id_product = (int)$product->id;
$image->position = Image::getHighestPosition($product->id) + 1;
$image->cover = 1;
if (!$image->add())
exit(Tools::jsonEncode(array('error' => Tools::displayError('Error while creating additional image'))));
else
{
$new_path = $image->getPathForCreation();
ImageManager::resize($image_path, $new_path.'.'.$image->image_format);
$images_types = ImageType::getImagesTypes('products');
foreach ($images_types as $image_type)
{
if (!ImageManager::resize($image_path, $new_path.'-'.Tools::stripslashes($image_type['name']).'.'.
$image->image_format, $image_type['width'], $image_type['height'], $image->image_format))
exit(Tools::jsonEncode(array('error' => Tools::displayError('An error occurred while copying image:').
' '.Tools::stripslashes($image_type['name']))));
}
$image->update();
}

CDbCriteria throwing column name is ambigous

I have the following method in a controller of my Yii app.
public function actionManage($typeid=0, $locationid=0, $page=1, $rows=12, $sidx='date_input', $sord='desc', $kategori='')
{
if (Yii::app()->request->isAjaxRequest) {
// Jika dilakukan operasi 'edit' pada row
if (isset($_REQUEST['oper']))
{
$oper = $_REQUEST['oper'];
$id = $_REQUEST['id'];
if ($oper == 'edit')
{
$value = $_REQUEST['value'];
$record = InputData::model()->findByPk($id);
$record->value = $value;
$record->update();
}
if($oper == 'delete'){
$model = InputData::model()->findByPk($id);
$model->delete();
}
}
// inisialisasi criteria query
$criteria = new CDbCriteria();
$criteria->order = "$sidx $sord";
// filter lokasi
if (is_numeric($locationid) && $locationid !== 0)
{
$criteria->with = array('data'=>array(
'condition'=>'data.locationid=:locationid',
'params'=>array(':locationid'=>$locationid)
));
} else {
if (is_numeric($typeid) && $typeid !== 0)
{
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.typeid=:typeid',
'params'=>array(':typeid'=>$typeid)
)
)
));
} else {
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc',
'params'=>array(':type_desc'=>$kategori)
)
)
));
}
}
// filter range tanggal
if (isset($_REQUEST['startdate'], $_REQUEST['enddate']))
{
$startdate = $_REQUEST['startdate'];
$enddate = $_REQUEST['enddate'];
$criteria->condition = 'date_input <= :enddate AND date_input >= :startdate';
$criteria->params = array(':startdate'=>$startdate, ':enddate'=>$enddate);
}
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
$dataProvider = new CActiveDataProvider('InputData', array(
'criteria'=>$criteria,
'pagination'=>array(
'currentPage'=>$page-1,
'pageSize'=>$rows
)
));
$count = $dataProvider->totalItemCount;
$total_pages = $count > 0 ? ceil($count/$rows) : 0;
if ($page > $total_pages) $page=$total_pages;
// generate response untuk jqgrid
$response = new stdClass();
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
foreach($dataProvider->getData() as $row)
{
$response->rows[] = array(
'id'=>$row->inputdataid,
'cell'=>array(
$row->inputdataid,
$row->date_input,
$row->time_input,
$row->data->location->location_name,
$row->data->data_name,
$row->data->variable->var_name,
round($row->value, 3),
$row->data->variable->unit->uom_name,
($row->inputOfficer !== NULL ? $row->inputOfficer->officer_name:''),
'<i class="fa fa-pencil-square-o"></i> Edit <i class="fa fa-trash-o"></i> Delete'
)
);
}
echo json_encode($response);
} else {
$url = $this->createUrl("dataAir/manage");
$delurl = $this->createUrl("dataAir/deleteRow");
$startdate = '2013-01-01';
$enddate = date_format(new DateTime(), 'Y-m-d');
$this->render('jqgrid', array(
'kategori'=>$kategori,
'url'=>$url,
'delurl'=>$delurl,
'startdate'=>$startdate,
'enddate'=>$enddate
));
}
}
this line causing the problem
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
when, I remove those lines the method work just fine. what could be the problem causing ambigous colum name? here is the error log
SELECT COUNT(DISTINCT "t"."inputdataid") FROM "app_inputdata" "t" LEFT OUTER JOIN "app_ref_periodicdata" "data" ON ("t"."dataid"="data"."dataid") WHERE ((date_input <= :enddate AND date_input >= :startdate) AND (dataid = 7)) AND (data.locationid=:locationid). Bound with :startdate='2013-01-01', :enddate='2015-02-02', :locationid='6'
You need to add the table alias t to your condition:
$criteria->addCondition("t.dataid = $dataid");
Also, since $dataid is being obtained from a $_REQUEST it is best to pass it as a parameter. This can be done in two ways:
$criteria->addCondition("t.dataid = :dataid", [":dataid" => $dataid]);
$criteria->compare("t.dataid", $dataid);
you have used table aliases,
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc', <<- I mean here you have used alias : type
'params'=>array(':type_desc'=>$kategori)
)
you just have to remember that the main model that you are working with, will always need alias t to unambigufy! (not sure if that is an actual word :D )

How to create list of anonymous types in select clause?

Here is one of queries I am using in my project:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes = attribute
};
If the context.Attributes returns multiple rows, the whole resultset also returning multiple rows.
Is there any possibility to return a single car type with multiple attributes as a list of attributes to the car??
Please help.
Thanks,
Mahesh
You just need to move the attribute query inside the result set:
var carQuery = from cars in context.Cars
.Where(c => c.CarID==3)
from stockTypes in context.StockTypes
.Where(st => cars.StockTypeId == st.StockTypeID).DefaultIfEmpty()
from carUnit in context.Car_Units
.Where(cu => cu.CarId == cars.CarID).DefaultIfEmpty()
from carAttributes in context.Car_Attributes
.Where(ca => ca.CarId == cars.CarID).DefaultIfEmpty()
select new
{
CarID = cars.CarID,
CarName = cars.CarName,
CarDescription = cars.CarDescription,
StockType = (stockTypes == null) ? null : new
{
StockTypeID = stockTypes.StockTypeID,
StockName = stockTypes.StockName
},
IsActive = cars.IsActive,
IsCab = cars.IsCab,
Unit = (carUnit == null) ? null : new
{
Id = carUnit.UnitId,
Name = carUnit.Unit.UnitName
},
Attributes =
from attribute in context.Attributes
.Where(attr => attr.AttributeId==carAttributes.AttributeId).DefaultIfEmpty()
.GroupBy(at => at.AttributeId)
select attribute
};