/**
* get Controller name
*/
$this ->getRequest()->getControllerName();
/**
Read more
Posted in Development
Here is an example on how I extracted email address from a mail log file: $subject = "1 Aug 5 13:26:20 269701-web1 postfix/smtp[20033]: E730B10582C3: to=, relay=gmail-smtp-in.l.google.com[74.125.91.27]:25, delay=1.4, delays=0.02/0.01/0.13/1.3, dsn=2.0.0, status=sent (250 2.0.0 OK 1312568780 fp10si6690298qab.63) 1 Aug 5 13:30:49 269701-web1 postfix/smtp[20753]: F06EF10582C3: to= , relay=mx4.hotmail.com[65.55.92.136]:25, delay=0.28, delays=0.02/0/0.1/0.15, dsn=2.0.0, status=sent (250 <20110805183048.F06EF10582C3@269701-web1.www.bloom.com> Queued mail for delivery) 1 Aug 5 13:34:13 269701-web1 postfix/smtp[20822]: 5121410582C3: to=, relay=mx1.labcorp.iphmx.com[68.232.129.161]:25, delay=0.91, delays=0.01/0/0.42/0.47, dsn=2.0.0, status=sent (250 ok: Message 21101182 accepted) 1 Aug 5 13:34:14 269701-web1 postfix/smtp[20822]: 75C8610582C3: to=, relay=mx2.labcorp.iphmx.com[68.232.129.150]:25, delay=1, delays=0.02/0/0.49/0.54, dsn=2.0.0, status=sent (250 ok: Message 22975937 accepted) 1 Aug 5 13:44:53 269701-web1 postfix/smtp[21625]: 84B5B10582C3: to=, relay=gmail-smtp-in.l.google.com[74.125.91.27]:25, delay=1.7, delays=0.01/0/0.27/1.4, dsn=2.0.0, status=sent (250 2.0.0 OK 1312569893 ef1si6693357qab.35) ";
function extract_emails_from($string){
preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
return $matches[0];
}
Read more
Posted in Development
Make sure you cd into the folder you want to delete all the contents $rm -rf * ( hit enter ) That should remove any contents in that folder you are currently in
Posted in Development
// sort an object by key
function sort_object_by_key( $obj, $order='' )
{
$tmp = array();
// deconstruct the object into an array
foreach( $obj as $key => $val )
{
$tmp[$key] = '';
}
// sort the array
if($order == 'DESC')
{
krsort( $tmp );
}
else
{
ksort( $tmp );
}
Read more
Posted in Development
rsync is a software application for Unix and Windows systems which synchronizes files and directories from one location to another while minimizing data transfer using delta encoding when appropriate. An important feature of rsync not found in most similar programs/protocols is that the mirroring takes place with only one transmission in each direction. rsync can copy or display directory contents and copy files, optionally using compression and recursion. In daemon mode, rsync listens on the default TCP port of 873, serving files in the native rsync protocol or via a remote shell such as RSH or SSH. In the latter case, the rsync client executable must be installed on both the local and the remote host. I use rsync a lot specially to backup my important files between two computers, but also to keep my local slackware repository up to date. rsync is great to keep folders and files synchronized between two computers or in the same computer, you can backup all your important data to an external disk using rsync. rsync uses Copy files with rsync From local to remote computer rsync --progress --partial -avz /folder/to/copy/ user@remote.server:/remote/folder This will copy all files in /folder/to/copy/ to /remote/folder in the remote server, the folder copy itself will not be created in the remote computer, and only its contents will be copied, if you want the folder itself to also be created and then its contents copied inside the newly created copy folder, use this command. rsync --progress --partial -avz /folder/to/copy user@remote.server:/remote/folder Note the trailing slash after copy that makes the difference. The rest of options are: progress: will show the percentage of the file copied partial: tells rsync to
Read more
Posted in Development
/var/log/maillog/ $ grep "status=sent" /var/log/maillog | grep "Aug 5" | wc -l Will return the number of emails
Posted in Development
Create tape archives and add or extract files. Syntax tar c [ bBeEfFhiklnopPqvwX [ 0-7 ] ] [ block ] [ tarfile ] [ exclude-file ] {-I include-file | -C directory | file | file } tar r [ bBeEfFhiklnqvw [ 0-7 ] ] [ block ] {-I include-file | -C directory | file | file } tar t [ BefFhiklnqvX [ 0-7 ] ] [ tarfile ] [ exclude-file ] {-I include-file | file } ... tar u [ bBeEfFhiklnqvw [ 0-7 ] ] [ block ] [ tarfile ] file ... tar x [ BefFhiklmnopqvwX [ 0-7 ] ] [ tarfile ] [ exclude-file ] [ file ... ] c Create. Writing begins at the beginning of the tarfile, instead of at the end. r Replace. The named file s are written at the end of the tarfile. A file created with extended headers must be updated with extended headers (see E flag under Function Modifiers). A file created without extended headers cannot be modified with extended headers. t Table of Contents. The names of the specified files are listed each time they occur in the tar file. If no file argument is given, the names of all files in the tarfile are listed. With the v function modifier, additional information for the specified files is displayed. u Update. The named file s are written at the end of the tarfile if they are not already in the tar file, or if they have been modified since last written to that tarfile. An update can be rather slow. A tarfile created on a 5.x system cannot be updated on a 4.x system. A file created with extended headers must be updated with extended headers (see E flag under Function Modifiers). A file created without extended headers cannot be modified with extended headers. x Extract or restore. The named file s are extracted from the tarfile and written to the directory specified in the tarfile, relative to the current directory. Use the relative path names of files and
Read more
Posted in Development
From command line: $ dstat -f This will show a great report in color for your system in real time.
Posted in Development
sar - Collect, report, or save system activity information. From command line: $ sar -b This command shows the amount of traffic and you can check for spikes in traffic
Posted in Development
You may need to sudo: From terminal: $ /etc/init.d/httpd stop $ /etc/init.d/httpd start $ /etc/init.d/httpd restart
Posted in Development
Using terminal: $ cd /var/log/httpd/ $ tail -f access_log | grep 64.24.44.47 The -f means run continually until you hit Control - C to stop it ( the ip can be whatever your filtering the results to if your interested in an IP's traffic ) Drop the | grep and the IP if you want all traffic $ tail -f access_log
Posted in Development
find /opt/wherever/you/want/to/search -type f -name *.jpg -ls You might have to do it a few times for different file types. Or you can just leave the "-name *.jpg" part out and it will just give you your report on ALL of your files. If you don't like full bytes you could pipe some commands together..... find /opt/wherever/you/want/to/search -type f -name *.jpg | awk '{system("ls -lh \""0"\"")}' Thanks Dave for this tidbit of information!
Posted in Development
If you are not using Magento's email invite function because its not what you need. If you want a share link that your customers can post on a blog, or on their web site and when they click the link and sign up, they are going to be set up as an invited friend. This takes advantage of Magento's native invite functionality, but using a different way to connect. Magento has an invite email that you can use, but there are times when that is not enough. This tutorial will help you understand how I adjusted to this task. Part I - Create a .htaccess Part II - Create the module Part III - Create the observer Part IV - What your code may look like to get it on a page in Magento
Posted in Development
Static blocks are a Magento feature that makes adding content to your Magento site easy and convenient. Static blocks allow for your Magento site to be updated via the admin panel making it faster than having to “hard-code” every time you need to make a change to your website. Static blocks can be used anywhere on your Magento site to display text, images, & navigation. Some Magento designs have static blocks already in place for your convenience; however, you might have to install them yourself. Below is a simple tutorial on how to install a static block in the footer of your Magento site
Step One: Create Static Block in Your Magento Admin Magento Admin Panel—>Static Blocks—>Add New Block
1) Name your Static Block, in this case Custom footer Links
2) Label the Identifier (This is the link you will use to call the block later) in this case, custom-footer-links
3) Choose what store view you would like it to render in
4) Set Status to Enabled
Step Two: Inserting Code to Call the Static Block
This part is going to require you to FTP into your Magento site and modify footer.phtml app—>design—>frontend—->default—> (your template)—>template—>page—>footer.phtml Find where in the footer you want your navigation links to display and insert: <?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘custom-footer-links’)->toHtml(); ?> Now most of the time the Static block should display just fine but in some cases you are going to have do some extra steps to have the block display. 1) Instead of inserting: <?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘custom-footer-links’)->toHtml(); ?> Use: <reference name=”left”> <block type=”cms/block” name=”left.permanent.callout”> <action method=”setBlockId”><block_id>custom-footer-links</block_id> </action> </block> </reference> 2)Modify catalog.xml app—>design—>frontend—>default—>f002—>layout—>catalog.xml Add under <!– Mage_Catalog –> <block type=”cms/block” name=”left.permanent.callout”> <action method=”setBlockId”><block_id>custom-footer-links</block_id> </action> </block>
Posted in Development
How to tell if your on the home page in magento or not
if ( $this ->getIsHomePage()) {
echo 'You are in Homepage!' ;
} else {
echo 'You are NOT in Homepage!' ;
}
Or you can try this:
$routeName = Mage::app()->getRequest()->getRouteName(); $identifier = Mage::getSingleton( 'cms/page' )->getIdentifier(); if ( $routeName == 'cms' && $identifier == 'home' ) { echo 'You are in Homepage!' ; } else { echo 'You are NOT in Homepage!' ; }
Posted in Development
Using terminal: $ grep --color=auto -Ri "page.xml" *
--color=auto will color the findings
-R will do a recursive search
-i is case insensitive
Read more
Posted in Development
Using Terminal: $ mail ( enter ) $ delete * ( enter ) Thats it you can type : $ h ( enter ) to verify they are all removed
Posted in Development
Here, I will show you, how you can change your order status programmatically (with PHP coding). First, you need to load your order. If you have order id, you can load order in the following way:-
$orderId = YOUR_ORDER_ID;
$order = Mage::getModel('sales/order')
->load($orderId);
If you have order increment id, you can load order in the following way:-
$orderIncrementId = YOUR_ORDER_INCREMENT_ID;
$order = Mage::getModel('sales/order')
->loadByIncrementId($orderIncrementId);
Now, here is the code to change order status:-
/**
* change order status to 'Completed'
*/
$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE, true)->save();
Similarly, you can change the order status to pending, processing, canceled, closed, holded, etc.
Read more
Posted in Development
3 Steps to create a custom observer. These instructions are to create an observer when a customer is in the process of checking out, and we are "Observing" the Save shipping piece. This was needed for a project that we are appending to the Gift Message feature for magento. We are adding some text to every order that passes through regardless if the user entered something or not. For this project I have a Website called Bloom Step 1: create the module xml In /app/etc/modules create an xml file called Bloom_Checkout.xml In this new file add the following:
<?xml version="1.0"?>
Read more
Posted in Development
You can recover MySQL database server password with following five easy steps.
Step # 1: Stop the MySQL server process.
Step # 2: Start the MySQL (mysqld) server/daemon process with the --skip-grant-tables option so that it will not prompt for password.
Step # 3: Connect to mysql server as the root user.
Step # 4: Setup new mysql root account password i.e. reset mysql password.
Step # 5: Exit and restart the MySQL server. Here are commands you need to type for each step (login as the root user):
Step # 1 : Stop mysql service # /etc/init.d/mysql stop Output: Stopping MySQL database server: mysqld.
Step # 2: Start to MySQL server w/o password: # mysqld_safe --skip-grant-tables & Output: [1] 5988 Starting mysqld daemon with databases from /var/lib/mysql mysqld_safe[6025]: started
Step # 3: Connect to mysql server using mysql client: # mysql -u root Output: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql>
Read more
Posted in Development
mysql -h 10.100.10.5 -u replicationusername -p'enteryourpasswordhere'
Posted in Development
find . -name "*.js" | xargs ls -goh | cut -b 1,13-128 You can do the same thing for css: find . -name "*.css" | xargs ls -goh | cut -b 1,13-128
Posted in Development
// Load by name $_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'Ruby Ring'); $_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'emerald earring'); // Load by SKU $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'Eram18j4'); //Load by ID (just load): $_product = Mage::getModel('catalog/product')->load($productID);
Posted in Development
Posted in Development
I found a solution for anyone who needs it.
Because Magento has a fallback hierarchy, you can easily override the customer session class without modifying core code.
1. Locate and copy this file
app/code/core/Mage/Customer/Model/Session.php
and insert it into this directory structure
app/code/local/Mage/Customer/Model/Session.php
Read more
Posted in Development
(string)Mage::helper('catalog/image')->init($_product, $image)->resize($size)
Example 1:
(string)Mage::helper('catalog/image')->init($_product, 'back_image')->resize(300)
Example 2:
(string)Mage::helper('catalog/image')->init($_product, 'image')->resize(250)
or
Example 3 (origional image without resize):
$_product->getMediaConfig()->getMediaUrl($_product->getData('image'))
Posted in Development
Using Zend_Layout as a Standalone Component
As a standalone component, Zend_Layout does not offer nearly as many features or as much convenience as when used with the MVC. However, it still has two chief benefits:
Read more
Posted in Development
Scenario: You have created a custom module. You have entered certain data in your database. You need to show the data randomly. Solution: In MySQL the rand() function helps the select query to fetch data randomly. In Magento, you can select random rows from MySQL table using Zend_Db_Expr(‘RAND()’). You have to create a new function in your module’s collection class
(YourNamespace/YourModule/Model/Mysql4/YourModule/Collection.php)
public function setRandomOrder()
{
$this->getSelect()->order(new Zend_Db_Expr('RAND()'));
return $this;
}
Now, you can fetch random data from your table using the above create setRandomOrder function. The code below can be kept in the block or template (.phtml) file of your module.
$collection = Mage::getModel('yourmodule/yourmodule')
Read more
Well, I just did another install of Magento and as a Magento developer I always wanted to know roughly how many files and folders are in that. I did do some custom work to this install, so these number are slightly higher than whats in a fresh install but its rather impressive: First here is the command I ran: for t in files links directories; do echo `find . -type ${t:0:1} | wc -l` $t; done 2> /dev/null The output showed: 20384 files 0 links 5165 directories Now thats a lot of files and folders!
Posted in Development
To get all items in remote folder
rsync -v -r --exclude-from 'exclude-sample.txt' -e ssh user@192.168.1.1:/path/to/remote/folder/ /path/to/local/computer/folder/
To only get new items from remote folder:
rsync -vru -e ssh dev@192.168.1.1:/path/to/remote/folder/ /path/to/local/computer/folder/
To show the progress of the transfer
rsync -e ssh user@192.168.1.1:/path/to/remote/file/ /path/to/local/computer/folder/ --progress
Posted in Development
SET FOREIGN_KEY_CHECKS=0; -- reset customers TRUNCATE customer_address_entity;
TRUNCATE customer_address_entity_datetime; TRUNCATE customer_address_entity_decimal;
TRUNCATE customer_address_entity_int; TRUNCATE customer_address_entity_text;
TRUNCATE customer_address_entity_varchar; TRUNCATE customer_entity;
TRUNCATE customer_entity_datetime; TRUNCATE customer_entity_decimal;
TRUNCATE customer_entity_int; TRUNCATE customer_entity_text;
TRUNCATE customer_entity_varchar; TRUNCATE log_customer;
TRUNCATE log_visitor; TRUNCATE log_visitor_info;
ALTER TABLE customer_address_entity AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_datetime AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_decimal AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_int AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_text AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_varchar AUTO_INCREMENT=1;
ALTER TABLE customer_entity AUTO_INCREMENT=1;
Read more
Posted in Development
Have you ever wanted to know how to put a time on the adminhtml Form.php
$dateFormatIso = Mage::app()->getLocale()->getDateTimeFormat(
Mage_Core_Model_Locale::FORMAT_TYPE_SHORT
);
$fieldset->addField('date_start', 'date', array(
'label' => Mage::helper('enterprise_catalogevent')->__('Start Date'),
'name' => 'date_start',
'required' => true,
'time' => true,
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateFormatIso
));
The magic is the 'time' line. By adding , 'time' => true, it puts the time at the bottom of the calendar.
Feel free to checkout our Magento support if you would like some help with this.
Posted in Development
$ set @@long_query_time = 5; $ SET GLOBAL long_query_time=5;
Posted in Development
top -o cpu -O +rsize -s 5 -n 20
Posted in Development
watch 'more mysqld-slow.log | grep Query_time | wc -l; more mysqld-slow.log | grep Query_time;' This can be helpful if your trying to debug slow queries or just capture them as they come in.
Posted in Development
This can have many causes as your search through the internet has obviously found. My problem with this particular issue was I had my products setup properly, so it was not the fact that it was out of stock. This site almost had me excited but only to find out my product creation script already took care of it: http://zaclee.net/magento/errors-magento/stock-item-for-product-is-not-valid So, after some hard core searching, I found that I was not using the proper product object. The only way I could get my auto add to cart working was to use this $product = Mage::getModel('catalog/product')->load($product_id); I had a different product object, ( loading by the sku ) and apparently you can not use that type of object to add items to the cart. 5 hours of my life lost, hopefully to spare yours.
Posted in Development
find . -name ".svn" -exec rm -rf {} \;
Posted in Development
Lest say you have a need in your Magento store to have an "auto add to cart". This would be in situations where maybe you provide a free sample if they purchase a specific product, or maybe you will attach a warranyt sku to specific products automatically. However, this item your adding to the magneto cart has custom options! This can be tricky. Here is an example function I use when I run into this situation.
protected function _saveCustomOption($product_id, $product, $qty)
{
// Load up a product that has the custom options and get the attributes, in this case we just have one custom option
// This custom option is a text field and our end goal is to populate that with sku-product name
$_product = Mage::getSingleton('catalog/product')->load($product_id);
$attrs = $_product->getOptions();
foreach($attrs as $attr)
{
// Loop through all the custom options ( once again we only have one in our scenario ) and assign the values we need
Read more
Posted in Development
If you have ever received a message similar to:
The host has been blocked because of too many authentication failures.
Fear not, just restart the service and you can log back in again! $ /etc/init.d/webmin stop ( hit enter ) $ /etc/init.d/webmin start ( hit enter ) Viola, service running and you can log back in again.
Posted in Development
If you are looking at the view source of your zend framework page, and you notice that your external javascript files and your external css files are being included many times, its because you have echo in front of each line:
<?php echo $this->headLink()->prependStylesheet($this->serverUrl().'/css/style.css'); ?> <?php echo $this->headLink()->prependStylesheet($this->serverUrl().'/css/colorbox.css'); ?> <?php echo $this->headScript()->appendFile($this->serverUrl().'/js/jquery.1.7.2.js') ?> <?php echo $this->headScript()->appendFile($this->serverUrl().'/js/oe.js') ?> <?php echo $this->headScript()->appendFile($this->serverUrl().'/js/colorbox/jquery.colorbox-min.js') ?> <?php echo $this->headLink()?> <?php echo $this->headScript()?>
The way to remove the css and javascript files from being included many times is to do the echo on the headLink() and headScript() after you have set the files and just echo one line:
Read more
Posted in Development
If you have Magneto 1.0.7.2 and your tired of being logged out of the admin area every few minutes, to adjust that setting: System->Configuration->Admin In the security section, change that to 86400 if you want it to be 1 day, or any value over 60. This will extend your admin time before your logged out! Life is good again!
Posted in Development
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done
Posted in Development
$store_id = Mage::app()->getStore()->getStoreId();
Posted in Development
Base Directory: Mage::getBaseDir() Mage::getBaseDir(‘base’) /var/www/magento/ App: Mage::getBaseDir(‘app’) /var/www/magento/app/ Code: code Mage::getBaseDir(‘code’) /var/www/magento/app/code Design: design Mage::getBaseDir(‘design’) /var/www/magento/app/design/ Etc: etc Mage::getBaseDir(‘etc’) /var/www/magento/app/etc Lib: lib Mage::getBaseDir(‘lib’) /var/www/magento/lib Locale: locale Mage::getBaseDir(‘locale’) /var/www/magento/app/locale Media: media Mage::getBaseDir(‘media’) /var/www/magento/media/ Skin: skin Mage::getBaseDir(‘skin’) /var/www/magento/skin/ Var: var Mage::getBaseDir(‘var’) /var/www/magento/var/ Tmp: tmp Mage::getBaseDir(‘tmp’) /var/www/magento/var/tmp Cache: cache Mage::getBaseDir(‘cache’) /var/www/magento/var/cache Log: log Mage::getBaseDir(‘log’) /var/www/magento/var/log Session: session Mage::getBaseDir(‘session’) /var/www/magento/var/session Upload: upload Mage::getBaseDir(‘upload’) /var/www/magento/media/upload Export: export Mage::getBaseDir(‘export’) /var/www/magento/var/export
Posted in Development
tar -cvfz mytarfilename.tgz /path/to/directory/to/tarball/
Posted in Development
Magento Settings: System >> Configuration >> System > ‘Cron (Scheduled Tasks)’ tab.
- Generate schedules every: 60
- Schedule ahead for: 1
- Missed if not run within: 60
- History cleanup every: 120
- Success history lifetime: 120
- Failure history lifetime: 120
$ crontab -e
# Execute the Magneto cron every 15 minutes
*/15 * * * * /bin/sh /path/to/magento/cron.sh
These settings allow Magento to generate and clean schedules within a 2-hour time frame.
Posted in Development
$ yum update;
Get the NFS parts needed
$ yum install nfs-utils and yum install nfs-utils-lib;
$ yum install subversion
$ mkdir /var/nfs/
$ chmod -R 777 /var/nfs/
$ cd /var/nfs/
$ svn checkout http://wherever.yourcode.com/ /var/nfs/
Read more
$ showmount -e 192.168.1.1
This will show the available mounts from the /etc/exports
Here is the example output
Export list for 192.168.1.1: /var/nfs 192.168.1.100,192.168.1.101
Posted in Development
So you want to get the table name that is declared in the xml and you are not in an upgrade/install script.
If you were in an upgrade/install script you could just use:
$tbl = $this->getTable('catalog/product');
In any other page you can use:
$tbl = Mage::getSingleton('core/resource')->getTableName('catalog/product');
If this will return: catalog_product_entity
This works with any declaration that is set in the xml!
Posted in Development
This is all the steps and details i used to create an instance of a web server to be used for a Magento Website.
1 - Start a m3.xlarge instance
2 - Make sure its part of a security group that has Ports 80, 443 open to all 0.0.0.0/0
3 - Add a SSH port execption for your IP
4 - Assign an Elastic IP to each new instance
5 - Get the ssh details from Connect Instance in the Amazon control panel and ssh into the device(s)
6- Change the date/time of the server
Read more
Posted in Development
Magento form validation, text validation, url validation
- 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.
Read more
Posted in Development
update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');
Real World example:
update catalog_product_entity_text set value = replace(value,'®','®');
Posted in Development
If you have a new magento installation, and you notice that the join process takes a very long time to complete, your sendmail is probably the source.
Some new servers dont have sendmail setup properly and you need to adjust a few things.
For slow email from the app, edit 3 files.
1) /etc/resolv.conf, add search whateveryourdomainnameis.com in before the nameservers.
[root@Web1 etc]# cat /etc/resolv.conf search winetapsocial.com nameserver 114.243.44.83 nameserver 114.243.44.84
Read more
Posted in Development
Lets say you wanted sql that looked something like:
SELECT `main_table`.*,`main_table`.`email` AS `invitation_email`,`main_table`.`group_id` AS `invitee_group_id` FROM `enterprise_invitation` AS `main_table` WHERE ((status ='new') OR (customer_id ='1234'))
In order to achieve this, your collection needs to be formatted like this:
$collection =Mage::getModel('enterprise_invitation/invitation')->getCollection(); $collection->addFieldToFilter(array('status','customer_id'), array( array('status','eq'=>'new'), array('customer_id','eq'=>'1234')));
Now to see what this looks like you can always echo the query that this creates by using
echo $collection->getSelect()->__toString();
Posted in Development
If you have ever needed to rewrite/overload a core magento Model.
Its actually pretty easy
Step 1: create the module instantiation file
app/etc/modules/Russellalbin_Sales.xml
<?xml version="1.0"?> <config> <modules> <Indiebooker_Sales> <active>true</active> <codePool>local</codePool> </Indiebooker_Sales> </modules> </config>
Read more
Posted in Development
Here is how you can get a product reviewed by a customer in Magento
$storeId = Mage::app()->getStore()->getId();
$customer_reviews = Mage::getModel('review/review') ->getResourceCollection() ->addStoreFilter($storeId) ->addEntityFilter('product', $product_id) ->addFieldToFilter('customer_id', array('eq' =>$customer->getData('id')));
Read more
Posted in Development
UPDATE invoice
SET invoice_date2 = FROM_UNIXTIME(invoice_date) WHERE invoice_date > 0;
UPDATE invoice
SET estimated_date2 = FROM_UNIXTIME(estimated_date) WHERE estimated_date > 0;
UPDATE invoice
SET completed_date2 = FROM_UNIXTIME(completed_date) WHERE completed_date > 0;
UPDATE lawn_contract
SET lawn_contract_date2 = FROM_UNIXTIME(lawn_contract_date) WHERE lawn_contract_date > 0;
UPDATE tree_shrub
SET estimated_date2 = FROM_UNIXTIME(estimated_date) WHERE estimated_date > 0;
UPDATE lawn_contract
SET estimated_date2 = FROM_UNIXTIME(estimated_date) WHERE estimated_date > 0;
Posted in Development
Step 1 - Create htaccess
Open notepad or any other text editor, paste the following code into it :
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
RewriteBase /donis
Read more
Posted in Development
This is how you would take a column from a table in MySQL, insert it into another column, but also append something to that value ( in this case .jpg )
UPDATE items SET imageName = CONCAT(label, '.jpg') WHERE hasImage = 1;
Posted in Development
$model = BanksToSalespeople::model();
$addresses = array();
$criteria = $model->dbCriteria;
$criteria->with = "users";
$criteria->together = true;
$criteria->join ="LEFT JOIN users ON t.userID = users.id";
$criteria->select = 'email';
$criteria->condition = "t.bankID = '$bankID' AND users.email != ''";
// This is how to get the query that is built from the Yii magic command builder:
$query = $model->getCommandBuilder()->createFindCommand($model->getTableSchema(),$criteria)->getText();
Posted in Development
The magic is 'pagination'=>false
That will not paginate the results and show all of them. Be aware that this may return a lot of them so make sure its what you want.
return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>false, ));
Posted in Development
If you own a mac and your son or daughter decides to play with the keyboard, you may find yourself with such an issue.
My screen was zoomed in about 30% so I had to move my mouse to the corners to get the page to move to see the entire page.
Here is how you fix that:
Hold down the CTRL button and scroll down with your mouse.
Viola! Zoom in or out depending on your situation.
Posted in Development
How to change the product position in the category product listing.
Sounds simple but most of people don’t know how to do it.
Magento allows you to order your products by name or by price when you’re surfing a category.
It also allows you to change the position when you’re sorting by default.
- Go to: Catalog -> Manage Categories.
- Select a Category.
- Select the Category Products tab.
Posted in Development
Magento add wysiwyg editor in 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(); }
Read more
Posted in Development
Magento Linux Upgrade from 1.6.0, 1.6.1 or 1.6.2 to 1.7.0.0
If you are not afraid of Magento Magic, just use the yoursite.com/downloader/
It seems to be the best way.
Upgrade via SSH version 1.6 to 1.7
1. Put your site into maintenance mode. This can often be as simple as editing your “/etc/apache2/sites-enabled/default” file to point to a custom “park” page that you have created to let your customers (and Google) know that your site is only temporarily down. However, if you are doing this right, you will do this upgrade on a VALIDATION SERVER (i.e. a test environment) and get all of the quirks worked out before rolling it out into production. Here is a PRO TIP from an SEO Guru (cr8s.net): Setting the HTTP headers on your temporary “park” page that lets your visitors know that you’re down for a bit to provide status code 502 (service temporarily unavailable) will buy you a little more time in case a search engine crawler comes and sees that your site is down. You should be able to get away with downtimes of up to 24 hours (or 30 to 60 minutes on very high traffic sites) without seeing a penalty to your search engine rankings. Of course, none of this will be an issue if you are using a VALIDATION ENVIRONMENT / TEST SERVER to do this upgrade, which you should DEFINITELY be doing.
Read more
Posted in Development
The following is run from the directory where Magento is installed:
find . -type f -exec chmod 644 {} \; find . -type d -exec chmod 755 {} \; chmod o+w var var/.htaccess app/etc chmod 550 mage chmod -R o+w media
If that is not working, try setting all directories to 775 by doing this:
Read more
Posted in Development
If you just did an upgrade to magento or for some reason you try to log into the admin and you cant...and you do not get any errors...its more than likely a caching issue.
remove everything from the var/cache folder
Get to your root of your magento install
cd /var/www/magento_root_location_on_your_server/
rm -rf var/cache/*
Dump your browser cache/history and try again..OR just try a different browser, I bet it will work.
Posted in Development
To fix this issue delete the tmp directory (if there is one) and re-create it with 755 permissions. Make sure the owner and group of the directory correspond with the user/group that owns the rest of the website files.
mkdir var/tmp/
chmod -R 755 var/tmp
Posted in Development
This is the most comprehensive description of the Magento 1.3.x, 1.4.x, 1.5.x, 1.6.x and 1.7.x upgrade process.
Additionally It contains step-by-step instructions and troubleshooting information.
Prepare for Magento upgrade (this part of the article is for old 1.3.x, 1.4.x versions only)
Lets imaging that you have old Magento 1.3.x - 1.4.x store and you need to upgrade it to latest Magento 1.7.x version. First of all it is highly recommended to backup your live store files/database and disable Magento compiler cache.
Next you need to get SSH access from your hosting provider and connect to your server via SSH protocol (using Linux command shell or Putty SSH client for Windows).
After connection via SSH, go to your store folder and execute these commands:
1 - Change permissions on lib/pear folder to writable (recursively):
Read more
Posted in Development
I struggled with an issue that bugged me for a few hours. I noticed that var/cache was empty! That was strange..so I did some research and this happened right after I setup apc and memcached.
It turns out the the instructions i followed was saving them into memcached instead of the file system under var/cache
Here is what my app/etc/local.xml looked like:
<cache>
If this next line was not commented out, it was going to be saved to memcached and NOT the file system
<!-- backend>memcached</backend -->
Read more
Posted in Development
What’s the easiest way to make an .htaccess file in Unix/Linux so that a directory is password protected? Suppose that your home directory is /home/matt and all your webstuff is in /var/www/protected/ . Follow these steps:
- Make an .htpasswd file. The htpasswd command in Unix does this. You should put the password file outside of your web directory. So a command like "htpasswd -bc /var/password/.htpasswd admin mysecretpassword" will create a new file using a username of admin and a password of mysecretpassword into the file /var/password/.htpasswd . At the prompt type "cat /var/password/.htpasswd" it will show you something like: "admin:E.mx8CsZffRI6".
- Make an .htaccess file located at /var/www/protected/.htaccess and use the following
AuthUserFile /var/password/.htpasswd AuthName EnterPassword AuthType Basic require valid-user
Posted in Development
All of these are via command line: Command Line:
sudo chmod 550 ./mage
./mage mage-setup .
./mage sync
./mage list-upgrades
./mage config-set preferred_state stable
./mage upgrade-all --force
rm -rf maintenance.flag
php -f ./index.php
Posted in Development
In your controller when building the $dataProvider add 'pagination'=>false
$dataProvider=new CActiveDataProvider('ResidentLedger', array( 'criteria'=>$criteria, 'pagination'=> false, ));
Posted in Development
Add this to the CActiveDataProvider: 'summaryText'=>''
$dataProvider=new CActiveDataProvider('ResidentLedger', array( 'criteria'=>$criteria, 'pagination'=> false, 'summaryText'=>'' ));
Posted in Development
In a terminal window:
$ export XDEBUG_CONFIG = "idekey=PHPSTORM" (hit enter)
Back to debugging!
Posted in Development
If your not getting your Category pages to show up its probably because you have not set your Store Root Category.
System => Manage Stores => Select your store to edit and then set it there.
I wasted 4 hours today wondering why my categories were not showing up.
Posted in Development
Here is the scenario, I was using the topMenu for my main navigation. I had some custom things being displayed in the UL that was not a catalog/category. It was hard coded into my version of page/html/topmenu.phtml
$module = Mage::app()->getRequest()->getModuleName(); // Mage_Page_Block_Template_Links
$block = Mage::getBlockSingleton('page/template_links'); $layout = $block->getLayout(); $links = $layout->getBlock('top.links'); $header = Mage::getBlockSingleton('page/html_header'); ?>
<?php $_menu = $this->getHtml('level-top') ?> <?php if($_menu): ?> <div class="nav-container">
Read more
Posted in Development
First step create the module declaration:
file: app/etc/modules/Russellalbin_Catalog.xml
<?xml version="1.0"?> <config> <modules> <Russellalbin_Catalog> <active>true</active> <codePool>local</codePool> </Russellalbin_Catalog> </modules> </config>
Read more
Posted in Development
If your trying to do a typical "Rewrite" of a Magento Abstract class, you can stop now and save yourself some headaches. Magento Abstract classes are not something you can do a rewrite on.
The only way to get it to work is to make a copy of the file in your local folder of app/code/local
Here is how I did an overload of Mage_Rule_Model_Abstract:
Step 1 Create a file app/code/local/Mage/Rule/Model/Abstract.php
Step 2 copy the contents from app/code/core/Mage/Rule/Model/Abstract.php and paste it into our new file we created on Step 1.
Step 3 test to see if its using our file instead of the core file, if you have a debugger, like the one in PHPstorm but a break point and execute the code!
You should now be all set and using our version of the abstract class instead of the core file, now you can edit it to suit your needs, like I did for allowing a negative number in the shopping cart rules.
Posted in Development
If you have ever needed to create a shopping cart price rule but the value needed to be negative, Magento prevents this by default. You may want this to create an extra fee based on some rules like if there is a certain sku in the cart, or whatever.
To overcome Magento's check to see if that number entered is negative we have to overload one magento core file, and create a rewrite of another. Hold on to your hat, here we go.
Overload a core Magento abstract class
Step 1 Create a file app/code/local/Mage/Rule/Model/Abstract.php
Step 2 copy the contents from app/code/core/Mage/Rule/Model/Abstract.php and paste it into our new file we created on Step 1.
Rewrite Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Actions
Step 1 Create a module instantiation file app/etc/modules/Russellalbin_Adminhtml.xml
Read more
Posted in Development
If you ever needed to create a custom Customer tab and put some information there, as well as submit a form, this should give you enough information to accomplish this task.
Create Module declaration
app/etc/modules/Russellalbin_Customertab.xml
<?xml version="1.0"?> <config> <modules> <Russellalbin_Customertab> <active>true</active> <codePool>local</codePool> </Russellalbin_Customertab> </modules> </config>
Create the module configuration file
Read more
Posted in Development
$configuration = new Zend_Config_Ini(
APPLICATION_PATH.'/configs/application.ini',
'development'
);
$host = $configuration->resources->db->params->host;
$pass = $configuration->resources->db->params->password;
$user = $configuration->resources->db->params->username;
$dbname = $configuration->resources->db->params->dbname;
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => $host,
'username' => $user,
'password' => $pass,
'dbname' => $dbname
));
Read more
Posted in Development
Step 1: instal postfix
sudo apt-get install postfix
Step 2: install mailutils
sudo apt-get install mailutils
Step 3: Test the email system
echo "test" | mail your@email.com
Step 4: Update the server:
sudo apt-get upgrade
Step 5: Install all the required PHP to make magento run
Read more
Posted in Development
Step 1: SSH into both servers
Step 2: Install mysql
sudo apt-get install mysql-server -y
Step 3: Master Server update to my.cnf. If your my.cnf has
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
Simply remove the # and then restart your mysql server and if not, just add them it should look like this:
Read more
Posted in Development
I am documenting this for a current installation, this is not yet finished!
Step 1: install apache
Step 2: update
Step 3: install new modules
Step 4: install more modules
Posted in Development
So, here is the scenario, you have a custom module that is returning a list of products.
You want to make sure that your using the Products per Page on Grid Default Value from the Magento Admin to stay true to whats normally done.
In order to get this value in your code, here is how to access it:
$limit = Mage::getStoreConfig('catalog/frontend/grid_per_page');
Posted in Development
$product_id = Mage::getModel("catalog/product")->getIdBySku( $_sku );
Posted in Development
#!/bin/bash
NOW=$(date +"%Y%m%d%H%M%S")
NEW_FOLDER_PATH="/var/www/magento/releases/$NOW"
VAR_FOLDER="/var/www/magento/shared/var/"
MEDIA_FOLDER="/var/www/magento/shared/media/"
SHARED_ETC_FOLDER="/var/www/magento/shared/app/etc"
MAGENTO_ROOT="/var/www/magento/"
GROUP="www-data"
REPO="ssh://username@192.168.1.1/~/git/projectname.git --depth 1 "
Read more
Posted in Development
Customize or add to the Magento topLinks ( top.links )
<?xml version="1.0"?>
<layout version="0.1.0">
<default>
<reference name="root">
<reference name="top.links">
<!-- Add custom links. Pretty self-explanatory.
Dig into app/code/core/Mage/Page/Block/Template/Links.php for more info -->
<action method="addLink" translate="label title">
<label>About Us</label>
<url>about</url> <!-- can use full url also -->
Read more
Posted in Development
Part 1 - Ubuntu
- Download iso from http://www.ubuntu.com/download/desktop and burn it to a disc or you can use http://www.pendrivelinux.com/ if you have boot from flash drive support
-
Stick in the disc, start your computer and press F12 during boot, then select to boot from cd ( this step may be different for your computer )
The install will take a good 20 minutes..
- I highly recommend plugging in your laptop and a wired internet connection to get the updates and 3rd party software during install
- I go and figure out what updates I want to install at this point, as I havn't invested a bunch of time and depending on your hardware they could cause problems that are easiest to fix by reinstalling. You do this by going to the top right icon and "Software Up to Date". If you run into troubles with the updates, I recommend going into settings and turning off "Indepent updates" under other software and all but "Important security updates". Then trying all of the above again.
Read more
Posted in Development
app/code/core//Mage/Admin/Model/Session.php: Mage::dispatchEvent('admin_session_user_login_success', array('user' => $user));
app/code/core//Mage/Admin/Model/Session.php: Mage::dispatchEvent('admin_session_user_login_failed',
app/code/core//Mage/Admin/Model/User.php: Mage::dispatchEvent('admin_user_authenticate_before', array(
app/code/core//Mage/Admin/Model/User.php: Mage::dispatchEvent('admin_user_authenticate_after', array(
Read more
Posted in Development
Here is fast and easy way to install Git on Centos 5.7.
1. Get the EPEL release for Centos 5.
# rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
2. Install git, git-daemon using yum
# yum install git git-daemon
Posted in Development
sudo /usr/local/mysql/support-files/mysql.server restart
Posted in Development
Version #1 use a simple array
$collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToFilter('sku', array('n2610','bb8100'));
$items = $collection->getItems(); echo count($collection);
Version #2 use a more specific array
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter( array( array('attribute'=>'sku','eq'=>"n2610"), array('attribute'=>'sku','eq'=>"bb8100") ));
$items = $collection->getItems(); echo count($collection);
Posted in Development
If you ever were curious about what the SQL is being built for a Magento Collection, its really, really easy
$collection = Mage::getModel('poll/poll')->getResourceCollection() ->addFieldToFilter('date_posted', array('from' =>'2014-02-01 00:00:00', 'to'=>'2014-02-28 23:59:59')); $collection->load(true);
The result will be something similar to this:
SELECT `main_table`.* FROM `poll` AS `main_table` WHERE (date_posted >= '2014-02-01 00:00:00' AND date_posted <= '2014-02-28 23:59:59')
Posted in Development
error: error in [unknown object].fireEvent():
event name: open_browser_callback
error message: MediabrowserUtility is not defined
Step 1: Add this to the adminhtml xml for the custom extension
<?xml version="1.0"?> <layout> <default> <reference name="head"> <action method="setCanLoadExtJs"><flag>1</flag></action> <action method="addJs"><script>mage/adminhtml/variables.js</script></action> <action method="addJs"><script>mage/adminhtml/wysiwyg/widget.js</script></action> <action method="addJs"><script>lib/flex.js</script></action> <action method="addJs"><script>lib/FABridge.js</script></action> <action method="addJs"><script>mage/adminhtml/flexuploader.js</script></action> <action method="addJs"><script>mage/adminhtml/browser.js</script></action> <action method="addJs"><script>prototype/window.js</script></action> <action method="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action> </reference> </default> </layout>
Read more
Posted in Development
$tableName=Mage::getSingleton('core/resource')->getTableName('catalog_product_option');
Posted in Development
One day, I was at work and a friend of mine was trying to recall what his Master lock combination was. He knew the first and last number. I had done a bit of googling and found that if you know the last number of the combination, there is a defined set of possible options! This was promising. After figuring out the algorythm, I set forth on a quest to provide a nice template for him to use when doing the recovery. It turns out that there are only 100 possible combination should you know that last number.
If you want to use it, please click here.
Posted in Development
When building admin area modules, you need to sometimes use the admin users. When doing so, you may want to combine the firstname and lastname into one. This is where concat comes in handy. It will combine them, into one string to be used as the visual for the dropdown. The following function will also show you how to get all the admin users using a collection.
/*
*
*/
public function getAdminUsersAsOptions()
{
$collection = Mage::getModel('admin/user')->getCollection()
->addFieldToSelect('firstname')
->addFieldToSelect('lastname')
->addFieldToSelect('user_id');
$collection->setOrder('lastname', 'ASC');
$fields = array('lastname', 'firstname');
$fieldConcat = $collection->getConnection()->getConcatSql($fields, ', ');
$collection->getSelect()->columns(array('value'=> 'user_id', 'name' => $fieldConcat));
$items = $collection->getItems();
$user_array = array();
foreach($items as $_user)
{
$user_array[$_user->getData('user_id')] = $_user->getData('name');
}
return $user_array;
}
Posted in Development
- Download MySQL DMG http://dev.mysql.com/downloads/mysql/
- Install both the MySQL and the startup packages ( this may require approval in your Mac OS X Privacy & Security settings )
- Start mysql via command line
sudo /usr/local/mysql/support-files/mysql.server start
- Start apache via command line
sudo apachectl start
- Create a folder for your virtual host files
sudo mkdir /etc/apache2/extra/vhosts
Read more
Posted in Development
I recently needed to gather just a handful of recent commits for a code review.
This actually is very easy to do, with the appropriate flags.
git --no-pager log --stat --since='2014-03-07 04:08:28' > git-log.txt
Now, you can only get the logs since that date/time.
Here is what it would look like:
commit 3551e428e9c214517165c180c306223c53cbdd01 Author: ralbin <russell@russellalbin.com> Date: Thu Mar 13 11:37:37 2014 -0500 making it so the reduced price is not so dark skin/frontend/default/theme589/css/styles.css | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) commit e07fd40bc9985164980f16f74864f57ce14ea3d7 Author: ralbin <russell@russellalbin.com> Date: Thu Mar 13 11:32:51 2014 -0500 applying css fix app/etc/modules/Engine23_Customer.xml | 2 +- skin/frontend/default/theme589/css/styles.css | 1 + 2 files changed, 2 insertions(+), 1 deletion(-)
Posted in Development
We had a store where we disabled user configuration of bundle products and set them up the way we wanted as defaults. That made this much easier, but something similar could be done to update the weight via an ajax call as the configuration is changes.
Override the getAdditionalData function in Mage_Catalog_Block_Product_View_Attributes
About line 10 you will see where we look for when a bundle product's weight is being set and override it. Once we catch the right piece of logic, we the weight of the products up and also catch the logic to do the proper formatting logic.
public function getAdditionalData(array $excludeAttr = array())
{
$data = array();
$product = $this->getProduct();
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
Read more
Posted in Development
First off the command to restart Apache2 is:
sudo apachectl -k restart
You can only lookup the command so many times before figuring out a way to remember it. I decided to try to figure out what apachectl was. I found that apachectl is not even Apache2, it's actually a controller for it, or apache controller, or apache ctl .... apachectl. Hopefully it's a bit easier to remember to call the apache controller than apache gobbly goop of letters.
Posted in Development
Step 1: create the module instantiation xml: app/etc/modules/Engine23_Contactform.xml
<?xml version="1.0"?> <config> <modules> <Engine23_Contactform> <active>true</active> <codePool>local</codePool> <depends> <Mage_Captcha/> </depends> </Engine23_Contactform> </modules> </config>
Step 2: Create the folder for our controller and config.xml: app/code/local/Engine23/Contactform
Step 3: Create the IndexController: app/code/local/Engine23/Contactform/controllers/IndexController.php
<?php
/*
* Adding Captcha to Contacts form
*/
require_once(Mage::getModuleDir('controllers', 'Mage_Contacts') . DS . 'IndexController.php');
class Engine23_Contactform_IndexController extends Mage_Contacts_IndexController
{
Read more
Posted in Development
We recently looked at the numbers to identify quick ways to improve a customer's conversion rates. We saw that three times as many visitors were making purchases if they used the search bar than if they didn't. Some of this can probably be associated to the fact that visitors who already know what they want are more likely to do a direct search for it. However, we hypothisized it was also the difference between having exactly what a customer wanted right inside the door vs making them find it in the aisle. The more work to find the product they want, the less likely they are to stick around long enough to find it. Thus we decided to to change around the header to encourage visitors to use the search bar.
Before:

After:

Read more
Posted in Development
Several years ago, I had heard that a new E-Commerce platform was growing in popularity. Varien's Magento. At the time it was community edition 1.3. I was not impressed to say the least. Things were awkward, it did not make a lot of sense on why there was SO much abstraction of files and folders. I found it frustrating that even the original developers did not use their own standards! What a train wreck!
Fastforward a few months:
I was asked by a local marketing firm to help them with some PHP and without asking too many questions, I said "Yes". It turns out that they had started to build a new commerce site and was sold on Magento by their original developer. He had quit, and left them high and dry. This was a huge problem because they were literally weeks from completion and they had no-one on staff who could understand what the heck was going on. After some Q and A I found they had built their site on Magento 1.3 and could not find ANYONE in Omaha who has experience with it. I reluctantly said I had poked around with it and found it very complicated (understatement of the year).
I decided that I knew enough to help and this began my quest to fix their issues.
It turns out that they just needed some cleanup on the checkout, and some basic adjustments to the existing functions. I was so releaved they did not need some custom extension, because I was NOT able to do much at that point in my Magento career.
Read more
Posted in Development
If you need to create a custom table and have a "created at" or perhaps an "updated at" column on your custom table. That is typically something you want.
In order to get this accomplished you need to have one extra parameter.
<?php /* @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this;
$installer->startSetup();
Read more
Posted in Development
Having some fun learning the Laravel framework and was trying to figure out how to do migrations and seeds for workbench packages. In general these are the commands, but read the rest for the particulars.
php artisan migrate --bench="Upshot/Poll"
php artisan migrate:rollback
php artisan db:seed --class="UpshotPollDatabaseSeeder"
Read more
Posted in Development
If you want to find the files that are larger than 500MB in your current directory
find . -type f -size +500000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
Posted in Development
Alright, so your a modern PHP developer and know that most framework updates are adding composer support out of the box, or are already using it. Sadly every time you develop in Magento you miss it and Magento’s 2.0 release with composer support is still a ways off. Well you’re in luck! Everyone give Mr. Damian Luszczymak a big hug for making an extension that adds composer support to Magento 1.0. It adds the composer autoloader prior to Magento’s, so if there are ever any conflicts Magento’s should overwrite them. Also, he did a great job of implementing it via an observer, so we shouldn’t have upgrade issues.
Alright, lets get down to it.
1) Download the extension at https://github.com/magento-hackathon/Magento-PSR-0-Autoloader and install the files.
2) Add <composer_vendor_path><![CDATA[{{root_dir}}/vendor]]></composer_vendor_path> to your main local.xml under global
3) Create a vendor folder in the Magento root folder
4) Install composer if you haven’t: https://getcomposer.org/
5) If you have composer installed as a global you can now go to the root Magento folder via command line and run "composer init" with defaults and "composer update".
That was very simple, and it works great!
Posted in Development
Step 1: Find your Mac public key change into your ssh directory in terminal
cd ~/.ssh/
View your public key
cat id_rsa.pub
Log into your CentOS via ssh and change into your ssh directory
cd ~/.ssh/
Create a id_rsa.pub
vim id_rsa.pub
You can truncate the entire known_hosts file, or just remove the same IP/URL that your trying to connect to, for us, to keep it simple we are just going to truncate the entire file
Read more
Posted in Development
I was asked to take a Magento codebase, split it off into 2 different exact copies.
They also wanted each to have updated local.xml with updated database credentials.
Furthermore, they wanted the databases replicated into 2 new ones, that the local.xml would be able to connect to.
#!/bin/bash
ok=0;
while ((ok==0)) do echo "Choose your installation Type:" echo -e "\t(p) Probes" echo -e "\t(e) Education" echo -e "\t(b) Both" echo -e "\t(x) Exit" echo -n "Please enter your choice:" read choice case $choice in "p"|"P")
Read more
Posted in Development
This code is helpful if your needing to know what Linux operating system your working on
cat /proc/version
Posted in Development
If you know the branch you want, all you have to do is the following in a console:
git fetch && git checkout remoteBranchName
If you don't know for sure the branch you want, we can easily list all options. Issue the first part of the command
git fetch
This will update your computer with all the code and branches that are on the remote repository. Now we can type the following to get all available options
git branch --all
Or alternately
git branch -a
Now you finish the checkout with
git checkout remoteBranchName
You should see some output that looks similar to Branch remoteBranchName set up to track remote branch remoteBranchName from origin.
Switched to a new branch 'remoteBranchName'
Now you're all set to develop on a branch that was created remotely. Don't forget you will have to commit and push (or create a pull request) any changes you make before your teammates can see them, and always remember to pull before you push!
Posted in Development
On Mac, if you use terminal and type
$ mysql
And you get the response
$mysql command not found
open up your editor like vim and save this to your bash profile
$ cd ~ $ vim .bash_profile
PATH=${PATH}:/usr/local/mysql/bin
Save and restart Finder
Read more
Posted in Development
I have been doing a bunch of work lately using the event observers system. This powerful feature of Magento community and Magento Enterprise allows for so much flexibility. I did find myself kind of stuck trying to find the right event to observe. My issue was I need to find an event that was after the customer was initialized, but before the Header.php and Header.phtml were brought in. I needed to change the status of some text based on the customers logged in/out status.
Fastforward to me using the wrong event. I found, what I thought was the perfect event, customer_session_init. So, after patting myself on the back for being so smart, I wrote all my logic, and did a happy dance that it was so easy. Well, after running the code, it turns out that because I was checking if the customer was logged in or not, and if not, AND I had some Header information, I was logging them in...well, sadly that "re-initiallized" the customer session!!!! So, I got the dreaded
Front controller reached 100 router match iterations
Well, I instantly figured out that I had found a great place to start my check but it was too early in the execution. I needed a better place, something later in the request flow. Just to prove things worked I chose the last "non-generic" event that was fired: controller_front_send_response_after
Read more
Posted in Development
I recently had a Windows computer, using Chrome get stuck where I could not log into my local magento installation. I then tried to log into the admin, and it appears as though things worked fine, but the login page reloads, with no error or messaging. Welcome to COOKIE purgatory.
Turns out that Chrome, being somewhat neurotic, does not like something about the configuration and/or the domain that the cookie is set.
The fix:
Step 1: Using some sort of method to update the mysql database ( adminer, phpmyadmin, command line )
Update core_config_data 2 paths and set the values to null
- web/cookie/cookie_httponly
- web/browser_capabilities/cookies
The following is the raw sql from my instance, you could use a different WHERE clause and use path LIKE 'web/cookie/cookie_httponly' for example, but using ID's is much safer.
Read more
Posted in Development
I recently needed to figure out what IP was hammering our site. It was so bad it almost came to crash.
tail -50000 /var/log/httpd/yourwebsite.com_http_request_log | awk '{print $1}' | sort | uniq -c | sort -n | tail
Posted in Development
I was recently asked if I can build a module that will exclude certain US cities and territories from showing up on the checkout, join, etc.
The biggest reason is that America Samoa and Armed Forces Africa are never going to be places that customers will be from!
I had considered selling this as an extension on Magento commerce, but I figured its been a while since I gave back to the community.
After this is installed, the settings are in System->Configuration->General->States Options In the new area: Exclude the selected US States
http://www.engine23.com/limit-us-states-and-territories.html
Posted in Development
So, ironically in the past 2 days, I was asked to perform the same task (on two separate projects!)
Basically, in both requests, there is a current template that has getChildHtml and instead of adding a new one to include a new template file, I wanted to be able to just append my to the existing one.
Several benefits, the main one being I am not over-writting a core template file that may change during upgrades...and there is existing placeholders on the template that I can add my custom data inside.
This one that I will be showing is the customer accout create form.
That form had all the elements I wanted, except in this case they wanted to add some extra content.
Now, yes, I could of just got the main template, app/frontend/base/default/template/persistent/customer/form/register.phtml and put it in my theme, and just hard coded my new content. BUT that is not the magento way, that does not allow for fallback, and that means that if we switch themes I need to remember to move that code, and hope that things dont change or break in the future.
The better way, just add your new section via xml!
I struggled with the exact syntax until I remembered I did a similar thing when I added captcha to a magento website earlier.
Read more
Posted in Development
If you are using PhpStorm then css and javascript minification is a set it and forget it process that requires no maintenance after setup. As a programmer it doesn’t get any better than that, so I felt very silly for not doing a good job of it over the years when I figured out this trick. It took a minute to figure out as i’m using Mac OSX Maverick, and all of the articles on it were for Windows. So, if you’re stuck and on windows you should be good to find specifics with a quick google. Alright, lets get going.
First, this was also my introduction to Node.js, but not to worry if it is yours too, we will only be using it as a simply command line utility. Head over to http://nodejs.org/ and click install to download, and then run the pkg, defaults will work. Then go into PhpStorm and install the node.js plugin to finish that integration. A little note, /usr/local/lib/node_modules is the important directory and it should hold by default npm ( Node Package Manager ). And by default everything should be symlinked so the npm command will work anywhere.
Download:
Read more
Posted in Development
Here is how you can use the URL key for a product, using getUrl and avoid the trailing slash
If you use
$box_url = Mage::getUrl('our-box.html');
and echo that string you will get something like
http://whatever.com/our-box.html/
That of course is not right and you probably will get a 404 page. Unless you did a URL rewrite but that is another topic all together. Here is how to use the same function, but use a parameter instead
$box_url = Mage::getUrl('', array('_direct'=>'our-box.html'));
That will get us what is needed so echoing this string gets us
http://whatever.com/our-box.html
Posted in Development
check the core_config_data for a setting called
SELECT * FROM core_config_data WHERE path LIKE '%merge%'
More than likely this feature was turned on, just change that value to a zero and your good to go.
Posted in Development
Some times, your theme does not need the compare products in the sidebar for a 2 column layout.
Here is the xml you add to your app/desing/PACKAGENAME/THEMEFOLDER/layout/local.xml
<?xml version="1.0" encoding="UTF-8"?> <layout> <default> <span ><reference name="right"> <span ><action method="unsetChild"><name>catalog.compare.sidebar</name></action> </reference>
</default> </layout>
Make sure you refresh your caches and you should see that go away.
Read more
Posted in Development
If you have a mac and have upgraded to the latest operating system 10.10, you may find that mysql is not able to connect.
The fix is pretty easy, its an update to the php.ini
What we need to do is tell mysql to connect through localhost instead of 127.0.0.1
First locate the php.ini you can use the following command in terminal
locate php.ini
Look for something like /private/etc/php.ini
This is an example of what may come back
/Users/engine23/php.ini /private/etc/php.ini-5.2-previous /private/etc/php.ini.default /private/etc/php.ini.default-5.2-previous
You may have may of them and if you dont have one called /private/etc/php.ini it may be named /private/etc/php.ini.default, if so copy that and rename it to just php.ini.
sudo cp /private/etc/php.ini.default /private/etc/php.ini
Now you know what file to edit, using terminal edit that file
sudo vim /private/etc/php.ini
Read more
Posted in Development
To delete a local branch
git branch -d the_local_branch
To remove a remote branch (if you know what you are doing!)
git push origin :the_remote_branch
Note
Read more
Posted in Development
kill -9 $(ps -e | grep apache2 | awk '{print $1}')
Posted in Development
$attribute = Mage::getModel('eav/config')->getAttribute('customer','subscription_length'); $optionArray = array(); foreach ($attribute->getSource()->getAllOptions(true, true) as $option) { $optionArray[$option['value']] = $option['label']; }
Posted in Development
mysql> CREATE USER 'edreamery_prod'@'localhost' IDENTIFIED BY 'edreamery_prod'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON *.* TO 'edreamery_prod'@'localhost' WITH GRANT OPTION; Query OK, 0 rows affected (0.00 sec) mysql> CREATE USER 'edreamery_prod'@'%' IDENTIFIED BY 'edreamery_prod'; Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON *.* TO 'edreamery_prod'@'%' WITH GRANT OPTION; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
Posted in Development
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://dev.magento19.com/index.php/api/soap/index/?wsdl=1' : Extra content at the end of the document in /Users/engine23/Sites/local.magento18.com/test.php:5 Stack trace: #0 /Users/engine23/Sites/local.magento18.com/test.php(5): SoapClient->__call('login', Array) #1 /Users/engine23/Sites/local.magento18.com/test.php(5): SoapClient->login('rjalbin', 'peanut') #2 {main} thrown in /Users/engine23/Sites/local.magento18.com/test.php on line 5
So, basically it boils down to bad URL in the request.
login('rjalbin', 'peanut');
// View all customers
var_dump($proxy->call($sessionId, 'customer.list', array('filters', '*')));
?>
Read more
Posted in Development
I just wasted 3 hours of my life trying to set this value in xml.
Normally you think that in a Block when you see $this->getChildrenWrapClass() that the value for that would come from xml or in an observer where that value is being set by $block->setChildrenWrapClass(), however for this you would be totally mistaken.
<reference name="catalog.topnav.renderer"> <action method="setData"><name>setChildrenWrapClass</name><value>abc123</value></action> <action method="setData"><name>children_wrap_class</name><value>321cba</value></action> <action method="setChildrenWrapClass"><value>ecreameryTest</value></action> </reference>
That was all the different types of xml I was trying to use to get that value set!
Well, it turns out this is actually a parameter that is passed into getHtml()
Sigh
Read more
Posted in Development
While searching the internet for a Magento issue, I stumbled across a set of cartoons from Inchoo. If your a Magento developer you certainly have heard of these guys by now. This is one awesome set of cartoons, please take a moment and enjoy.
http://inchoo.net/tag/inchooers/
Thank you Inchoo!
Posted in Development
How to fix this issue when you move a virtual machine from one computer to another.
The mac is set in the config and needs to be updated on the VMWare.
First ssh into the server and get the information from /etc/sysconfig/network-scripts/ifcfg-eth0
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0 BOOTPROTO=dhcp HWADDR=00:0C:29:48:56:52 #IPV6INIT=yes IPV6_AUTOCONF="yes" #NM_CONTROLLED=yes ONBOOT=yes TYPE=Ethernet #USERCTL=no #PEERDNS=yes
Read more
Posted in Development
One thing that seems to be lacking in some documentation is to create the samba user.
This is here because there is lots of instructions on how to setup the samba configuration /etc/samba/smb.conf and I dont need to duplicate that here. This is helpful when your configuration is setup and you can connect but your username/password is being rejected...and your sure that the username and password your using is correct.
Even though you have the configuration set to communicate with the Samba server, if your user cannot log in, it is because you never gave samba the user information.
The following is for creating a new user, you can skip if you already have a linux user on the system.
$ useradd ralbin $ passwd ralbiin
Read more
Posted in Development
I just was asked to update/change the Admin Customer Grid to show the default Shipping information.
So the new grid has Email, Company Name ( custom attribute ), Customer Name, Address, City, State, Postcode, Country, Phone, Group, Customer Since and Website.
First thing we need to create the module to handle this. This is new module is called Dpc.
app/etc/modules/Dpc_Adminhtml.xml
<?xml version="1.0"?> <config> <modules> <Dpc_Adminhtml> <active>true</active> <codePool>local</codePool> <depends> <Mage_Core /> </depends> </Dpc_Adminhtml> </modules> </config>
Then the app/code/local/Dpc/etc/config.xml
Read more
Posted in Development
When ever you have an catalog product attribute and are looking for the options, here is the code sample you need to get the values.
$attribute= Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'created_by'); if ($attribute->usesSource()) { $options = $attribute->getSource()->getAllOptions(false); }
Posted in Development
I think the title of this says it all. This is how you can add an index and a new column to a table during an upgrade script
$installer= $this;
$installer->startSetup(); $tableName = $installer->getTable('dpc_subscription/event'); $indexName = $installer->getIdxName($tableName, array('is_shipped')); $installer->getConnection()->addColumn($tableName, 'is_shipped', array( 'type' => Varien_Db_Ddl_Table::TYPE_INTEGER, 'unsigned' => true, 'nullable' => false, 'default' => '0', 'comment' => 'Is shipped' )); $installer->getConnection()->addIndex($tableName, $indexName, array('is_shipped')); $installer->endSetup();
Posted in Development
Most of the time doing a rewrite of a Block is pretty simple. However you will run into issues when you want to do something as simple as remove the + from a Bundle product price.
Most of the time, you can just do a rewrite of the block in XML and its done. However when you try to do this with some blocks, they just dont work! The reason....some blocks are not called using the factory method. These blocks are the ones that are extended from, so they are just part of the php code. The way to get at those is by rewriting the blocks we can do a rewrite ( for example Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option_Checkbox ). Then we can extend our version of Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option.
Here is how I achieve this for Bundle Products and the checkbox options for the children products.
Read more
Posted in Development
Step 1: Create CSR and pass that along to company that is issuing the SSL
Step 2: copy private key to server
Step 3: move the created SSL files from the company that issued the SSL to the server
Step 4: Create another Load Balancer to handle the SSL request and point to server
Posted in Development
$products = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('image'); $a = array(); foreach($products as $id => $_product){ $a[(int)$id] = (int)$id; } $has_images = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('image')->addAttributeTofilter('image', array('notnull' => ''));
foreach($has_images as $id => $_product) { $b[(int)$id] = (int)$id; }
$product_ids_missing_images = array_diff($a, $b); foreach($product_ids_missing_images as $_id){ echo '<div>'.$_id.'</div>'; }
Posted in Development
In case you need to export to a csv all the categories in your site, here is the code.
The csv just has the ID of the category, the Name of the category and the url key
$categories = Mage::getModel("catalog/category")->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('url_key');
fputcsv($file,array('Category ID', 'Name', 'URL Key'));
// id, name, url-key
foreach($categories as $_category)
{
fputcsv($file,array($_category->getData('entity_id'), $_category->getData('name'), $_category->getData('url_key')));
}
fclose($file);
Posted in Development
If you modify an admin form, lets say you add a column to the database for another field. If you start to test, but the form is not saving the new fields, and it appears that Magneto is ignoring your new columns, well....it is.
Long story short, there is a function called
protected function _prepareDataForTable(Varien_Object $object, $table)
Found In :
Read more
Posted in Development
If you create a custom adminhtml grid and you get the resulting data 2x after you use a column header or filter, the problem is with the xml.
The solution is to remove part of the xml. The red text (output="toHtml") on the nested block is the code you need to remove
***** BAD XML that is showing the block twice ***** <adminhtml_flat_entry_grid> <block type="core/text_list" name="root" output="toHtml"> <block type="engine23_blog/adminhtml_flat_entry_grid" name="blog_ajax_grid" output="toHtml"/> </block> </adminhtml_flat_entry_grid>
**** Correct XML to remove the extra block when filters/sorting is used ****
Read more
Posted in Development
I needed to get a mysql query where the MIN and MAX were set, but I could exclude any that the same. I struggled a bit to figure out the proper syntax but my friend Tom B. from Gallup helped me out ( Thank you sir, that is one digital drop for you! ). For those of you who may need to get this in the future...or maybe future me in a few weeks after I forget the syntax....here it is:
SELECT SQL_CALC_FOUND_ROWS MIN(`entity_id`) as minResult, MAX(`entity_id`) as maxResult, `oms_id` FROM `customer_entity` WHERE `oms_id` IS NOT NULL GROUP BY `oms_id` HAVING minResult != maxResult
Posted in Development
I recently posted this on LinkedIn and felt this was also a good place for this.

Well, I just passed the 4th and final certification exam that Magento offers. I just did a quick search and there are a total of 6 of us in the United States, and 35 world wide who decided to take all 4 exams. After this year of studying and preparing, its a very good thing for any Magento developer to strive to do. It forces you to fully understand the platform as whole.
Read more
Posted in Development
When upgrading Magento from 1.12 or 1.13 to 1.14 you may experience this error
Fatal error: Call to a member function rewrite() on a non-object
If you do, its because of caching
A simple fix, if you do not have any server caching like memcached or varnish, etc. is to remove the contents of the /var folder in your file systems.
Posted in Development
| |