Magento: Add custom text at the bottom of invoice pdf - magento

I am very new in Magento.
I want to add some "term & condition" at the bottom of customer invoice.
I know This question is already posted on the portal, But I didn't found any solution yet.
Can anyone explain me how to do that.

Open the file app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php and add the below function at the end of the file
public function insertConditions($page)
{
$page->drawLine(25, $this->y, 570, $this->y);
$this->y -= 25;
$page->drawText(Mage::helper('sales')->__('Your custom text here!'), 35, $this->y, 'UTF-8');
}
Now, you need to call this insertConditions() function in the getPdf() function like below :
public function getPdf($invoices = array())
{
$this->_beforeGetPdf();
$this->_initRenderer('invoice');
$pdf = new Zend_Pdf();
$this->_setPdf($pdf);
$style = new Zend_Pdf_Style();
$this->_setFontBold($style, 10);
foreach ($invoices as $invoice) {
if ($invoice->getStoreId()) {
Mage::app()->getLocale()->emulate($invoice->getStoreId());
Mage::app()->setCurrentStore($invoice->getStoreId());
}
$page = $this->newPage();
$order = $invoice->getOrder();
/* Add image */
$this->insertLogo($page, $invoice->getStore());
/* Add address */
$this->insertAddress($page, $invoice->getStore());
/* Add head */
$this->insertOrder(
$page,
$order,
Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId())
);
/* Add document text and number */
$this->insertDocumentNumber(
$page,
Mage::helper('sales')->__('Invoice # ') . $invoice->getIncrementId()
);
/* Add table */
$this->_drawHeader($page);
/* Add body */
foreach ($invoice->getAllItems() as $item){
if ($item->getOrderItem()->getParentItem()) {
continue;
}
/* Draw item */
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
/* Add totals */
$this->insertTotals($page, $invoice);
if ($invoice->getStoreId()) {
Mage::app()->getLocale()->revert();
}
}
$this->insertConditions($page); // the custom text is added here
$this->_afterGetPdf();
return $pdf;
}
PS. I would advice to override the core files instead of changing them directly.

Related

Magento Order History Comments: Modify Date

I am creating a script to add orders programmatically in Magento. I need help to change the date of the entries in the Comments History (quote, invoice, shipping, etc.). I can manipulate the date of the order itself (setCreatedAt) and some of the comments related to the creation of the order are correct (e.g. "Sep 29, 2008 8:59:25 AM|Pending Customer Notification Not Applicable"), but I cannot change the date of the comment when I use addStatusHistoryComment...
Here's a snippet of my code:
try {
if(!$order->canInvoice()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->setCreatedAt('2008-09-23 13:05:20');
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
- >addObject($invoice->getOrder());
$transactionSave->save();
//END Handle Invoice
//START Handle Shipment
$shipment = $order->prepareShipment();
$shipment->setCreatedAt('2008-09-23 14:20:10');
$shipment->register();
$order->setIsInProcess(true);
$order->addStatusHistoryComment('Shipping message goes here...', true);
$shipment->setEmailSent(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', 'Some tracking no.')
->setData('number', '111222333444')
->setData('carrier_code', 'fedex') //custom, fedex, ups, usps, dhl
->setData('order_id', $shipment->getData('order_id'))
->save();
//END Handle Shipment
}
catch (Mage_Core_Exception $ex) {
echo "Problem creating order invoice and/or shipment: ".$ex."\n";
}
Thanks in advance.
If I understand your question correctly, you just need to do this:
$comments = $order->getStatusHistoryCollection(true);
$comments now contains a collection of all the status history comments, and you can loop over them with whatever sort of criteria you like.
foreach ($comments as $c) {
if ( /* some stuff */ ) {
$c->setData('created_at',$new_date)->save();
}
}
So this is untested, but should work:
You need to create a new method based off addStatusHistoryComment:
/app/code/core/Mage/Sales/Model/Order.php
/*
* Add a comment to order
* Different or default status may be specified
*
* #param string $comment
* #param string $status
* #return Mage_Sales_Model_Order_Status_History
*/
public function addStatusHistoryComment($comment, $status = false)
{
if (false === $status) {
$status = $this->getStatus();
} elseif (true === $status) {
$status = $this->getConfig()->getStateDefaultStatus($this->getState());
} else {
$this->setStatus($status);
}
$history = Mage::getModel('sales/order_status_history')
->setStatus($status)
->setComment($comment)
->setEntityName($this->_historyEntityName);
->setCreatedAt('2008-09-23 14:20:10'); //I added this line
$this->addStatusHistory($history);
return $history;
}
Obviously you either need to rewrite this method, or refactor the code to do the same.

get the values of custom options

I'm trying to alter a price based on some custom options set. Therefore I'm trying to get the value a customer has entered, not the default values set in the backend. To do this I'm using the event catalog_product_get_final_price used in Mage_Bundle_Model_Product_Price. I have registered the following observer:
public function observer_callback($evt_obs)
{
$event = $evt_obs->getEvent();
$data = $event->getData();
/* #var $collection Mage_Catalog_Model_Resource_Product_Collection */
$collection = $data['collection'];
$items = $collection->getItems();
/* #var $item Mage_Catalog_Model_Product */
foreach ($items as $item) {
if ( $item->getName() == 'Bundel Test2') {
$options = $item->getCustomOptions();
/* #var $option Mage_Catalog_Model_Product_Option */
foreach ($options as $option) {
// Here I'm trying to get the value given by the user/customer
var_dump($option->getData());
}
}
}
return $this;
}
It is a custom option from a bundle type. So the product can't be configurable.
I'm new to magento so I'm probably missing something.
Can anyone help me?
Hope this piece of code can help you:
public function productFinalPrice($observer){
$product = $observer->getEvent()->getProduct();
$productType=$product->getTypeID();
if($productType == 'your_product_type')
{
$option = $product->getCustomOptions();
$searchedOption = null;
//search for your option;
foreach ($product->getOptions() as $o) {
if($o->getTitle()=="your_attribute_title" && $o->getType()=="your_type_of_option(eg. area"){
$optionId = $o->getOptionId();//got your searched optionId
break;
}
}
foreach($option as $key => $o) {
if($key == "option_".$optionId) {
$searchedOption = $o;
//here you get the option object with the values in it
}
}
$articleNumber = $searchedOption->getData('value'); // getthe value of your option
//calculate final price like you need it
$product->setFinalPrice($finalPrice);
}
return $this;
}
best regards

Creating categories and sub-categories in Magento Extension

I am new to Magento Extension Development and wondering which is the best way to create categories and sub-categories from within an extension. The Extension I am working on is synchronizing product-data from an ERP-System. The extension is operating with a System->Configuration Dialog which holds the data for the connection to the server (user/pwd/etc.) Now I am wondering, if it is better to connect via Ajax request or use a Soap call. Ajax seems very slow in this case for about 700 Products. So what do you suggest?
Furthermore, I am a little stuck by creating categories and sub-categories. Is there simple way to do that. I found some stuff on creating a category and then use the ->move() function. Moreover I am wondering if the 'path' of the category is essential on creating sub-categories.
You should use magento models:
Create category with subcategory:
/**
* After installation system has two categories: root one with ID:1 and Default category with ID:2
*/
/** #var $category1 Mage_Catalog_Model_Category */
$category1 = Mage::getModel('catalog/category');
$category1->setName('Category 1')
->setParentId(2)
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->save();
/** #var $category2 Mage_Catalog_Model_Category */
$category2 = Mage::getModel('catalog/category');
$category2->setName('Category 1.1')
->setParentId($category1->getId()) // set parent category which was created above
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setIsAnchor(true)
->setPosition(1)
->save();
public static function addCatalogCategory($item, $id, $storeId = 0) {
/*
* resource for checking category exists
* http://fishpig.co.uk/blog/load-a-category-or-product-by-an-attribute.html
*/
$categories = Mage::getResourceModel('catalog/category_collection');
// Select which fields to load into the category
// * will load all fields but it is possible to pass an array of
// select fields to load
$categories->addAttributeToSelect('*');
// Ensure the category is active
$categories->addAttributeToFilter('is_active', 1);
// Add Name filter
$categories->addAttributeToFilter('name', $item->GROUP_NAME);
// Limit the collection to 1 result
$categories->setCurPage(1)->setPageSize(1);
// Load the collection
$categories->load();
if ($categories->getFirstItem()->getId()) {
$category = $categories->getFirstItem();
return $category->getId();
}
/* get category object model */
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
$data = array();
/* if the node is root */
if (Heliumv_Synchronization_Helper_Data::xml_attribute($item, 'type') == 'root') {
$data['category']['parent'] = 2; // 2 top level id
} else {
/* is node/leaf */
$data['category']['parent'] = $id;
}
$data['general']['path'] = $item->PARENT_ID;
$data['general']['name'] = $item->GROUP_NAME;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "1";
$data['general']['url_key'] = "";
$data['general']['display_mode'] = "PRODUCTS";
$data['general']['is_anchor'] = 0;
/* add data to category model */
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
echo Mage::log($e->getMessage());
}
}
I hope this helps someone. cheers

Codeigniter Cart - Check if item added to cart

I'm using the Cart class in Codeigniter. What I want to do should (hopefully!) be simple... but i'm struggling.
On the product page, I have a button to 'add to cart'. What I want to happen is that when the item is already in the cart, the button changes to 'remove from cart'.
<? //if(**not in cart**) { ?>
Add to cart
<? } else { ?>
Remove from cart
<? } ?>
How can I query the cart to see if that item is in there or not and get the 'rowid' so I can use that for a remove function?
Many thanks!
I had a similar problem - I got round it by extending the CI_Cart library with 2 new functions - in_cart() and all_item_count().
<?php
class MY_Cart extends CI_Cart {
function __construct()
{
parent::__construct();
$this->product_name_rules = '\d\D';
}
/*
* Returns data for products in cart
*
* #param integer $product_id used to fetch only the quantity of a specific product
* #return array|integer $in_cart an array in the form (id => quantity, ....) OR quantity if $product_id is set
*/
public function in_cart($product_id = null) {
if ($this->total_items() > 0)
{
$in_cart = array();
// Fetch data for all products in cart
foreach ($this->contents() AS $item)
{
$in_cart[$item['id']] = $item['qty'];
}
if ($product_id)
{
if (array_key_exists($product_id, $in_cart))
{
return $in_cart[$product_id];
}
return null;
}
else
{
return $in_cart;
}
}
return null;
}
public function all_item_count()
{
$total = 0;
if ($this->total_items() > 0)
{
foreach ($this->contents() AS $item)
{
$total = $item['qty'] + $total;
}
}
return $total;
}
}
/* End of file: MY_Cart.php */
/* Location: ./application/libraries/MY_Cart.php */
You could check in your model if the job name or whatever you would like to check already exists. If it exists display delete button else show add.

Need help with Wishlist

The wishlist section in the sidebar disappears when all the items in it are removed.. but i want to shot it even when there is no items in wishlist with a text "Add some items to your wishlist".. as like "Compare section".. how do i do it?
i tried editing the .phtml file for doing it, but its not working.. do i need to edit any xml layout file for this?
For just info, please don't reputate.
The wishlist class has been changed after 1.4.2 :
* #deprecated after 1.4.2.0
* #see Mage_Wishlist_Block_Links::__construct
*
* #return array
*/
public function addWishlistLink()
{
return $this;
}
and here is the your requested feature ( look at count ) :
/**
* Add link on wishlist page in parent block
*
* #return Mage_Wishlist_Block_Links
*/
public function addWishlistLink()
{
$parentBlock = $this->getParentBlock();
if ($parentBlock && $this->helper('wishlist')->isAllow()) {
$count = $this->helper('wishlist')->getItemCount();
if ($count > 1) {
$text = $this->__('My Wishlist (%d items)', $count);
}
else if ($count == 1) {
$text = $this->__('My Wishlist (%d item)', $count);
}
else {
$text = $this->__('My Wishlist');
}
$parentBlock->addLink($text, 'wishlist', $text, true, array(), 30, null, 'class="top-link-wishlist"');
}
return $this;
}
Magento 1.6.1.0
/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
contains the function _toHtml():
protected function _toHtml()
{
if (($this->getCustomWishlist() && $this->getItemCount()) || $this->hasWishlistItems()) {
return parent::_toHtml();
}
return '';
}
Copy:
/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
to:
/app/code/local/Mage/Wishlist/Block/Customer/Sidebar.php
In the copied file, replace the contents of function _toHtml() with return parent::_toHtml();:
protected function _toHtml()
{
return parent::_toHtml();
}

Resources