Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Refine Tags

Snippets tagged "javascript helper" Snippets tagged "javascript helper"

jQuery AdminDoubleList replacements

jQuery AdminDouble List

These two js functions do the job while using jQuery with admin double list

function double_list_move(src, dest)
{
    var L = $(src).children();
    $(L).each(function(i){
        if(L[i].selected){
            $(dest).append('<option value="'+$(L[i]).val()+'">'+ $(L[i]).text()+'</option>');
            $(L[i]).remove();
        }
    });
 
}
 
function double_list_submit()
{
    var sel = $("form").find("select.sf_admin_multiple-selected");
    var C = $(sel).children();
    $(C).each(
        function(i){
            if(!C[i].selected)
                C[i].selected=true;
        }
    );
 
}
 

Enjoy it.

by Thomas Schäfer on 2008-03-19, tagged helper  javascript  jquery 

Phone Number Helper

format a phone number with 7, 10, or 11 digits. also can convert phone number letters to numbers

lib/helpers/PhoneHelper.php

<?php 
 
function format_phone($phone = '', $convert = false, $trim = true)
{
    // If we have not entered a phone number just return empty
    if (empty($phone)) {
        return '';
    }
 
    // Strip out any extra characters that we do not need only keep letters and numbers
    $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
 
    // Do we want to convert phone numbers with letters to their number equivalent?
    // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
    if ($convert == true) {
        $replace = array('2'=>array('a','b','c'),
                 '3'=>array('d','e','f'),
                     '4'=>array('g','h','i'),
                 '5'=>array('j','k','l'),
                                 '6'=>array('m','n','o'),
                 '7'=>array('p','q','r','s'),
                 '8'=>array('t','u','v'),                                '9'=>array('w','x','y','z'));
 
        // Replace each letter with a number
        // Notice this is case insensitive with the str_ireplace instead of str_replace 
        foreach($replace as $digit=>$letters) {
            $phone = str_ireplace($letters, $digit, $phone);
        }
    }
 
    // If we have a number longer than 11 digits cut the string down to only 11
    // This is also only ran if we want to limit only to 11 characters
    if ($trim == true && strlen($phone)>11) {
        $phone = substr($phone, 0, 11);
    }                        
 
    // Perform phone number formatting here
    if (strlen($phone) == 7) {
        return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
    } elseif (strlen($phone) == 10) {
        return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
    } elseif (strlen($phone) == 11) {
        return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
    }
 
    // Return original phone if not 7, 10 or 11 digits long
    return $phone;
}
 
by Alex Zogheb on 2008-02-08, tagged formatting  helper  javascript  number  phone  regex 

Accordion Helper

A symfony helper for the stickman labs accordion http://www.stickmanlabs.com/accordion/

hopefully plugin oneday

<?php
 
use_helper('Tag', 'Javascript');
 
function accordion($container, $options = array()){
 
    $response = sfContext::getInstance()->getResponse();
    $response->addJavascript(sfConfig::get('sf_prototype_web_dir').'/js/prototype');
    $response->addJavascript(sfConfig::get('sf_prototype_web_dir').'/js/effects');
    $response->addJavascript('accordion', 'last');
 
    $options = _parse_attributes($options);
    $on_load = (isset($options['on_load']) && $options['on_load'] == false) ? false : true;
    if(isset($options['use_stylesheet']) && $options['use_stylesheet']==true) $response->addStylesheet('accordion');
 
    $output= '';
    //onLoad
    $output .= $on_load ? "Event.observe(window, 'load', function() {" : '';
 
    //new accordion
    $output .= "var accordion_$container = new accordion ('$container', ";
 
 
    $accordion_options = array();
 
    //speed
    if (isset($options['resize_speed'])) $accordion_options['resizeSpeed'] = $options['resize_speed'];
 
    //classes
    if(isset($options['toggle']) || isset($options['toggle_active']) || isset($options['content'])){
        if(isset($options['toggle'])) $accordion_options['classNames']['toggle'] = "'{$options['toggle']}'";
        if(isset($options['toggle_active'])) $accordion_options['classNames']['toggleActive'] = "'{$options['toggle_active']}'";
        if(isset($options['content'])) $accordion_options['classNames']['content'] = "'{$options['content']}'";
        $accordion_options['classNames'] = _options_for_javascript_no_sort($accordion_options['classNames']);
    }
 
    //size
    if(isset($options['height']) || isset($options['width'])){
        if(isset($options['height'])) $accordion_options['defaultSize']['height'] = $options['height'];
        if(isset($options['width'])) $accordion_options['defaultSize']['width'] = $options['width'];
        $accordion_options['defaultSize'] = _options_for_javascript_no_sort($accordion_options['defaultSize']);
    }
 
    //direction
    if (isset($options['direction'])) $accordion_options['direction'] = "'{$options['direction']}'";    
 
    //event
    if (isset($options['on_event'])) $accordion_options['onEvent'] = "'{$options['on_event']}'";
 
    $output .= _options_for_javascript_no_sort($accordion_options);
 
    //new accordion end
    $output .= ");";
 
    if(isset($options['activate'])){
        $number = $options['activate'];
        $output .= "accordion_$container.activate($$('#$container .{$options['toggle']}')[$number]);";
    }
 
    //onLoad
    $output .= $on_load ? "});" : '';
 
    return javascript_tag($output);
 
}
 
  function _options_for_javascript_no_sort($options)
  {
    $opts = array();
    foreach ($options as $key => $value)
    {
      $opts[] = "$key:$value";
    }
 
    return '{'.join(', ', $opts).'}';
  }
 
by Alex Zogheb on 2008-02-08, tagged accordion  helper  javascript 

jsValidator integration helper

A real client-side validation with some nice features, without Ajax tricks provided by sfYzAjaxValidationPlugin may be easily done using jsValidator (http://sourceforge.net/projects/jsformutils/) and little helper that follows.

<?php
/**
 * Generates JavaScript code to validate a form using 
 * jsValidator as client-side validation engine (see http://sourceforge.net/projects/jsformutils/)
 * 
 * @param string $targetForm id attribute of the form to be validated
 * @param mixed $options associative array of options
 * @param string $action action to validated, defaults to current
 * 
 * Options are:
 *  stopOnFirstError: boolean, default: false
 *  labelMessageDelimiter: string, default: ' : ',
 *  messageSeparator: string, default: "\n",
 *  messageHeader: string, default: 'These fields are invalid:\n---\n' + 
 *  highlightErrors: boolean, whether to mark erroneous fields 
 *  errorElementClass: string, CSS class name to be applied to wrong fields
 *  highlightLabels: boolean, whether to mark fields or fields' labels
 */
function generate_validator($targetForm, $options, $action)
{
  $NL = "\n";
  $funcPrefix = 'validate_';
  $labelsKey = 'labels';
  $fieldsKey = 'fields';
  $jsCode = '';
 
  $paramHolder = sfContext::getInstance()->getRequest()->getParameterHolder();  
  $rulesFilePath = sfConfig::get('sf_app_module_dir').'/'.$paramHolder->get('module').'/'.
    sfConfig::get('sf_app_module_validate_dir_name').'/';
 
  // Load rules from YAML file.   
  if (file_exists($rulesFilePath.$paramHolder->get('action').'.yml'))
    $rules = sfYaml::load($rulesFilePath.$paramHolder->get('action').'.yml');
  else
    $rules = sfYaml::load($rulesFilePath.$action.'.yml');
 
  // Generate jsValidator compliant rules.  
  $jsRules = array();
  foreach ($rules['fields'] as $fieldId => $validationRule)
  {
    foreach ($validationRule as $validator=>$rule)
    {
      // Remove server-side sfCallbackValidator.
      if ($validator == 'sfCallbackValidator')
      {
        unset($validationRule[$validator]);
        continue;
      }
      // Map Symfony validators to jsValidator.
      $jsvalidator = preg_replace('/^sf(\w+Validator)$/', 'js\\1', $validator);
      if ($jsvalidator != $validator)
      {
        $validationRule[$jsvalidator] = $validationRule[$validator];
        unset($validationRule[$validator]); 
      }
    }
    $jsRules[] = array_merge ( 
      array ('field' => $fieldId, 'label' => $rules['labels'][$fieldId]),
      $validationRule
    );    
  }
 
  // Generate final JavaScript code. 
  $jsCode .= 'function '.$funcPrefix.$targetForm.'()'.$NL;
  $jsCode .= 
  '{'.$NL.
  ' var options = '.json_encode($options).';'.$NL.
  ' var rules = '.json_encode($jsRules).';'.$NL.
  ' var jsv = new jsValidator();'.$NL.
  ' jsv.SetOptions(options);'.$NL.$NL.
  ' if (!jsv.Validate(rules))'.$NL.
  ' {'.$NL.
  '   alert(jsv.GetErrorMessage());'.$NL.
  '   return false;'.$NL.  
  ' }'.$NL.
  ' return true;'.$NL.  
  '}'.$NL;
 
  return javascript_tag($jsCode);
}
?>
 

However, I need to clear this out. Besides placing this code into jsValidatorHelper.php either in modules' lib directory or symfony's one, we need to call it properly in the corresponding view.

First of all, include the helper (use JavaScript as well, jsValidator depends on it)

<?php use_helper('JavaScript', 'jsValidator') ?>
 

Validation is performed based on the same simple rule mechanism that Symfony provides. The only difference is that JavaScript validator needs these rules to be in JSON format and it needs some more options, that configure it's behavior.

<?php
// Here we set validation options.
// For more information please refer to documentation of jsValidator
$options = array(
  'stopOnFirstError' => false,
  'labelMessageDelimiter' => ' : ',
  'messageSeparator' => "\n",
  'messageHeader' => "These fields are invalid:\n---\n",
  'highlightErrors' => true,
  'errorElementClass' => 'errClass',
  'highlightLabels' => true
  ); 
// Output auto-generated JavaScript code.
echo generate_validator('editComment', $options, 'update'); 
?>
 

We also have to set up form to point to our validator before submitting. Note, that callback in onsubmit is named by concatenating "validate_" and form's id attribute.

<?php echo form_tag('comment/update', array('id'=>'editComment','onsubmit' => 'return validate_editComment()')) ?>
 

Each field must be somehow identified in the resulting error message. We achieve this by adding some extra information to <action>.yml configuration file.

# define labels for erroneous fields
labels:
  <field_id>: <field_label_text>
 

There is a limitation to validation *.yml file structure. The syntax should be something like this:

# define labels for erroneous fields
labels:
  author: Author
  email: E-mail
  body: Body
 
fields:
  author:
    required:
      msg: The name field cannot be left blank
  email:
    sfEmailValidator:
      email_error: The email address is not valid.
  body:
    required:
      msg: The text field cannot be left blank
 
fillin:
  enabled:       on
 

And finally, don't forget to place jsValidator into /web/js folder, and include it in view.yml

<actionTemplate>:
  javascripts: [jsvalidator]
 

Feel free to modify the snippet code and validator to achieve best results!

by Alex Oroshchuk on 2007-12-04, tagged helper  javascript  validation 
(1 comment)

Delayed javascript page redirect

In order to delay a page redirect with several seconds, I wrote this simple helper

<?php
  use_helper('Javascript');
 
  /**
   * Adds javascript code to delay a page redirect
   *
   * @param string 'module/action' or '@rule' of the action (same argument as url_for())
   * @param int time of delay in seconds. Default = 5
   * @return JavaScript tag for delayed page redirect
   */
  function delayed_redirect($internal_uri, $time = 5)
  {
    sfContext::getInstance()->getResponse()->addJavascript(sfConfig::get('sf_prototype_web_dir').'/js/prototype');
    $code = 'new PeriodicalExecuter(function() { location.href=\''.url_for($internal_uri).'\';}, '.$time.')';
 
    return javascript_tag($code);
  }
 

See http://www.symfony-project.com/book/1_0/07-Inside-the-View-Layer#Adding%20Your%20Own%20Helpers for information on how to add your own helper

by wtreur on 2007-10-04, tagged helper  javascript  redirect 

Make Your Dynamic Page States Bookmarkable

I've found this to be a pretty good solution for the dynamic page state v. bookmarking conflict that prevents users from bookmarking a specific state of your dynamic page. Typically, if a general user bookmarks your page after spending some time interacting with its dynamic features, she will be disappointed to find her bookmark doesn't reflect the state of the page when she bookmarked it.

If your Javascript is built in a way that you can hijack the window's onLoad handler to initialize a custom state, based what fragment might be in the URI, you just might find this helper function useful.

JavascriptHelper.php

Save this to your project or application's /lib/helper folder.

<?php
 
require_once(sfConfig::get('sf_symfony_lib_dir') . '/helper/JavascriptHelper.php');
 
/**
 * An alternative to the sf default link_to_function.
 * 
 * Adds logic to onclick's concat'd "; return false;" so it only shows up if 
 * the value of the href option doesn't include a #fragment. If no fragment is
 * embedded in the href it is set to "javascript:void(0)" a la Google. 
 * 
 * With the "; return false;" absent, the fragment will show up in the 
 * browser's address bar, and will be included if the user copies the link or 
 * bookmarks the current state of your dynamic page. You can then add a bit of 
 * logic to your window initialization Javascript to detect any fragments in 
 * the URL and adjust the onLoad state accordingly.
 * 
 * @author  Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * @version tested on symfony 1.0.3
 * @see     link_to_function()
 * 
 * @param   string $name
 * @param   string $function
 * @param   mixed $options
 * 
 * @return  string
 */
function my_link_to_function($name, $function, $options = array())
{
    $options = _parse_attributes($options);
 
    $has_href = isset($options['href']);
 
    if(!isset($options['href']))
    {
        $options['href'] = 'javascript:void(0)';
    }
    $options['onclick'] = $function;
 
    if(!$has_href || strpos($options['href'], '#') === false)
    {
        $options['onclick'] .= '; return false;';
    }
 
    return content_tag('a', $name, $options);
}
by Kris Wallsmith on 2007-06-08, tagged helper  javascript 
(2 comments)

AJAX Degredation Helper that creates
tags with fragments inside

This helper creates a div tag tag into which links can call other actions and dynamically display its output via AJAX. When JS is not enabled, the links reload the page with GET parameters and allow this helper to load the output.

What do you think of this code? First of all, has it already been done before? And do you think it will actually be useful? How well does it conform to the MVC structure?

Actual code:

<?php
/**
 * This file includes functions that assist in making AJAX degradable
 *
 * These small helper functions add in some of the basic features that allow for degradable
 * JS. The idea is to dynamically load contents when JS is available and let the page reload with
 * appropriate html when JS is not.
 * @author Yining Zhao
 * @package YZ_Helpers
 * @subpackage AJAX_Degredation
 * @since 1/16/2007
 */
 
/**
 * This class creates a pair of <div> tags in which AJAX functions can input dynamic HTML.
 *
 * Usually what happends is that a link is pressed to activate the AJAX command via its onClick method.
 * The HREF attribute is suppressed by a 'return false;' at the end of the onClick method. However
 * when JS is not available, the onClick method is not activated and thus the HREF is called. The 
 * link in the HREF reloads the page and uses GET to pass along the variables to load the designated
 * fragment.
 *
 * If the $trigger_var is 'login_box', here is what the following GET parameters will do:
 *      login_box_display will load the fragment if it is set to 'on', otherwise div style = visibility:none and nothing is loaded
 *          e.g. URL: www.website.com/file.php?login_box_display=on //will load fragment
 *
 *      login_box_make_persistant will let set login_box_display to 'on' in the user session, so as long as
 *          login_box_make_persistant is not set to 'no', the fragment will automatically be loaded on every page 
 *          load regardless of the GET statement
 *          e.g. URL: www.website.com/file.php?login_box_make_persistant=on //will load fragment on every page load
 * 
 * Sample usage of function:
 *      //This function is being called from listSuccess.php template file in my Post module    
 *      div_fragment_creater('login_box','partial','loginPartial',array('referer'=>$referer),array('id'=>'login_div_id'))
 *
 * The source: {@source} 
 *
 * @param string $trigger_var The variable passed via GET that determines if the partial is loaded
 * @param string $fragment_type This tells the function if you are using a partial or a component
 * @param string $fragment_filename The name of the fragment to be called
 * @param array $fragment_values_ary This passes in the values for the fragment
 * @param array $div_attr_ary This contains all the html attributes for the <div> tag
 * @return void Since this function is designed to echo the necessary html, return is void
 */
function div_fragment_creater($trigger_var,$fragment_type, 
                                    $fragment_filename,$fragment_values_ary,$div_attr_ary)
{
    $sf_user=sfContext::getInstance()->getUser()->getAttributeHolder();
    $sf_params=sfContext::getInstance()->getRequest()->getParameterHolder();
    //If in the GET there is a make_persistant command for the given trigger variable, then the display command for the
    //tigger is set for sessions
    if($sf_params->get($trigger_var.'_make_persistant')=='on')
    {
        $sf_user->set($trigger_var.'_display','on');
    } else if($sf_params->get($trigger_var.'_make_persistant')=='off')
    {
        $sf_user->remove($trigger_var.'_display');
        $sf_params->remove($trigger_var.'_display');
    }
    //If the display is set for the trigger in either sf_params or sf_user, display the fragment.
    //Otherwise, don't display the fragment and make the div attribute style = display:none
    $output_fragment=false;
    if(($sf_params->get($trigger_var.'_display')=='on')||($sf_user->get($trigger_var.'_display')=='on'))
    {
        $output_fragment=true;
 
    } else
    {
        $div_attr_arry['style'] = 'display:none';
    }
 
    $div_attr_keys = array_keys($div_attr_ary);
    $div_attr_ary_size = count($div_attr_keys);
    $div_attr='';
    $div_attr_collection='';
    //Cteates the attributes for the <div>
    for($i=0;$i<$div_attr_ary_size;$i++)
    {
        //This creates a string where the div attribute is set to its corresponding value; e.g. id=5
        $div_attr_name = $div_attr_keys[$i];
        $div_attr_collection.=$div_attr_name . ' = "' . $div_attr_ary[$div_attr_name] . '" ';
    }
    echo '<div '.$div_attr_collection.' >';
    if($output_fragment==true)
    {
        switch($fragment_type)
        {
            case 'partial':
                echo include_partial($fragment_filename, $fragment_values_ary);
                break;
            case 'component':
                use_component($fragment_filename, $fragment_values_ary);
                break;
        }
    }
    echo '</div>';
}
?>

Usage Example: In myApp/myModule/list.php:

<body>
Anything is possible...
<?php 
//Creates div with id = myDiv. Usually this div is invisible and empty. But when the get or session variable of triggerVar_display is set to 'on', this div becomes visible and displays the whatsPossiblePartial partial file.
div_fragment_creater('triggerVar','partial','whatsPossiblePartial',array('id'=>$id),array('id'=>'myDiv'))
 
//Provides link to load action into myDiv. If JS is not enabled, link will reload page with triggerVar_display set to 'on'
 
echo link_to_remote('Click To See Whats Possible', array(
            'url'=>'MyModule/WhatPossible?id='.$value,
            'update'=>array('success' => 'myDiv'),
            'loading'=>"Element.show('indicator')",
            'complete'=>visual_effect('blind_down','myDiv',array('duration'=>0.5))';',
            ),          array('href'=>'list?triggerVar_display=on'));
?>
</body>

Inside the whatPossibleSuccess.php:

<html> ...
<?php 
//This file is basically just a wrapper for the whatsPossiblePartial. the reason I have this wrapper is so that I can access it from via link_to_remote() on other pages.
echo include_partial(whatsPossiblePartial,array('id'=>$this->id));
?>
...
</html>
by whoknows on 2007-01-18, tagged ajax  degradation  helper  javascript 

Helper for Javascript Tabbed Panes

I figured I'd post this little helper for using the tabbed pane JS from http://webfx.eae.net/dhtml/tabpane/tabpane.html in your templates.

Simply download the JS package from the site above and place it in your web/js folder. I chose to move the css files from the JS folder to my CSS folder, but you can do whatever you like.

tabsHelper.php

<?php
/**
 * Helper for Javascript Tabbed Panes
 * 
 * Example Usage
 * <code>
 *  <?php use_helper('tabs') ?>
 *  <?php tabMainJS("tp1","tabPane1", "tabPage1", 'General');?>
 *            This is text of tab 1. This is text of tab 1. This is text of tab 1. 
 *      <?php tabPageOpenClose("tp1", "tabPage2", 'Security');?>
 *            This is text of tab 2. This is text of tab 2. This is text of tab 2. 
 *  <?php tabInit();?>
 * </code>
 * 
 * @package    Helpers
 * @author     Jason Ibele
 * @version    SVN: $Id: tabsHelper.php 4 2006-07-19 14:00:47Z jason.ibele $
 */
 
$response = sfContext::getInstance()->getResponse();
$response->addJavascript('tab/tabpane.js');
$response->addStylesheet('tab/tab.webfx.css');
 
/**
 * Opens a new TabPane object and creates first tab
 *
 * @param string $mid         JavaScript variable name to use for webFXTabPane object
 * @param string $id          Main container div ID
 * @param string $page_id     Name for div ID, each needs to be unique
 * @param string $H2_title    The title for the tab
 * @param string $main_class  Optional class name for main Div (note this must match original class definitions)
 * @param string $page_class  Optional class name for page Div (note this must match original class definitions)
 */
function tabMainJS($mid, $id, $page_id, $H2_title, $main_class='tab-pane', $page_class='tab-page')
{
  echo '<div class="'.$main_class.'" id="'.$id.'">'."\n\t";
  echo '<script type="text/javascript">'."\n\t";
  echo $mid.' = new WebFXTabPane( document.getElementById( "'.$id.'" ) );'."\n\t";
  echo '</script>'."\n\t";
  echo '<div class="'.$page_class.'" id="'.$page_id.'">'."\n\t";
  echo '<h2 class="tab">'.$H2_title.'</h2>'."\n\t";
  echo '<script type="text/javascript">'.$mid.'.addTabPage( document.getElementById( "'.$page_id.'" ) );</script>'."\n";
}
 
/**
 * Closes and existing pane div and opens a new one with required JS
 *
 * @param string $mid         JavaScript variable to use for webFXTabPane object
 * @param string $page_id     Name for div ID, each needs to be unique
 * @param string $H2_title    The title for the tab
 * @param string $page_class  Optional class name for page Div (note this must match original class definitions)
 */
function tabPageOpenClose($mid, $page_id, $H2_title, $page_class='tab-page')
{
  echo '</div>'."\n\t";
  echo '<div class="'.$page_class.'" id="'.$page_id.'">'."\n\t";
  echo '<h2 class="tab">'.$H2_title.'</h2>'."\n\t";
  echo '<script type="text/javascript">'.$mid.'.addTabPage( document.getElementById( "'.$page_id.'" ) );</script>'."\n";
}
 
/**
 * Initiates the javascript for tabs and closes the remaining divs
 *
 * @param string $mid    JavaScript variable to use for webFXTabPane object
 * @param string $n      selected index of tab you want to force as set
 */
function tabInit($mid='', $n='')
{
  echo "\t".'</div>'."\n\t";
  echo '<script type="text/javascript">'."\n\t";
  echo 'setupAllTabs();'."\n\t";
 
  if($n){ // n = selected index of tab you want to force as set
    echo $mid.'.setSelectedIndex('.$n.');';
  }
 
  echo '</script>'."\n";
  echo '</div>'."\n";
}
 
?>

template

<?php use_helper('tabs') ?>
 
 
 
 
 
<!-- open the first tab -->
<?php tabMainJS("tp1","tabPane1", "tabPage1", 'General');?><!-- General is the name of the tab -->
 
          This is text of tab 1. This is text of tab 1. This is text of tab 1. 
 
 
<!-- second tab -->     
    <?php tabPageOpenClose("tp1", "tabPage2", 'Security');?> <!-- Security is the name of the tab -->
 
          This is text of tab 2. This is text of tab 2. This is text of tab 2. 
 
 
<!-- third tab -->      
    <?php tabPageOpenClose("tp1", "tabPage3", 'Example');?> <!-- Example is the name of the tab -->
 
          This is text of tab 3. This is text of tab 3. This is text of tab 3.
 
 
<!-- close tabs and initiate the JS -->
<?php tabInit();?>
by Jason Ibele on 2006-07-31, tagged helper  javascript  tabs 
(1 comment)

Popup tooltips

http://www.symfony-project.com/trac/ticket/540

Helper to work with http://tooltip.crtx.org Tooltip.js library (small js library that is using prototype and script.aculo.us, and so is the perfect match for symfony).

You will need to put that file into /helper/ directory, and put Tooltip.js (which you can get at the above-mentioned url) to the /sf/js/prototype/ directory.

Example of usage:

<?php use_helper('Tooltip') ?>
 
<?php echo tooltips_js('autoMoveToCursor=false showEvent=click', 'appear=true blindDown=true', 'blindUp=true', array('style.position' => 'absolute'), array('style.position' => 'absolute')) ?> 
 
<div id="some_id">some text</div>
 
<?php echo tooltip_div('some_id', 'css_class', array('style' => 'visibility: hidden'))?>
  Tooltip text.
</div>

Code is "phpdocumentor ready".

TooltipHelper.php as follows

<?php
 
require_once(sfConfig::get('sf_symfony_lib_dir').'/helper/JavascriptHelper.php');
 
 
/*
 * This file is part of the symfony package.
 * (c) 2006 Dmitry Parnas <parnas@rock.zp.ua>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
 
/**
 * TooltipsHelper.
 *
 * @package    symfony
 * @subpackage helper
 * @author     Dmitry Parnas <parnas@rock.zp.ua>
 * @version    
 */
 
/*
   Helpers to work with Tooltip.js [http://tooltip.crtx.org]
 */
 
 
/**
 * Builds open div tag ready with inforamtion for Tooltip.js
 *
 * Example:
 * <code>
 *   <?php echo tooltip_div('my_element_id', 'css_class_for_it', array('style' => 'visibility: hidden')) ?>
 * </code>
 *
 * @param string HTML id of the element this tooltip is for
 * @param css_class CSS class to skin tooltip in (if not default)
 * @param array Other attributes for the tag. You can also pass string suitable for _parse_attributes()
 *
 * @return string An HTML div string
 *
 */
function tooltip_div($element_id, $css_class = '', $options = array())
{                                                                                                                       
  $response = sfContext::getInstance()->getResponse();
  $response->addJavascript('/sf/js/prototype/prototype');
  $response->addJavascript('/sf/js/prototype/effects');
  $response->addJavascript('/sf/js/prototype/Tooltip');
 
  $options = _parse_attributes($options);
 
  $options['class'] = $css_class.' tooltip for_'.$element_id;
 
  return tag('div', $options, true);
}
 
 
 
/**
 * Builds script that sets optional settings for tooltips on the page.
 *
 * Example:
 * <code>
 *   <?php echo tooltips_js('autoMoveToCursor=false showEvent=click', 'appear=true blindDown=true', 'blindUp=true', array('style.position' => 'absolute'), array('style.position' => 'absolute')) ?>
 * </code>
 *
 * @param array Tooltip.js settings. You can also pass string suitable for _parse_attributes()   
 * @param array Ordered list of script.aculo.us effects you want to apply during tooltip show process. You can also pass string suitable for _parse_attributes()
 * @param array Ordered list of script.aculo.us effects you want to apply during tooltip hide process. You can also pass string suitable for _parse_attributes()
 * @param array Other settings for tooltip show process. You can also pass string suitable for _parse_attributes()
 * @param array Other settings for tooltip hide process. You can also pass string suitable for _parse_attributes()
 *
 * @return string An HTML script string.
 *
 */
function tooltips_js($options = array(), $show_effects = array(), $hide_effects = array(), $show_options = array(), $hide_options = array())
{
  $response = sfContext::getInstance()->getResponse();
  $response->addJavascript('/sf/js/prototype/prototype');
  $response->addJavascript('/sf/js/prototype/effects');
  $response->addJavascript('/sf/js/prototype/Tooltip');
 
 
  $options      = _parse_attributes($options);
  $show_effects = _parse_attributes($show_effects);
  $hide_effects = _parse_attributes($hide_effects);
  $show_options = _parse_attributes($show_options);
  $hide_options = _parse_attributes($hide_options);
 
  $code = '';
 
  foreach($options as $key => $value)
  {
    $value = _method_option_to_s($value);
 
    $value = (is_bool($value)) ? ($value === false) ? 'false' : 'true' : $value;
 
    $code .= '  Tooltip.'.$key.' = '.$value."\n";
  }
 
  $code .= _build_functions('show', $show_effects, $show_options);
  $code .= _build_functions('hide', $hide_effects, $hide_options);
 
  return javascript_tag($code);
}
 
 
function _build_functions($type, $effects = array(), $options = array())
{
  $code = '';
 
  if($effects) // there is no reason to build showMethod if there is no effects defined
  {
    $code .= '  Tooltip.'.$type.'Method = function (tooltip, options)'."\n";
    $code .= '  {'."\n";
 
    foreach($effects as $key => $value)
    {
      $code .= '    Effect.'.ucfirst($key).'(tooltip, options)'."\n";
    }
 
    if($options)
    {
      foreach($options as $key => $value)
      {
        $value = _method_option_to_s($value);
 
        $value = (is_bool($value)) ? ($value === false) ? 'false' : 'true' : $value;
 
        $code .= '    tooltip.'.$key.' = '.$value."\n";
      }
    }
 
    $code .= '  }'."\n";
 
    return $code;
  }
 
}
 
?>
by Adam Clarke on 2006-05-27, tagged helper  javascript  popup  tooltip 
(7 comments)