Tuesday, 21 May 2013

Add wysiwyg editor in custom magento module.

Just Follw this simple 4 steps in your custom module.
step-1
Go to following path and open Edit.php
app\code\local\Namespace\Modulename\Block\Adminhtml\Modulename
and Add this Function
protected function _prepareLayout()
{
// Load Wysiwyg on demand and Prepare layout
if (Mage::getSingleton(‘cms/wysiwyg_config’)->isEnabled() && ($block = $this->getLayout()->getBlock(‘head’))) {
$block->setCanLoadTinyMce(true);
}
parent::_prepareLayout();
}

step-2
Go to following path and open Form.php
app\code\local\Namespace\Modulename\Block\Adminhtml\Modulename\Edit\Tab
and find function protected function _prepareForm()
and add
$form->setHtmlIdPrefix(‘modulename’);
$wysiwygConfig = Mage::getSingleton(‘cms/wysiwyg_config’)->getConfig(
array(‘tab_id’ => ‘form_section’)
);
And add field property
$wysiwygConfig["files_browser_window_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg_images/index’);
$wysiwygConfig["directives_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg/directive’);
$wysiwygConfig["directives_url_quoted"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/cms_wysiwyg/directive’);
$wysiwygConfig["widget_window_url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/widget/index’);
$wysiwygConfig["files_browser_window_width"] = (int) Mage::getConfig()->getNode(‘adminhtml/cms/browser/window_width’);
$wysiwygConfig["files_browser_window_height"] = (int) Mage::getConfig()->getNode(‘adminhtml/cms/browser/window_height’);
$plugins = $wysiwygConfig->getData(“plugins”);
$plugins[0]["options"]["url"] = Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/system_variable/wysiwygPlugin’);
$plugins[0]["options"]["onclick"]["subject"] = “MagentovariablePlugin.loadChooser(‘”.Mage::getSingleton(‘adminhtml/url’)->getUrl(‘adminhtml/system_variable/wysiwygPlugin’).”‘, ‘{{html_id}}’);”;
$plugins = $wysiwygConfig->setData(“plugins”,$plugins);
$fieldset->addField(‘fieldname’, ‘editor’, array(
‘name’ => ‘fieldname’,
‘label’ => Mage::helper(‘modulename’)->__(‘Content’),
‘title’ => Mage::helper(‘modulename’)->__(‘Content’),
‘style’ => ‘width:700px; height:300px;’,
‘wysiwyg’ => true,
‘required’ => false,
‘state’ => ‘html’,
‘config’ => $wysiwygConfig,
));

step-3
Go to following path and open modulename.xml if its not available than create id
app\design\adminhtml\default\default\layout
and add
<?xml version=”1.0″?>
<layout>
<modulename_adminhtml_controllername_index>
<reference name=”content”>
<block type=”modulename/adminhtml_blockname” name=”blockname” />
</reference>
</modulename_adminhtml_controllername_index>
<modulename_adminhtml_controllername_edit>
<update handle=”editor”/>
</modulename_adminhtml_controllername_edit>
</layout>

step-4
if you want to Display editor's content in front side use below code .

$_cmsHelper = Mage::helper(‘cms’);
$_process = $_cmsHelper->getBlockTemplateProcessor();
echo $_process->filter($item['content']);

Magento : Login/Logout Code in Header

<?php if (! Mage::getSingleton('customer/session')->isLoggedIn()): ?>

<a href="<?php echo Mage::helper('customer')->getLoginUrl(); ?>"><?php echo $this->__('Login') ?></a>

<?php else: ?>

<a href="<?php echo Mage::helper('customer')->getLogoutUrl(); ?>"><?php echo $this->__('Logout') ?></a>

<?php endif; ?>

Tuesday, 14 May 2013

Magento Forms: Prototype Javascript Validation In Custom Module

If you want to use magento's default validatin inyour custom module it may helps you.

Adding Javascript validation to your own forms is extremely simple. First, you need to create a Form (form.js) object to represent your form.
<script type="text/javascript">
//< ![CDATA[
  var myForm= new VarienForm('formId', true);
//]]>
</script>
 
example how to add validation in custom module through class name is as below:
<label for="name">Name *</label>
<input type="text" id="name" name="name" value="" class="required-entry"/>
<label for="email">Email Address *</label>
<input type="text" id="email" name="email"  class="required-entry validate-email"/>
 
Here are the few magento javascript validation classes as below:

validate-select   - Please select an option

required-entry   - This is a required field

validate-number  - Please enter a valid number in this field

validate-digits   - Please use numbers only in this field. please avoid spaces or other characters such as dots or commas

validate-alpha  - Please use letters only (a-z or A-Z) in this field.

validate-code  - Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-alphanum  - Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed

validate-street  - Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field

validate-phoneStrict  - Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-phoneLax  - Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-fax  - Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890

validate-date - Please enter a valid date

validate-email  - Please enter a valid email address. For example johndoe@domain.com.

validate-emailSender  - Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

validate-password  - Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-admin-password  - Please enter 7 or more characters. Password should contain both numeric and alphabetic characters

validate-cpassword  - Please make sure your passwords match

validate-url  - Please enter a valid URL. http:// is required

validate-clean-url  - Please enter a valid URL. For example http://www.example.com or www.example.com

validate-identifier  - Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

validate-xml-identifier  - Please enter a valid XML-identifier. For example something_1, block5, id-4

validate-ssn  - Please enter a valid social security number. For example 123-45-6789

validate-zip - Please enter a valid zip code. For example 90602 or 90602-1234


Monday, 13 May 2013

Get the current category/product/cms page in Magento


<?php
$currentCategory = Mage::registry('current_category');
$currentProduct = Mage::registry('current_product');
$currentCmsPage = Mage::registry('cms_page');
?>

Get Product Collection by Product Type in Magento


$collectionSimple = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'));

$collectionConfigurable = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'configurable'));

$collectionBundle = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'bundle'));

$collectionGrouped = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'grouped'));

$collectionVirtual = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('type_id', array('eq' => 'virtual'));

Join custom table to product collection in magento


$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 'main_table.foreign_id = table_alias.primary_key', array('table_alias.*'), 'schema_name_if_different');


For Example,


$collection = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('sku')
                ->addAttributeToSelect('price')
                ->addAttributeToSelect('status')
                ->addAttributeToSelect('visibility')
                ->addAttributeToFilter('type_id', array('eq' => 'simple'))
                ->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                ->addAttributeToFilter('visibility', array('neq' => 1));

Add tracking no in shipment in magento through script

1.create a csv file . In it put following fields OrderNumber,Email,TrackingNumber,Carrier . & csv's name is orders_tracking_import.csv
2 Create ordertracking.php file in your magento's root directory

<?php
    require_once("app/Mage.php");
    Mage::app();
 
    if (isset($_POST['MAX_FILE_SIZE'])) {

        $email = true;
 
        $target_path = basename( $_FILES['uploadedfile']['name']);
        $_FILES['uploadedfile']['tmp_name'];
        $target_path = basename( $_FILES['uploadedfile']['name']);
         
        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
?>

The file <?php echo basename( $_FILES['uploadedfile']['name']); ?> has been uploaded succesfully!


<?php  
            ini_set("auto_detect_line_endings", 1);
            $current_row = 1;
            $handle = fopen($target_path, "r");
            $csvData = array();
         
            while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE )
            {
                $number_of_fields = count($data);
//print_r($number_of_fields);exit;
                if ($current_row == 1) {    //Header line
                    for ($c=0; $c < $number_of_fields; $c++)
                    {
                        $header_array[$c] = $data[$c];
                    }
                } else {    //Data line
                    for ($c=0; $c < $number_of_fields; $c++)
                    {
                        $data_array[$header_array[$c]] = $data[$c];
                    }
                    $csvData[] = $data_array;
                }
                $current_row++;
            }
           
            fclose($handle);
         
            foreach($csvData as $rec) {
                                             
                $includeComment = false;
                $comment = NULL;
               
                $order = Mage::getModel('sales/order')->loadByIncrementId($rec['OrderNumber']);
               
                //This converts the order to "Completed".


   if ($order->canShip())
 {

                    $convertor = Mage::getModel('sales/convert_order');
                    $shipment = $convertor->toShipment($order);
                    $shipment->setIncrementId($orderId);
                   
                    foreach ($order->getAllItems() as $orderItem) {
                   
                        if (!$orderItem->getQtyToShip()) {
                            continue;
                        }
                        if ($orderItem->getIsVirtual()) {
                            continue;
                        }
                   
                        $item = $convertor->itemToShipmentItem($orderItem);
                   
                        $qty = $orderItem->getQtyToShip();
                   
                        $item->setQty($qty);
                        $shipment->addItem($item);
                    }
                   
                 } else {
               
                    foreach ($order->getShipmentsCollection() as $shipment) {
                        $shipmentId = $shipment->getIncrementId();
                    }
                        $shipment = Mage::getModel('sales/order_shipment')->loadByIncrementId($shipmentId);
                }
             
                $carrierTitle = NULL;
               
                // FOR GUIDANCE ON THIS SECTION LOOK AT MY FIRST POST... IT HAS BETTER COMMENTS
               
                if ($rec['Carrier'] == 'ups') {
                    $carrierTitle = 'United Parcel Service';
                }
                if ($rec['Carrier'] == 'dhl') {
                    $carrierTitle = 'DHL (Deprecaied)';
                }
                if ($rec['Carrier'] == 'fedex') {
                    $carrierTitle = 'Federal Express';
                }
if ($rec['Carrier'] == 'dhlint') {
                    $carrierTitle = 'DHL';
                }
                if ($rec['Carrier'] == 'usps') {
                    $carrierTitle = 'United States Postal Service';
                }
                if ($rec['Carrier'] == 'custom') {
                    $carrierTitle = 'Custom Value';
                }
               
                $data = array();
                $data['carrier_code'] = $rec['Carrier'];
                $data['title'] = $carrierTitle;
                $data['number'] = $rec['TrackingNumber'];
               
                $track =Mage::getModel('sales/order_shipment_track')->addData($data);

                $shipment->addTrack($track);
             
               
    if ($order->canShip()){
                    $shipment->register();
                    $shipment->addComment($comment, $email && $includeComment);
                    $shipment->setEmailSent(true);
                    $shipment->getOrder()->setIsInProcess(true);
                   
                    $transactionSave = Mage::getModel('core/resource_transaction')
                        ->addObject($shipment)
                        ->addObject($shipment->getOrder())
                        ->save();
                   
                    $shipment->sendEmail($rec['Email'], ($includeComment ? $comment : ''));
                   
                    $shipment->save();
                }
   else {
                    $track->save();
                    $shipment->sendEmail($rec['Email'], ($includeComment ? $comment : ''));
                    $order->setStatus('complete');
                    $order->addStatusToHistory('complete', '', false);
                    $order->save();
                }    
                                 

            }
         
        } //end if statment for file upload check
       
    } else { // end if statement for post check for upload

?>

<form enctype="multipart/form-data" action="" method="POST">
  <p>
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
    CSV File:
    <input name="uploadedfile" type="file" />
  </p>
  <p>
    <input type="submit" name="upload" id="upload" value="Submit" />
  </p>
</form>


<?php
   
    }

?>