rss
twitter
    Find out what I'm doing, Follow Me :)
Powered By Blogger

Wednesday, February 17, 2010

FAST FIXES FOR YOUR JOOMLA PROBLEMS

I get a lot of emails asking how to fix a particular problem in Joomla. Problems can arise for all sorts of reasons and are often caused by some incompatibility with your host or an extension. The following suggestions are very basic but I know many people are giving up too soon, so if you run into trouble, I hope you'll find this helpful:

If you receive an error message, copy the error and Google it. You may find a page where others are describing the same problem and hopefully a solution.
Search the Joomla forums and if there are no other relevant posts, start your own. It is helpful to describe your problem in as much detail as practical, including any errors you receive. Just be aware that this is a public forum and so it is a very bad idea to include private information such as passwords. If you are polite, you will most likely receive a friendly response.
If the problem relates to an extension, contact the extension developer directly. Many have a support page or forum on their site.
If time is against you, or you can't find an answer, consider paying an expert to fix the problem. You can try freelance sites such as Joomlancers, ODesk, Elance or Guru
If something is wrong but you are not receiving an error message, you might like to try bumping up the level of error reporting. In Administrator, go to Global Configuration - Server - Error Reporting - Maximum and remember to Save.

Friday, February 12, 2010

Magento: How to get all active payment modules

This code bellow will get you all active Magento payment modules. This example below return an array which you can use to create drop down menu or something else in Magento’s front-end or admin sections.

class Inchoo_Vendor_Model_Activpayment
{

public function getActivPaymentMethods()
{
$payments = Mage::getSingleton('payment/config')->getActiveMethods();

$methods = array(array('value'=>'', 'label'=>Mage::helper('adminhtml')->__('--Please Select--')));

foreach ($payments as $paymentCode=>$paymentModel) {
$paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title');
$methods[$paymentCode] = array(
'label' => $paymentTitle,
'value' => $paymentCode,
);
}

return $methods;

}

}

Thursday, February 11, 2010

How to override Magento admin view (template) files, quick and dirty way

Suppose you are working on a extension that needs to either change some stuff or implement new stuff in the one of the Magento admin areas. For example, imagine a “Images” tab on the product edit section. If you were in a position where you need to do certain modifications on “Images” tab then you would most likely need to modify the app/design/adminhtml/default/default/template/catalog/product/helper/gallery.phtml file to do so. One of Inchoo coworkers and a good friend of mine, Ivan Weiler, made a Magento Admin theme module that enables you to achieve similar functionality for admin template files as you have for frontend template files.

However, sometimes you wont wish your extensions depend on the additional module for certain functionality. Stuff like “overriding” the admin view files can easily be achieved with just a few minor modifications of extended class.

Content of my app\code\community\MyCompany\MyModule\Block\Adminhtml\Catalog\Product\Helper\Form\Gallery\Content.php file.


class MyCompany_MyModule_Block_Adminhtml_Catalog_Product_Helper_Form_Gallery_Content extends Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content
{
/**
* This method has been overridden merely for the purpose of setting up a new view file
* to be used in place of the default theme folder.
*
* @see app/code/core/Mage/Core/Block/Mage_Core_Block_Template#fetchView($fileName)
*/
public function fetchView($fileName)
{
extract ($this->_viewVars);
$do = $this->getDirectOutput();

if (!$do) { ob_start(); }

include getcwd().'/app/code/community/MyCompany/MyModule/blocks/Adminhtml/catalog/product/helper/gallery.phtml';

if (!$do) {$html = ob_get_clean(); }
else { $html = ''; }

return $html;
}
}
Which goes inline with the config.xml file entry like:

...



MyCompany_MyModule_Block_Adminhtml_Catalog_Product_Helper_Form_Gallery_Content



...
In the example below, I am pointing the block to look for my view file within my module folder, and not within some Magento design folder. Basically my gallery.phtml is the same as the original Magento adminhtml view file for the same purpose, but now I can go in and implement my additional stuff in it.

Approach like this can have its advantage in terms of keeping all the required overridden design files in your own module directory.

For those who need it… cheers.

Wednesday, January 20, 2010

how to insert modules inside articles

How to insert modules inside articles

Your website content is divided into what I call "Primary" and "Secondary" content. Your Primary Content are your articles that appear in the main part of the page and these are handled using Article Manager in the Administrator. Your Secondary Content items are pieces of information that appear in other positions such as the header, footer, left and right. These are handled using Module Manager. However did you know that you can place a module into an article? Here are the steps:

1)Login to Administrator and go to the Module Manager

2)Start creating a new Module or edit an existing Module

3)Enter the normal Module parameters

4)You would normally choose a position from the drop down menu but in this case overwrite this with your own name making sure that it doesn't already exist - you can position your cursor in this box and type freely

5)Create a new article, or edit an existing one and at the point where you want your module to appear, enter {loadposition yourposition} where yourposition is the name you allocated in the previous step

6)If this does not work, go to Plugin Manager and ensure that 'Content - Load Module' is enabled

How AJAX work in Magento

Ajax in Magento can be pretty troublesome.Because you will need to take controllers and layout into account.And I almost used up a whole day trying to make ajax work. Here are some of the steps I’d like to share so that you will not waste lots of your time, before making this work :D .
Let’s first know in Magento terms what we need.

Controller: The url on which Ajax will work on, or the request URL. You will have to set up the controller with its frontend router set in config.xml and its corresponding controller class.
Layout: Layout to handle the requested URL and return HTML if required.
Block: The block to call through layout for the above controller.

Now lets be descriptive.

If you want to show a loader while request is being processed just add the following whereever you like in the phtml page.First fetch the Javascript.



Then echo the loader which pops up. This loader will be similar to that of the admin.


Now to Call Ajax, use the following lines
/*Please note that the URL is created in reloadurl. Also see that the response text will be echoed in div with id=output-div*/

var reloadurl = 'getUrl('router/controller/action') ?>';
Element.show('loadingmask');
new Ajax.Request(reloadurl, {
method: 'post',
parameters: "Params_Here",
onComplete: function(transport) {
Element.hide('loadingmask');
$('output-div').innerHTML = "";
$('output-div').innerHTML = transport.responseText;

}
});

After the Ajax Request is made it goes to your controller’s action, which in turn sees to your layout as follows:
class Namespace_module_frontendController extends Mage_Core_Controller_Front_Action
{
public function actionAction(){
$this->loadLayout()->renderLayout();
}
}

And here is the main part in layout where I spent most of my time in. Since in layout we will have to define reference where the html will echo (Most of the times), i got stuck here, because i need to echo the output on the div with id output-div not in any reference.And the trick is to name the layout as root and output as html. Like the following:





You are done now! What ever you write or echo in phtml file you will see populated in the DIV. Now you can treat block as normally as you do before.

Happy Coding!!
10 PHP Functions You Probably Not Used

When scripting in PHP, we often restrict ourselves to a limited number of API functions: the common ones, like print(), header(), define(), isset(), htmlspecialchars(), etc. If some needed functionality doesn’t exist, we often write it making use of these basic components which we have in mind. The PHP API actually offers a lot of functionality, some useless and some useful; often seldom used. I have been looking through the available functions and was interested to find some really cool functions that I should have known about. Here, I share my findings.

1. sys_getloadavg()
sys_getloadvg() is a function which returns three samples of the “load” on a system. Load is the number of processes in the system run queue. The 3 items in the array are the average load for the past 1, 5 and 15 minutes. The PHP Manual shows a great usage of this:

$load = sys_getloadavg();
if ($load[0] > 80) {
header('HTTP/1.1 503 Too busy, try again later');
die('Server too busy. Please try again later.');
}

Rather than have your web service become unavailable for everyone, you simply die when there’s too much load — primitively, this will allow some requests and deny others. The function will not work on Windows, though.

2. pack()
I actually use pack() fairly often, to make the 32-byte hexadecimal strings returned by md5() into 16-byte binary strings*:

$pass_hash = pack("H*", md5("my-password"));
$pass_hash = md5("my-password", true); // equivalent (PHP 5+)

It is very useful when storing data in databases; to save space. (In the case of packing hexadecimal values to binary strings).

3. cal_days_in_month()
cal_days_in_month() usefully returns the number of days in a given month:

$days = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y")); // 31
echo ( $days - date("d") + 1 ) . " days until " . date("F", mktime(0, 0, 0, date("m") + 1, 1, 1970));

4. _()
If you’ve developed for Wordpress, you’ll know about the __() and _e() functions to make the software i18n-able. You can use gettext() (or _(), which is an alias), together with some other functions, to achieve the same functionality, in Wordpress or not. This example was taken from the PHP Manual:
// Set language to German
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

echo _("Have a nice day");
You will need to build PHP with GNU gettext support. I suspect that there is a third-party solution out there which does the same thing, working on a standard installation. (Edit: in fact, there is — here; thanks Toni).


5. get_browser()

Wouldn’t it be nice to find out what a user’s browser could do before sending the page? Well, you can with get_browser(). You will need php_browscap.ini first, and point the browscap directive to the file. You could have something similar to this:

$browser = get_browser(null, true);
if(!$browser["frames"] || !$browser["cookies"])
echo "Please download an up-to-date browser. Some sections of this site may be inaccessible";

This will not detect individual configurations of browsers, however; it can not be used to detect whether Javascript is enabled, for example. It may be useful to profile users — ie, by what browser and platform they use.

6. debug_print_backtrace()
It can be quite difficult to trace through code manually, particularly when looking for a logic error; after all, you wrote the logic! debug_print_backtrace() can get you out of a difficult situation. Here the function is being used to understand a rather pointless script:

$a = 0;

function iterate() {
global $a;
if( $a < 10 )
recur();
echo $a . ", ";
}

function recur() {
global $a;
$a++;

// how did I get here?
echo "\n\n\n";
debug_print_backtrace();

if( $a < 10 )
iterate();

}

iterate();

# OUTPUT:

#0 recur() called at [C:\htdocs\php_stuff\index.php:8]
#1 iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0 recur() called at [C:\htdocs\php_stuff\index.php:8]
#1 iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2 recur() called at [C:\htdocs\php_stuff\index.php:8]
#3 iterate() called at [C:\htdocs\php_stuff\index.php:25]

#0 recur() called at [C:\htdocs\php_stuff\index.php:8]
#1 iterate() called at [C:\htdocs\php_stuff\index.php:21]
#2 recur() called at [C:\htdocs\php_stuff\index.php:8]
#3 iterate() called at [C:\htdocs\php_stuff\index.php:21]
#4 recur() called at [C:\htdocs\php_stuff\index.php:8]
#5 iterate() called at [C:\htdocs\php_stuff\index.php:25]

[...]


7. metaphone()

metaphone() is a function returning the same key for words which sound the same. soundex() does the same thing, but is less accurate (according to PHP Manual):

echo metaphone("train") . "\n"; // TRN
echo metaphone("terrain") . "\n"; // TRN
echo metaphone("not a train") . "\n"; // NTTRN

echo soundex("train") . "\n"; // T650
echo soundex("terrain") . "\n"; // T650
echo soundex("not a train"); // N336

8. natsort()
natsort() is a function which will sort items in an array naturally (ie, in an order which seems logical to a person), rather than by characters’ ordinal values. Take, for example:

$items = array(
"100 apples", "5 apples", "110 apples", "55 apples"
);

// normal sorting:
sort($items);
print_r($items);
# Outputs:
# Array
# (
# [0] => 100 apples
# [1] => 110 apples
# [2] => 5 apples
# [3] => 55 apples
# )

natsort($items);
print_r($items);
# Outputs:
# Array
# (
# [2] => 5 apples
# [3] => 55 apples
# [0] => 100 apples
# [1] => 110 apples
# )

9. levenshtein()
levenshtein() tells you how “far” away two words are. It will return the minimum number of inserts, replaces and deletions needed to transform one string to the other. Take, for example, the following code:

$dictionary = array(
"php", "javascript", "css"
);

$word = "japhp";

$best_match = $dictionary[0];
$match_value = levenshtein($dictionary[0], $word);

foreach($dictionary as $w) {
$value = levenshtein($word, $w);
if( $value < $match_value ) {
$best_match = $w;
$match_value = $value;
}
}

echo "Did you mean the '$best_match' category?";
In this case, the user has been asked to provide a category name. They provided “japhp”, which is invalid. Since this is likely to be a typing error, the code above will make a suggestion (“Did you mean the ‘php’ category?”).

10. glob()
glob() will make you feel stupid after using opendir(), readdir() and closedir() to search for a file. It’s this simple:
foreach (glob("*.php") as $file)
echo "$file\n";

Any more?
There are loads of functions out there. If you can’t get enough, http_build_query(), register_shutdown_function() and pspell_suggest are also worth a mention.What’s your favourite discovery?