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

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?