+ Start a Discussion
Dave The RaveDave The Rave 
Hi All,

Here is the change I am looking to make:

If fieldA (SortType_C) from CustomObject_C =  BLANK then change value of SortType_C to "Other"

I am a new administrator and learning fast, I managed to access the developer console but I am new to DML.

Can anyone help me with the code?

Thanks,

Dave The Rave
Best Answer chosen by Dave The Rave
Dave The RaveDave The Rave
The invalid query message is here "The query has to start with 'FIND' or 'SELECT'."

Just to be clear my object is called RealEstateObject__c
and my field is called SortRealEstate__c

Thanks Dave
ankita varma 3ankita varma 3 
Hi All, 
I have started learning Einstein Analytics recently, I want to create a new Dataflow in Analytics studio. I searched all the options and tabs but did not find create option for Dataflow, please help me out with this.
 
Best Answer chosen by ankita varma 3
Narender Singh(Nads)Narender Singh(Nads)
Abel PalmaAbel Palma 
I´m trying to make the test class of this, but I having problems, I have an error......System.StringException: Invalid id: Colaborador__c:{Id=a0Of4000003bHFxEAM}

this is my apex class
public class ActionColocarCls {
 @AuraEnabled
    public static Colaborador__c getAccountData (Id accountId){        
        Colaborador__c searchAcc = new Colaborador__c();
        searchAcc = [SELECT Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__C WHERE Id =: accountId];
        system.debug('Account: ' + searchAcc);
        return searchAcc;
    }
}

This is the test class that I´m doing 
@isTest
global class ActionColocarClsTest {
	
    
	@testSetup
    static void setup()	{
        Profile profileAdmin = [SELECT Id FROM Profile WHERE name = 'System Administrator'];
        UserRole roleAdmin=[SELECT Id FROM UserRole WHERE PortalType = 'None' Limit 1];
        User user_test=new User(UserRoleId = roleAdmin.Id, ProfileId = profileAdmin.Id,
                                Username='contactAdmin@deloitte.com',
                                Alias='Admin', Email = 'contactAdmin@deloitte.com',
                                
                                EmailEncodingKey = 'UTF-8', Firstname = 'test',
                                Lastname = 'user', languagelocalekey= 'en_US',
                                LocaleSidKey = 'en_Us', TimeZoneSidKey = 'America/Chicago');
        
        insert user_test;
        User userAdmin=[SELECT id FROM User WHERE email = 'contactAdmin@deloitte.com' LIMIT 1];
        System.runAs(userAdmin){
            
            Colaborador__c con = new Colaborador__c();               
                con.Name='Joe';   
				con.ApellidoMaterno__c='Vargas';
				con.ApellidoPaterno__c='Medina';            
                con.Empresa__c='Deloitte'; 
                con.Sector__c='Digital'; 
                con.Capability__c='SalesForce';
                con.Nivel__c='Analista';  
                
            insert con;                                                    
            Colaborador__c objCol =[SELECT id,Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__C];                 
               }
    }
     static testmethod void tesActionColocar(){
         Test.startTest();
         Colaborador__c objCol2 = [SELECT id FROM Colaborador__C LIMIT 1];         
         String accountId=String.valueOf(objCol2) ;              
         system.debug('resumen' + objCol2);
         ActionColocarCls.getAccountData(accountId);
         Colaborador__c objColaborador = [SELECT Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__c WHERE Id =:accountId];                                              
         system.debug('Taer records de colaboradores' +objColaborador);                                       
         Test.stopTest();
            }
}

 
Best Answer chosen by Abel Palma
Raj VRaj V
Use the below code . Below code was wrong 
Colaborador__c objCol2 = [SELECT id FROM Colaborador__C LIMIT 1];         
         String accountId=String.valueOf(objCol2.Id) ;


 
@isTest
global class ActionColocarClsTest {
	
    
	@testSetup
    static void setup()	{
        Profile profileAdmin = [SELECT Id FROM Profile WHERE name = 'System Administrator'];
        UserRole roleAdmin=[SELECT Id FROM UserRole WHERE PortalType = 'None' Limit 1];
        User user_test=new User(UserRoleId = roleAdmin.Id, ProfileId = profileAdmin.Id,
                                Username='contactAdmin@deloitte.com',
                                Alias='Admin', Email = 'contactAdmin@deloitte.com',
                                
                                EmailEncodingKey = 'UTF-8', Firstname = 'test',
                                Lastname = 'user', languagelocalekey= 'en_US',
                                LocaleSidKey = 'en_Us', TimeZoneSidKey = 'America/Chicago');
        
        insert user_test;
        User userAdmin=[SELECT id FROM User WHERE email = 'contactAdmin@deloitte.com' LIMIT 1];
        System.runAs(userAdmin){
            
            Colaborador__c con = new Colaborador__c();               
                con.Name='Joe';   
				con.ApellidoMaterno__c='Vargas';
				con.ApellidoPaterno__c='Medina';            
                con.Empresa__c='Deloitte'; 
                con.Sector__c='Digital'; 
                con.Capability__c='SalesForce';
                con.Nivel__c='Analista';  
                
            insert con;                                                    
            Colaborador__c objCol =[SELECT id,Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__C];                 
               }
    }
     static testmethod void tesActionColocar(){
         Test.startTest();
         Colaborador__c objCol2 = [SELECT id FROM Colaborador__C LIMIT 1];         
         String accountId=String.valueOf(objCol2.Id) ;              
         system.debug('resumen' + objCol2);
         ActionColocarCls.getAccountData(accountId);
         Colaborador__c objColaborador = [SELECT Name, Empresa__c, Sector__c, Capability__c,Nivel__c FROM Colaborador__c WHERE Id =:accountId];                                              
         system.debug('Taer records de colaboradores' +objColaborador);                                       
         Test.stopTest();
            }
}

 
Michael Hedrick 2Michael Hedrick 2 
Hello All,
I have a Class that performs a call out;
Global class CallTrexWebServiceAccountUpdate{
    
    public static Account accounts {get;set;}
    public static String myresponse{get;set;}

    webservice static string ABCWebServiceAccountUpdate(String id) {
    
        ABCWebServiceAccountUpdateAsync(id);
        return myresponse;        
    }


    @future(Callout=true)
      static void ABCWebServiceAccountUpdateAsync(String id)  
       {
       System.debug(id); 
           accounts = [SELECT id,Partner_Type__c FROM Account WHERE id =:id];
             if(id != null )
               {
                   HttpRequest req = new HttpRequest();
                   Http http = new Http();
                   req.setMethod('GET');
                            
                   String url = 'https://blabla/Services.asmx/UpdateAccount?accountId='+id;
                   req.setEndpoint(url);
            
                   HTTPResponse resp = http.send(req);
                   myresponse = resp.getBody();
             }
       }
    }

Have a test Class and this works fine.


I now have additional Apex triggers to deploy and now  its failing on the above Class.  The trigger I am deploying is related to the Cases.

The fatal error is on line :   HTTPResponse resp = http.send(req);
Methods defined as TestMethod do not support Web service callouts

And this code did deploy to production originally but I deployed with just the Class and test Class.

If anyone can spot the issue or has any suggestions I would greatly appreciate it.

Regards,
M
Best Answer chosen by Michael Hedrick 2
Raj VRaj V
Global class CallTrexWebServiceAccountUpdate{
    
    public static Account accounts {get;set;}
    public static String myresponse{get;set;}

    webservice static string ABCWebServiceAccountUpdate(String id) {
    if(!Test.isRunningTest()){
        ABCWebServiceAccountUpdateAsync(id);
        return myresponse;   
}	else{

return 'Dummry Resp' ;
}	
    }


    @future(Callout=true)
      static void ABCWebServiceAccountUpdateAsync(String id)  
       {
       System.debug(id); 
           accounts = [SELECT id,Partner_Type__c FROM Account WHERE id =:id];
             if(id != null )
               {
                   HttpRequest req = new HttpRequest();
                   Http http = new Http();
                   req.setMethod('GET');
                            
                   String url = 'https://blabla/Services.asmx/UpdateAccount?accountId='+id;
                   req.setEndpoint(url);
            
                   HTTPResponse resp = http.send(req);
                   myresponse = resp.getBody();
             }
       }
    }

 
Mano sfdcMano sfdc 
Hi Experts,

I'm new to test classes and I have created an Apex Class, some one please help me on creating Test Class. Thanks in Advance.



public class TestUserRoleController 
{
    public String getObjType() 
    {
        return String.valueOf(Account.sObjectType);
    }
    
    public UserRoleHelper.RoleNodeWrapper getRootNodeOfTree(Id roleOrUserId) 
    {
        return UserRoleHelper.getRootNodeOfUserTree(roleOrUserId);
    }

    public String getJsonString() 
    {
        String str = null;
        str = UserRoleHelper.getTreeJSON('00E7F000001qt7I');
        return str; 
    }
    
    public String selectedValues {get; set;}
  
}
Best Answer chosen by Mano sfdc
Maharajan CMaharajan C
Hi Mano,

Add one more Parameter get 100% coverage:

@isTest
public class TestUserRoleController_Test {
    @isTest
    static void testUserRoleHelper() {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        
        UserRole ur = new UserRole(Name = 'CEO');
        insert ur;
        
        String orgId = UserInfo.getOrganizationId();
        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
        
        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
        String uniqueName = orgId + dateString + randomInt;
        User tuser = new User(  firstname = 'Test',
                              lastName = 'Test',
                              email = uniqueName + '@test' + orgId + '.org',
                              Username = uniqueName + '@test' + orgId + '.org',
                              EmailEncodingKey = 'ISO-8859-1',
                              Alias = uniqueName.substring(18, 23),
                              TimeZoneSidKey = 'America/Los_Angeles',
                              LocaleSidKey = 'en_US',
                              LanguageLocaleKey = 'en_US',
                              ProfileId = pf.Id,
                              UserRoleId = ur.Id);
        
        insert tuser ;
        
        TestUserRoleController con = new TestUserRoleController();
        con.getObjType() ; 
        con.getRootNodeOfTree(ur.id) ;
        con.getJsonString();
        con.selectedValues='Test';
    }
}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!

Thanks,
Raj
Mano sfdcMano sfdc 
Hi Experts,

I have created an Apex Class, some one please help me on creating Test Class. Thanks in Advance.

Note: In Same Class (end of the class) I have tried test class, but no luck.



public class UserRoleHelper {

    /********************* Properties used by getRootNodeOfUserTree function - starts **********************/
    // map to hold roles with Id as the key
    private static Map <Id, UserRole> roleUsersMap;

    // map to hold child roles with parentRoleId as the key
    private static Map <Id, List<UserRole>> parentChildRoleMap;

    // List holds all subordinates
    private static List<User> allSubordinates {get; set;}
        
    // Global JSON generator
    private static JSONGenerator gen {get; set;}

    /********************* Properties used by getRootNodeOfUserTree function - ends **********************/
    
    
    /********************* Properties used by getSObjectTypeById function - starts ********************* */
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;
    
    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;

    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;
    /********************* Properties used by getSObjectTypeById function - ends **********************/
    
    /* // initialize helper data */ 
    static {
        // initialize helper data for getSObjectTypeById function
        init1();
        
        // initialize helper data for getRootNodeOfUserTree function
        init2();
    }
    
    /* // init1 starts <to initialise helper data> */
    private static void init1() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
        
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
        
        //get the object prefix in IDs
        keyPrefixSet = gd.keySet();
        
        // fill up the prefixes map
        for(String sObj : keyPrefixSet) {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
        }
    }
    /* // init1 ends */

    /* // init2 starts <to initialise helper data> */
    private static void init2() {
        
        // Create a blank list
        allSubordinates = new List<User>();
        
        // Get role to users mapping in a map with key as role id
        roleUsersMap = new Map<Id, UserRole>([select Id, Name, parentRoleId, (select id, name from users) from UserRole order by parentRoleId]);
        
        // populate parent role - child roles map
        parentChildRoleMap = new Map <Id, List<UserRole>>();        
        for (UserRole r : roleUsersMap.values()) {
            List<UserRole> tempList;
            if (!parentChildRoleMap.containsKey(r.parentRoleId)){
                tempList = new List<UserRole>();
                tempList.Add(r);
                parentChildRoleMap.put(r.parentRoleId, tempList);
            }
            else {
                tempList = (List<UserRole>)parentChildRoleMap.get(r.parentRoleId);
                tempList.add(r);
                parentChildRoleMap.put(r.parentRoleId, tempList);
            }
        }
    } 
    /* // init2 ends */

    /* // public method to get the starting node of the RoleTree along with user list */
    public static RoleNodeWrapper getRootNodeOfUserTree (Id userOrRoleId) {
        return createNode(userOrRoleId);
    }
    
    /* // createNode starts */
    private static RoleNodeWrapper createNode(Id objId) {
        RoleNodeWrapper n = new RoleNodeWrapper();
        Id roleId;
        if (isRole(objId)) {
            roleId = objId;
            if (!roleUsersMap.get(roleId).Users.isEmpty()) {
                n.myUsers = roleUsersMap.get(roleId).Users;
                allSubordinates.addAll(n.myUsers);
                n.hasUsers = true;
            }
        }
        else {
            List<User> tempUsrList = new List<User>();
            User tempUser = [Select Id, Name, UserRoleId from User where Id =: objId];
            tempUsrList.add(tempUser);
            n.myUsers = tempUsrList;
            roleId = tempUser.UserRoleId;
        }
        n.myRoleId = roleId;
        n.myRoleName = roleUsersMap.get(roleId).Name;
        n.myParentRoleId = roleUsersMap.get(roleId).ParentRoleId;

        if (parentChildRoleMap.containsKey(roleId)){
            n.hasChildren = true;
            n.isLeafNode = false;
            List<RoleNodeWrapper> lst = new List<RoleNodeWrapper>();
            for (UserRole r : parentChildRoleMap.get(roleId)) {
                lst.add(createNode(r.Id));
            }           
            n.myChildNodes = lst;
        }
        else {
            n.isLeafNode = true;
            n.hasChildren = false;
        }
        return n;
    }
    
    public static List<User> getAllSubordinates(Id userId){
        createNode(userId);
        return allSubordinates;
    }
    
    public static String getTreeJSON(Id userOrRoleId) {
        gen = JSON.createGenerator(true);
        RoleNodeWrapper node = createNode(userOrRoleId);
        gen.writeStartArray();
            convertNodeToJSON(node);
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    private static void convertNodeToJSON(RoleNodeWrapper objRNW){
        gen.writeStartObject();
            gen.writeStringField('title', objRNW.myRoleName);
            gen.writeStringField('key', objRNW.myRoleId);
            gen.writeBooleanField('unselectable', false);
            gen.writeBooleanField('expand', true);
            gen.writeBooleanField('isFolder', true);
            if (objRNW.hasUsers || objRNW.hasChildren)
            {
                gen.writeFieldName('children');
                gen.writeStartArray();
                    if (objRNW.hasUsers)
                    {
                        for (User u : objRNW.myUsers)
                        {
                            gen.writeStartObject();
                                gen.writeStringField('title', u.Name);
                                gen.writeStringField('key', u.Id);
                            gen.WriteEndObject();
                        }
                    }
                    if (objRNW.hasChildren)
                    {
                        for (RoleNodeWrapper r : objRNW.myChildNodes)
                        {
                            convertNodeToJSON(r);
                        }
                    }
                gen.writeEndArray();
            }
        gen.writeEndObject();
    }
    
    /* // general utility function to get the SObjectType of the Id passed as the argument, to be used in conjunction with */ 
    public static String getSObjectTypeById(Id objectId) {
        String tPrefix = objectId;
        tPrefix = tPrefix.subString(0,3);
        
        //get the object type now
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    }
    /* // utility function getSObjectTypeById ends */
    
    /* // check the object type of objId using the utility function getSObjectTypeById and return 'true' if it's of Role type */
    public static Boolean isRole (Id objId) {
        if (getSObjectTypeById(objId) == String.valueOf(UserRole.sObjectType)) {
            return true;
        }
        else if (getSObjectTypeById(objId) == String.valueOf(User.sObjectType)) {
            return false;
        } 
        return false;
    }
    /* // isRole ends */
    
    public class RoleNodeWrapper {
    
        // Role info properties - begin
        public String myRoleName {get; set;}
        
        public Id myRoleId {get; set;}
        
        public String myParentRoleId {get; set;}
        // Role info properties - end
        
        
        // Node children identifier properties - begin
        public Boolean hasChildren {get; set;}
        
        public Boolean isLeafNode {get; set;}
        
        public Boolean hasUsers {get; set;}
        // Node children identifier properties - end
        
        
        // Node children properties - begin
        public List<User> myUsers {get; set;}
    
        public List<RoleNodeWrapper> myChildNodes {get; set;}
        // Node children properties - end   
        
        public RoleNodeWrapper(){
            hasUsers = false;
            hasChildren = false;
        }
    }   
    
 }
 



//    @isTest
//    static void testUserRoleHelper() {
        
        /*
        // test the output in system debug with role Id
        Id roleId = '00E90000000pMaP';
        RoleNodeWrapper startNodeWithRoleId = UserRoleHelper.getRootNodeOfUserTree(roleId);
        String strJsonWithRoleId = JSON.serialize(startNodeWithRoleId);
        system.debug(strJsonWithRoleId);
        */
        //system.debug('****************************************************');

        // now test the output in system debug with userId
//        Id userId = UserInfo.getUserId() ;
        /*
        RoleNodeWrapper startNodeWithUserId = UserRoleHelper.getRootNodeOfUserTree(userId);
        String strJsonWithUserId = JSON.serialize(startNodeWithUserId);
        system.debug(strJsonWithUserId);
        */
        
        // test whether all subordinates get added
        //Id userId = '005900000011xZv';
//        String str = UserRoleHelper.getTreeJSON(userId);
        //List<User> tmpUsrList = UserRoleHelper.getAllSubordinates('00E90000000pMaP');
        //system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%tmpUsrList:' + tmpUsrList);
//   }
Best Answer chosen by Mano sfdc
Raj VRaj V
Here is the code 
@isTest
public class UserRoleHelperTert {
    @isTest
    static void testUserRoleHelper() {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        
        UserRole ur = new UserRole(Name = 'CEO');
        insert ur;
        
        String orgId = UserInfo.getOrganizationId();
        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
        
        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
        String uniqueName = orgId + dateString + randomInt;
        User tuser = new User(  firstname = 'Test',
                              lastName = 'Test',
                              email = uniqueName + '@test' + orgId + '.org',
                              Username = uniqueName + '@test' + orgId + '.org',
                              EmailEncodingKey = 'ISO-8859-1',
                              Alias = uniqueName.substring(18, 23),
                              TimeZoneSidKey = 'America/Los_Angeles',
                              LocaleSidKey = 'en_US',
                              LanguageLocaleKey = 'en_US',
                              ProfileId = pf.Id,
                              UserRoleId = ur.Id);
        
        insert tuser ;
        
        UserRoleHelper urCls = new UserRoleHelper() ;
        UserRoleHelper.getRootNodeOfUserTree(ur.Id);
        UserRoleHelper.getAllSubordinates(ur.Id);
        UserRoleHelper.getTreeJSON(ur.Id);
        
    }
}

 
Kathryn Cantwell 17Kathryn Cantwell 17 
I am trying to upload (via Data Loader) Products and their related SKUs.  I am not able to map to the Product SKU field in Data Loader, although I made certain the field is not hidden in the org.  I have tried to upload the Product SKU separately from the Product, to no avail.  All fields are able to be mapped, including custom fields, except for this Salesforce standard field.  

Many thanks for your assistance!

Data Loader Screen Print - Product SKU Field is Not Available
Best Answer chosen by Kathryn Cantwell 17
Alain CabonAlain Cabon
Hi,

What tool are you using?

StockKeepingUnit / Product SKU is accessible from this "data loader" without problem
The field is just "hidden" by default nevertheless at first and that should be changed.

User-added image


User-added image

I updated the Product SKU field of Product (Product2) with this tool.
 
Best Answer chosen by Mano sfdc
Sampath SuranjiSampath Suranji
Hi,
Try something like below,
@isTest
public class MetadataFieldsTest {
    
    public static testmethod void testAll(){
        try
        {
            MetadataFields objM = new MetadataFields();
            objM.obj='contact';
            
            objM.getobj();
            objM.setobj('contact');
            List<SelectOption> objList = objM.getobjs();
            objM.fetchFields();
        }
        catch(Exception ex){}
        
    }
    
}

Regards
Sampath​
Raghav ChaturvediRaghav Chaturvedi 
<apex:page controller="SearchRecords" showHeader="true" >
    <apex:form id="frm">
        <apex:actionFunction name="showcon" action="{!showContact}" reRender="frm" />
        <apex:pageblock >
            <apex:pageBlockSection title="Search Account Records" columns="1">
                Enter Name<apex:inputText value="{!getstring}" id="theTextInput"/>
            </apex:pageBlockSection>
            <apex:commandButton action="{!searchRecords}" value="Search" id="theSearch" reRender="frm"/>
                <apex:pageBlockSection title="Account Detail">
                    <apex:pageBlocktable value="{!accountlist}" var="acc">
                        <apex:column >
                          <input type="radio" onclick="showcon()"/>
                        </apex:column>
                        <apex:column value="{!acc.name}" headerValue="Account Name"/>
                        <apex:column value="{!acc.Phone}" headerValue="Phone"/>
                    </apex:pageBlocktable>
                </apex:pageBlockSection>
                <apex:pageBlockSection title="Related Contact">
                    <apex:pageBlockTable value="{!Contactlist}" var="con">
                        <apex:column value="{!con.Name}" headerValue="Contact Name"/>
                        <apex:column value="{!con.Phone}" headerValue="Phone"/>
                        <apex:column value="{!con.Email}" headerValue="Email"/>
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

public class SearchRecords {
    public String AccId{get;set;}
    public string getstring{get;set;}
    public List<Account> accountlist {get;set;}
    public list<Contact> Contactlist{get;set;}
    public void searchRecords(){
        accountlist= new list<Account>();
        if(getstring!=null){
            accountlist= Database.query('select id,name,Phone from Account where name like \'%'+getstring+'%\'');
        }
    } 
    public void showContact(){
     Contactlist=[select Id,Name,Email,Phone from contact where accountId =:Accid];  
    }
}
Best Answer chosen by Raghav Chaturvedi
Ajay K DubediAjay K Dubedi
Hi Raghav,

 Your problem has solved Please run given code.
 
 <apex:page controller="SearchRecords" showHeader="true" >
    <apex:form id="frm">
        <apex:actionFunction name="showcon" action="{!showContact}" reRender="frm" />
        <apex:pageblock >
            <apex:pageBlockSection title="Search Account Records" columns="1">
                Enter Name<apex:inputText value="{!getstring}" id="theTextInput"/>
            </apex:pageBlockSection>
            <apex:commandButton action="{!searchRecords}" value="Search" id="theSearch" reRender="frm"/>
            <apex:pageBlockSection title="Account Detail">
                <apex:pageBlocktable value="{!accountlist}" var="acc">
                    <apex:column >
                        <input type="radio" name="group1"/ >
                        <apex:actionSupport event="onclick" action="{!showContact}" ReRender="conpgblk">
                            <apex:param assignTo="{!accId}" name="accname" value="{!acc.id}"/>
                        </apex:actionSupport>
                    
                    </apex:column>
                    <apex:column value="{!acc.name}" headerValue="Account Name"/>
                    <apex:column value="{!acc.Phone}" headerValue="Phone"/>
                </apex:pageBlocktable>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Related Contact" id="conpgblk">
                <apex:pageBlockTable value="{!Contactlist}" var="con">
                    <apex:column value="{!con.LastName}" headerValue="Contact Name"/>
                    <apex:column value="{!con.Phone}" headerValue="Phone"/>
                    <apex:column value="{!con.Email}" headerValue="Email"/>
                    
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>



public class SearchRecords {
    public String accId{get;set;}
    public string getstring{get;set;}
    public List<Account> accountlist {get;set;}
    public list<Contact> Contactlist{get;set;}
    public void searchRecords(){
        accountlist= new list<Account>();
        if(getstring!=null){
            accountlist= Database.query('select id,Name,Phone from Account where Name like \'%'+getstring+'%\'');
        }
    } 
    public PageReference showContact(){
        System.debug('AccId-->'+accId);
        Contactlist=[select Id,LastName,Email,Phone from contact where AccountId =:accId];  
        return null;
    }
}

Please mark it as best answer if you find it helpful.

Thank You
Ajay Dubedi
 
NHarrisNHarris 
So i have created a validation rule that will trigger an error message on new opportunities if the advertiser account owner is not in a sales role. Right now it works perfectly when there is a management company with an advertiser. However there are some accounts that only have a management company, i need my validation rule to bypass those opportunities and only look at the ones that have a property attached. 

AND(ISNEW(), 
ISPICKVAL(Advertiser__r.Owner.AG_Sales_Territory__c," "))

 
Best Answer chosen by NHarris
Abdul KhatriAbdul Khatri
just realise, I place the space between the quotes " " instead of "", corrected and here is the one that should work.
 
AND(
ISNEW(), 
NOT ( ISBLANK(Advertiser__c ) ),
ISPICKVAL(Advertiser__r.Owner.AG_Sales_Territory__c,"")
)