Calculate Total Price with Symfony (Solved) - php

I have the following problem with shopping cart. I don’t know where to place the calculation, so it can update total price dynamically (Such when the cart item is removed, or the quantity updated). Because I need to call updateTotalPrice() method almost everywhere, but I don’t want to repeat the code that many times
So far it look like this
CartService
class CartService extends AbstractController
{
private CartRepository $cartRepository;
private ManagerRegistry $managerRegistry;
private CartItemRepository $cartItemRepository;
public function __construct(CartItemRepository $cartItemRepository, CartRepository $cartRepository, ManagerRegistry $managerRegistry)
{
$this->cartItemRepository = $cartItemRepository;
$this->cartRepository = $cartRepository;
$this->managerRegistry = $managerRegistry;
}
/**
* Get Cart by ID
*
* #return Cart|null
*/
public function getCartByUserId(): ?Cart
{
/**
* #var User $user
*/
$user = $this->getUser();
return $this->cartRepository->findOneBy(['customer' => $user->getId()]);
}
/**
* Create Cart for Customer
*
* #return Cart|null
*/
public function createNewCart(): ?Cart
{
$entityManager = $this->managerRegistry->getManager();
$cart = new Cart();
/**
* #var User $user
*/
$cart->setCustomer($this->getUser());
$entityManager->persist($cart);
$entityManager->flush();
return $cart;
}
/**
* #param Cart $cart
* #param Product $product
* #return CartItem|null
*/
public function isProductInCart(Cart $cart, Product $product): ?CartItem
{
return $this->cartItemRepository->findOneBy(['product' => $product->getId(), 'cart' => $cart->getId()]);
}
/**
* Add new product to cart
*
* #param Cart $cart
* #param Product $product
* #param int $quantity
* #return void
*/
public function insertProduct(Cart $cart, Product $product, int $quantity): void
{
$entityManager = $this->managerRegistry->getManager();
$insertProduct = new CartItem();
$insertProduct->setCart($cart)
->setCart($cart)
->setQuantity($quantity)
->setProduct($product);
$cart->addCartItem($insertProduct);
$cart->setTotalprice($cart->getTotalprice() + $insertProduct->getQuantity() * $insertProduct->getProduct()->getPrice());
$entityManager->persist($insertProduct);
$entityManager->flush();
}
/**
* Update item's quantity
*
* #param CartItem $cartItem
* #param int $quantity
* #return void
*/
public function updateCartItemQuantity(CartItem $cartItem, int $quantity): void
{
$entityManager = $this->managerRegistry->getManager();
$cartItem->setQuantity($quantity);
$entityManager->persist($cartItem);
$entityManager->flush();
}
/**
* Remove specific product from cart
*
* #param int $id
* #return void
*/
public function removeProductFromCart(int $id): void
{
$product = $this->cartItemRepository->findOneBy(['product' => $id]);
$entityManager = $this->managerRegistry->getManager();
$entityManager->remove($product);
$entityManager->flush();
}
/**
* Set or update total price
*
* #param Cart $cart
* #param float $totalprice
* #return void
*/
public function updateTotalPrice(Cart $cart, float $totalprice): void
{
$entityManager = $this->managerRegistry->getManager();
$cart->setTotalprice($cart->getTotalprice() + $totalprice);
$entityManager->persist($cart);
$entityManager->flush($cart);
}
/**
* Add Product to Cart
*
* #param Product $product
* #param $cartItem
* #return void
*/
public function addOrUpdateProduct(Product $product, $cartItem): void
{
$cart = $this->getCartByUserId();
if (!$cart instanceof Cart) {
$cart = $this->createNewCart();
}
$isProductInCart = $this->isProductInCart($cart, $product);
//If product doens't exist, insert it inside cart. If exist, update quantity and add message
if (!$isProductInCart) {
$this->insertProduct($cart, $product, $cartItem->getQuantity());
$this->addFlash('productAdded', 'Product added to Cart');
} else {
$this->updateCartItemQuantity($isProductInCart, $cartItem->getQuantity() + $isProductInCart->getQuantity());
$this->updateTotalPrice($cart, $cartItem->getQuantity() * $cartItem->getProduct()->getPrice());
$this->addFlash('productAdded', 'Product already in cart. Quantity Updated');
}
}
OrderController (That's the cart)
<?php
namespace App\Controller;
/**
* #IsGranted("IS_AUTHENTICATED_FULLY")
*/
#[Route('/cart', name: 'cart.')]
class OrderController extends AbstractController
{
/**
* Show current Cart
*
* #param CartService $cartService
* #return Response
*/
#[Route('/', name: 'show_cart')]
public function showCart(CartService $cartService): Response
{
$cart = $cartService->getCartByUserId();
return $this->render('cart/index.html.twig', [
'cart' => $cart,
]);
}
/**
* Update existing cart item quantity
*
* #param CartItem $cartItem
* #param int $quantity
* #param CartService $cartService
* #return Response
*/
#[Route('/updatecartquantity/{id}/{quantity}', name: 'updatequantity')]
public function updateCartQuantity(CartItem $cartItem, int $quantity, CartService $cartService): Response
{
$cartService->updateCartItemQuantity($cartItem, $quantity);
return $this->redirect($this->generateUrl('cart.show_cart'));
}
/**
* Remove product from cart
*
* #param CartService $cartService
* #param int $id
* #return Response
*/
#[Route('/removeitem/{id}', name: 'removefromcart')]
public function removeFromCart(CartService $cartService, int $id): Response
{
$cartService->removeProductFromCart($id);
return $this->redirect($this->generateUrl('cart.show_cart'));
}
}
Product Controller (Shows the product -> After choosing quantity can be inserted inside cart
#[Route('/product', name: 'product.')]
class ProductController extends AbstractController
{
/**
* Show Product, and add to cart
*
* #param Product $product
* #param CartService $cartService
* #param Request $request
* #return Response
*/
#[Route('/showproduct/{id}', name: 'showproduct')]
public function showProduct(Product $product, CartService $cartService, Request $request): Response
{
$form = $this->createForm(CartItemType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$item = $form->getData();
$item->setProduct($product);
$cartService->addOrUpdateProduct($product, $item);
}
return $this->render('product/showproduct.html.twig', [
'product' => $product,
'form' => $form->createView()
]);
}
}

I solved by adding showCart() method, which instead inserts and updates values in database, it runs only, when I want to display Cart.
public function showCart(): ?Cart
{
$cart = $this->getCartByUserId();
$cartItem = $this->cartItemRepository->findBy(['cart' => $cart]);
$totalprice = 0;
foreach ($cartItem as $carti) {
$totalprice += $carti->getQuantity() * $carti->getProduct()->getPrice();
}
$cart->setTotalprice($totalprice);
return $cart;
}

Related

How to add image parameter in Gloudemans Shoppingcart

I am trying to add an image parameter in Gloudemans Shoppingcart but am getting an error
Please supply a valid weight
I am pretty sure this is because am inserting the image parameter in a position configured for "weight", now my question is where do I add the image parameter? it doesn't seem to exist in any of the Gloudemans config files, please assist, below am listing all files under config in Gloudemans shoppingcart
Cart Controller
public function addItem($id)
{
$product=Product::find($id);
Cart::add($id,$product->product_name,1,$product->price,$product->product_image);
return back();
}
Cart.php file under folders vender\bumbummen99\src
<?php
namespace Gloudemans\Shoppingcart;
use Carbon\Carbon;
use Closure;
use Gloudemans\Shoppingcart\Contracts\Buyable;
use Gloudemans\Shoppingcart\Contracts\InstanceIdentifier;
use Gloudemans\Shoppingcart\Exceptions\CartAlreadyStoredException;
use Gloudemans\Shoppingcart\Exceptions\InvalidRowIDException;
use Gloudemans\Shoppingcart\Exceptions\UnknownModelException;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\DatabaseManager;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Collection;
class Cart
{
const DEFAULT_INSTANCE = 'default';
/**
* Instance of the session manager.
*
* #var \Illuminate\Session\SessionManager
*/
private $session;
/**
* Instance of the event dispatcher.
*
* #var \Illuminate\Contracts\Events\Dispatcher
*/
private $events;
/**
* Holds the current cart instance.
*
* #var string
*/
private $instance;
/**
* Holds the creation date of the cart.
*
* #var mixed
*/
private $createdAt;
/**
* Holds the update date of the cart.
*
* #var mixed
*/
private $updatedAt;
/**
* Defines the discount percentage.
*
* #var float
*/
private $discount = 0;
/**
* Defines the tax rate.
*
* #var float
*/
private $taxRate = 0;
/**
* Cart constructor.
*
* #param \Illuminate\Session\SessionManager $session
* #param \Illuminate\Contracts\Events\Dispatcher $events
*/
public function __construct(SessionManager $session, Dispatcher $events)
{
$this->session = $session;
$this->events = $events;
$this->taxRate = config('cart.tax');
$this->instance(self::DEFAULT_INSTANCE);
}
/**
* Set the current cart instance.
*
* #param string|null $instance
*
* #return \Gloudemans\Shoppingcart\Cart
*/
public function instance($instance = null)
{
$instance = $instance ?: self::DEFAULT_INSTANCE;
if ($instance instanceof InstanceIdentifier) {
$this->discount = $instance->getInstanceGlobalDiscount();
$instance = $instance->getInstanceIdentifier();
}
$this->instance = sprintf('%s.%s', 'cart', $instance);
return $this;
}
/**
* Get the current cart instance.
*
* #return string
*/
public function currentInstance()
{
return str_replace('cart.', '', $this->instance);
}
/**
* Add an item to the cart.
*
* #param mixed $id
* #param mixed $name
* #param int|float $qty
* #param float $price
* #param float $weight
* #param array $options
*
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function add($id, $name = null, $qty = null, $price = null, $weight = 0, array $options = [])
{
if ($this->isMulti($id)) {
return array_map(function ($item) {
return $this->add($item);
}, $id);
}
$cartItem = $this->createCartItem($id, $name, $qty, $price, $weight, $options);
return $this->addCartItem($cartItem);
}
/**
* Add an item to the cart.
*
* #param \Gloudemans\Shoppingcart\CartItem $item Item to add to the Cart
* #param bool $keepDiscount Keep the discount rate of the Item
* #param bool $keepTax Keep the Tax rate of the Item
* #param bool $dispatchEvent
*
* #return \Gloudemans\Shoppingcart\CartItem The CartItem
*/
public function addCartItem($item, $keepDiscount = false, $keepTax = false, $dispatchEvent = true)
{
if (!$keepDiscount) {
$item->setDiscountRate($this->discount);
}
if (!$keepTax) {
$item->setTaxRate($this->taxRate);
}
$content = $this->getContent();
if ($content->has($item->rowId)) {
$item->qty += $content->get($item->rowId)->qty;
}
$content->put($item->rowId, $item);
if ($dispatchEvent) {
$this->events->dispatch('cart.added', $item);
}
$this->session->put($this->instance, $content);
return $item;
}
/**
* Update the cart item with the given rowId.
*
* #param string $rowId
* #param mixed $qty
*
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function update($rowId, $qty)
{
$cartItem = $this->get($rowId);
if ($qty instanceof Buyable) {
$cartItem->updateFromBuyable($qty);
} elseif (is_array($qty)) {
$cartItem->updateFromArray($qty);
} else {
$cartItem->qty = $qty;
}
$content = $this->getContent();
if ($rowId !== $cartItem->rowId) {
$itemOldIndex = $content->keys()->search($rowId);
$content->pull($rowId);
if ($content->has($cartItem->rowId)) {
$existingCartItem = $this->get($cartItem->rowId);
$cartItem->setQuantity($existingCartItem->qty + $cartItem->qty);
}
}
if ($cartItem->qty <= 0) {
$this->remove($cartItem->rowId);
return;
} else {
if (isset($itemOldIndex)) {
$content = $content->slice(0, $itemOldIndex)
->merge([$cartItem->rowId => $cartItem])
->merge($content->slice($itemOldIndex));
} else {
$content->put($cartItem->rowId, $cartItem);
}
}
$this->events->dispatch('cart.updated', $cartItem);
$this->session->put($this->instance, $content);
return $cartItem;
}
/**
* Remove the cart item with the given rowId from the cart.
*
* #param string $rowId
*
* #return void
*/
public function remove($rowId)
{
$cartItem = $this->get($rowId);
$content = $this->getContent();
$content->pull($cartItem->rowId);
$this->events->dispatch('cart.removed', $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Get a cart item from the cart by its rowId.
*
* #param string $rowId
*
* #return \Gloudemans\Shoppingcart\CartItem
*/
public function get($rowId)
{
$content = $this->getContent();
if (!$content->has($rowId)) {
throw new InvalidRowIDException("The cart does not contain rowId {$rowId}.");
}
return $content->get($rowId);
}
/**
* Destroy the current cart instance.
*
* #return void
*/
public function destroy()
{
$this->session->remove($this->instance);
}
/**
* Get the content of the cart.
*
* #return \Illuminate\Support\Collection
*/
public function content()
{
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
/**
* Get the number of items in the cart.
*
* #return int|float
*/
public function count()
{
return $this->getContent()->sum('qty');
}
/**
* Get the number of items instances in the cart.
*
* #return int|float
*/
public function countInstances()
{
return $this->getContent()->count();
}
/**
* Get the total price of the items in the cart.
*
* #return float
*/
public function totalFloat()
{
return $this->getContent()->reduce(function ($total, CartItem $cartItem) {
return $total + $cartItem->total;
}, 0);
}
/**
* Get the total price of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function total($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->totalFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the total tax of the items in the cart.
*
* #return float
*/
public function taxFloat()
{
return $this->getContent()->reduce(function ($tax, CartItem $cartItem) {
return $tax + $cartItem->taxTotal;
}, 0);
}
/**
* Get the total tax of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function tax($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->taxFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the subtotal (total - tax) of the items in the cart.
*
* #return float
*/
public function subtotalFloat()
{
return $this->getContent()->reduce(function ($subTotal, CartItem $cartItem) {
return $subTotal + $cartItem->subtotal;
}, 0);
}
/**
* Get the subtotal (total - tax) of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function subtotal($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->subtotalFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the discount of the items in the cart.
*
* #return float
*/
public function discountFloat()
{
return $this->getContent()->reduce(function ($discount, CartItem $cartItem) {
return $discount + $cartItem->discountTotal;
}, 0);
}
/**
* Get the discount of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function discount($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->discountFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the price of the items in the cart (not rounded).
*
* #return float
*/
public function initialFloat()
{
return $this->getContent()->reduce(function ($initial, CartItem $cartItem) {
return $initial + ($cartItem->qty * $cartItem->price);
}, 0);
}
/**
* Get the price of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function initial($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->initialFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the price of the items in the cart (previously rounded).
*
* #return float
*/
public function priceTotalFloat()
{
return $this->getContent()->reduce(function ($initial, CartItem $cartItem) {
return $initial + $cartItem->priceTotal;
}, 0);
}
/**
* Get the price of the items in the cart as formatted string.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function priceTotal($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->priceTotalFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the total weight of the items in the cart.
*
* #return float
*/
public function weightFloat()
{
return $this->getContent()->reduce(function ($total, CartItem $cartItem) {
return $total + ($cartItem->qty * $cartItem->weight);
}, 0);
}
/**
* Get the total weight of the items in the cart.
*
* #param int $decimals
* #param string $decimalPoint
* #param string $thousandSeperator
*
* #return string
*/
public function weight($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->weightFloat(), $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Search the cart content for a cart item matching the given search closure.
*
* #param \Closure $search
*
* #return \Illuminate\Support\Collection
*/
public function search(Closure $search)
{
return $this->getContent()->filter($search);
}
/**
* Associate the cart item with the given rowId with the given model.
*
* #param string $rowId
* #param mixed $model
*
* #return void
*/
public function associate($rowId, $model)
{
if (is_string($model) && !class_exists($model)) {
throw new UnknownModelException("The supplied model {$model} does not exist.");
}
$cartItem = $this->get($rowId);
$cartItem->associate($model);
$content = $this->getContent();
$content->put($cartItem->rowId, $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Set the tax rate for the cart item with the given rowId.
*
* #param string $rowId
* #param int|float $taxRate
*
* #return void
*/
public function setTax($rowId, $taxRate)
{
$cartItem = $this->get($rowId);
$cartItem->setTaxRate($taxRate);
$content = $this->getContent();
$content->put($cartItem->rowId, $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Set the global tax rate for the cart.
* This will set the tax rate for all items.
*
* #param float $discount
*/
public function setGlobalTax($taxRate)
{
$this->taxRate = $taxRate;
$content = $this->getContent();
if ($content && $content->count()) {
$content->each(function ($item, $key) {
$item->setTaxRate($this->taxRate);
});
}
}
/**
* Set the discount rate for the cart item with the given rowId.
*
* #param string $rowId
* #param int|float $taxRate
*
* #return void
*/
public function setDiscount($rowId, $discount)
{
$cartItem = $this->get($rowId);
$cartItem->setDiscountRate($discount);
$content = $this->getContent();
$content->put($cartItem->rowId, $cartItem);
$this->session->put($this->instance, $content);
}
/**
* Set the global discount percentage for the cart.
* This will set the discount for all cart items.
*
* #param float $discount
*
* #return void
*/
public function setGlobalDiscount($discount)
{
$this->discount = $discount;
$content = $this->getContent();
if ($content && $content->count()) {
$content->each(function ($item, $key) {
$item->setDiscountRate($this->discount);
});
}
}
/**
* Store an the current instance of the cart.
*
* #param mixed $identifier
*
* #return void
*/
public function store($identifier)
{
$content = $this->getContent();
if ($identifier instanceof InstanceIdentifier) {
$identifier = $identifier->getInstanceIdentifier();
}
if ($this->storedCartWithIdentifierExists($identifier)) {
throw new CartAlreadyStoredException("A cart with identifier {$identifier} was already stored.");
}
$this->getConnection()->table($this->getTableName())->insert([
'identifier' => $identifier,
'instance' => $this->currentInstance(),
'content' => serialize($content),
'created_at' => $this->createdAt ?: Carbon::now(),
'updated_at' => Carbon::now(),
]);
$this->events->dispatch('cart.stored');
}
/**
* Restore the cart with the given identifier.
*
* #param mixed $identifier
*
* #return void
*/
public function restore($identifier)
{
if ($identifier instanceof InstanceIdentifier) {
$identifier = $identifier->getInstanceIdentifier();
}
if (!$this->storedCartWithIdentifierExists($identifier)) {
return;
}
$stored = $this->getConnection()->table($this->getTableName())
->where('identifier', $identifier)->first();
$storedContent = unserialize(data_get($stored, 'content'));
$currentInstance = $this->currentInstance();
$this->instance(data_get($stored, 'instance'));
$content = $this->getContent();
foreach ($storedContent as $cartItem) {
$content->put($cartItem->rowId, $cartItem);
}
$this->events->dispatch('cart.restored');
$this->session->put($this->instance, $content);
$this->instance($currentInstance);
$this->createdAt = Carbon::parse(data_get($stored, 'created_at'));
$this->updatedAt = Carbon::parse(data_get($stored, 'updated_at'));
$this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->delete();
}
/**
* Erase the cart with the given identifier.
*
* #param mixed $identifier
*
* #return void
*/
public function erase($identifier)
{
if ($identifier instanceof InstanceIdentifier) {
$identifier = $identifier->getInstanceIdentifier();
}
if (!$this->storedCartWithIdentifierExists($identifier)) {
return;
}
$this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->delete();
$this->events->dispatch('cart.erased');
}
/**
* Merges the contents of another cart into this cart.
*
* #param mixed $identifier Identifier of the Cart to merge with.
* #param bool $keepDiscount Keep the discount of the CartItems.
* #param bool $keepTax Keep the tax of the CartItems.
* #param bool $dispatchAdd Flag to dispatch the add events.
*
* #return bool
*/
public function merge($identifier, $keepDiscount = false, $keepTax = false, $dispatchAdd = true)
{
if (!$this->storedCartWithIdentifierExists($identifier)) {
return false;
}
$stored = $this->getConnection()->table($this->getTableName())
->where('identifier', $identifier)->first();
$storedContent = unserialize($stored->content);
foreach ($storedContent as $cartItem) {
$this->addCartItem($cartItem, $keepDiscount, $keepTax, $dispatchAdd);
}
$this->events->dispatch('cart.merged');
return true;
}
/**
* Magic method to make accessing the total, tax and subtotal properties possible.
*
* #param string $attribute
*
* #return float|null
*/
public function __get($attribute)
{
switch ($attribute) {
case 'total':
return $this->total();
case 'tax':
return $this->tax();
case 'subtotal':
return $this->subtotal();
default:
return;
}
}
/**
* Get the carts content, if there is no cart content set yet, return a new empty Collection.
*
* #return \Illuminate\Support\Collection
*/
protected function getContent()
{
if ($this->session->has($this->instance)) {
return $this->session->get($this->instance);
}
return new Collection();
}
/**
* Create a new CartItem from the supplied attributes.
*
* #param mixed $id
* #param mixed $name
* #param int|float $qty
* #param float $price
* #param float $weight
* #param array $options
*
* #return \Gloudemans\Shoppingcart\CartItem
*/
private function createCartItem($id, $name, $qty, $price, $weight, array $options)
{
if ($id instanceof Buyable) {
$cartItem = CartItem::fromBuyable($id, $qty ?: []);
$cartItem->setQuantity($name ?: 1);
$cartItem->associate($id);
} elseif (is_array($id)) {
$cartItem = CartItem::fromArray($id);
$cartItem->setQuantity($id['qty']);
} else {
$cartItem = CartItem::fromAttributes($id, $name, $price, $weight, $options);
$cartItem->setQuantity($qty);
}
return $cartItem;
}
/**
* Check if the item is a multidimensional array or an array of Buyables.
*
* #param mixed $item
*
* #return bool
*/
private function isMulti($item)
{
if (!is_array($item)) {
return false;
}
return is_array(head($item)) || head($item) instanceof Buyable;
}
/**
* #param $identifier
*
* #return bool
*/
private function storedCartWithIdentifierExists($identifier)
{
return $this->getConnection()->table($this->getTableName())->where('identifier', $identifier)->exists();
}
/**
* Get the database connection.
*
* #return \Illuminate\Database\Connection
*/
private function getConnection()
{
return app(DatabaseManager::class)->connection($this->getConnectionName());
}
/**
* Get the database table name.
*
* #return string
*/
private function getTableName()
{
return config('cart.database.table', 'shoppingcart');
}
/**
* Get the database connection name.
*
* #return string
*/
private function getConnectionName()
{
$connection = config('cart.database.connection');
return is_null($connection) ? config('database.default') : $connection;
}
/**
* Get the Formatted number.
*
* #param $value
* #param $decimals
* #param $decimalPoint
* #param $thousandSeperator
*
* #return string
*/
private function numberFormat($value, $decimals, $decimalPoint, $thousandSeperator)
{
if (is_null($decimals)) {
$decimals = config('cart.format.decimals', 2);
}
if (is_null($decimalPoint)) {
$decimalPoint = config('cart.format.decimal_point', '.');
}
if (is_null($thousandSeperator)) {
$thousandSeperator = config('cart.format.thousand_separator', ',');
}
return number_format($value, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the creation date of the cart (db context).
*
* #return \Carbon\Carbon|null
*/
public function createdAt()
{
return $this->createdAt;
}
/**
* Get the lats update date of the cart (db context).
*
* #return \Carbon\Carbon|null
*/
public function updatedAt()
{
return $this->updatedAt;
}
}
I have tried checcking out Crinsane's repo but there is no documentation about this

How to populate a dropdown in Symfony 3

I am a newbie in symfony and i have decided to explore symfony 3. I have two models: products and category and I want to populate a dropdown in a new product form with all the categories. How can i do this pls?
Below is what have done so far:
<?php
Product Model:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Persisters\Entity;
use Doctrine\ORM\Mapping\Column;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
/**
* #ORM\Column( type ="string", length=100)
*/
private $name;
/**
* #ORM\Column(type="decimal", scale=2)
*/
private $price;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set category
*
* #param \AppBundle\Entity\Category $category
*
* #return Product
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
}
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
*/
class Category
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $products;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
public function __construct()
{
$this->products= new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add product
*
* #param \AppBundle\Entity\Product $product
*
* #return Category
*/
public function addProduct(\AppBundle\Entity\Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Product $product
*/
public function removeProduct(\AppBundle\Entity\Product $product)
{
$this->products->removeElement($product);
}
/**
* Get products
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
<
?php
DefaultController:
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Category;
use AppBundle\Entity\Product;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class DefaultController extends Controller
{
/**
* #Route("/product_new")
*/
public function newAction(Request $request)
{
$category = new Category();
$product = new Product();
$form = $this->createFormBuilder($product)
->add('name', TextType::class)
->add('price', NumberType::class)
->add('description', TextareaType::class)
->add('category', EntityType::class, array(
'class' => 'AppBundle:Category',
'choices' => $category->getProducts(),
))
->add('save', SubmitType::class, array('label'=>'Create New Product'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
// $category->setName( $request->request->get('category'));
//$product->setCategory( new Category('Cat1'));
$product = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
//$entityManager->persist($category);
$entityManager->persist($product);
$entityManager->flush();
return $this->render('product/product_status.html.twig',
['msg' =>'Saved new product with id ' . $product->getId()]);
}else
{
return $this->render('product/product_new.html.twig', ['form'=> $form->createView(),]);
}
}
/**
* #Route("/new_product", name="new_product")
*/
public function createAction(Request $request)
{
$product = new Product();
$product->setName("Keyboard");
$product->setPrice(19.9);
$product->setDescription("Ergonomic and stylish!");
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($product);
$entityManager->flush();
return $this->render('product/product_status.html.twig',
['msg' =>'Saved new product with id ' . $product->getId()]);
}
/**
* #Route("/show_product/{productId}")
*/
public function showAction($productId)
{
$product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);
if(!$product)
{
$this->createNotFoundException("No Product was found with Id". $productId);
}
return $this->render('product/product_search.html.twig', ['product' => $product]);
}
/**
* #Route("/product_list", name ="productlist")
*/
public function listAction()
{
$products = $this->getDoctrine()->getRepository('AppBundle:Product')->findAll();
if(!$products)
{
$this->createNotFoundException("No Product was found ");
}
return $this->render('product/product_list.html.twig', ['products' => $products]);
}
/**
* #Route("/update_product/{productId}", name ="updateproduct")
*/
public function updateAction($productId)
{
$entityManager = $this->getDoctrine()->getManager();
$product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);
if($product)
{
$product->setName("Project");
$product->setDescription("Sony Projector with LCD light");
$entityManager->flush();
return $this->redirectToRoute('productlist');
}
}
/**
* #Route("/delete_product/{productId}", name ="deleteproduct")
*/
public function deleteAction($productId)
{
$entityManager = $this->getDoctrine()->getManager();
$product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($productId);
if($product)
{
$entityManager->remove($product);
$entityManager->flush();
return $this->redirectToRoute('productlist');
}
}
}
You can use query_builder option like below. You can adapt it to your application. Full example is here: Full webform style CRUD example with an embedded associated entity in symfony
....
private $country;
public function __construct()
{
$this->country = [
....
'class' => 'FootballFrontendBundle:Country',
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('c')->orderBy('c.name', 'ASC');
}
];
}
public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
....
->add('country', 'entity', $this->country);
}
....

Symfony 3: Doctrine listAction: Did you forget a "use" statement for another namespace?

I'm trying to make an easy listAction to retrieve data from Doctrine but I got this error:
Attempted to load class "ProductRepository" from namespace "AppBundle\Entity".
Did you forget a "use" statement for another namespace?
This come out when i call the route ex.com/list that must
to list the data coming from product table
Controller: (src/AppBundle/Controller)
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use AppBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
new Translator('it', new MessageSelector(), __DIR__.'/../cache');
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
* #param Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction(Request $request)
{
$request->getLocale();
$request->setLocale('it');
return $this->render('default/index.html.twig', [
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
]);
}
/**
*
* #Route("list", name="list")
* #return Response
*
*/
public function listAction()
{
return $product = $this->getDoctrine()
->getRepository('AppBundle\Entity\Product')
->findAll();
/* if (!$product) {
throw $this->createNotFoundException(
'Nessun prodotto trovato'
);
}*/
}
/**
* #Route("create",name="create")
* #return Response
*/
public function createAction()
{
$product = new Product();
$product->setName('Pippo Pluto');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$product->setSeller('1');
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->render('default/index.html.twig');
}
/**
* #param $id
* #Route("show/{id}",name="show/{id}")
* #return Response
*/
public function showAction($id)
{
$product = new Product();
$product = $this->getDoctrine()
->getRepository('AppBundle:Product')
->find($id);
if (!$product) {
throw $this->createNotFoundException(
'Nessun prodotto trovato per l\'id '.$id
);
}
}
}
Entity: (src/AppBundle/Entity)
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* #ORM\Table(name="product")
* #ORM\Entity(repositoryClass="AppBundle\Entity\ProductRepository")
*/
class Product
{
/**
* #var int
*
* #ORM\Column(name="`id`", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="`name`", type="string")
*/
private $name;
/**
* #var float
*
* #ORM\Column(name="`price`", type="float")
*/
private $price;
/**
* #var string
*
* #ORM\Column(name="`description`", type="string")
*/
private $description;
/**
* #var int
*
* #ORM\Column(name="`seller`", type="integer")
*/
private $seller;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Set price
*
* #param float $price
*
* #return Product
*/
public function setPrice($price) {
$this->price = $price;
return $this;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Set seller
*
* #param int $seller
*
* #return Product
*/
public function setSeller($seller) {
$this->seller = $seller;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Get seller
*
* #return int
*/
public function getSeller()
{
return $this->seller;
}
}
I can't understand what I'm missing to use. thanks.
That error "Attempted to load class "ProductRepository" from namespace "AppBundle\Entity" is generated because you, by mistake I guess, renamed the repositoryClass in your AppBundle/Entity/Product class.
So instead of * #ORM\Entity(repositoryClass="AppBundle\Entity\ProductRepository") you should have * #ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository"), which means that the repository classes are meant to be located into Repository directory and not Entity.
And a controller action method must always return a response, or a redirect, etc.
And, even though your way works too, you would always want to call the findAll() method on a repository object, and not an entity one. So, again,
in your listAction instead of ->getRepository('AppBundle\Entity\Product')->findAll() needs to be ->getRepository('AppBundle:Product')->findAll()
I might be wrong, but i think that is becouse You dont render anything. Try this code: $product = $this->getDoctrine() ->getRepository('AppBundle\Entity\Product') ->findAll(); return $this->render('default/index.html.twig',['product' => $product]);

Doctrine fetching filtered associated objects with findAll

I' searched all over the Internet but I've not found a definite answer to this question.
I have the following entities:
/**
* #ORM\Entity
* #ORM\Table(name="category")
*/
class Category
{
/*
* ...
*/
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Add product
*
* #param \AppBundle\Entity\Product $product
*
* #return Category
*/
public function addProduct(\AppBundle\Entity\Product $product)
{
$this->products[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Product $product
*/
public function removeProduct(\AppBundle\Entity\Product $product)
{
$this->products->removeElement($product);
}
/**
* Get products
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/*
* ...
*/
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* #ORM\Column(type="boolean")
*/
protected $active;
/**
* Set category
*
* #param \AppBundle\Entity\Category $category
*
* #return Product
*/
public function setCategory(\AppBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set active
*
* #param boolean $active
*
* #return Product
*/
public function setActive($active)
{
$this->active= $active;
return $this;
}
/**
* Get active
*
* #return boolean
*/
public function getActive()
{
return $this->active;
}
}
I only want to do this:
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('AppBundle\Entity\Category')->findAll();
$json = $serializer->serialize($categories, 'json');
and in the json result I want to make sure that all categories have their associated products filtered by status=true.In other words I want to get the results in the front end as an array of category objects with each category having an array of products that are active only.
I know it can be done trivially in Django.
Can it be done in doctrine?If yes how.
Strait answers please.
SOLUTION I'VE USED
$qb = $em->createQueryBuilder()
->select('c')
->from('AppBundle:Category','c')
->leftJoin('c.products','p','WITH','p.status = :status')
->addSelect('p')
->setParameter('status', true);

Magento Fatal error: Call to a member function getBillingAddress() on a non-object in /Abstract.php on line 689

I'm getting the following error: Fatal error: Call to a member function getBillingAddress() on a non-object in /data/web/public/app/code/core/Mage/Payment/Model/Method/Abstract.php on line 689
I'm on Magento 1.9.1.1. Also have this problem with a completely different magento installation on a different server. Both same versions 1.9.1.1.
This error happens, when from the Manage Customers page, you'll want to create an order for a specific customer. Happens with any registerd customer.
Could this be a core magento bug? And how to fix it?
All help very much appreciated!
Abstract.php
/**
* Payment method abstract model
*
* #author Magento Core Team <core#magentocommerce.com>
*/
abstract class Mage_Payment_Model_Method_Abstract extends Varien_Object
{
const ACTION_ORDER = 'order';
const ACTION_AUTHORIZE = 'authorize';
const ACTION_AUTHORIZE_CAPTURE = 'authorize_capture';
const STATUS_UNKNOWN = 'UNKNOWN';
const STATUS_APPROVED = 'APPROVED';
const STATUS_ERROR = 'ERROR';
const STATUS_DECLINED = 'DECLINED';
const STATUS_VOID = 'VOID';
const STATUS_SUCCESS = 'SUCCESS';
/**
* Bit masks to specify different payment method checks.
* #see Mage_Payment_Model_Method_Abstract::isApplicableToQuote
*/
const CHECK_USE_FOR_COUNTRY = 1;
const CHECK_USE_FOR_CURRENCY = 2;
const CHECK_USE_CHECKOUT = 4;
const CHECK_USE_FOR_MULTISHIPPING = 8;
const CHECK_USE_INTERNAL = 16;
const CHECK_ORDER_TOTAL_MIN_MAX = 32;
const CHECK_RECURRING_PROFILES = 64;
const CHECK_ZERO_TOTAL = 128;
protected $_code;
protected $_formBlockType = 'payment/form';
protected $_infoBlockType = 'payment/info';
/**
* Payment Method features
* #var bool
*/
protected $_isGateway = false;
protected $_canOrder = false;
protected $_canAuthorize = false;
protected $_canCapture = false;
protected $_canCapturePartial = false;
protected $_canCaptureOnce = false;
protected $_canRefund = false;
protected $_canRefundInvoicePartial = false;
protected $_canVoid = false;
protected $_canUseInternal = true;
protected $_canUseCheckout = true;
protected $_canUseForMultishipping = true;
protected $_isInitializeNeeded = false;
protected $_canFetchTransactionInfo = false;
protected $_canReviewPayment = false;
protected $_canCreateBillingAgreement = false;
protected $_canManageRecurringProfiles = true;
/**
* TODO: whether a captured transaction may be voided by this gateway
* This may happen when amount is captured, but not settled
* #var bool
*/
protected $_canCancelInvoice = false;
/**
* Fields that should be replaced in debug with '***'
*
* #var array
*/
protected $_debugReplacePrivateDataKeys = array();
public function __construct()
{
}
/**
* Check order availability
*
* #return bool
*/
public function canOrder()
{
return $this->_canOrder;
}
/**
* Check authorise availability
*
* #return bool
*/
public function canAuthorize()
{
return $this->_canAuthorize;
}
/**
* Check capture availability
*
* #return bool
*/
public function canCapture()
{
return $this->_canCapture;
}
/**
* Check partial capture availability
*
* #return bool
*/
public function canCapturePartial()
{
return $this->_canCapturePartial;
}
/**
* Check whether capture can be performed once and no further capture possible
*
* #return bool
*/
public function canCaptureOnce()
{
return $this->_canCaptureOnce;
}
/**
* Check refund availability
*
* #return bool
*/
public function canRefund()
{
return $this->_canRefund;
}
/**
* Check partial refund availability for invoice
*
* #return bool
*/
public function canRefundPartialPerInvoice()
{
return $this->_canRefundInvoicePartial;
}
/**
* Check void availability
*
* #param Varien_Object $payment
* #return bool
*/
public function canVoid(Varien_Object $payment)
{
return $this->_canVoid;
}
/**
* Using internal pages for input payment data
* Can be used in admin
*
* #return bool
*/
public function canUseInternal()
{
return $this->_canUseInternal;
}
/**
* Can be used in regular checkout
*
* #return bool
*/
public function canUseCheckout()
{
return $this->_canUseCheckout;
}
/**
* Using for multiple shipping address
*
* #return bool
*/
public function canUseForMultishipping()
{
return $this->_canUseForMultishipping;
}
/**
* Can be edit order (renew order)
*
* #return bool
*/
public function canEdit()
{
return true;
}
/**
* Check fetch transaction info availability
*
* #return bool
*/
public function canFetchTransactionInfo()
{
return $this->_canFetchTransactionInfo;
}
/**
* Check whether payment method instance can create billing agreements
*
* #return bool
*/
public function canCreateBillingAgreement()
{
return $this->_canCreateBillingAgreement;
}
/**
* Fetch transaction info
*
* #param Mage_Payment_Model_Info $payment
* #param string $transactionId
* #return array
*/
public function fetchTransactionInfo(Mage_Payment_Model_Info $payment, $transactionId)
{
return array();
}
/**
* Retrieve payment system relation flag
*
* #return bool
*/
public function isGateway()
{
return $this->_isGateway;
}
/**
* flag if we need to run payment initialize while order place
*
* #return bool
*/
public function isInitializeNeeded()
{
return $this->_isInitializeNeeded;
}
/**
* To check billing country is allowed for the payment method
*
* #return bool
*/
public function canUseForCountry($country)
{
/*
for specific country, the flag will set up as 1
*/
if($this->getConfigData('allowspecific')==1){
$availableCountries = explode(',', $this->getConfigData('specificcountry'));
if(!in_array($country, $availableCountries)){
return false;
}
}
return true;
}
/**
* Check method for processing with base currency
*
* #param string $currencyCode
* #return boolean
*/
public function canUseForCurrency($currencyCode)
{
return true;
}
/**
* Check manage billing agreements availability
*
* #return bool
*/
public function canManageBillingAgreements()
{
return ($this instanceof Mage_Payment_Model_Billing_Agreement_MethodInterface);
}
/**
* Whether can manage recurring profiles
*
* #return bool
*/
public function canManageRecurringProfiles()
{
return $this->_canManageRecurringProfiles
&& ($this instanceof Mage_Payment_Model_Recurring_Profile_MethodInterface);
}
/**
* Retrieve model helper
*
* #return Mage_Payment_Helper_Data
*/
protected function _getHelper()
{
return Mage::helper('payment');
}
/**
* Retrieve payment method code
*
* #return string
*/
public function getCode()
{
if (empty($this->_code)) {
Mage::throwException(Mage::helper('payment')->__('Cannot retrieve the payment method code.'));
}
return $this->_code;
}
/**
* Retrieve block type for method form generation
*
* #return string
*/
public function getFormBlockType()
{
return $this->_formBlockType;
}
/**
* Retrieve block type for display method information
*
* #return string
*/
public function getInfoBlockType()
{
return $this->_infoBlockType;
}
/**
* Retrieve payment iformation model object
*
* #return Mage_Payment_Model_Info
*/
public function getInfoInstance()
{
$instance = $this->getData('info_instance');
if (!($instance instanceof Mage_Payment_Model_Info)) {
Mage::throwException(Mage::helper('payment')->__('Cannot retrieve the payment information object instance.'));
}
return $instance;
}
/**
* Validate payment method information object
*
* #return Mage_Payment_Model_Abstract
*/
public function validate()
{
/**
* to validate payment method is allowed for billing country or not
*/
$paymentInfo = $this->getInfoInstance();
if ($paymentInfo instanceof Mage_Sales_Model_Order_Payment) {
$billingCountry = $paymentInfo->getOrder()->getBillingAddress()->getCountryId();
} else {
$billingCountry = $paymentInfo->getQuote()->getBillingAddress()->getCountryId();
}
if (!$this->canUseForCountry($billingCountry)) {
Mage::throwException(Mage::helper('payment')->__('Selected payment type is not allowed for billing country.'));
}
return $this;
}
/**
* Order payment abstract method
*
* #param Varien_Object $payment
* #param float $amount
*
* #return Mage_Payment_Model_Abstract
*/
public function order(Varien_Object $payment, $amount)
{
if (!$this->canOrder()) {
Mage::throwException(Mage::helper('payment')->__('Order action is not available.'));
}
return $this;
}
/**
* Authorize payment abstract method
*
* #param Varien_Object $payment
* #param float $amount
*
* #return Mage_Payment_Model_Abstract
*/
public function authorize(Varien_Object $payment, $amount)
{
if (!$this->canAuthorize()) {
Mage::throwException(Mage::helper('payment')->__('Authorize action is not available.'));
}
return $this;
}
/**
* Capture payment abstract method
*
* #param Varien_Object $payment
* #param float $amount
*
* #return Mage_Payment_Model_Abstract
*/
public function capture(Varien_Object $payment, $amount)
{
if (!$this->canCapture()) {
Mage::throwException(Mage::helper('payment')->__('Capture action is not available.'));
}
return $this;
}
/**
* Set capture transaction ID to invoice for informational purposes
* #param Mage_Sales_Model_Order_Invoice $invoice
* #param Mage_Sales_Model_Order_Payment $payment
* #return Mage_Payment_Model_Method_Abstract
*/
public function processInvoice($invoice, $payment)
{
$invoice->setTransactionId($payment->getLastTransId());
return $this;
}
/**
* Set refund transaction id to payment object for informational purposes
* Candidate to be deprecated:
* there can be multiple refunds per payment, thus payment.refund_transaction_id doesn't make big sense
*
* #param Mage_Sales_Model_Order_Invoice $invoice
* #param Mage_Sales_Model_Order_Payment $payment
* #return Mage_Payment_Model_Method_Abstract
*/
public function processBeforeRefund($invoice, $payment)
{
$payment->setRefundTransactionId($invoice->getTransactionId());
return $this;
}
/**
* Refund specified amount for payment
*
* #param Varien_Object $payment
* #param float $amount
*
* #return Mage_Payment_Model_Abstract
*/
public function refund(Varien_Object $payment, $amount)
{
if (!$this->canRefund()) {
Mage::throwException(Mage::helper('payment')->__('Refund action is not available.'));
}
return $this;
}
/**
* Set transaction ID into creditmemo for informational purposes
* #param Mage_Sales_Model_Order_Creditmemo $creditmemo
* #param Mage_Sales_Model_Order_Payment $payment
* #return Mage_Payment_Model_Method_Abstract
*/
public function processCreditmemo($creditmemo, $payment)
{
$creditmemo->setTransactionId($payment->getLastTransId());
return $this;
}
/**
* Cancel payment abstract method
*
* #param Varien_Object $payment
*
* #return Mage_Payment_Model_Abstract
*/
public function cancel(Varien_Object $payment)
{
return $this;
}
/**
* #deprecated after 1.4.0.0-alpha3
* this method doesn't make sense, because invoice must not void entire authorization
* there should be method for invoice cancellation
* #param Mage_Sales_Model_Order_Invoice $invoice
* #param Mage_Sales_Model_Order_Payment $payment
* #return Mage_Payment_Model_Method_Abstract
*/
public function processBeforeVoid($invoice, $payment)
{
$payment->setVoidTransactionId($invoice->getTransactionId());
return $this;
}
/**
* Void payment abstract method
*
* #param Varien_Object $payment
*
* #return Mage_Payment_Model_Abstract
*/
public function void(Varien_Object $payment)
{
if (!$this->canVoid($payment)) {
Mage::throwException(Mage::helper('payment')->__('Void action is not available.'));
}
return $this;
}
/**
* Whether this method can accept or deny payment
*
* #param Mage_Payment_Model_Info $payment
*
* #return bool
*/
public function canReviewPayment(Mage_Payment_Model_Info $payment)
{
return $this->_canReviewPayment;
}
/**
* Attempt to accept a payment that us under review
*
* #param Mage_Payment_Model_Info $payment
* #return bool
* #throws Mage_Core_Exception
*/
public function acceptPayment(Mage_Payment_Model_Info $payment)
{
if (!$this->canReviewPayment($payment)) {
Mage::throwException(Mage::helper('payment')->__('The payment review action is unavailable.'));
}
return false;
}
/**
* Attempt to deny a payment that us under review
*
* #param Mage_Payment_Model_Info $payment
* #return bool
* #throws Mage_Core_Exception
*/
public function denyPayment(Mage_Payment_Model_Info $payment)
{
if (!$this->canReviewPayment($payment)) {
Mage::throwException(Mage::helper('payment')->__('The payment review action is unavailable.'));
}
return false;
}
/**
* Retrieve payment method title
*
* #return string
*/
public function getTitle()
{
return $this->getConfigData('title');
}
/**
* Retrieve information from payment configuration
*
* #param string $field
* #param int|string|null|Mage_Core_Model_Store $storeId
*
* #return mixed
*/
public function getConfigData($field, $storeId = null)
{
if (null === $storeId) {
$storeId = $this->getStore();
}
$path = 'payment/'.$this->getCode().'/'.$field;
return Mage::getStoreConfig($path, $storeId);
}
/**
* Assign data to info model instance
*
* #param mixed $data
* #return Mage_Payment_Model_Info
*/
public function assignData($data)
{
if (is_array($data)) {
$this->getInfoInstance()->addData($data);
}
elseif ($data instanceof Varien_Object) {
$this->getInfoInstance()->addData($data->getData());
}
return $this;
}
/**
* Parepare info instance for save
*
* #return Mage_Payment_Model_Abstract
*/
public function prepareSave()
{
return $this;
}
/**
* Check whether payment method can be used
*
* TODO: payment method instance is not supposed to know about quote
*
* #param Mage_Sales_Model_Quote|null $quote
*
* #return bool
*/
public function isAvailable($quote = null)
{
$checkResult = new StdClass;
$isActive = (bool)(int)$this->getConfigData('active', $quote ? $quote->getStoreId() : null);
$checkResult->isAvailable = $isActive;
$checkResult->isDeniedInConfig = !$isActive; // for future use in observers
Mage::dispatchEvent('payment_method_is_active', array(
'result' => $checkResult,
'method_instance' => $this,
'quote' => $quote,
));
if ($checkResult->isAvailable && $quote) {
$checkResult->isAvailable = $this->isApplicableToQuote($quote, self::CHECK_RECURRING_PROFILES);
}
return $checkResult->isAvailable;
}
/**
* Check whether payment method is applicable to quote
* Purposed to allow use in controllers some logic that was implemented in blocks only before
*
* #param Mage_Sales_Model_Quote $quote
* #param int|null $checksBitMask
* #return bool
*/
public function isApplicableToQuote($quote, $checksBitMask)
{
if ($checksBitMask & self::CHECK_USE_FOR_COUNTRY) {
if (!$this->canUseForCountry($quote->getBillingAddress()->getCountry())) {
return false;
}
}
if ($checksBitMask & self::CHECK_USE_FOR_CURRENCY) {
if (!$this->canUseForCurrency($quote->getStore()->getBaseCurrencyCode())) {
return false;
}
}
if ($checksBitMask & self::CHECK_USE_CHECKOUT) {
if (!$this->canUseCheckout()) {
return false;
}
}
if ($checksBitMask & self::CHECK_USE_FOR_MULTISHIPPING) {
if (!$this->canUseForMultishipping()) {
return false;
}
}
if ($checksBitMask & self::CHECK_USE_INTERNAL) {
if (!$this->canUseInternal()) {
return false;
}
}
if ($checksBitMask & self::CHECK_ORDER_TOTAL_MIN_MAX) {
$total = $quote->getBaseGrandTotal();
$minTotal = $this->getConfigData('min_order_total');
$maxTotal = $this->getConfigData('max_order_total');
if (!empty($minTotal) && $total < $minTotal || !empty($maxTotal) && $total > $maxTotal) {
return false;
}
}
if ($checksBitMask & self::CHECK_RECURRING_PROFILES) {
if (!$this->canManageRecurringProfiles() && $quote->hasRecurringItems()) {
return false;
}
}
if ($checksBitMask & self::CHECK_ZERO_TOTAL) {
$total = $quote->getBaseSubtotal() + $quote->getShippingAddress()->getBaseShippingAmount();
if ($total < 0.0001 && $this->getCode() != 'free'
&& !($this->canManageRecurringProfiles() && $quote->hasRecurringItems())
) {
return false;
}
}
return true;
}
/**
* Method that will be executed instead of authorize or capture
* if flag isInitializeNeeded set to true
*
* #param string $paymentAction
* #param object $stateObject
*
* #return Mage_Payment_Model_Abstract
*/
public function initialize($paymentAction, $stateObject)
{
return $this;
}
/**
* Get config payment action url
* Used to universalize payment actions when processing payment place
*
* #return string
*/
public function getConfigPaymentAction()
{
return $this->getConfigData('payment_action');
}
/**
* Log debug data to file
*
* #param mixed $debugData
*/
protected function _debug($debugData)
{
if ($this->getDebugFlag()) {
Mage::getModel('core/log_adapter', 'payment_' . $this->getCode() . '.log')
->setFilterDataKeys($this->_debugReplacePrivateDataKeys)
->log($debugData);
}
}
/**
* Define if debugging is enabled
*
* #return bool
*/
public function getDebugFlag()
{
return $this->getConfigData('debug');
}
/**
* Used to call debug method from not Payment Method context
*
* #param mixed $debugData
*/
public function debugData($debugData)
{
$this->_debug($debugData);
}
}
I had similar issue in success page, so i load object by loadByIncrementId function, it worked for me
$orderId = '600008796';
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
then you can access to billing/shipping address by object
$order->getBillingAddress()->getFirstname();
$order->getBillingAddress()->getEmail();
$order->getShippingAddress()->getFirstname();
$order->getShippingAddress()->getEmail();

Categories