Saturday, July 28, 2012

POP UP:

POP UP:
This example shows how to display vf for a button as a pop up.You need jquery in your static resource before you  test this example.

<apex:page >
<apex:includeScript value="{!$Resource.jquery}" />
<apex:stylesheet value="{!URLFOR($Resource.jQuery_Colorbox, 'colorbox.css')}"/>
<apex:includeScript value="{!URLFOR($Resource.jQuery_Colorbox, 'jquery.colorbox-min.js')}" />
<!--<apex:includeScript value="{!URLFOR($Resource.jQueryUI189Start, 'js/jquery-ui-1.8.9.custom.min.js')}" />-->
<script src="../../soap/ajax/20.0/connection.js" type="text/javascript"></script>
<input class="btn" type="button" onclick="$.colorbox({href: '/apex/ScNdPoPuP',modal:true, width:330, overlayClose:false});" value="Complete" />
<input class="btn" type="button" onclick="$.colorbox({href: '/apex/ScNdPoPuP',modal:true, width:330, overlayClose:false});" value="Needs Attention" />
</apex:page>

DRAG & DROP :

DRAG & DROP :
This example shows instead of select list of values you can drag and drop as shown below

SF Drag Drop MultiSelect List Demo

======================================

Visual force page (DemoSfDragDropList)

<apex:page controller="DemoSFDragDropList">
 <apex:sectionHeader title="http://www.jitenderbhatia.com" subtitle="SF Drag Drop MultiSelect List Demo"/>
 <c:SFDragDropList list1="India;United States;France;Germany;Japan" outputFieldId="list_2_serialised"/>
 <div style="clear:both">
 <apex:form >
     <input type="hidden" id="list_2_serialised" name="list_2_serialised" value="{!list2FinalItems}"/>
     <apex:commandButton action="{!showSelectedItems}" reRender="selectedItems" value="Show Selected Value" status="status"/>
 </apex:form>
 <apex:actionStatus id="status" startText="Fetching..."></apex:actionStatus>
 <apex:outputPanel id="selectedItems">
     <i>{!list2FinalItems}</i>
 </apex:outputPanel>
 </div>
</apex:page>


Apex Class(DemoSFDragDropList)

public class DemoSFDragDropList{
    public string list2FinalItems{get;set;}
    public DemoSFDragDropList(){
        
    }
    
    public pagereference showSelectedItems(){
        list2FinalItems = ApexPages.currentpage().getParameters().get('list_2_serialised');
        return null;
    }
    
    @istest
    private static void testthis(){
        DemoSFDragDropList cont = new DemoSFDragDropList();
        cont.showSelectedItems();    
    }
}


SFDragDropList  (Visualforce Component)

<apex:component controller="SFDragDropListController">
<apex:attribute name="list1" description="values for list one" type="string" assignTo="{!list1}" required="true"/>
<apex:attribute name="list2" description="values for list two" type="string" assignTo="{!list2}"/>
<apex:attribute name="outputFieldId" description="values which is stored in target list, fill in given textbox" type="string" assignTo="{!outputFieldId}" required="true"/>
<c:BaseDragDropComponent />
<script>
$(function(){
    mychange = function ( $list ){
        $( '#{!outputFieldId}').val( $.dds.serialize( 'list_2' ) );
    }
    $('ul').drag_drop_selectable({
        onListChange:mychange
    });
    $( '#{!outputFieldId}').val( $.dds.serialize( 'list_2' ) );
});
</script>

<div class='panel'>
<h2>Source List</h2>
<ul id="list_1">
    <apex:repeat value="{!list1Items}" var="item">
        <li id="{!item}">{!item}</li>
    </apex:repeat>
</ul>
</div>

<div class='panel'>
<h2>Target List</h2>
<ul id="list_2">
    <apex:repeat value="{!list2Items}" var="item">
        <li id="{!item}">{!item}</li>
    </apex:repeat>
</ul>
</div>
</apex:component>
                   

public class SFDragDropListController{
    public string list1 {get;set;}
    public string list2 {get;set;}
    public SFDragDropListController(){
    }
    
    public List<string> getList1Items(){
        return list1 != null ? list1.split(';') : null;        
    }
    
    public List<string> getList2Items(){
        return list2 != null ? list2.split(';') : null;        
    }
    
    @istest
    private static void testthis(){
        SFDragDropListController cont = new SFDragDropListController();
        cont.getList1Items();    
        cont.getList2Items();    
    }
}


BaseDragDropComponent

<apex:component >
<style type='text/css'>
.panel {float:left;width:300px;margin:20px;}

.panel ul {
    list-style-type:none;
    border:1px solid #ccc;
    background:#e6e6e6;
    padding:20px;
    min-height:150px;
    width:200px;
}

.panel li {
    display:block;
    border:1px solid #999;
    background:#fff;
    width:140px;
    padding:5px 10px;
    margin-bottom:5px;
}

.dds_selected {
    background:#ffc;
}
.dds_ghost {
    opacity:0.5;
}
.dds_move {
    background:#cfc;
}
.panel .dds_hover {
    background:#fc9;
    border:3px dashed #c96;
}

.holder {
    border:3px dashed #333;
    background:#fff;
}

</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.3/jquery-ui.min.js'></script>
<script type='text/javascript'>
/**
 *   Multi-Select And Drag
 *
 *   Not elegant solution to this problem, but the problem, despite being easily
 *   desribed is not simple. This code is more a proof of concept, but should be
 *   extendable by anyone with the time / inclination, there I grant permission
 *   for it to be re-used in accodance with the MIT license:
 *
 *   Copyright (c) 2009 Chris Walker (http://thechriswalker.net/)
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a copy
 *   of this software and associated documentation files (the "Software"), to deal
 *   in the Software without restriction, including without limitation the rights
 *   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *   copies of the Software, and to permit persons to whom the Software is
 *   furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *   THE SOFTWARE.
 */
(function($){
    $.fn.drag_drop_selectable = function( options ){
        $.fn.captureKeys();
        var $_this = this;
        var settings = $.extend({},$.fn.drag_drop_selectable.defaults,options||{});
        return $(this).each(function(i){
            var $list = $(this);
            var list_id = $.fn.drag_drop_selectable.unique++;
            $.fn.drag_drop_selectable.stack[list_id]={"selected":[ ],"all":[ ]};//we hold all as well as selected so we can invert and stuff...
            $list.attr('dds',list_id);
            $.fn.drag_drop_selectable.settings[list_id] = settings;
            $list.find('li')
            //make all list elements selectable with click and ctrl+click.
            .each(function(){
                var $item = $(this);
                //add item to list!
                var item_id = $.fn.drag_drop_selectable.unique++;
                $item.attr('dds',item_id);
                $.fn.drag_drop_selectable.stack[list_id].all.push(item_id);
                $(this).bind('click.dds_select',function(e){
                    if($.fn.isPressed(CTRL_KEY) || ($.fn.drag_drop_selectable.stack[$.fn.drag_drop_selectable.getListId( $(this).attr('dds') )].selected.length == 1 && $(this).hasClass('dds_selected'))){
                        //ctrl pressed add to selection
                        $.fn.drag_drop_selectable.toggle(item_id);
                    }else{
                        //ctrl not pressed make new selection
                        $.fn.drag_drop_selectable.replace(item_id);
                    }
                }).bind('dds.select',function(){
                    $(this).addClass('dds_selected').addClass( $.fn.drag_drop_selectable.settings[$.fn.drag_drop_selectable.getListId($(this).attr('dds'))].selectClass );

                }).bind('dds.deselect',function(){
                    $(this).removeClass('dds_selected').removeClass( $.fn.drag_drop_selectable.settings[$.fn.drag_drop_selectable.getListId($(this).attr('dds'))].selectClass );;
                }).css({cursor:'pointer'});
            })
            //OK so they are selectable. now I need to make them draggable, in such a way that they pick up their friends when dragged. hmmm how do I do that?
            .draggable({
                 helper:function(){
                    $clicked = $(this);
                    if( ! $clicked.hasClass('dds_selected') ){
                        //trigger the click function.
                        $clicked.trigger('click.dds_select');
                    }
                    var list = $.fn.drag_drop_selectable.getListId($clicked.attr('dds'));
                    var $helper = $('<div dds_list="'+list+'"><div style="margin-top:-'+$.fn.drag_drop_selectable.getMarginForDragging( $clicked )+'px;" /></div>').append( $.fn.drag_drop_selectable.getSelectedForDragging( $clicked.attr('dds') ) );
                        $.fn.drag_drop_selectable.getListItems( list ).filter('.dds_selected').addClass($.fn.drag_drop_selectable.settings[list].ghostClass);
                    return $helper;
                 },
                 distance:5, //give bit of leeway to allow selecting with click.
                 revert:'invalid',
                 cursor:'move',
                 stop:function(e, ui){
                    var list = $.fn.drag_drop_selectable.getListId($clicked.attr('dds'));
                    $.fn.drag_drop_selectable.getListItems( list ).filter('.dds_selected').removeClass($.fn.drag_drop_selectable.settings[list].ghostClass);
                 }
            });
            $list.droppable({
                drop:function(e,ui){
                    var oldlist = parseInt(ui.helper.attr('dds_list'));
                    ui.helper.find('li.dds_selected').each(function(){
                        var iid = parseInt( $(this).attr('dds_drag') );
                        $.fn.drag_drop_selectable.moveBetweenLists( iid, oldlist, list_id );
                    });

                    //now call callbacks!
                    if( $.fn.drag_drop_selectable.settings[oldlist] && typeof($.fn.drag_drop_selectable.settings[oldlist].onListChange) == 'function'){
                        setTimeout(function(){ $.fn.drag_drop_selectable.settings[oldlist].onListChange( $('ul[dds='+oldlist+']') ); },50);
                    }
                    if( $.fn.drag_drop_selectable.settings[list_id] && typeof($.fn.drag_drop_selectable.settings[list_id].onListChange) == 'function'){
                        setTimeout(function(){ $.fn.drag_drop_selectable.settings[list_id].onListChange( $('ul[dds='+list_id+']') ); },50);
                    }


                },
                accept:function(d){
                    if( $.fn.drag_drop_selectable.getListId( d.attr('dds') ) == $(this).attr('dds')){
                        return false;
                    }
                    return true;
                },
                hoverClass:$.fn.drag_drop_selectable.settings[list_id].hoverClass,
                tolerance:'pointer'
            });
        });
    };
    $.fn.drag_drop_selectable.moveBetweenLists=function(item_id, old_list_id, new_list_id){
        //first deselect.
        $.fn.drag_drop_selectable.deselect(parseInt(item_id));
        //now remove from stack
        $.fn.drag_drop_selectable.stack[old_list_id].all.splice( $.inArray( parseInt(item_id),$.fn.drag_drop_selectable.stack[old_list_id].all ),1);
        //now add to new stack.
        $.fn.drag_drop_selectable.stack[new_list_id].all.push( parseInt(item_id) );
        //now move DOM Object.
        $('ul[dds='+old_list_id+']').find('li[dds='+item_id+']').removeClass($.fn.drag_drop_selectable.settings[old_list_id].ghostClass).appendTo( $('ul[dds='+new_list_id+']') );
    };
    $.fn.drag_drop_selectable.getSelectedForDragging=function(item_id){
        var list = $.fn.drag_drop_selectable.getListId( item_id );
        var $others = $.fn.drag_drop_selectable.getListItems( list ).clone().each(function(){
            $(this).not('.dds_selected').css({visibility:'hidden'});
            $(this).filter('.dds_selected').addClass( $.fn.drag_drop_selectable.settings[list].moveClass ).css({opacity:$.fn.drag_drop_selectable.settings[list].moveOpacity});;
            $(this).attr('dds_drag',$(this).attr('dds'))
            $(this).attr('dds','');
        });
        return $others;
    };
    $.fn.drag_drop_selectable.getMarginForDragging=function($item){
        //find this items offset and the first items offset.
        var this_offset = $item.position().top;
        var first_offset = $.fn.drag_drop_selectable.getListItems( $.fn.drag_drop_selectable.getListId( $item.attr('dds') ) ).eq(0).position().top;
        return this_offset-first_offset;
    }

    $.fn.drag_drop_selectable.toggle=function(id){
        if(!$.fn.drag_drop_selectable.isSelected(id)){
            $.fn.drag_drop_selectable.select(id);
        }else{
            $.fn.drag_drop_selectable.deselect(id);
        }
    };
    $.fn.drag_drop_selectable.select=function(id){
        if(!$.fn.drag_drop_selectable.isSelected(id)){
            var list = $.fn.drag_drop_selectable.getListId(id);
            $.fn.drag_drop_selectable.stack[list].selected.push(id);
            $('[dds='+id+']').trigger('dds.select');
        }
    };
    $.fn.drag_drop_selectable.deselect=function(id){
        if($.fn.drag_drop_selectable.isSelected(id)){
            var list = $.fn.drag_drop_selectable.getListId(id);
            $.fn.drag_drop_selectable.stack[list].selected.splice($.inArray(id,$.fn.drag_drop_selectable.stack[list].selected),1);
            $('[dds='+id+']').trigger('dds.deselect');
        }
    };
    $.fn.drag_drop_selectable.isSelected=function(id){
        return $('li[dds='+id+']').hasClass('dds_selected');
    };
    $.fn.drag_drop_selectable.replace=function(id){
        //find the list this is in!
        var list = $.fn.drag_drop_selectable.getListId(id);
        $.fn.drag_drop_selectable.selectNone(list);
        $.fn.drag_drop_selectable.stack[list].selected.push(id);
        $('[dds='+id+']').trigger('dds.select');
    };
    $.fn.drag_drop_selectable.selectNone=function(list_id){
        $.fn.drag_drop_selectable.getListItems(list_id).each(function(){
            $.fn.drag_drop_selectable.deselect( $(this).attr('dds') );
        });return false;
    };
    $.fn.drag_drop_selectable.selectAll=function(list_id){
        $.fn.drag_drop_selectable.getListItems(list_id).each(function(){
            $.fn.drag_drop_selectable.select( $(this).attr('dds') );
        });return false;
    };
    $.fn.drag_drop_selectable.selectInvert=function(list_id){
        $.fn.drag_drop_selectable.getListItems(list_id).each(function(){
            $.fn.drag_drop_selectable.toggle( $(this).attr('dds') );
        });return false;
    };
    $.fn.drag_drop_selectable.getListItems=function(list_id){
        return $('ul[dds='+list_id+'] li');
    };
    $.fn.drag_drop_selectable.getListId=function(item_id){
        return parseInt($('li[dds='+item_id+']').parent('ul').eq(0).attr('dds'));
    };
    $.fn.drag_drop_selectable.serializeArray=function( list_id ){
        var out = [];
        $.fn.drag_drop_selectable.getListItems(list_id).each(function(){
            out.push($(this).attr('id'));
        });
        return out;
    };
    $.fn.drag_drop_selectable.serialize=function( list_id ){
            return $.fn.drag_drop_selectable.serializeArray( list_id ).join(";");
    };

    $.fn.drag_drop_selectable.unique=0;
    $.fn.drag_drop_selectable.stack=[];
    $.fn.drag_drop_selectable.defaults={
        moveOpacity: 0.8, //opacity of moving items
        ghostClass: 'dds_ghost', //class for "left-behind" item.
        hoverClass: 'dds_hover', //class for acceptable drop targets on hover
        moveClass:  'dds_move', //class to apply to items whilst moving them.
        selectedClass: 'dds_selected', //this default will be aplied any way, but the overridden one too.
        onListChange: function(list){ console.log( list.attr('id') );} //called once when the list changes
    }
    $.fn.drag_drop_selectable.settings=[];


    $.extend({
        dds:{
                selectAll:function(id){ return $.fn.drag_drop_selectable.selectAll($('#'+id).attr('dds')); },
                selectNone:function(id){ return $.fn.drag_drop_selectable.selectNone($('#'+id).attr('dds')); },
                selectInvert:function(id){ return $.fn.drag_drop_selectable.selectInvert($('#'+id).attr('dds')); },
                serialize:function(id){ return $.fn.drag_drop_selectable.serialize($('#'+id).attr('dds')); }
            }
    });

    var CTRL_KEY = 17;
    var ALT_KEY = 18;
    var SHIFT_KEY = 16;
    var META_KEY = 92;
    $.fn.captureKeys=function(){
        if($.fn.captureKeys.capturing){ return; }
        $(document).keydown(function(e){
            if(e.keyCode == CTRL_KEY ){ $.fn.captureKeys.stack.CTRL_KEY  = true  }
            if(e.keyCode == SHIFT_KEY){ $.fn.captureKeys.stack.SHIFT_KEY = true  }
            if(e.keyCode == ALT_KEY  ){ $.fn.captureKeys.stack.ALT_KEY   = true  }
            if(e.keyCode == META_KEY ){ $.fn.captureKeys.stack.META_KEY  = true  }
        }).keyup(function(e){
            if(e.keyCode == CTRL_KEY ){ $.fn.captureKeys.stack.CTRL_KEY  = false }
            if(e.keyCode == SHIFT_KEY){ $.fn.captureKeys.stack.SHIFT_KEY = false }
            if(e.keyCode == ALT_KEY  ){ $.fn.captureKeys.stack.ALT_KEY   = false }
            if(e.keyCode == META_KEY ){ $.fn.captureKeys.stack.META_KEY  = false }
        });
    };
    $.fn.captureKeys.stack={ CTRL_KEY:false, SHIFT_KEY:false, ALT_KEY:false, META_KEY:false }
    $.fn.captureKeys.capturing=false;
    $.fn.isPressed=function(key){
        switch(key){
            case  CTRL_KEY: return $.fn.captureKeys.stack.CTRL_KEY;
            case   ALT_KEY: return $.fn.captureKeys.stack.ALT_KEY;
            case SHIFT_KEY: return $.fn.captureKeys.stack.SHIFT_KEY;
            case  META_KEY: return $.fn.captureKeys.stack.META_KEY;
            default: return false;
        }
    }
})(jQuery);

</script>
</apex:component>


Calendar Page:

Calendar Page:
This example shows how to select a calendar date and create your own tasks and events in the time of record creation .The controller looks as

public class repeatCon { public void next() { addMonth(1); } public void prev() { addMonth(-1); } public repeatCon() {   Date d = system.today(); // default to today Integer mo = d.month(); String m_param = System.currentPageReference().getParameters().get('mo'); String y_param = System.currentPageReference().getParameters().get('yr'); // allow a month to be passed in on the url as mo=10 if (m_param != null) { Integer mi = Integer.valueOf(m_param); if (mi > 0 && mi <= 12) { d = Date.newInstance(d.year(),mi,d.day()); } } // and year as yr=2008 if (y_param != null) { Integer yr = Integer.valueOf(y_param); d = Date.newInstance(yr, d.month(), d.day()); } setMonth(d); }  public List<Month.Week> getWeeks() { //system.assert(month!=null,'month is null'); return month.getWeeks(); } public Month getMonth() { return month; } private void setMonth(Date d) { month = new Month(d);   } private void addMonth(Integer val) { Date d = month.getFirstDate(); d = d.addMonths(val); setMonth(d); } private Month month;   public static testMethod void chkrepeatCon() {     repeatCon rCon = new repeatCon();         List<Month.Week> testWeeks = new List<Month.Week>();     testWeeks = rCon.getWeeks();          //system.assertequals(1,testWeeks.size());     Integer testVal = 1;     rCon.addMonth(testVal);      rCon.next();     rCon.prev();   }    static testmethod void getValidDateRange(){         Date myDate = date.newinstance(1960, 2, 17);         Month mnth = new Month(myDate);         List<Date> dateList = mnth.getValidDateRange();         system.assertEquals(dateList.size(), 2);     }     static testmethod void getMonthName(){         Date myDate = date.newinstance(1960, 2, 17);         Month mnth = new Month(myDate);         String monthName = mnth.getMonthName();         system.assertEquals(monthName ,'February' );     }           static testmethod void getYearName(){         Date myDate = date.newinstance(1960, 2, 17);         Month mnth = new Month(myDate);         String yearName = mnth.getYearName();         system.assertEquals(yearName , '1960' );     }     static testmethod void getWeekdayNames(){         Date myDate = date.newinstance(1960, 2, 17);         Month mnth = new Month(myDate);         String[] weekNames = mnth.getWeekdayNames();         system.assertEquals(weekNames.size(), 7 );     }     static testmethod void getDayClass(){         Date myDate = date.newinstance(1960, 2, 17);         Month.Day mnthDay = new Month.Day(myDate,2);        system.assertEquals(mnthDay.getDayOfYear(), 48 );         system.assertEquals(mnthDay.getFormatedDate(), '12 21 08' );         system.assertEquals(mnthDay.getDayNumber(), null );         system.assertEquals( mnthDay.getCSSName(), 'calActive');              }    }
also you need another class for calendar functions mentioned in the above class

public class Month { public List<Week> weeks; public Date firstDate; // always the first of the month private Date upperLeft; public List<Date> getValidDateRange() { // return one date from the upper left, and one from the lower right List<Date> ret = new List<Date>(); ret.add(upperLeft); ret.add(upperLeft.addDays(5*7) ); return ret; } public String getMonthName() { return DateTime.newInstance(firstDate.year(),firstdate.month(),firstdate.day()).format('MMMM'); } public String getYearName() { return DateTime.newInstance( firstDate.year(),firstdate.month(),firstdate.day()).format('yyyy'); } public String[] getWeekdayNames() { Date today = system.today().toStartOfWeek(); DateTime dt = DateTime.newInstanceGmt(today.year(),today.month(),today.day()); list<String> ret = new list<String>(); for(Integer i = 0; i < 7;i++) { ret.add( dt.formatgmt('EEEE') ); dt= dt.addDays(1); } return ret; } public Date getfirstDate() { return firstDate; } public Month( Date value ) { weeks = new List<Week>(); firstDate = value.toStartOfMonth(); upperLeft = firstDate.toStartOfWeek(); Date tmp = upperLeft; for (Integer i = 0; i < 5; i++) { Week w = new Week(i+1,tmp,value.month()); //system.assert(w!=null); this.weeks.add( w ); tmp = tmp.addDays(7); } } public List<Week> getWeeks() { //system.assert(weeks!=null,'could not create weeks list'); return this.weeks; } /* * helper classes to define a month in terms of week and day */ public class Week { public List<Day> days; public Integer weekNumber; public Date startingDate; // the date that the first of this week is on // so sunday of this week public List<Day> getDays() { return this.days; } public Week () { days = new List<Day>(); } public Week(Integer value,Date sunday,Integer month) { this(); weekNumber = value; startingDate = sunday; Date tmp = startingDate; for (Integer i = 0; i < 7; i++) { Day d = new Day( tmp,month ); tmp = tmp.addDays(1); d.dayOfWeek = i+1; // system.debug(d); days.add(d); } } public Integer getWeekNumber() { return this.weekNumber;} public Date getStartingDate() { return this.startingDate;} } public class Day { public Date theDate; public Integer month, dayOfWeek; public String formatedDate; // for the formated time private String cssclass = 'calActive'; public Date getDate() { return theDate; } public Integer getDayOfMonth() { return theDate.day(); } public String getDayOfMonth2() { if ( theDate.day() <= 9 ) return '0'+theDate.day(); return String.valueof( theDate.day()); } public Integer getDayOfYear() { return theDate.dayOfYear(); } public String getFormatedDate() { return formatedDate; } public Integer getDayNumber() { return dayOfWeek; } public String getCSSName() { return cssclass; } public Day(Date value,Integer vmonth) { theDate=value; month=vmonth; formatedDate = '12 21 08';// time range.. //9:00 AM - 1:00 PM // three possible Inactive,Today,Active if ( theDate.daysBetween(System.today()) == 0 ) cssclass ='calToday'; // define inactive, is the date in the month? if ( theDate.month() != month) cssclass = 'calInactive'; } } }
and the visualforce page is

<apex:page controller="repeatCon" id="thePage"  >
    <apex:stylesheet value="/sCSS/Theme2/default/homeCalendar.css" />
    
    <apex:form id="theForm">
         <apex:outputPanel id="theCalendar" >
         
            <div class="mCalendar" style="width:182px;" ><div class="topLeft" ><div class="topRight"/></div>
            <div class="body">
            <table cellspacing="0" cellpadding="2" border="0">
                <tbody>
                    <tr class="header">
                        <td><apex:commandLink action="{!prev}" rerender="theCalendar">
                            <img title="Previous Month" class="prevCalArrow" alt="Previous Month" src="/s.gif" />
                        </apex:commandLink></td>
                        <td colspan="5" >
                        {!month.monthname} {!month.yearname}
                        </td>
                        <td><apex:commandLink action="{!next}" rerender="theCalendar">
                            <img title="Next Month" class="nextCalArrow" alt="Next Month"
                                src="/s.gif" />
                        </apex:commandLink></td>
                    </tr>
                    
                    <tr>
                        <th scope="col" class="calDays">Sun</th>
                        <th scope="col" class="calDays">Mon</th>
                        <th scope="col" class="calDays">Tue</th>
                        <th scope="col" class="calDays">Wed</th>
                        <th scope="col" class="calDays">Thu</th>
                        <th scope="col" class="calDays">Fri</th>
                        <th scope="col" class="calDays">Sat</th>
                    </tr>
                    
                    <apex:repeat value="{!weeks}" var="wk" id="foreachWeek">
                        <tr class="days">
                            <!-- or highlight -->
                            <apex:repeat value="{!wk.days}" var="day" id="foreachday">
                                <td valign="top"><a class="calActive"
                                    href="/00U/c?md0=2008&md3={!day.dayOfYear}" target="_self"
                                    title="Day View - {!day.date}">{!day.dayofmonth2}</a></td>
                            </apex:repeat>
                        </tr>
                    </apex:repeat>
                    
                </tbody>
            </table>
            </div>
            <div class="bottomLeft"><div class="bottomRight"/></div>
            </div>
            
            </apex:outputPanel>
        </apex:form>
</apex:page>
                                    


REST API:

REST API:
This article shows how to use webservice callout by REST API.The first thing you need to make your destination url in remote site settings.In this example i call my own domain destination so you can try same with your domain since it will ask permission before you call your destination and you need to allow the source first time call.So the destination gave response by creating some target class like this

@RestResource(urlMapping='/GetService/*')   global with sharing class getservice1 {       @HttpGet      global static String getRestMethod()      {           RestRequest req = RestContext.request;         RestResponse res = RestContext.response;         String name = req.params.get('name');         return 'Hello '+name+', you have just invoked a custom Apex REST web service exposed
 using REST API' ;     } }

Once you finish your destination response now come back to your source and try establish call out from source like this

public abstract class OAuthRestController {
    static String clientId = '3MVG9zeKbAVObYjM0ERpVyn5vpvdS7P0qclqomMNsU03lguvoqJl5TRRSiee5lFk__5w2.4jvZzvGxJs2biQ3'; // Set this in step 3
    static String clientSecret = '7933821080022371323'; // Set this in step 3
    static String redirectUri = 'https://rajkumar-dev-ed.my.salesforce.com/apex/RestCall'; // YOUR PAGE URL IN THE SOURCE ORG
    static String loginUrl = 'https://kakumanu-dev-ed.my.salesforce.com/'; // YOUR MY DOMAIN URL IN THE TARGET ORG
    static String cookieName = 'oauth';

    public PageReference login() {
        // Get a URL for the page without any query params
        String url = ApexPages.currentPage().getUrl().split('\\?')[0];
     
        System.debug('url is '+url);

        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
        if (oauth != null) {
            // TODO - Check for expired token
        }
     
        System.debug('oauth='+oauth);
        if (oauth != null) {
            // All done
            return null;
        }
     
        // If we get here we have no token
        PageReference pageRef;
     
        if (! ApexPages.currentPage().getParameters().containsKey('code')) {
            // Initial step of OAuth - redirect to OAuth service
            System.debug('OAuth Step 1');
     
            String authuri = loginUrl+'/services/oauth2/authorize?'+
                'response_type=code&client_id='+clientId+'&redirect_uri='+redirectUri;
                         
            pageRef = new PageReference(authuri);
        } else {
            // Second step of OAuth - get token from OAuth service
            String code = ApexPages.currentPage().getParameters().get('code');

            System.debug('OAuth Step 2 - code:'+code);
             
            String body = 'grant_type=authorization_code&client_id='+clientId+
                '&redirect_uri='+redirectUri+'&client_secret='+clientSecret+
                '&code='+code;
            System.debug('body is:'+body);
             
            HttpRequest req = new HttpRequest();
            req.setEndpoint(loginUrl+'/services/oauth2/token');
            req.setMethod('POST');
            req.setBody(body);
     
            Http h = new Http();
            HttpResponse res = h.send(req);
 
            String resp = res.getBody();
            System.debug('FINAL RESP IS:'+EncodingUtil.urlDecode(resp, 'UTF-8'));
         
            ApexPages.currentPage().setCookies(new Cookie[]{new Cookie(cookieName,
                res.getBody(), null,-1,false)});
             
            // Come back to this page without the code param
            // This makes things simpler later if you end up doing DML here to
            // save the token somewhere
            pageRef = new PageReference(url);
            pageRef.setRedirect(true);
        }
     
        return pageRef;
    }
 
    public static String getRestTest() {
        String oauth = (ApexPages.currentPage().getCookies().get(cookieName) != null ) ?
            ApexPages.currentPage().getCookies().get(cookieName).getValue() : null;
        JSONObject oauthObj = new JSONObject( new JSONObject.JSONTokener(oauth));
         
        String accessToken = oauthObj.getValue('access_token').str,
               instanceUrl = oauthObj.getValue('instance_url').str;

        HttpRequest req = new HttpRequest();

        req.setMethod('GET');
        req.setEndpoint(instanceUrl+'/services/apexrest/GetService/getservice1?name=Kumar');
        req.setHeader('Authorization', 'OAuth '+accessToken);

        Http http = new Http();

        HTTPResponse res = http.send(req);

        System.debug('BODY: '+res.getBody());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
     
        return res.getBody();
    }
}


for the above example you need your source org client id and client that you can get by creating a simple remote access from your app setup.This example is sending a name (kumar) to the destination org and getting some message as a response from target.So time for displaying response on visualforce like this

<apex:page controller="OAuthRestController" action="{!login}" showHeader="true">
  <h1>Rest Test</h1>
  getRestTest says "{!restTest}"
</apex:page>

Friday, July 27, 2012

Multiple Attachments:

Multiple Attachments:
This article about multiple attachments for any related list attachments of either custom or standard objects.

public with sharing class MultiAttachmentController 
{
    // the parent object it
    public Id sobjId {get; set;}
    
    // list of existing attachments - populated on demand
    public List<Attachment> attachments;
    
    // list of new attachments to add
    public List<Attachment> newAttachments {get; set;}
    
    // the number of new attachments to add to the list when the user clicks 'Add More'
    public static final Integer NUM_ATTACHMENTS_TO_ADD=5;

    // constructor
    public MultiAttachmentController()
    {
        // instantiate the list with a single attachment
        newAttachments=new List<Attachment>{new Attachment()};
    }   
    
    // retrieve the existing attachments
    public List<Attachment> getAttachments()
    {
        // only execute the SOQL if the list hasn't been initialised
        if (null==attachments)
        {
            attachments=[select Id, ParentId, Name, Description from Attachment where parentId=:sobjId];
        }
        
        return attachments;
    }

    // Add more attachments action method
    public void addMore()
    {
        // append NUM_ATTACHMENTS_TO_ADD to the new attachments list
        for (Integer idx=0; idx<NUM_ATTACHMENTS_TO_ADD; idx++)
        {
            newAttachments.add(new Attachment());
        }
    }    
    
    // Save action method
    public void save()
    {
        List<Attachment> toInsert=new List<Attachment>();
        for (Attachment newAtt : newAttachments)
        {
            if (newAtt.Body!=null)
            {
                newAtt.parentId=sobjId;
                toInsert.add(newAtt);
            }
        }
        insert toInsert;
        newAttachments.clear();
        newAttachments.add(new Attachment());
        
        // null the list of existing attachments - this will be rebuilt when the page is refreshed
        attachments=null;
    }
    
    // Action method when the user is done
    public PageReference done()
    {
        // send the user to the detail page for the sobject
        return new PageReference('/' + sobjId);
    }
    
    /******************************************************
     *
     * Unit Tests
     *
     ******************************************************/
     
    private static testMethod void testController()
    {
        Account acc=new Account(Name='Unit Test');
        insert acc;
        MultiAttachmentController controller=new MultiAttachmentController();
        controller.sobjId=acc.id;
        
        System.assertEquals(0, controller.getAttachments().size());
        
        System.assertEquals(1, controller.newAttachments.size());
        
        controller.addMore();
        
        System.assertEquals(1 + NUM_ATTACHMENTS_TO_ADD, controller.newAttachments.size());
        
        // populate the first and third new attachments
        List<Attachment> newAtts=controller.newAttachments;
        newAtts[0].Name='Unit Test 1';
        newAtts[0].Description='Unit Test 1';
        newAtts[0].Body=Blob.valueOf('Unit Test 1');

        newAtts[2].Name='Unit Test 2';
        newAtts[2].Description='Unit Test 2';
        newAtts[2].Body=Blob.valueOf('Unit Test 2');
        
        controller.save();
        
        System.assertEquals(2, controller.getAttachments().size());
        System.assertNotEquals(null, controller.done());
    }
}
and the component looks like that
<apex:component controller="MultiAttachmentController" allowDML="true">
    <apex:attribute name="objId" type="String" description="The id of the object to manage attachments for" required="true" assignTo="{!sobjId}"/>
    <apex:form id="attForm">
        <apex:pageBlock title="Upload Attachments">
            <apex:repeat value="{!newAttachments}" var="newAtt">
                <apex:pageBlockSection columns="3">
                   <apex:pageBlockSectionItem >
                        <apex:outputLabel value="File"/>                         
                        <apex:inputFile value="{!newAtt.body}" filename="{!newAtt.name}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Description"/>                      
                        <apex:inputText value="{!newAtt.Description}"/>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
            </apex:repeat>
            <apex:commandButton value="Add More" action="{!addMore}"/>
            <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandButton value="Done" action="{!done}"/>
        </apex:pageBlock>
    </apex:form>
    <apex:pageBlock title="Existing Attachments">
        <apex:pageBlockTable value="{!attachments}" var="attachment">
            <apex:column headerValue="Action">
               <apex:outputLink value="{!URLFOR($Action.Attachment.Download, attachment.Id)}" target="_blank">View</apex:outputLink>
            </apex:column>
            <apex:column value="{!attachment.Name}"/>
            <apex:column value="{!attachment.Description}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:component>

<apex:page showHeader="True" sidebar="true">
    <c:MultiAttachment objId="{!$CurrentPage.Parameters.id}"/> 
</apex:page>

 




NEW EVENT:

NEW EVENT:
This article about How to create a visualforce page for event using custom controller.

public class EventController {
public string valcid{get; set;}
    public EventController(ApexPages.StandardController controller) {
        EventCheck();
    }
public Account Acc{get; set;}
public Event event{get; set;}
public Contact con{get; set;}

    public void EventCheck()
    {
    event=new Event();
    Acc=new Account();
    Contact cont=new Contact();
     String selectedAccId = System.currentPageReference().getParameters().get('what_id');
     if(selectedAccId !=null)
     {
    // System.debug('@@@@@@@@@@@@'+selectedAccId );
     Acc=[Select id,Name from Account where id=:selectedAccId];
     event.whatid='00190000006MsiI';
 //   event.ownerid=UserInfo.getUserId();
 event.ownerid='00590000000lvzt';
   // event.Location=Acc.Name;
    event.StartDateTime=System.Now().addHours(1);
    event.EndDateTime=System.Now().addHours(2); 
  }
   String selectedConId = System.currentPageReference().getParameters().get('who_id');
   if(selectedConId !=null)
   {
    // System.debug('@@@@@@@@@@@@'+selectedAccId );
     
    Cont=[Select id from Contact where id=:selectedConId ];
    event.ownerid=UserInfo.getUserId();
    event.StartDateTime=System.Now().addHours(1);
    event.EndDateTime=System.Now().addHours(2); 
   }
  
    }
Public void GetVal()
{
//System.debug('@@@@@@@@@@@@Entered GetVal**************');
con=[Select LastName,MailingStreet from contact where id=:valcid];
event.description=con.LastName ;
event.location=con.MailingStreet;
}
public Pagereference saveEvent()
{
insert event;
String returnurl='/'+event.whatid;
Pagereference seekerpage=new PageReference(returnurl);  
return seekerpage; 
}
 public Pagereference cancelEvent()
{

String cancelurl='/'+event.whatid;
Pagereference backpage=new PageReference(cancelurl);  
return backpage; 
}  
}

and the VFP looks like this
<apex:page standardController="Event" tabStyle="Event" label="New Event" extensions="EventController">
  <apex:form id="myform" >
  <script>
  function call(nm,n)
  {
  document.getElementById('j_id0:myform:EventPage:Contctid').value=document.getElementById('j_id0:myform:EventPage:Calender:contact_txt_lkid').value;
 }
  function GetVal()
  {
  
  }
  </script>
  <apex:pageBlock id="EventPage" tabStyle="Event">
  <apex:inputHidden id="Contctid" value="{!valcid}"/>
  <apex:actionFunction action="{!GetVal}" name="GetVal" reRender="Description,loc_txt"></apex:actionFunction> 
   <apex:pageBlockButtons title="Event Edit" dir="Event Edit" >
  <apex:commandButton id="SaveEvent" value="Save" Action="{!saveEvent}"/>
  <apex:commandButton id="CancelEvent" value="Cancel" Action="{!cancelEvent}"/>
  </apex:pageBlockButtons>
 <apex:pageBlockSection id="Calender" title="Calendar Details" collapsible="false"  showHeader="true" columns="2"  >
   <apex:inputfield id="assignto_txt" value="{!event.ownerid}" />
   <apex:inputfield id="loc_txt" value="{!event.location}"/>
   <apex:inputfield id="subject_txt" required="true" value="{!event.Subject}"/> 
   <apex:inputfield id="start_txt" value="{!event.StartDateTime}"/>
  <apex:inputfield id="contact_txt" value="{!event.whoid}" onblur="call('{!$Component.myform.EventPage.Calender.contact_txt}','{!$Component.myform.EventPage.Calender.contact_txt_lkid}');GetVal();"/>
  <apex:inputfield id="end_txt" value="{!event.EndDateTime}"/>
   <apex:inputfield id="whoto_txt" value="{!event.whatid}" />
   <apex:inputfield id="allday_txt" value="{!event.IsAllDayEvent}"/>
  </apex:pageBlockSection>
  <apex:pageBlockSection id="Description" title="Description Information" collapsible="false"  showHeader="true" columns="1"  >
   <apex:inputfield id="description_txt" value="{!event.description}" />
    </apex:pageBlockSection>
    <apex:pageBlockSection id="Recurrence" title="Recurrence" collapsible="false"  showHeader="true" columns="1">
    
   
   <div>
   <apex:inputfield id="IsRecurrence"  value="{!event.IsRecurrence}" onclick="ActivityFunction.selectMakeRecurring('IsRecurrence','evt15','evt4','StartDateTime','EndDateTime');" />


 <apex:inputfield id="RecurrenceType" value="{!event.RecurrenceType}"/>&nbsp;&nbsp;<apex:inputfield id="RecurrenceDayOfMonth" value="{!event.RecurrenceDayOfMonth}"/>
   
   <div id="recpat" style="">
<table width="100%">
<tbody>
<tr>
<td class="labelCol">
<label>Frequency</label>
</td>
<td>
<table class="recurrenceTable">
<tbody>
<tr>
<td>
<div>
<div>
<input checked="checked" id="rectypeftd" name="rectype" onclick="ActivityFunction.adjustRecurrenceFrequency('d');" type="radio" value="ftd"/>
<label for="rectypeftd">Daily</label></div>
<div>
<input id="rectypeftw" name="rectype" onclick="ActivityFunction.adjustRecurrenceFrequency('w');ActivityFunction.setDayOfWeekDefault('RecurrenceStartDateTime');" type="radio" value="ftw"/>
<label for="rectypeftw">Weekly</label></div>
<div>
<input id="rectypeftm" name="rectype" onclick="ActivityFunction.adjustRecurrenceFrequency('m');" type="radio" value="ftm"/>
<label for="rectypeftm">Monthly</label></div>
<div>
<input id="rectypefty" name="rectype" onclick="ActivityFunction.adjustRecurrenceFrequency('y');" type="radio" value="fty"/>
<label for="rectypefty">Yearly</label></div></div>
</td>
<td>
<div class="periodElementGroup" id="d" style="display:">
<div><input checked="checked" id="recdd0" name="recd" title="Recurs every weekday" type="radio" value="d0"/>
<label for="recdd0">Every weekday</label></div>
<div>
<input id="recdd1" name="recd" title="Specify interval in days" type="radio" value="d1" /><label for="recdd1">
</label>Every 
<input id="di" name="di" onkeypress="document.getElementById('recdd1').checked=true;" size="3" title="specify interval in days" type="text" value="1"/> day(s)
</div>
</div>
<div class="periodElementGroup" id="w" style="display:none">
<div>Recurs every <input id="wi" name="wi" size="3" title="specify interval in weeks" type="text" value="1"/> week(s) on</div>
<div><input id="1" name="1" type="checkbox" value="1"/><label for="1">Sunday</label>
<input id="2" name="2" type="checkbox" value="1"/>
<label for="2">Monday</label><input id="4" name="4" type="checkbox" value="1"/><label for="4">Tuesday</label><input id="8" name="8" type="checkbox" value="1"/><label for="8">Wednesday</label><input id="16" name="16" type="checkbox" value="1"/><label for="16">Thursday</label><input id="32" name="32" type="checkbox" value="1"/><label for="32">Friday</label><input id="64" name="64" type="checkbox" value="1"/><label for="64">Saturday</label></div></div><div class="periodElementGroup" id="m" style="display:none"><div><input checked="checked" id="recmm0" name="recm" title="Specify number of days into month and monthly interval" type="radio" value="m0"/><label for="recmm0"></label>On day <select id="mdom" name="mdom" onchange="document.getElementById('recmm0').checked=true;" title="select day of the month"><option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select> of every <input id="mint" name="mint" onkeypress="document.getElementById('recmm0').checked=true;" size="3" title="specify interval in months" type="text" value="1"/> month(s)</div>
<div><input id="recmm1" name="recm" title="Specify which day of which week and the monthly interval" type="radio" value="m1"/>
<label for="recmm1"></label>On the 
<select id="mnins" name="mnins" onchange="document.getElementById('recmm1').checked=true;" title="select which week of the month">
<option value="1" selected="selected">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">last</option>
</select> 
<select id="mndow" name="mndow" onchange="document.getElementById('recmm1').checked=true;" title="select which day of the week">
<option value="127" selected="selected">day</option>
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="4">Tuesday</option>
<option value="8">Wednesday</option>
<option value="16">Thursday</option>
<option value="32">Friday</option>
<option value="64">Saturday</option>
</select> of every 
<input id="mnint" name="mnint" onkeypress="document.getElementById('recmm1').checked=true;" size="3" title="specify interval in months" type="text" value="1"/> 
month(s)</div></div>
<div id="y" style="display:none">
<div>
<input checked="checked" id="recyy0" name="recy" title="Specify month and day" type="radio" value="y0"/>
<label for="recyy0"></label>On every 
<select id="ymoy" name="ymoy" onchange="document.getElementById('recyy0').checked=true;" title="select the month">
<option value="0" selected="selected">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select> 
<select id="ydom" name="ydom" onchange="document.getElementById('recyy0').checked=true;" title="select day of the month">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select></div><div><input id="recyy1" name="recy" title="Specify day of particular week in a specific month" type="radio" value="y1"/>
<label for="recyy1"></label>On the 
<select id="ynins" name="ynins" onchange="document.getElementById('recyy1').checked=true;" title="select which week of the month">
<option value="1" selected="selected">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
<option value="5">last</option>
</select> <select id="yndow" name="yndow" onchange="document.getElementById('recyy1').checked=true;" title="select which day of the week">
<option value="127" selected="selected">day</option>
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="4">Tuesday</option>
<option value="8">Wednesday</option>
<option value="16">Thursday</option>
<option value="32">Friday</option>
<option value="64">Saturday</option>
</select> of <select id="ynmoy" name="ynmoy" onchange="document.getElementById('recyy1').checked=true;" title="select the month"><option value="0" selected="selected">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select></div></div></td></tr>
</tbody></table></td></tr>

</tbody></table></div>
   
   
   
    <apex:inputfield id="RecurrenceStartDateTime" value="{!event.RecurrenceStartDateTime}" required="true"/>
     <apex:inputfield id="RecurrenceEndDateOnly" value="{!event.RecurrenceEndDateOnly}" required="true"/>
  
   </div>
    </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
  <!--call('{!$Component.myform.EventPage.Calender.contact_txt}','{!event.whoid}');-->
</apex:page>


Sunday, July 22, 2012

Google Calendar Integration:

Google Calendar Integration:
It is simple to integrate google calendar with sfc.Watch this video enjoy the integration less than 5 mins.

Thursday, July 19, 2012

Outlook Integration With SFC:

Outlook Integration With SFC:
If you are looking for Administrator Setup for Salesforce for Outlook 2010 instructions please click on my previous blog ling where I explain that setup before an user can use this functionality.

Here is the scenario:
All business users have been migrated to Windows 7, 64 bit and Outlook 2010. They were utilizing the Outlook 2003/2007 on Windows XP or Windows 7 32 bit.
Now a plugin is required.

Solution:
   As an user, you need to perform the following task before you can utilize full functionality of Add Email and Create Case.
Step 1:
   Make sure your administrator has set up the configuration for your profile.

Step 2:
   Download the plugin. Navigate to: Setup | Personal Setup | Desktop Integration | Salesforce for Outlook
You should have 2 buttons:
View my Configuration <== this will be available only when your administrator has set you up.
Download <== Download the plugin.




Step 3:
  After downloading the Plugin, run the plugin but have outlook closed.

Step 4:
   After setting it up, log into Outlook & click on the Red Salesforce Icon on your desktop and login into Salesforce.
 Step 5:
   The login screen would appear for Outlook Plugin. You can change the URL to Production or Sandbox. Enter in your credentials and click on Login.
Step 6:
   The next screen would bring up "Salesforce for Outlook is requesting Permission to". Click on Allow. 
After clicking on Allow, it will bring up your configuration which the administrator of your instance has set you up for. Click OK.

Within Outlook, you will see 2 buttons "Add Email" & "Add Case".

Step 7:
For Add Email, your outlook email should be in Salesforce itself and this must be setup so that this functionality would work correctly.
Setup | Personal Setup | Email | My Email to Salesforce

Step 8:
   On this screen, please configure the following:

Under the section:
"My Acceptable Email Addresses"
   Make sure your full email address as it is setup in Outlook.

Step 9:
  Under the section: Email Associations
The following should be checked:
  • Always send them to My Unresolved Items
  • Always save email attachments <== (Salesforce will not take more then 10MB per attachment) 
  • Email me confirmation of association
  • Excluded Domains <== Empty 

Just a couple of Notes about Add Email from Outlook:

     Once you click Add Email from Outlook, Outlook will place the message on the header of the email sent to salesforce. The message will display "Sent to Salesforce.com"

An email from salesforce, will be emailed to your inbox stating that this task was successful.

To view your email you sent to salesforce, log into salesforce
https://login.salesforce.com
on the Home Page you will see a section on the left side "Shortcut".
Inside this section, "My Unresolved Items"
 Click on it.
Within this screen, you should see the email sent thru you outlook. You can assign this to an existing case. The section where it states "Assign to Salesforce.com Records" Click on Accounts drop down and select Case. Place it the number of the Case and click save.

It will be assign to the Case Number assigned and it will be in the Activities related list within the Case Page Layout.

Wednesday, July 18, 2012

URLFOR():


URLFOR():

This article about urlfor() structure and functionality.This is very useful function in salesforce.com


URLFOR function returns a relative URL using this syntax:
{!URLFOR(targetid, [inputs], [no override])}
targetYou can replace target with a URL or action, s-control or static resource
id: This is id of the object or resource name (string type) in support of the provided target.
inputsAny additional URL parameters you need to pass you can use this parameter.
you will to put the URL parameters in brackets and separate them with commas
ex: [param1="value1", param2="value2"]
no override: A Boolean value which defaults to false, it applies to targets for standard Salesforce pages.
 Replace "no override" with "true" when you want to display a standard Salesforce page regardless of
 whether you have defined an override for it elsewhere.
Obtaining URL of a s-control:


<!-- Use $SControl global veriable to reference your s-control and pass it to the URLFOR function -->
 <apex:outputLink value="{!URLFOR($SControl.MySControlName)}">Link to my S-Control</apex:outputLink> 


Obtaining URL of a Static Resource


<!-- Use $Resource global veriable to reference your resource file -->
<apex:image url="{!URLFOR($Resource.LogoImg)}" width="50" height="50" />

<!-- If your file is in another ZIP file, then pass the path of the file as id to URLFOR -->
<apex:image url="{!URLFOR($Resource.CorpZip, 'images/logo.gif')}" width="50" height="50" />



Obtaining URLs of an Object's Actions:
In order to get URL of the an object's actions you need to know what actions that object supports.
 Below are some of the common actions most Objects support:
  • View: Shows the detail page of an object
  • Edit: Shows the object in Edit mode
  • Delete: URL for deleting an object
  • New: URL to create a new record of an object
  • Tab: URL to the home page of an object
However, each object may support additional actions for example Contactalso supports "Clone"
 action and Case supports "CloseCase" action.
<!-- Use $Action global varialble to access the New action reference -->
<apex:outputLink value="{!URLFOR($Action.Account.New)}">New</apex:outputLink>
<br/>
<!-- View action requires the id parameter, a standard controller can be used to obtain the id -->
<apex:outputLink value="{!URLFOR($Action.Account.view, account.id)}">View</apex:outputLink> 
<br/>
<!-- Edit action requires the id parameter, id is taken from standard controller in this example -->
<apex:outputLink value="{!URLFOR($Action.Account.Edit, account.id)}">Edit</apex:outputLink>  
<br/>
<!-- Delete action requires the id parameter, also a confirm message is added to prevent deleting the record when clicked by mistake -->
<apex:outputLink value="{!URLFOR($Action.Account.delete, account.id)}" onclick="return window.confirm('Are you sure?');">Delete</apex:outputLink> 
<br/>
<!-- From all custom buttons, links, s-controls and visualforce pages you can use the following to get the link of the object's homepage -->
<apex:outputLink value="{!URLFOR($Action.Account.Tab, $ObjectType.Account)}">Home</apex:outputLink> 




Examples:



Files and folders:



Resource file:URLFOR($Resource.LogoImg)
Resource file in ZIP folder:URLFOR($Resource.CorpZip, 'images/logo.gif')
Note: The path to the file is case sensitive



Actions shared among all objects:



View record:URLFOR($Action.Account.View, account.id)
Create new record:URLFOR($Action.Account.New)
Edit record:URLFOR($Action.Account.Edit, account.id)
Delete record:URLFOR($Action.Account.Delete, account.id)
List view:URLFOR($Action.Account.Tab, $ObjectType.Account)

Note: Some objects support other additional actions, for example Case supports "CloseCase"
 action. To know which action can be used, check the buttons and links which can be overridden
 for an object (as shown on the next image), just use the name of the function like this:
 URLFOR($Action.Object.Name, …)