function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pooja kasliwalpooja kasliwal 

Dynamically find data type of fields and compare them

Hi Everyone,
         There are four picklist one for source object , second for sourcefield( childobject.fieldname of source object) ,another for target object and one for target(childobject.fieldname of target object). now I want to validate sourcefield and target field by their type like type of source field could be anything and type of target field should be string because anything to string type conversion is possible.but I am unable to get type of both the fields.I tried something but its not working properly.Please sugget me how can I achieve it?
Here is the vf code:-

<apex:page controller="ObjectMapper1" sidebar="false" id="page" readOnly="true">
    <apex:form id="form">
        <apex:pageBlock >
             <apex:pageMessages ></apex:pageMessages>     
             <apex:pageBlockSection columns="5" id="pb">
                 <apex:pageBlockSectionItem >
                       <apex:outputLabel >Source Objects</apex:outputLabel>
                       <apex:selectList size="1" value="{!sourceobject}" id="selectobject">
                           <apex:selectOption itemvalue="--None--"/>
                           <apex:selectOptions value="{!source_objects}"/>
                           <apex:actionSupport event="onchange"  reRender="form" />
                       </apex:selectList>
                 </apex:pageBlockSectionItem>
                 
                 <apex:pageBlockSectionItem >
                      <apex:outputLabel >Source Field</apex:outputLabel>
                      <apex:selectList size="1" value="{!sourcefield}" id="selectfield" >
                            <apex:selectOption itemvalue="--None--"/>
                            <apex:selectOptions value="{!child_Objects}" />
                            <apex:actionSupport event="onchange" reRender="form"/>
                      </apex:selectList>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                      <apex:outputLabel >Target Object</apex:outputLabel>
                      <apex:selectList size="1" value="{!targetobject}" id="selectobject" >
                            <apex:selectOption itemvalue="--None--"/>
                            <apex:selectOptions value="{!target_objects}" />
                            <apex:actionSupport event="onchange" reRender="form"/>
                      </apex:selectList>
                </apex:pageBlockSectionItem>
              
                <apex:pageBlockSectionItem >
                      <apex:outputLabel >Target Field</apex:outputLabel>
                      <apex:selectList size="1" value="{!targetfield}" id="selectobject">
                            <apex:selectOptions value="{!child_target_Objects}"  />
                            <apex:actionSupport event="onchange"  reRender="form" action="{!error}"/>
                      </apex:selectList>
                </apex:pageBlockSectionItem>
                
                
            
                <apex:commandButton value="+" id="thebutton" action="{!AddRecord}" style="width:30px;height:20px" disabled="{!buttonDisable}"  reRender="form" />
            </apex:pageBlockSection>

            <apex:pageBlockTable value="{!objectwrapperlist}" id="bottomsection" var="objwrap" columns="5">
          
                  <apex:column headerValue="Source Object">
                      <apex:outputLabel value="{!objwrap.source_object}" />
                  </apex:column>
                  <apex:column headerValue="Source Field">
                      <apex:outputLabel value="{!objwrap.source_field}" />
                  </apex:column>
                  <apex:column headerValue="Target Object">
                      <apex:outputLabel value="{!objwrap.target_object}" />
                  </apex:column> 
                  
                      <apex:column width="5%">
                      <apex:outputLabel >
                          <apex:commandButton value="-" action="{!removeRecords}"   reRender="bottomsection"><apex:param name="val" assignTo="{!index}" value="{!objwrap.index_number}"/></apex:commandbutton>
                      </apex:outputLabel>
                  </apex:column>
        
              </apex:pageBlockTable> 
         </apex:pageblock> 
     </apex:form>
</apex:page>

Here is the controller:-
public class ObjectMapper1
 {

     public String target_object { get; set; }
  
     public String sourcefield { get; set; }
     public String sourceobject { get; set; }
     public Integer counter=0;
     public Integer index{get;set;}
     public string targetobject{get;set;}
     public string targetfield{ get; set; }
     boolean buttonDisable;
     Schema.DisplayType sourcefielddataType;
     Schema.DisplayType targetfielddataType;  
   
/*--------------------------------------------- Method For getting source object -------------------------------------*/   
    public selectoption[] getsource_objects()
        {
            selectoption[] source_objects = new selectoption[0];
            for (Schema.SObjectType obj: Schema.getGlobalDescribe().values()) 
                {
                    String name = obj.getDescribe().getName();
                    if (!obj.getDescribe().isCustomSetting() && obj.getDescribe().getRecordTypeInfos().size() > 0 && obj.getDescribe().isCreateable() &&!name.containsignorecase('history') && !name.containsignorecase('tag') && !name.containsignorecase('share') && !name.containsignorecase('feed')&& !name.containsignorecase('Announcement')&& !name.containsignorecase('CampaignMember')&& !name.containsignorecase('GroupRecord')&& !name.containsignorecase('ContentVersion')&& !name.containsignorecase('Macro')&& !name.containsignorecase('search'))
                    {
                        source_objects.add(new SelectOption(obj.getDescribe().getName(), obj.getDescribe().getLabel()));
                    }
                }
                 source_objects.sort();
                 return source_objects;
        }
        
        
   /*--------------------------------------------- Method For getting target objects ----------------------------------------------------*/ 
    public selectoption[] gettarget_objects()
        {
            selectoption[] target_objects = new selectoption[0];
            for (Schema.SObjectType obj: Schema.getGlobalDescribe().values()) 
                {
                    String name = obj.getDescribe().getName();
                    if (!obj.getDescribe().isCustomSetting() && obj.getDescribe().getRecordTypeInfos().size() > 0 && obj.getDescribe().isCreateable() &&!name.containsignorecase('history') && !name.containsignorecase('tag') && !name.containsignorecase('share') && !name.containsignorecase('feed')&& !name.containsignorecase('Announcement')&& !name.containsignorecase('CampaignMember')&& !name.containsignorecase('GroupRecord')&& !name.containsignorecase('ContentVersion')&& !name.containsignorecase('Macro')&& !name.containsignorecase('search'))
                    {
                        target_objects.add(new SelectOption(obj.getDescribe().getName(), obj.getDescribe().getLabel()));
                    }
                }
                 target_objects.sort();
                 return target_objects;
        }
   
/*--------------------------------------------- Method For getting related child_source_objects.fieldname ----------------------------------------------------*/
    public selectoption[] getchild_Objects() 
    {
         selectoption[] child_Objects = new selectoption[0];
         if(sourceobject == '--None--' || sourceobject == null )
         {
              child_Objects.add(new selectoption('--None--','--None--'));
         }
         else
         {
               map<string,string> childObjectsMap = new map<string,string>();
               map<string,schema.sobjecttype> describe = schema.getglobaldescribe(); // gives the map of all sobjects
               LIST<Schema.childRelationship> childobject = describe.get(sourceobject).getdescribe().getchildRelationships(); // gives the map of all sobjects name and add it to the list
               for(Schema.childRelationship child : childObject)
                {
                     childObjectsMap.put(child.getChildSObject().getDescribe().getName(),child.getChildSObject().getDescribe().getLabel());
                }
                for(string childs :childObjectsMap.keyset())
                {
                    if(!childs.containsignorecase('history') && !childs.containsignorecase('tag') && !childs.containsignorecase('share') && !childs.containsignorecase('feed'))
                    {
                         map<string,schema.sobjecttype> descibe = schema.getglobaldescribe(); // gives the map of all sobjects
                         if(descibe.containskey(childs)) 
                         {
                              map<string,schema.sobjectfield> fieldmap = descibe.get(childs).getdescribe().fields.getmap(); // gives the map of all the fields;
                              
 
                              for(string fieldname:fieldmap.keyset())
                              {
                                 child_Objects.add(new selectoption(childs+'.'+fieldname,childs+'.'+fieldname));
                              }
                            //sourcefielddataType = fieldMap.get(sourcefield).getDescribe().getType();
                                                                
}

                         }
                    }
                }
        
         return child_Objects;
    } 
    
    
/*-----------------------------------------------------method ----------------------------------------------*/
/*public static String getFieldType(String fieldName){
    // Assume that "sObjectName" is populated elsewhere
Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
 
Schema.DescribeSObjectResult r = t.getDescribe();
Schema.DescribeFieldResult f = r.fields.getMap().get(fieldName).getDescribe();
 
if (f.getType() == Schema.DisplayType.String){
    return 'String';
} // .... else if
 
return null;
}*/
 



/*--------------------------------------------- Method For getting related child_target_objects.fieldname ----------------------------------------------------*/
public selectoption[] getchild_target_Objects() 
    {
         selectoption[] child_target_Objects = new selectoption[0];
         if(targetobject== '--None--' || targetobject== null )
         {
              child_target_Objects.add(new selectoption('--None--','--None--'));
         }
         else
         {
               map<string,string> childObjectsMap = new map<string,string>();
               map<string,schema.sobjecttype> describe = schema.getglobaldescribe(); // gives the map of all sobjects
               LIST<Schema.childRelationship> childobject = describe.get(targetobject).getdescribe().getchildRelationships(); // gives the map of all sobjects name and add it to the list
               for(Schema.childRelationship child : childObject)
                {
                     childObjectsMap.put(child.getChildSObject().getDescribe().getName(),child.getChildSObject().getDescribe().getLabel());
                }
                for(string childs :childObjectsMap.keyset())
                {
                    if(!childs.containsignorecase('history') && !childs.containsignorecase('tag') && !childs.containsignorecase('share') && !childs.containsignorecase('feed'))
                    {
                         map<string,schema.sobjecttype> descibe = schema.getglobaldescribe(); // gives the map of all sobjects
                         if(descibe.containskey(childs)) 
                         {
                              map<string,schema.sobjectfield> fieldmap = descibe.get(childs).getdescribe().fields.getmap(); // gives the map of all the fields;
                              

                              for(string fieldname:fieldmap.keyset())
                              {
                                // targetfielddataType = fieldMap.get(targetfield).getDescribe().getType();
                                  child_target_Objects.add(new selectoption(childs+'.'+fieldname,childs+'.'+fieldname));
                              }
                         }
                    }
                }
         }
         return child_target_Objects;
    } 

    
    public pageReference AddRecord()
    {
        ObjectWrapper objwrapper= new ObjectWrapper();
        objwrapper.source_object=sourceobject; 
        objwrapper.source_field= sourcefield;
        objwrapper.target_object= targetobject;
        objwrapper.target_field= targetfield;
        objwrapper.index_number = counter++;
        objectwrapperlist.add(objwrapper);
        return null;
    }

/*--------------------------------------------- Method For Enable and disable '+' button ----------------------------------------------------*/
    public boolean getbuttonDisable()
    {
         if((sourceobject != null && sourceobject != '--None--') && (sourcefield != null && sourcefield != '--None--')&&(targetobject != null && targetobject!= '--None--')&&(targetfield != null && targetfield!= '--None--'))
         {
             buttonDisable = false;
         }
                
         else
         {     
             buttonDisable = true; 
         }
         return buttonDisable;
    }
/*------------------------------------------------ Method For displaying error message ----------------------------------------------------*/             
    public PageReference error() 
    {
    Schema.SObjectType t = Schema.getGlobalDescribe().get(sourceobject);
 
                                Schema.DescribeSObjectResult r = t.getDescribe();
                                Schema.DescribeFieldResult f = r.fields.getMap().get(sourcefield).getDescribe();
 
                                system.debug(f.getType());
        if(f.getType() == Schema.DisplayType.STRING)/*||
                (f.getType() == Schema.DisplayType.BOOLEAN)||
                    (f.getType() == Schema.DisplayType.DATETIME)||
                        (f.getType() == Schema.DisplayType.STRING)||
                            (f.getType() == Schema.DisplayType.CURRENCY)||
                                (f.getType() == Schema.DisplayType.DOUBLE)||
                                    (f.getType() == Schema.DisplayType.ADDRESS)||
                                        (f.getType() == Schema.DisplayType.PHONE)||
                                            (f.getType() == Schema.DisplayType.DATE)||
                                                (f.getType() == Schema.DisplayType.TEXTAREA)||
                                                    (f.getType() == Schema.DisplayType.ID)||
                                                        (f.getType() == Schema.DisplayType.URL)||
                                                            (f.getType() == Schema.DisplayType.EMAIL))*/
                                                                
                                                                     
                {
                 ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Source object and target object can not be same');
                 ApexPages.addMessage(myMsg); 
                }
        return null;
    }
                
    public list<ObjectWrapper> objectwrapperlist{get;set;} 
    // Constructor of the classs 
    public ObjectMapper1()
    {
          this.objectwrapperlist= new list<ObjectWrapper>();  
          ObjectWrapper objwrapper = new ObjectWrapper();
    } 
    
    public class ObjectWrapper
    {
          public string source_object{ get;set;}
          public string source_field{get;set;}
          public string target_object{get;set;}
          public string target_field{get;set;}
          public integer index_number{get;set;}
    }
      
/*---------------------------------------- this method is to remove the rows. -----------------------------------------------------------*/
    public PageReference removeRecords()
    {
          for(Integer i=0;i<objectwrapperlist.size();i++)
          {
                if(objectwrapperlist[i].index_number== index)//1 == 1
                {
                      objectwrapperlist.remove(i);
                }
          }
          counter--;
          return null;
    } 
   
}
pconpcon
This is a large of amount of code that is almost impossible for anyone on these boards to spend the time trying to figure exactly you are doing.  Is there a way you can reduce down your code (possibly just to an example Apex Class) that demonstrates what you are trying to do and where you are having problems.  Please include the field type definition of the fields you are using.  Also keep in mind that providing better context in your end goal may assist in find a better solution to your problem than providing code that you think is the best solution.

NOTE: When add code, please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.
pooja kasliwalpooja kasliwal
Thank you pcon , what I need is to validate source field and target field by its type. I am unable to get the type of source field and target field which I set. I have the logic to find out the type but its in a for loop , and everytime its overwrite its value and take last value. Please suggest me to find the type of source field and target field which I set everytime.
pconpcon
Again, the amount of code you have provided is too much to do anything with in this forum.  If you can provide a subset of Apex code that shows what you are trying to do then we can help you to determine what is wrong with your logic and help you move forward.