Friday, June 14, 2013

Add custom address city user profile fields joomla 2.5

If you want to add basic location fields in user profile both for registration and profile like city, country, address, postcode you don't have to install any plug-ins .. Joomla 2.5 gives the option to do that by default :)

Here is how it goes:

Step 1: Go to 'Extensions' -> 'Plug in Manager'
Step 2: Search 'Profile'
Step 3: Enable the plug in called 'User - Profile', its disabled by default.

Step 4: Click on plugin and from right menu select the fields you want.
Step 5: Save & Close and you are done :)

Monday, June 10, 2013

Disable right click on link anchor a tag

I have a link that I use a jQuery plugin to open in a popup window and that's how it is to be used. So in order to prevent users to right click and open it in a new window I wanted to disable right click on my anchor tag.. the solution is simple.. add 'oncontextmenu="return false"'

<a href='myLink.php' oncontextmenu="return false">Click me</a>

View page / popup without template Joomla 2.5

So I wanted to create a popup in my custom Joomla component that is basically a whole page in itself not an alert box so I needed to create a page without template (header footer) showing and just what I want.

For example: <a href='index.php?option=my_component&view=popup_page'>Click here</a>

(I used jQuery plugin to open it up in a popup instead of new page)
To view this page without template, all you need to do is simply add '&tmpl=component', so in the above case the URL will simply become:

For example: <a href='index.php?option=my_component&view=popup_page&tmpl=component'>Click here</a>

Hope it helps someone :)

Friday, August 31, 2012

Index PHP Array to use in Javascript / Javascript array

So here is what I wanted, I wanted to the text of check box when clicked on check box like
<input type='checkbox' value='1' name='chkbox'>First chk box</input>

So I wanted 'First chk box' when clicked on it, in here you might be able to simply get it using innerHTML but my case was bit different so I got a php array that had id=>value (1=>'First chk box') array now the issue is you can't use it in javascript

So step 2 is converting php array to javascript array, following are the things you can do

1. Simply make a javascript array and put php values in it
var jsArray = new Array('<?=$phpArr[0]?>',<?=$phpArr[1]?>',....);

That doesn't work in my case because my indexes were different

2. You can have insertion in JS Array using the splice function to insert in mid, you can google that, but the issue with that is you can't have a javascript array like

arr[1] = index1
arr[2] = index2
arr[5] = index5

means you need EACH index defined which is not my case, I could have skipping index so here is solution for me, or you if you have similar issue... or any of above might work for you...

3. var jsArray = <?php echo json_encode($phpArray) ?>;
Now if could do is simply using
jsArray[chkbox.value] 
and it would give me 'First chk box'

Friday, August 24, 2012

Generate Random Password Joomla and PHP

The following few lines creates a random password and puts it into and md5 encrypted format to be saved in joomla database. If you are using non-encrypted password you can just use the first part, or if you are using simple md5 encryption and not looking for key:salt as joomla then you can simply take the $key from first part and encrypt it using the md5 function and store that. :)

        $key = "";
        srand((double)microtime() * rand(1000, 9999));
        $charset = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
        for($len=0; $len<8; $len++)
            $key .= $charset[rand(0, strlen($charset)-1)];
        //End of part 1, you will have a simple random password here in $key
        $salt = JUserHelper::genRandomPassword(32);
        $crypt = JUserHelper::getCryptedPassword($key, $salt);
        $password = $crypt . ':' . $salt;

$password will have the value that you can save into database in users table.

Wednesday, August 8, 2012

Joomla 2.5 - Redirect to login page with return URL

If you have a private page that is supposed to be viewed only by registered users and if URL is accessed directly or is accessed on session expire you want to redirect user to login page and on successful login return him to the requested page then simply make a function named something like 'validateUser' and call it for all such views. Here is the brief and comprehensive function:


function validateUser()
{
        $user = JFactory::getUser();
        $userId = $user->get('id');
        if(!$userId)
        {
            $mainframe = &JFactory::getApplication();
            $return = JFactory::getURI()->toString();
            $url  = 'index.php?option=com_users&view=login';
            $url .= '&return='.base64_encode($return);
            $mainframe->redirect($url, JText::_('You must login first') );
            return false;
        }
        return true;
}

Note: If you are trying to do something similar for Joomla 1.5 note you would have to use 'option=com_user' instead of 'users'.

Wednesday, August 1, 2012

Remove parameter from URL PHP

If you are looking to remove a specific parameter from the URL here is how to do it:

Assume you have URL
http://www.b4blinky.com/index.php?option=com_content&view=article&id=1
And you want to remove the id


$currURL = $_SERVER[QUERY_STRING];
//this will get you option=com_content&view=article&id=1
parse_str($currURL,$params); //Puts the url parameters in key=>value pair
//This will give you option=>com_content, view=>article, id=>1
unset($params[$fieldName]);  //Removes the parameter on which 'x' is clicked
//This will remove the $fieldName from the array e.g. 'id'
$newURL = http_build_query($params); //Rebuilds the query with the remaining parameters
//This will rebuild array excluding id
$newURL = 'index.php?'.$newURL;
//and finally your newURL like
index.php?option=com_content&view=article

That you can modify if relative doesn't work for you.

Hope it helps. Happy coding :)

Friday, July 27, 2012

Difference between find_in_set and in MySQL

If you are confused with these functions then there is short explanation

They are both used for matching a single value again comma separated multiple values

IN: Works when you are looking for database/column value against commas separated list
e.g. WHERE id IN (1,2,3)

FIND_IN_SET: Works the other way around i.e. when you are looking for a single values against a comma separated list stored in a column
e.g. WHERE FIND_IN_SET('name',namesColumn)
where names is a column having value like ('john,paul,richard')

Thursday, July 26, 2012

HTML is stripped in Joomla component configuration / parameters filter

If you are looking to add HTML anywhere in Joomla and 'text filtering' option in 'global configuration' is failing then here is what you need to do

You need to add a filter='safehtml' in your field tag be it your component field or parameter e.g.

<field menu="hide" name="sharethisbtncode" type="textarea"  filter="SAFEHTML" label="Sharethis Buttons Code" description="HTML buttons code of the buttons needed to be displayed" />

Without it Joomla will use the default and strip HTML.

Also know that it will only work for simple HTML like in this example buttons code, if you are looking for including something like javascript like header of analytics or some other you will need to use filter="RAW"

Following is the list of all the filter options:


case 'RULES': // Used for permissions etc
case 'UNSET': // Does nothing.
case 'RAW': // No Filter.
case 'SAFEHTML': // Filter safe HTML.
case 'SERVER_UTC': // Convert a date to UTC based on the server timezone offset.
case 'USER_UTC': // Convert a date to UTC based on the user timezone offset.
default: // Check for a custom callback filter that you can write


For more details refer to:
http://docs.joomla.org/API16:JForm/filter

Include js in head tag Joomla 2.5

If you are looking for how to include javascript in the head tag of html without having to write it in the template for features like sharethis, Google analytics here is how to

Simply use the following two lines:

$document = &JFactory::getDocument();
$document->addCustomTag('<script type="text/javascript">my javascript</script>');

And it will add javascript to the head tag.

You can also include js/css files by using

$document->addStyleSheet('path');
$document->addScript('path');

Wednesday, July 25, 2012

Broken dead links checker php solution

If you want to know how to check for broken or dead links using php, following is a simple script that uses curl to check broken links, you can run it on your database if you have a table of links that you want to check for possible broken links:


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $data = curl_exec($ch);
            curl_close($ch);

This sets nobody=true which means it doesn't request for the whole page hence speeding up the link checking. There are plenty of ways within curl to check for broken or redirecting links, I personally use this by putting a simple length check on data variable, if its 0 then it means the link is dead.

i.e.
if(strlen($data)==0)
   echo 'dead link=>'.$url;

You can do something else if you like.

Cheers.

Tuesday, July 24, 2012

[Solved] DIV background color not showing

If you have a div tag that has background-color set but it doesn't show at all because there is dynamic content in it with some further tags that have content in it and hence you can not set a fixed height e.g.

<div class="bgcolorRed">
      <div>...content....</div>
      <dl>.....content....</dl>
</div>

Just simply add 'overflow: hidden' along with you background color in CSS and it will work
i.e.

.bgcolorRed {
     background-color: red;
     overflow: hidden;
}

Hope that helps.

Sunday, July 22, 2012

Technorati API Closed

Technorati was one of the most popular used website few years back but as it started to decline sadly the team also seemed not to care much about it. They closed their API that was widely used by people and developers worldwide in 2009 promising for something new but its been three years and there is nothing which leaves a heavy doubt that probably it won't be coming ever again.

Here is the link where the announced the closure of existing API and announcement of new API and features which never came.
http://technorati.com/developers/

Here is an interesting blog article by another person who mentioned that even the founder of Technorati used the API on his blog and I checked it now and there was nothing of Technorati.
http://blog.programmableweb.com/2010/03/04/technorati-api-disappears-no-longer-representing-the-technorati/

Tuesday, July 3, 2012

[Solution] You are not permitted to use that link to directly access that page Joomla 2.5 Error

If you are having the error "You are not permitted to use that link to directly access that page" on clicking on 'cancel' button in joomla admin inside a component then try the following:


Try selecting a row with a check box and then click edit, once the page loads click cancels, if this doesn't give the error and adding a look to title to edit, something like 


index.php?option=com_myschool&view=student&layout=edit&id=1


and clicking on this and then pressing cancel gives you the error then the following is the quick and easy solution, replace the layout edit with task=subcontrollername.edit and leave rest the same, e.g.

index.php?option=com_myschool&view=student&task=student.edit&id=1
or this also works
index.php?option=com_myschool&task=student.edit&id=1

Note: You will be in a view with plural like views/students/tmpl/default.php but you have to use the subcontroller name of the single one i.e. student.

Adding javascript file in Joomla view file

If you want to use a javascript file in a view file (i.e. myComponent/views/student/tmpl/default.php) you will not be able to inlcude using

<script type="text/javascript" src="" />

As you will see it won't load the file and hence won't work. So to include a file you will need to use something like this:


$document = &JFactory::getDocument();
$document->addScript( 'myfilepath/myjsfile.js' );

Thursday, June 21, 2012

Joomla path variables (JPATH)


Following is the list of JPATH variables that you can use while component development in Joomla, do let me know if you find any other.

JURI::Root() = http://localhost/myJoomla or http://www.test.com
JPATH_COMPONENT_ADMINISTRATOR = /var/www/html/myjoomla/administrator/components/com_mycomp
JPATH_COMPONENT_SITE= /var/www/html/myjoomla/components/com_mycomp
JPATH_ROOT = /var/www/html/myjoomla
JPATH_SITE = /var/www/html/myjoomla
JPATH_ADMINISTRATOR = /var/www/html/myjoomla/administrator

JPATH_BASE is the root path for the current requested application, so if you are in the administrator application, JPATH_BASE == JPATH_ADMINISTRATOR... if you are in the site application JPATH_BASE == JPATH_SITE... if you are in the installation application JPATH_BASE == JPATH_INSTALLATION.



Wednesday, June 20, 2012

Joomla 2.5 extend jgrid.published column in custom component


Ever wanted to have a column/field like published in articles for your own component? Well here is how you can make one.
If you go to com_content and see how it is done there you will see that for published it uses the following line of code in views/articles/tmpl/default.php

<?php echo JHtml::_('jgrid.published', $item->state, $i, 'articles.', $canChange, 'cb', $item->publish_up, $item->publish_down); ?>


Simplying it you can use it as

<?php echo JHtml::_('jgrid.published', $item->state, $i, 'articles.'); ?>

Which is

<?php echo JHtml::_('jgrid.published', $item->yourFieldName, $i, 'classPrefix.'); ?>

If you just put this one line you will be able to see that your Boolean field will start showing correctly, and especially if you field name is ‘published’ then you are done and you can click on it to toggle between publish and un publish, however if your field name is something other than published e.g. approved or available then you have some work to do.
First you will need to create a new class in com_componentName/helpers/html/className.php
This will be a JFieldClassName class having code like this
<?php
defined('_JEXEC') or die;
abstract class JHtmlClassName
{
                static function approved($value = 0, $i)
                {
                                $states = array(0=> array('disabled.png','tableName.approved','’,'Toggle to approve'),
                    1=> array('tick.png',    'tableName.unapproved', ',        'Toggle to unapprove'), );
                                $state   = JArrayHelper::getValue($states, (int) $value, $states[1]);
                                $html    = JHtml::_('image', 'admin/'.$state[0], JText::_($state[2]), NULL, true);                                                  $html    = '<a href="#" onclick="return listItemTask(\'cb'.$i.'\',\''.$state[1].'\')" title="'.JText::_($state[3]).'">'. $html.'</a>';
                }
                return $html;
                }
} ?>
Now to call this you will have to first register it for both approved/unapproved in controller’s contruct
com_componentName/controllers/classNames.php
                public function __construct($config = array())
                {
                                parent::__construct($config);
                                $this->registerTask('unapproved', 'approved');
                }
Followed by the function which will call the model to update the status:
        function approved()
        {
                                $ids        = JRequest::getVar('cid', array(), '', 'array');
                                $values = array('approved' => 1, 'unapproved' => 0);
                                $task     = $this->getTask();
                                $value   = JArrayHelper::getValue($values, $task, 0, 'int');
                                $model = $this->getModel();
                                if (!$model->approved($ids, $value)) {
                                                                JError::raiseWarning(500, $model->getError());
                                }
                                $this->setRedirect(url to get you back to the same page);
        }
Now its all up are ready and you can just create a function in your respective model which takes the value (which will be 0 or 1) and id and update the status , and finally you can use it by writing the following line in default.php
<?php echo JHtml::_('className.approved', $item->approved, $i, 'tableName.'); ?>
You will need to include the html helper file you created first by putting the following like at the top of default.php
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');


Tuesday, May 1, 2012

Joomla 2.5 Admin Component Multi View Create & Save

To create a field in the Joomla 2.5's administrator part of the component and to store it you have to do the following things:

First to create a multi select drop down field you have to add the following attribute into the xml
multiple="multiple"

like I did in the following:


<field
        name="practice_areas_ids"
        type="list"
        class="inputbox"
        default=""
        label="Practice Area(s)"
        multiple="multiple">
<option value="1">Area 1</option>
<option value="2">Area 2</option>
                        <option value="3">Area 3</option>
</field>


Now you will be able to see and select multiple fields when you click on 'New' or 'Edit' in your component however this won't save the multi selected array into your database and will store just the first value e.g. if you select Area 2 & Area 3 it will only store 2. To save comma separated all values you have to do the following:

Go to your store/bind or whichever function you are using and add an implode line, here is mine for clarity:
$practice_ids = implode(",", $_REQUEST['jform']['practice_areas_ids']);

Now this let's you select multiple fields and store their ids successfully into the database, that leaves us with our last problem which is if you open your row/entry in edit you will see that the selected Area(s) will not show as selected, that is because it is reading the field as comma separated list instead of an array so as we did implode on saving, we need to do explode on displaying. To do that follow the following:

Go to 'models'/modelName.php and look for the function 'loadFormData()'
Go inside it and after you have obtained the $data and before returning, replace the multiple select field with exploded array, like:



         protected function loadFormData() 
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_jobm.edit.italy.data', array());
if (empty($data)) 
{
$data = $this->getItem();
}
                $data->practice_areas_ids = explode(',', $data->practice_areas_ids);
return $data;
}

Joomla redirect from view.html.php

If you ever want to redirect url from view of a component i.e. view.html.php simply use the following two lines:

$app =& JFactory::getApplication(); 
$app->redirect('index.php?option=com_mycomponent&view=default'); 

If else statement in Select MySQL

Ever wanted to show one thing for one value and another for rest as stored in the database? As an easy example if you have a column 'gender' that has 1 for male and 0 for female then instead of having to parse it before displaying you can simply do so using MySQL if statement. Here is the syntax

IF(condition, if true, if false)

SELECT name,IF(gender='1','Male','Female') AS gender
FROM person