Sunday, 30 December 2012

Get all the required fields of sObject dynamically?


There is no direct property available in Apex dynamic API to represent the required field. However there is another way to know about it.
If any field have below three properties then it is mandatory field.
  1. If it is Creatable
  2. If it is not nillable and
  3. If it does not have any default value
Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(so.apiName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
List<String> lstrequiredfields=new List<String>();

for(String f : fields.keyset())
{
 Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
 if( desribeResult.isCreateable()  && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
 {
//This is mandatory / required field
      lstrequiredfields.add(f);

 }
}

Getting All fields from an object using dynamic apex


Here in the following snippet

Schema.getGlobalDescribe() returns the map with all sobject types in our org

By using this we can get Sobject type based on api name of object as in second line of snippet.

After getting the sobject type we can get the all the describe result of that object using "getDescribe()" method as in the third line of snippet.

Then we can get all field from that object by using "fields.getMap" as in the the
fourth line of snippet.



Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get('API_Name_Of_SObject') ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;

Create instance of sobject dynamically

Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime,then how we handle it .By using dynamic apex we handle it.
See the following snippet.


public SObject getNewSobject(String t)
{

 // Call global describe to get the map of string to token.
 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

 // Get the token for the sobject based on the type.
 Schema.SObjectType st = gd.get(t);

 // Instantiate the sobject from the token.
 Sobject s = st.newSobject();

 return s;
}

Wednesday, 26 December 2012

Getting Childrelationships from an object using dynamic Apex


If an sObject is a parent object, you can access the child relationship as well as the child sObject using the ChildRelationship object methods.
A ChildRelationship object is returned from the sObject describe result using the getChildRelationship method. For example:

Schema.DescribeSObjectResult   describeresult = Account.SObjectType.getDescribe();//it gives Account  object properties or describe results
List<Schema.ChildRelationship>   lstchildrelationships =describeresult.getChildRelationships(); //It gives you all the childrelationships associated with the account.
To get relationship names from the above list
for(Schema.ChildRelationship relname:lstchildrelationships){
      System.debug('Relationshipname:'+relname.getrelationshipname();
}
Limitation:
You can only use 100getChildRelationships method calls per Apex request.

The following table describes the methods available as part of the ChildRelationship object. None of the methods take an argument.
NameData TypeDescription
getChildSObjectSchema.SObjectTypeReturns the token of the child sObject on which there is a foreign key back to the parent sObject.
getFieldSchema.SObjectFieldReturns the token of the field that has a foreign key back to the parent sObject.
getRelationshipNameStringReturns the name of the relationship.
isCascadeDeleteBooleanReturns true if the child object is deleted when the parent object is deleted, false otherwise.
isDeprecatedAndHiddenBooleanReserved for future use.
isRestrictedDeleteBooleanReturns true if the parent object can't be deleted because it is referenced by a child object, false otherwise.



Thursday, 13 December 2012

Dynamic Apex Example

Here i am going to explain a simple example for dynamic apex.


Here  we have page with a picklist containing all the objects in org.When we select an object from it then it navigates to you to insertion page of selected  object otherwise it simply shows the fields in pageblock table  on visualforce page.

Controller for this page
===================
//This is class for Displaying All objects in picklist
public class AllObjDynamicDisplayClass{

   /* public PageReference fields() {
        return null;
    }*/


    //public String objectName { get; set; }

    public String ren { get; set; }
    public PageReference Fields() {
         Schema.SObjectType gd;
          Schema.DescribeSobjectResult a11;
        if(selectedObj!=null){
              gd = Schema.getGlobalDescribe().get(selectedObj);
              a11=gd.getDescribe();
        }
        pagereference pg;
      //here we are comparing the selected object is creatable or not
        if(a11.isCreateable() && a11.isAccessible() && a11.isDeprecatedAndHidden()==false && a11.isQueryable() && a11.isSearchable())
        pg=new Pagereference('/'+a11.getKeyPrefix()+'/e?');
        return pg;
    }
//we are returning the fields from selected object if it is not creatable
   public List<Schema.SObjectField> getFields(){
    List<Schema.SObjectField> sss=new list<Schema.SObjectField>();
    if(selectedObj!=null){
    sss.clear();
    Schema.SObjectType gd = Schema.getGlobalDescribe().get(selectedObj);
    Schema.DescribeSobjectResult a11=gd.getDescribe(); 
    Map<String, Schema.SObjectField> M = a11.fields.getMap();
    for(Schema.SObjectField s1:m.values()){
        system.debug('----'+s1+'\n');
        sss.add(s1);
    }
   }
    return sss;
}
    public List<SelectOption> items { get; set; }
    public String selectedObj { get; set; }
    public AllObjDynamicDisplayClass(){
        List<Schema.sObjecttype> lst= Schema.getGlobalDescribe().values();//this is used for getting all the objects from org
        items= new List<SelectOption>();
        items.add(new SelectOption('','--None--'));
        for(Schema.sobjecttype s:lst){
       // if(String.valueOf(s).contains('__c'))
            items.add(new SelectOption(string.valueOf(s),String.valueOf(s)));
        }
    }
}

page
========

<apex:page controller="AllObjDynamicDisplayClass" sidebar="false">
    <apex:form >
        <apex:actionFunction action="{!fields}" name="fun"/>
        <apex:pageBlock >
            <apex:pageblockSection ></apex:pageblockSection>
             <apex:SelectList value="{!selectedObj}" size="1" onchange="fun()">
                 <apex:selectOptions value="{!items}"/>
             </apex:SelectList>
                  <apex:pageBlocktable value="{!Fields}" var="f" >
              <apex:column headerValue="{!selectedObj} Field Names" value="{!f}"/>
              </apex:pageBlocktable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
============================

Output:
======

Wednesday, 5 December 2012

Small story for great determination



As for determination, one should follow the example of the sparrow who lost her eggs in the waves of the ocean.


A sparrow laid her eggs on the shore of  the ocean, but the big ocean carried away the eggs on its waves. The sparrow became very upset and asked the ocean to return her eggs. The ocean did not even consider her appeal. So the sparrow decided to dry up the ocean. She began to pick out the water in her small beak, and everyone laughed at her for her impossible determination. The news of her activity spread, and at last Garuda, the gigantic bird carrier of Lord Vishnu, heard it. He became compassionate toward his small sister bird, and so he came to see the sparrow.Garuda was very pleased by the determination of the small sparrow, and he promised to help. Thus Garuòa at once asked the ocean to return her eggs lest he himself take up the work of the sparrow. The ocean was frightened at this, and returned the eggs. Thus the sparrow became happy by the grace of Garuda.  But if anyone follows the principles with great determination, the Lord(helping hand) will surely help, for God helps those who help themselves.

So ,Nothing is impossible in the world even the word impossible says i am possible.

All the best.

Saturday, 24 November 2012

Passing parameters from controller to another page


The following snippet is used for passing parameters from controller used in one visualforce page to another visualforce page.

PageReference pageref=new Pagereference('/apex/Attachmentoncustomobj'); 

pageref.getParameters().put('id',recid);

Attachmentoncustomobj  is the name of the page to which we want to send the parameters.


Accessing Fieldsets from Controller

Here i am trying to explain ,how to get field set in controller and how to get field values from a particular fieldset and display those fields in fieldset on visualforce page.

I am taking Account object for explainin this.

To get all the field sets in Account object
Schema.SObjectType.Account.fieldSets.getMap().keySet();

the above line gives you the set of field sets in Account object

Now to get the fields from a particular field set associated with Account object we need to write as shown below

Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()

here "balu131__account_fieldset" is the name of the Field set of Account.

the above line gives you the different properties of fields in that field set like getLabel,getfieldpath,getType etc.,
to get field name we need to use "getFieldPath" property.
the following snippet shows you how to hold the field names.
List<string> fieldnames=new List<string>();//this is a list preparing for holding the field names.

for(Schema.FieldSetMember  s:Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()){
fieldnames.add(s.getFieldPath()); //adding field names to list
}

Eg: Accessing field set in controller and displaying that on visualforce page
====
Controller
=======

public with sharing class Fieldsetclass1 {
public List<string> fieldnames{get;set;}
public Account actobj{get;set;}
public Fieldsetclass1(){
actobj=new Account();
fieldnames=new List<String>();
for(Schema.FieldSetMember s:Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()){
fieldnames.add(s.getFieldPath());

}
}
public pagereference save(){
insert actobj;
return new pagereference('/'+actobj.id);
}

}



Page
====

<apex:page controller="Fieldsetclass1" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:Commandbutton value="Save" action="{!save}" rerender="pbt"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:repeat value="{!fieldnames}" var="fname">
<apex:inputField value="{!actobj[fname]}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Output:
=====




Sunday, 21 October 2012

Dynamic Visualforce Components


Visualforce is primarily intended to be a static, markup-driven language that lets developers create a user interface that matches the Salesforce look-and-feel. However, there are occasions when it is necessary to programmatically create a page. Usually, this is to achieve complicated user interface behavior that is difficult or impossible with standard markup.
Dynamic Visualforce components offer a way to create Visualforce pages that vary the content or arrangement of the component tree according to a variety of states, such as a user’s permissions or actions, user or organization preferences, the data being displayed, and so on. Rather than using standard markup, dynamic Visualforce components are designed in Apex.
A dynamic Visualforce component is defined in Apex like this:
Component.Component_namespace.Component_name
For example, <apex:dataTable> becomes Component.Apex.DataTable.
The Standard Component Reference contains the dynamic representation for all valid Visualforce components.
Visualforce components that are dynamically represented in Apex behave like regular classes. Every attribute that exists on a standard Visualforce component is available as a property in the corresponding Apex representation with get and set methods. For example, you could manipulate the value attribute on an <apex:outputText> component as follows:
Component.Apex.OutputText outText = new Component.Apex.OutputText();
outText.value = 'Some dynamic output text.';
Consider using dynamic Visualforce components in the following scenarios:
  • You can use dynamic Visualforce components inside complex control logic to assemble components in combinations that would be challenging or impossible to create using equivalent standard Visualforce. For example, with standardVisualforce components, you typically control the visibility of components using the rendered attribute with the global IF() formula function. By writing your control logic in Apex, you can choose to display components dynamically with a more natural mechanism.
  • If you know that you’ll be iterating over objects with certain fields, but not specifically which objects, dynamic Visualforce components can “plug in” the object representation by using a generic sObject reference. 
Note:
====
Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your organization. Existing Visualforce pages shouldn’t be rewritten in a dynamic manner and, for most use cases, standard Visualforce components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt itself to user state or actions in ways that can’t be elegantly coded into static markup.

This tag acts as a placeholder for your dynamic Apex components. It has one required parameter—componentValue—which accepts the name of an Apex method that returns a dynamic component.
The following Visualforce components do not have dynamic Apex representations:
<apex:attribute>
<apex:component>
<apex:componentBody>
<apex:composition>
<apex:define>
<apex:dynamicComponent>
<apex:include>
<apex:insert>
<apex:param>
<apex:variable>
===========
Example
========
<apex:page controller="SimpleDynamicController">
    <apex:dynamicComponent componentValue="{!dynamicDetail}" /> 
</apex:page>

/* Controller */ 
    
public class SimpleDynamicController {

    public Component.Apex.Detail getDynamicDetail() {
        Component.Apex.Detail detail = new Component.Apex.Detail();
        detail.expressions.subject = '{!acct.OwnerId}';
        detail.relatedList = false;
        detail.title = false;
        return detail;
    }

    // Just return the first Account, for example purposes only 
    
    public Account acct {
        get { return [SELECT Id, Name, OwnerId FROM Account LIMIT 1]; }
    }
}

=================If you want to another example click on this link  Account Search page

Displaying Visualforce Components from Apex Class using DynamicComponent


Here i am trying to explain to display the visualforce components from apex class by using DynamicComponent Tag.

On every component we have

Dynamic Visualforce Notation in component reference for example


for <apex:inputField> we have Dynamic Visualforce Notation is Component.Apex.InputField
By using this type of notations i build search page for searching Account records by account name.
By using this we can control the visualforce components from Apex Class.

Controller:
=============
public with sharing class DynamicComponentExample11 {
    public DynamicComponentExample11(ApexPages.StandardController con) { }
    public string enterstring{get;set;}
    public List<Account> lstaccount{get;set;}
    public Component.Apex.SectionHeader getHeaderWithDueDateCheck() {
        date dueDate = date.newInstance(2011, 7, 4);
        boolean overdue = date.today().daysBetween(dueDate) < 0;

        Component.Apex.SectionHeader sectionHeader = new Component.Apex.SectionHeader();
        if (overdue) {
            sectionHeader.title = 'This Form Was Due On ' + dueDate.format() + '!';
            return sectionHeader;
        } else {
            sectionHeader.title = 'Form Submission';
            return sectionHeader;
        }
    }
 
    Public List<Account> getAccounts(){
     
        if(enterstring!=null && enterstring!='')
            lstaccount=[select id,name,type,industry from account where name like:enterstring+'%'];
        else
            lstaccount=[select id,name,type,industry from account];
        return lstaccount;
 
    }
    public void search1(){
        getAccounts();
     
    }


 public Component.Apex.PageBlock getpageBlock(){
        Component.Apex.PageBlock pb=new Component.Apex.PageBlock();
        Component.Apex.PageBlockTable  ptable=new Component.Apex.PageBlockTable();
        Component.Apex.OutputLabel optlabel=new Component.Apex.OutputLabel();
        Component.Apex.CommandButton cmdbtn=new Component.Apex.CommandButton();
        cmdbtn.value='Search';
        cmdbtn.expressions.action='{!search1}';
        optlabel.value='Enter Name';
        Component.Apex.Inputtext intext=new Component.Apex.InputText();
        intext.id='searchtext';
        intext.expressions.value='{!enterstring}';
        optlabel.for='intext';
        ptable.expressions.value='{!accounts}';
        ptable.var='a';
        if(enterstring!=null && enterstring!='')
         ptable.rendered=true;
        else
         ptable.rendered=false;
        Component.Apex.Column namecolumn=new Component.Apex.Column();
        namecolumn.expressions.value='{!a.name}';  
        Component.Apex.Column industrycolumn=new Component.Apex.Column();
        industrycolumn.expressions.value='{!a.Industry}';
        Component.Apex.Column typecolumn=new Component.Apex.Column();
        typecolumn.expressions.value='{!a.type}';
        pb.childcomponents.add(optlabel);
        pb.childcomponents.add(intext);
        pb.childcomponents.add(cmdbtn);
        pb.childcomponents.add(ptable);
        ptable.childcomponents.add(namecolumn);
        ptable.childcomponents.add(typecolumn);
        ptable.childcomponents.add(industrycolumn);
        return pb;
    }
}
=====================
Visualforce page
============================

<apex:page standardcontroller="Account" extensions="DynamicComponentExample11">
    <apex:form >
           <apex:dynamicComponent componentValue="{!pageBlock}"/>
    </apex:form>
</apex:page>

=======================
Output:
======




Wednesday, 15 August 2012

Handling Recursive Calling in Trigger


Here  i wrote two triggers on account and contact  with names called continsert on account and accountupdate  on contact


in continsert trigger i am inserting contact with name of Account  at the time of update

in accountupdate trigger i am updating account  at the time of contact insertion


See the below triggers:
-------------------------------------
1)Trigger on Account to insert a contact when account is update

trigger continsert on Account (after update) {
        List<contact> lstcontact=new List<Contact>();
       for(Account acc:Trigger.new){
               Contact cnt=new Contact();
               cnt.lastname=acc.name;
               cnt.accountid=acc.id;
               lstcontact.add(cnt);     
       }
       if(lstcontact!=null && lstcontact.size()>0){
                             insert lstcontact;
                        
        }
}

2)Trigger on Contact to update the account when contact is inserted

trigger accountupdate on Contact (after insert) {
    List<Account> lstaccount=new List<Account>();
    for(Contact c:Trigger.new){
            if(c.accountid!=null){
                Account acc=new Account(id=c.accountid);
                acc.description='contact is created with name:'+c.lastname;
                lstaccount.add(acc);
            }
   
    }
    if(lstaccount!=null && lstaccount.size()>0){
                     update lstaccount;
       }

}


Now when i am  trying to insert contact  then account will update  then continsert on account is also fired with accountupdate on contact because here in accountupdate trigger we are updating account.
When i am trying to update an account then contact is inserting then accountupdate on contact is alsos fired with continsert trigger on account because here in continsert trigger we are inserting contact.

So it throws an error and it is because of recursive calling.

To Avoid or Remove the recursive calling from above  triggers  please follow the following instructions
=========================================================================

So to avoid recurive calling we need to write a class with static boolean variable and use it at the DML statements on both triggers.

see the below code for recursiveavoid class with boolean variable and modified triggers by using boolean variable at the DML statements.

Please use the same as i am  explaining in your recurive trigger Message update and Autotaskupdate some thing

class with boolean variable:
===================
public class recursiveavoid{
    public static boolean recursive=false;
}

See the below triggers:
-------------------------------------
1)Trigger on Account to insert a contact when account is update

trigger continsert on Account (after update) {
        List<contact> lstcontact=new List<Contact>();
       for(Account acc:Trigger.new){
               Contact cnt=new Contact();
               cnt.lastname=acc.name;
               cnt.accountid=acc.id;
               lstcontact.add(cnt);     
       }
//Here i am using boolean variable  called "recursive" to avoid reursive calling from trigger to another trigger
       if(lstcontact!=null && lstcontact.size()>0 && recursiveavoid.recursive==false){
               recursiveavoid.recursive=true;
               insert lstcontact;
           
              
        }
}

2)Trigger on Contact to update the account when contact is inserted

trigger accountupdate on Contact (after insert) {
    List<Account> lstaccount=new List<Account>();
    for(Contact c:Trigger.new){
            if(c.accountid!=null){
                Account acc=new Account(id=c.accountid);
                acc.description='contact is created with name:'+c.lastname;
                lstaccount.add(acc);
            }
   
    }
//Here i am using boolean variable  called "recursive" to avoid reursive calling from trigger to another trigger
    if(lstaccount!=null && lstaccount.size()>0 && recursiveavoid.recursive==false){
            recursiveavoid.recursive=true;
            update lstaccount;                   
    }
 }

Thursday, 9 August 2012

Display Trigger names of selected objects

Hi,
I am trying to explain to show the trigger names for selected object from picklist on visualforce page.

For this i used Dynamic apex and Apextrigger object.

Controller:
------------
public  class Dynamicobjectstriggerspageclass {
    public boolean ren { get; set; }
    public List<apextrigger> Triggerss { get; set; }
    public List<SelectOption> items { get; set; }
    public String selectedObj { get; set; }
    Public List<SelectOption> trignames{get;set;}
    public string selectedtrigname{get;set;}
    public Dynamicobjectstriggerspageclass (){
        Triggerss=new List<apextrigger>();
        trignames=new List<selectoption>();
        List<Schema.sObjecttype> lst= Schema.getGlobalDescribe().values();
        items= new List<SelectOption>();
        items.add(new SelectOption('','--None--'));
        for(Schema.sobjecttype s:lst){
        //if(String.valueOf(s).contains('__c'))
            items.add(new SelectOption(string.valueOf(s),String.valueOf(s)));
        }
        items.sort();
    }  
    public void fun1(){
       
    }
    public List<selectoption> getapextriggers(){
    
        if(selectedObj!=null && selectedObj!=''){
               Triggerss=new List<apextrigger>();
               trignames=new List<selectoption>();     
        trignames.add(new SelectOption('','--None--'));
        for(ApexTrigger aptrig:[select id,name from apextrigger where TableEnumOrId=:selectedObj]){
             trignames.add(new SelectOption(aptrig.id,aptrig.name));
        }
        }
        return trignames;      
    }

}
--------------------------------------
Visualforce Page
---------------------------------------
<apex:page controller="Dynamicobjectstriggerspageclass">
<apex:form >
<apex:actionfunction name="fun" action="{!fun1}" rerender="trig"/>
  <apex:pageblock >
      <apex:outputText value="Object Name"/> &nbsp;
        <apex:SelectList value="{!selectedObj}" size="1" onchange="fun()">
          <apex:selectOptions value="{!items}"/>
           </apex:SelectList>
         <apex:outputpanel >
                <apex:outputText value="Trigger Name:"/>&nbsp;
                <apex:selectList value="{!selectedtrigname}" id="trig" multiselect="false" size="1">
                                <apex:selectoptions value="{!apextriggers}"/>
                </apex:selectList>
         </apex:outputpanel>
   </apex:pageblock>
  </apex:form>
</apex:page>

Wednesday, 1 August 2012

Retrieing all fields without specifying field names in SOQL Query

Hi,
I am trying to explain how to get all fields data from an sobject without specifying particular fields  in query(SOQL) in Apex.
Because we cannot use '*' symbol in SOQL query to retrieve all fields from an sobject as in oracle(sql) in Apex.For every field to query  in
sobject  we need to specify  field names.So in the case of selecting all fields we need to write all fields in SOQL ,to avoid this
the  dynamic SOQL preparation with all fields using dynamic apex snippet is helpful.
Here just we need to prepare a string with all fields using dynamic apex with comma separation and we  insert this in 'SOQL' query.


Map<String, Schema.SObjectField> M = Schema.SObjectType.Account.fields.getMap();
public List<sObject> lstaccount{get;set;}
 Public List<string> fieldlst{get;set;}
Public List<Schema.SobjectField> lstfields{get;set;}

string fieldnames=' ';
            fieldlst=new List<String>();
            fieldnamestoquery=new List<String>();
            for(Schema.SObjectField s:m.values()){
                    Schema.DescribeFieldResult sfield=s.getDescribe();
                    fieldnames+=s+',';  //Here we concatenating all field names with comma seperation for preparing SOQL query
                    lstfields.add(s);
                   fieldlst.add(string.valueof(sfield.getName()));//Field list contains apinames all fields of Account
            }
           
            fieldnames=fieldnames.substring(0,fieldnames.length()-1);//Fieldnames string contains all the fields with comma separation

            string query='select '+fieldnames+' from Account';//Here we are preparing string query(dynamic SOQL using "fieldnames" string)
            if(query!=null && query!='')
                    lstaccount=database.query(query);//Here we will get all field values from account.

Passing values of parameters to customcomponent from visualforce page

I am explaining here how to pass values from visualforce page to custom component.
To pass values from visualforce page we should have <apex:attribute> tag with name,type,assignto and description properties.
Now i am writing custom componet.
To write custom component we need to go setup->Appsetup->Develop->components
Apex components  starts with <apex:component> and ends with </apex:component>
eg:
==
<apex:component controller="controllerforcomponent">
    <apex:attribute name="sobjectname" type="string" assignTo="{!objectname}" required="true" description="for objectname storing"/>
    <apex:pageBlock >
        <apex:pageBlockTable value="{!records}" var="a">
            <apex:column value="{!a.id}"/>   
            <apex:column value="{!a['firstname']}"/>           
        </apex:pageBlockTable>   
    </apex:pageBlock>
</apex:component>
==========================================================================
controller
===========
public  class controllerforcomponent {
     public String objectname{get;set;}
     public LIst<sobject> lstData{get;set;}
     public String sQuery;
     public List<Sobject> getrecords(){
         sQuery ='';
         sQuery = sQuery + 'select id,firstname,lastname from ' + objectname;
         system.debug('squery:'+squery);
         lstdata = new LIst<Sobject>();
         lstdata = database.query(sQuery);
         if(lstData.size() != null && lstdata.size()>0)
             return lstdata;
         else
             return null;
     }
       
}
==========================================================================

=Here"name" property is useful for pass values to component from visualforce page.When we set the  value to "name" property value called sobjectname as shown below.

<apex:page sidebar="false" >
    <c:Mycustomcomponent sobjectname="user"/>
</apex:page>

 this "user" will pass to customcomponent through sobjectname and assignto string property  called " objectname"  through <apex:attribute> tag in  our controller called "controllerforcomponent".
Our business logic is writing in controller.


output for page with customcomponent:
===============================



What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...