• Rohit Sharma 66
  • NEWBIE
  • 223 Points
  • Member since 2015
  • Salesforce Developer and Administrator

  • Chatter
    Feed
  • 8
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 75
    Replies
Hi,

I have two custom objects like Private1 and Private2. For these two objects given lookup relationship to Account object. Here whatever the records are entered into these two objects then that particular Account team member can able to see the two custom object's records.

Actually, I have tried for one custom object and below is the code but I need the same scenario for multiple objects. Can anybody please help me on this.
And also I am new to salesforce inaddition to this, Can anybody help on test class for the above scenario?

Single Object record sharing (Private1):
global class PrivateSharingAccMember implements Database.Batchable<sObject> {
    static String emailAddress = 'rupesh@gmail.com';
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([select Id, Account__c from Private1__c]);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        Map<ID, Private1__c> pvtMap = new Map<ID, Private1__c>((List<Private1__c>)scope);
        List<Private1__Share> newJobShrs = new List<Private1__Share>();
        
        List<Private1__Share> oldJobShrs = [select Id from Private1__Share WHERE ParentId IN :pvtMap.keySet() AND (RowCause = :Schema.Private1__Share.rowCause.Private_One__c)];
        
        for(Private1__c pvt : pvtMap.values()){
            Private1__Share pvtAccountShr = new Private1__Share();
            
            pvtAccountShr.ParentId = pvt.Id;
            pvtAccountShr.UserOrGroupId = pvt.Account__c;
            pvtAccountShr.AccessLevel = 'Read';
            pvtAccountShr.RowCause = Schema.Private1__Share.RowCause.Private_One__c;
            
            newJobShrs.add(pvtAccountShr);
        }
        
        }
    global void finish(Database.BatchableContext BC){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddress = new String[] {emailAddress};
        mail.setToAddresses(toAddress);
        mail.setSubject('Apex Sharing Records Completed');
        mail.setPlainTextBody('The Apex Sharing Records finished processing');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

Please help me on this at your earliest convenience anyone.
I have a VF page with a custom controller. It has a sign up form to create a new contact. When I tried adding a picklist field for the MailingStateCode field, I was unsure how to get the prepopulated values. Do I make a setter and getter for it? If so how? If not, what shall I do?
I need help with creating a field on the 'contracts' page that will lookup the 'type' of account on the accounts section; for example, need to know if a particular contract is for a vendor account or a supplier account.
i am writing the visual force using extension on the page they are showing the required filed has missing wTHIS IS VF PAGESHOW ERROR MESSAGE 
public class leaddetails {
    public lead leads{set;get;}
    public lead lead{set;get;}
    public leaddetails(ApexPages.StandardController controller){
        leads =(lead)controller.getRecord();
    }
    public pageReference createLead(){
        if(leads.name!=null){
            account acc=new account();
            acc.Name=lead.name;
            acc.Parentid= lead.company;
            acc.AnnualRevenue=lead.AnnualRevenue;
            acc.Fax=lead.Fax;
            acc.Type='Other';
            acc.Phone=lead.MobilePhone;
            acc.Industry=lead.Industry;
            insert acc;
            contact con=new contact();
             con.lastName=lead.lastName;
            con.firstName=lead.firstName;
            con.Description=lead.Industry;
            con.Title=acc.Name;
            con.Email=lead.Email;
            con.Phone=lead.MobilePhone;
            insert con;
             pageReference p=new pageReference('/'+acc.id);
            return p;
         }else{
        Insert leads;
         pageReference p=new pageReference('/'+leads.id);
            return p;

}
   }
    public void cancelLead(){
        lead=null;
    }
}
 
01if(Trigger.isInsert && Trigger.isAfter)
02{
03    ContactController.processContact(Trigger.newMap, Trigger.oldMap);
04}
05else if(Trigger.isUpdate && Trigger.isAfter)
06{
07    ContactController.processContact(Trigger.newMap, Trigger.oldMap);
08}
09 
10 
11 
12// call process contact on both insert and update
13public  void processContact(Map<Id, Contact> newContactMap, Map<Id, Contact> oldContactMap) 
14{ 
15    List<Queue__c> lstQ = new List<Queue__c>();    
16    Id idContactCustomerRecType;
17    Map<Id, String> mapIdToAccountName = new Map<Id, String>();
18     
19    // Assuming Developer Name is 'Customer'
20    List<RecordType> lstRecType = new List<RecordType>([SELECT Id FROMRecordType WHERE DeveloperName = 'Customer' AND SobjectType ='Contact']);
21    if(!lstRecType.isEmpty())
22        idContactCustomerRecType = lstRecType[0].Id;
23         
24    if(idContactCustomerRecType != null)
25    {
26        // we can;t fetch parent fields directly, so collect account Ids first
27        for(Contact objContact : newContactMap.values())
28        {
29            if(objContact.AccountId != null)
30                mapIdToAccountName.put(objContact.AccountId, null);
31        }
32    }
33     
34    // iterate over account with matching collected Ids and fetch names
35    for(Account objAccount : [SELECT Id, Name FROM Account WHERE Id IN : mapIdToAccountName.keySet()])
36    {
37        mapIdToAccountName.put(objAccount.Id, objAccount.Name);
38    }
39     
40    // loop again to perform business logic
41    for(Contact objContact : newContactMap.values())
42    {
43        /* 1. If Contact RecordType is Customer AND if LastName != Account.Name, insert Queue **/
44        if( objContact.RecordTypeId == idContactCustomerRecType 
45            && objContact.AccountId != null
46            && objContact.LastName != mapIdToAccountName.get(objContact.AccountId)
47            (
48                Trigger.isInsert
49                    ||
50                (
51                    Trigger.isUpdate
52                        &&
53                    (   
54                        objContact.A__c!= oldContactMap.get(objContact.Id).A__c
55                        || objContact.B__c!= oldContactMap.get(objContact.Id).B__c
56                        || objContact.D__c!= oldContactMap.get(objContact.Id).D__c
57                    )
58                )
59            )
60            )
61        {
62            Queue__c objQ = new Queue__c();
63            objQ.Object_Name__c='Contact';
64             
65            if(Trigger.isUpdate)
66            {
67                if(objContact.PID__c == null)
68                    objQ.Description__c= 'PID Missing';
69                else
70                    objQ.Description__c= 'Updated Contact';
71            }
72            else
73            {
74                objQ.Description__c= 'New Contact';
75            }
76             
77            objQ.Record_Id__c = objContact.Id;
78            objQ.Notification_Timestamp__c= objContact.CreatedDate;
79            lstQ.add(objQ);
80        }
81             
82    }
83     
84    if(!lstQ.isEmpty())
85        insert lstQ;
86     
87}
Hello All,

We have a test class that is causing errors when I try to move items into production. I know what is causing the error (I am not a developer and we do not have one here) it is the last line that when the developer created the test case would have been null, but since then there was a change. I just need to comment out one line.

I know how to comment out the line, I just don't know how to get that test class back into prod, when I try the test runs and errors out so it is basically a catch22 here. Thanks in advance for any assistance.
Hi All,

I need to create a trigger on Account object every time an account record with status "Activo" is modified to send an email alert to the account owner and also all the users in the account team.
NOTE: The status field is Estado__c

Any idea how to do it?

Thanks in advance!
Hi,

Here is my code and I am getting error for DMLException and cannot change the setup object
trigger TransferInactiveUsers on User (after update) {
    Integer count = 0;
    List<ID> userids = new List<ID>();
    For (User usr : Trigger.new){
        if (Trigger.oldMap.get(usr.Id).IsActive == true)
            if(Trigger.newMap.get(usr.Id).IsActive == false)
            userids.add(usr.Id);
    }
    
    List<Account> acctList=[SELECT ID FROM Account WHERE OwnerId IN :userids];
    for(Account ac : acctList)
    {
        ac.OwnerId = System.Label.Owner_ID;
        count++;
    }
    
    update acctList;
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('Owners changed for records ');
    mail.setPlainTextBody('The Total number of records whose owner changed are :'+count);
    mail.toAddresses = new String[] { 'Label.Email_addr_one'};
        Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
    
    if (results[0].success) {
        System.debug('The email was sent successfully.');
    } else {
        System.debug('The email failed to send: '+ results[0].errors[0].message);
    }
}
 
HI,

I have dependent picklist in SFDC custom object, and like to show these two picklist fields in Lightning component. For eg  like parent filed A and its child picklist filed B, Based on picklist values in A field the value in B changes.

Can anyone suggest how to implement this in Lightning component. I tried using UI:inputSelect, but its not working.
Hi , 
I am working on Lightning, and trying to use export to excel in javascript controller.
I need to export data in two/three sheets of a single workbook. Like 1 sheet will contains open cases, 2nd sheet will contain closed cases etc.
I found few blogs but they are working fine to export data in one sheet, but I want to export data in multiple sheets of 1 workbook.
Can anyone plese help.
Hi,

I need to implement single sign on which enable portal user from 1 org to login directly to diffrent sfdc org. 
When user click on the case number in portal he should be redirected to the case detail page in the different sfdc org. 
I tried implement this, but it is asking for the sfdc credential, which should not be happen. Portal user should allow to loging to the sfdc.

Any help will be appreceated.
Hi , 
I am working on Lightning, and trying to use export to excel in javascript controller.
I need to export data in two/three sheets of a single workbook. Like 1 sheet will contains open cases, 2nd sheet will contain closed cases etc.
I found few blogs but they are working fine to export data in one sheet, but I want to export data in multiple sheets of 1 workbook.
Can anyone plese help.
I'm not understanding how merge fields work when using templates sent via apex.  Here is my current code:
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            Id templateId;
            String[] toAddresses = new String[]{'sales.admin@companydomain.com'};
            email.setToAddresses(toAddresses);
            email.setTargetObjectId(p.Id);
            email.setTemplateId('00X11000000OO2B');
            email.setorgWideEmailAddressId('0D2150000008TCX');
            email.setSaveAsActivity(false);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

What I'm still really confused about, even after reading the documentation, is what the setTargetObjectId and setWhatId actually do.  

I need to merge several fields from our custom project object, so I was assuming that's what I would use the specific project record id as the setTargetObjectId, but I'm not sure if that's correct as everything I've read says the setTargetObjectId is who you're sending the email to, which in this case is our sales admin.  
So, where / how do I set what the record is that I want to merge fields from, e.g. a specific project record.  Thanks in advance.
String currentmonth = String.Valueof(Date.Today().Month());
for(test__c revn :revnlist){
if(revn.invoice_month__c.equals(currentmonth)){
revenuelist.add(revn);
               }
}
It is not entering into If condition.Here the invoice_month__cholds the values like 1,2,3.. and currentmonth values like 1,2,3..etc
I've got milestones comleting automatically through triggers and I'm trying to create a test class for code coverage (I'm not good at these).
Here's my trigger
trigger CW_CompleteFirstResponseTimeMilestone on Case (after update) {
if (UserInfo.getUserType() == 'Standard')
{
    DateTime completionDate = System.now();
        List<Id> updateCases = new List<Id>();
        For (Case c : Trigger.new)
        {
            if((c.Incident_First_Response__c != null) && (c.Impact__c == 'Site Production Down') && ((c.SlaStartDate<=completionDate) && (c.SlaExitDate==null)))
            {
            updateCases.add(c.Id);
            CW_MilestoneUtils.completeMilestone(updateCases, 'CW First Response - P1', completionDate);
            }else{
                if((c.Incident_First_Response__c != null) && (c.Impact__c == 'Site Production Severely Impaired') && ((c.SlaStartDate<=completionDate) && (c.SlaExitDate==null)))
                {
                updateCases.add(c.Id);
                CW_MilestoneUtils.completeMilestone(updateCases, 'CW First Response - P2', completionDate);
                }else{
                    if((c.Incident_First_Response__c != null) && (c.Impact__c == 'Site Production Moderately Impaired') && ((c.SlaStartDate<=completionDate) && (c.SlaExitDate==null)))
                    {
                    updateCases.add(c.Id);
                    CW_MilestoneUtils.completeMilestone(updateCases, 'CW First Response - P3', completionDate);
                    }else{
                        if((c.Incident_First_Response__c != null) && (c.Impact__c == 'Site Production Can Continue Without Interruption') && ((c.SlaStartDate<=completionDate) && (c.SlaExitDate==null)))
                        {
                        updateCases.add(c.Id);
                        CW_MilestoneUtils.completeMilestone(updateCases, 'CW First Response - P4', completionDate);
                        }
        }
    
        }}}
                
           }
}

Here's what I have for the test class so far.  It comes up covering nothing(like I said, I'm not good at these)
@isTest
private class CW_TestCompleteMilestoneCaseTest{

static testMethod void CW_TestCompleteMilestoneCaseTest(){
User u1;
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];        
System.runAs (thisUser) {
        //create Tier 2 user
        u1 = CW_DataCreation.CW_u1DataCreation();
    
RecordType rtAcct = [select Id from RecordType WHERE Name = 'Worksite' and SobjectType = 'Account' limit 1];

test.startTest();
system.runAs(u1){
//create an account
Account a1 = new Account(Name='My Account', RecordType = rtAcct, Technology_Account__c = true);
insert a1;

    Entitlement ent = new Entitlement(Name='Testing', AccountId=a1.Id, 
    StartDate=Date.valueof(System.now().addDays(-2)), EndDate=Date.valueof(System.now().addYears(2)));
    insert ent;
  
        Case c = new Case();
        c.Subject = 'Test Case with Entitlement';
        c.EntitlementId = ent.Id;
        c.AccountId = a1.Id;
        c.Description = 'Test';
        c.Product__c = 'Fleet'; 
        c.CW_Type__c = 'Product Support';
        c.CW_Case_Reason_Custom__c = 'Incident';
        c.Application__c = 'Underground';
        c.Subsystem__c = 'Infrastructure';
        c.Incident_Start__c = datetime.now();
        c.Impact__c = 'Site Production Down';
    insert c;
    
    //update First Response
	c.Incident_First_Response__c = datetime.now();
	update c;
    
    DateTime completionDate = System.now();
    List<Id> updateCases = new List<Id>();
    
      if((c.Incident_First_Response__c != null) && (c.Impact__c == 'Site Production Down') && ((c.SlaStartDate<=completionDate) && (c.SlaExitDate==null)))
     {    
      updateCases.add(c.Id);
    CW_MilestoneUtils.completeMilestone(updateCases, 'CW First Response - P1', completionDate);
     }//}
    
    
}}}
///from SF entitlement admin guide
static testMethod void testCompleteMilestoneViaCase(){
    Entitlement entl = [select id from Entitlement limit 1];
    String entlId;
    if (entl != null)
        entlId = entl.Id;
    List<Case> cases = new List<Case>{};
    for(Integer i = 0; i < 1; i++){
        Case c = new Case(Subject = 'Test Case ' + i);
        cases.add(c);
        if (entlId != null){
            c = new Case(Subject = 'Test Case with Entitlement ' + i,
            EntitlementId = entlId);
            cases.add(c);
        }
    }

    insert cases;

   
    
    
}
}

Any help would be greatly appreciated!
  • July 07, 2016
  • Like
  • 0
Why we are using Seealldata=true in test cases,

Why we are using Private in test cases.
I have a custom covert button that uses the following Apex Class:
public class CustomConvertLead {

    public CustomConvertLead(ApexPages.StandardController controller) {

    }

    public PageReference ConvertL(){
    
        Id idd = ApexPages.CurrentPage().getParameters().get('id');
        Boolean ok = false;
        Id AccId, ConId;
        Lead ll = [SELECT Id,Company__c, Contact__c, Company, Engagement_Target__c, FirstName, LastName, Amount__c,
                   Reason_Inquiry__c, Referral_Name__c, OwnerId, Description, Rating, Email,
                   AnnualRevenue, EBITDA__c, NumberOfEmployees, LeadSource, Lead_Source_Description__c
                    
                   FROM Lead WHERE Id =:idd LIMIT 1];
        
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(idd);
        lc.setDoNotCreateOpportunity(true);
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
 
        if (ll.Company__c != null && ll.Contact__c != null){
            lc.setAccountId(ll.Company__c);
            lc.setContactId(ll.Contact__c);
            Database.LeadConvertResult result = Database.convertLead(lc);
        }
        else { 
            ok = true;
            if (ll.Company__c != null) 
                lc.setAccountId(ll.Company__c);
            if (ll.Contact__c != null)
                lc.setContactId(ll.Contact__c);    
            if (ll.Company__c == null){
                List<Account> cc = [SELECT Id FROM Account WHERE Name = :ll.Company];
                if (cc.size() != 0)
                    lc.setAccountId(cc[0].Id);
            }
            if (ll.Contact__c == null){
                List<Contact> cc =[SELECT Id, AccountId  FROM Contact WHERE LastName = :ll.LastName OR (Email = :ll.Email AND Email != NULL)];
                if (cc.size() != 0){
                    lc.setAccountId(cc[0].AccountId);
                    lc.setContactId(cc[0].Id);
                }
                
            }
                
            Database.LeadConvertResult result = Database.convertLead(lc);
            AccId = result.getAccountId();
            ConId = result.getContactId();     
        }
        
        Idea_Pitch__c i = new Idea_Pitch__c();
        if (ll.FirstName != null)
            i.Name = ll.FirstName + ' '+ ll.LastName + ' ' + ll.Company;
        else 
            i.Name = ll.LastName + ' ' + ll.Company;
        i.Converted_Time_Stamp__c = datetime.now();
        i.Project_Type__c = ll.Reason_Inquiry__c;
        i.Referred_by__c = ll.Referral_Name__c; //there are 2 refferred_by_contact on Idea
        // what should OwnerId be mapped to
        i.Rating__c = ll.Rating;
        i.Description__c = ll.Description;
        i.Annual_Revenue__c = ll.AnnualRevenue;
        i.EBITDA__c = ll.EBITDA__c;
        i.Capital_Formation_Amount__c = ll.Amount__c;
        i.No_of_Employees__c = ll.NumberOfEmployees;
        i.Status__c = '1. Idea Development';
        i.Lead_Source__c = ll.LeadSource;
        i.Lead_Source_Description__c = ll.Lead_Source_Description__c;
        i.Engagement_Target__c = ll.Engagement_Target__c;
        List<CampaignMember> cms = [SELECT CampaignID, LeadID, Status FROM CampaignMember WHERE LeadID = :ll.Id LIMIT 1];
        if (cms.size() != 0)
            i.Campaign_Conference__c = cms[0].CampaignID;
        if (ok == false){
            i.Company__c = ll.Company__c;
            i.Contact__c = ll.Contact__c;
        }
        else {
            i.Company__c = AccId;
            i.Contact__c = ConId;
        }
        
        INSERT i;
        
        PageReference p = new PageReference('/'+i.Id);
        return p;
    
    }
}
I want to add a few more field updates. I have added the feilds in through the developer console. However you can not add the New Apex Class to an active org. I have the new code built in one of my sandboxes. 

public class CustomConvertLead {

    public CustomConvertLead(ApexPages.StandardController controller) {

    }

    public PageReference ConvertL(){
    
        Id idd = ApexPages.CurrentPage().getParameters().get('id');
        Boolean ok = false;
        Id AccId, ConId;
        Lead ll = [SELECT Id,Company__c, Contact__c, Company, Engagement_Target__c, FirstName, LastName, Amount__c,
                   Reason_Inquiry__c, Referral_Name__c, OwnerId, Description, Rating, Email,
                   AnnualRevenue, EBITDA__c, NumberOfEmployees, LeadSource, Lead_Source_Description__c
                    
                   FROM Lead WHERE Id =:idd LIMIT 1];
        
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(idd);
        lc.setDoNotCreateOpportunity(true);
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        
        
        if (ll.Company__c != null && ll.Contact__c != null){
            lc.setAccountId(ll.Company__c);
            lc.setContactId(ll.Contact__c);
            Database.LeadConvertResult result = Database.convertLead(lc);
        }
        else { 
            ok = true;
            if (ll.Company__c != null) 
                lc.setAccountId(ll.Company__c);
            if (ll.Contact__c != null)
                lc.setContactId(ll.Contact__c);    
            if (ll.Company__c == null){
                List<Account> cc = [SELECT Id FROM Account WHERE Name = :ll.Company];
                if (cc.size() != 0)
                    lc.setAccountId(cc[0].Id);
            }
            if (ll.Contact__c == null){
                List<Contact> cc =[SELECT Id, AccountId  FROM Contact WHERE LastName = :ll.LastName OR (Email = :ll.Email AND Email != NULL)];
                if (cc.size() != 0){
                    lc.setAccountId(cc[0].AccountId);
                    lc.setContactId(cc[0].Id);
                }
                
            }
                
            Database.LeadConvertResult result = Database.convertLead(lc);
            AccId = result.getAccountId();
            ConId = result.getContactId();     
        }
        
        Idea_Pitch__c i = new Idea_Pitch__c();
        if (ll.FirstName != null)
            i.Name = ll.FirstName + ' '+ ll.LastName + ' ' + ll.Company;
        else 
            i.Name = ll.LastName + ' ' + ll.Company;
        i.Converted_Time_Stamp__c = datetime.now();
        i.Project_Type__c = ll.Reason_Inquiry__c;
        i.Referred_by__c = ll.Referral_Name__c; //there are 2 refferred_by_contact on Idea
        // what should OwnerId be mapped to
        i.Rating__c = ll.Rating;
        i.Description__c = ll.Description;
        i.Annual_Revenue__c = ll.AnnualRevenue;
        i.EBITDA__c = ll.EBITDA__c;
        i.Capital_Formation_Amount__c = ll.Amount__c;
        i.No_of_Employees__c = ll.NumberOfEmployees;
        i.Status__c = '1. Idea Development';
        i.Lead_Source__c = ll.LeadSource;
    i.Lead_Source_New_IdeaO__c = ll.Lead_Source_New_LeadO__c;
        i.Lead_Source_Description__c = ll.Lead_Source_Description__c;
    i.Lead_Source_Description_New_IdeaO__c = ll.Lead_Source_Description_New_LeadO__c;
        i.Engagement_Target__c = ll.Engagement_Target__c;
        List<CampaignMember> cms = [SELECT CampaignID, LeadID, Status FROM CampaignMember WHERE LeadID = :ll.Id LIMIT 1];
        if (cms.size() != 0)
            i.Campaign_Conference__c = cms[0].CampaignID;
        if (ok == false){
            i.Company__c = ll.Company__c;
            i.Contact__c = ll.Contact__c;
        }
        else {
            i.Company__c = AccId;
            i.Contact__c = ConId;
        }
        
        INSERT i;
        
        PageReference p = new PageReference('/'+i.Id);
        return p;
    
    }
}
My question is when I use change set to bring it over, will it just take the place of the orginal code or do I need to do something else?

 
Hi,

I have a custom object linked to accounts, the data held in the custom object (child object to accounts) is fed in via an integration from another system which is set up as an admin profile in salesforce. I would like to limit access to this record by only allowing the account owner to view the records in the child object. Other than adding account owner id to the external system, does anyone have any idea on how this can be provisioned in SF
Hi,

I receiving "Field is not writeable: OpportunityShare.OpportunityId" error for the below code.Can someone please help me to sort out the error?


trigger shareRecord on Opportunity (after insert,after update) {
    List<OpportunityShare> share=new List<OpportunityShare>();
    User u=[select id from User where alias='kshar'];
    for(Opportunity op:Trigger.New){
        if(op.amount>50000){
            OpportunityShare p=new OpportunityShare();
            p.OpportunityId=op.id;
            p.UserOrGroupId=u.id;
            p.OpportunityAccessLevel='Read';
            p.RowCause='Manual';
            share.add(p);
        }
    }
    insert share;
}
Hi,

I have two custom objects like Private1 and Private2. For these two objects given lookup relationship to Account object. Here whatever the records are entered into these two objects then that particular Account team member can able to see the two custom object's records.

Actually, I have tried for one custom object and below is the code but I need the same scenario for multiple objects. Can anybody please help me on this.
And also I am new to salesforce inaddition to this, Can anybody help on test class for the above scenario?

Single Object record sharing (Private1):
global class PrivateSharingAccMember implements Database.Batchable<sObject> {
    static String emailAddress = 'rupesh@gmail.com';
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([select Id, Account__c from Private1__c]);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        Map<ID, Private1__c> pvtMap = new Map<ID, Private1__c>((List<Private1__c>)scope);
        List<Private1__Share> newJobShrs = new List<Private1__Share>();
        
        List<Private1__Share> oldJobShrs = [select Id from Private1__Share WHERE ParentId IN :pvtMap.keySet() AND (RowCause = :Schema.Private1__Share.rowCause.Private_One__c)];
        
        for(Private1__c pvt : pvtMap.values()){
            Private1__Share pvtAccountShr = new Private1__Share();
            
            pvtAccountShr.ParentId = pvt.Id;
            pvtAccountShr.UserOrGroupId = pvt.Account__c;
            pvtAccountShr.AccessLevel = 'Read';
            pvtAccountShr.RowCause = Schema.Private1__Share.RowCause.Private_One__c;
            
            newJobShrs.add(pvtAccountShr);
        }
        
        }
    global void finish(Database.BatchableContext BC){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddress = new String[] {emailAddress};
        mail.setToAddresses(toAddress);
        mail.setSubject('Apex Sharing Records Completed');
        mail.setPlainTextBody('The Apex Sharing Records finished processing');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

Please help me on this at your earliest convenience anyone.
I have a VF page with a custom controller. It has a sign up form to create a new contact. When I tried adding a picklist field for the MailingStateCode field, I was unsure how to get the prepopulated values. Do I make a setter and getter for it? If so how? If not, what shall I do?
Here is my code
<apex:page tabStyle="Account" standardController="Account">
    <style >
        p {
        font-size:16px;
        }
        .beenWorkingOut {
        font-size:16px;
        }
        .paraCrunch {
        margin-left:10%;
        margin-right:10%;
        }
        a {
        text-decoration:none;
        }
    </style>
    <apex:pageBlock title="AB Welcome Call/Enrollment Call ">
        <apex:pageBlockSection title="Summary" columns="2">
            <apex:outputField value="{!Account.CustNumber__c}"/>
            <apex:outputField value="{!Account.Phone}"/>
            <apex:outputField value="{!Account.Name}"/>
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:pageBlockSectionItem />
            <apex:outputLink onClick="window.open('/{!account.id}')">(View Account)</apex:outputLink>
        </apex:pageBlockSection>
        <apex:pageBlockTable title="Modules" value="{!account.Modules__r}" var="item">
            <apex:outputField value="{!item.Pre_Launch_Date__c}"/>
            <apex:outputField value="{!item.Base_Product__c}"/>
            <apex:outputField value="{!item.White_Labeled_As__c}"/>
            <apex:outputField value="{!item.Status__c}"/>
            <apex:outputField value="{!item.Recordings_Complete__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
    <apex:form >
        <span style="float:right">
            <apex:commandButton action="{!save}" value="Save" /> &nbsp;
            
            
            
            <apex:commandLink onclick="return confirm('Are you sure you want to cancel? All changes will be lost!');" action="{!cancel}" value="cancel"/>
        </span>
        <br />
        <br />
        <br />
        <span style="float:right; font-size:12px; color:grey;">version 1.0 - revised 2015.04.07</span>
        <apex:pageBlock title="Details">
            <apex:pageBlockSection title="Introduction and Product Review" columns="1">
                <p class="paraCrunch">
                When Amerisource Bergen
                
                    
                    
                    <p class="paraCrunch"></p>
                    My name is 
                    
                    
                    <b>{!$User.FirstName} {!$User.LastName}</b> I am calling from Prescribe Wellness on behalf of AmerisourceBergen. May I please speak with {!Account.PW_Champion__c}?
                
                
                
                </p>
                <p class="paraCrunch">
                    Hi {!Account.PW_Champion__c}, this is 
                    
                    
                    <b>{!$User.FirstName} {!$User.LastName}</b> from Prescribe Wellness.  The reason for my call is today is that as a member of Elevate’s Advanced Features you will receive the Patient Engagement Center provided by Prescribe Wellness. The Patient Engagement Center is a tool that will help you address medication adherence, star ratings, and patient loyalty. We provide you the tools needed to take action on your pharmacy data.   
            
                
                
                </p>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Account Details" columns="1">
                <p class="paraCrunch">
                    <ul class="beenWorkingOut">
                        <li>
                            <a id="two1" href="#" style="color:black;" onclick="setColorById('two1','green');return false;">Review The Solutions They are Receiving</a>
                        </li>
                    </ul>
                </p>
                <apex:pageBlockSectionItem />
                <apex:inputField value="{!Account.Name}"/>
                <apex:inputField value="{!account.CustNumber__c}"/>
                <apex:inputField value="{!Account.Phone}"/>
                <apex:inputField value="{!Account.Groups__c}"/>
                <apex:outputLink onClick="window.open('/{!account.id}')">(View Account)</apex:outputLink>
                <apex:pageBlockSectionItem />
                <apex:pageBlockTable title="Modules" value="{!account.Modules__r}" var="item">
                    <apex:column value="{!item.Pre_Launch_Date__c}"/>
                    <apex:column value="{!item.Base_Product__c}"/>
                    <apex:column value="{!item.White_Labeled_As__c}"/>
                    <apex:column value="{!item.Status__c}"/>
                    <apex:column value="{!item.Recordings_Complete__c}"/>
                </apex:pageblocktable>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Collect Forms" columns="1">
                <p class="paraCrunch">
                    <ul class="beenWorkingOut">
                    Online enrollment form and data form (if applicable):
                    The first step in setting up your Patient Engagement Center is completing the online enrollment form.
                        Direct them to prescribewellness.com/elevate and have them click on their dispensing system if listed. If not, click on All Other Dispensing Systems. 
Ask if they have multiple locations that are Elevate with Advanced Features. If so, have them fill out the 
                        <apex:outputLink value="http://developer.salesforce.com/">Enrollment Form</apex:outputLink> for each location. 
 
Create a case to set up a hierarchy – include all account numbers in the case.

                    
                      
                    
                    *If they are not able to fill out the form on the phone, please send the 
                        <apex:outputLink value="https://na18.salesforce.com/00X12000001rQCZ?setupid=CommunicationTemplatesEmail">email template</apex:outputLink>
 that contains the link to prescribewellness.com/elevate. 
                    
                    
                    </ul>
                </p>
                <apex:pageBlockSectionItem />
            </apex:pageblocksection>
            <apex:pageBlockSection title="Review Account Details" columns="1">
                <p class="paraCrunch">
                I would like to confirm your pharmacy information and ask you a few questions.
                    
                    
                    <ul class="beenWorkingOut">
                        <li>
                            <a id="four1" href="#" style="color:black;" onclick="setColorById('four1','green');return false;">Verify the account information: </a>
                        </li>
                        <apex:pageBlockSectionItem />
                        <apex:inputField value="{!Account.Pharmacy_Email__c}"/>
                        <apex:inputField value="{!account.Phone}"/>
                        <apex:inputField value="{!Account.Fax}"/>
                        <apex:inputField value="{!Account.NCPDP__c}"/>
                        <apex:inputField value="{!Account.NPI__c}"/>
                        <apex:inputField value="{!Account.Web_Input_DSP__c}"/>
                        <apex:inputField value="{!Account.Primary_Contact__c}"/>
                        <apex:inputField value="{!Account.PW_Champion__c}"/>
                        <apex:inputField value="{!Account.PW_Champion_Email__c}"/>
                        <p class="paraCrunch">
                When did the Pharmacy open?
                </p>
                        <apex:inputField value="{!Account.DEA_Start_Date__c}"/>
                    </ul>
                </p>
                <p class="paraCrunch">
                Ask the Pre-Launch Meeting questions.
                </p>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Obtaining the pharmacie's data:" columns="1">
                <p class="paraCrunch">
                    <ul class="beenWorkingOut">
                        <li>
                            <a id="five1" href="#" style="color:black;" onclick="setColorById('five1','green');return false;">If automated data extraction</a>
                        </li>
                        <p class="paraCrunch">
                o   For your dispensing system we receive your pharmacy’s data directly from the dispensing system. Once we have received your pharmacy’s data, we will send you an activation email. One of our trainers will then call you to schedule a time for a one-on-one training.
                </p>
                        <li>
                            <a id="five2" href="#" style="color:black;" onclick="setColorById('five2','green');return false;">If manual data extraction is required</a>
                        </li>
                        <p class="paraCrunch">
                 o   For your dispensing system, we will need to schedule a meeting with our data team so they can establish the connection with your dispensing system. We establish the connection through an application called TeamViewer. 
           </p>
                        <p class="paraCrunch">
                 o    Schedule the integration meeting in Salesforce. Note that it can be anyone in the pharmacy who we conduct the integration meeting with.
           </p>
                        <p class="paraCrunch">
                 o    A member of our data team will contact you on [date and time] to conduct the integration meeting.
           </p>
                        <p class="paraCrunch">
                 o     After the integration meeting is complete and we have your pharmacy data, we will send you an activation email. One of our trainers will then call you to schedule a time for a one-on-one training.
           </p>
                    </ul>
                </p>
                <apex:pageBlockSectionItem />
            </apex:pageBlockSection>
            <apex:pageBlockSection title="University Training" columns="1">
                <p class="paraCrunch">
        (please refer to the welcome email for login instructions or resend the welcome email)
Prescribe Wellness has developed a series of online training courses designed to maximize your experience navigating your new tools. Please refer to the university courses at any time for further instruction on how to use Prescribe Wellness.

</p>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Wrap-Up" columns="1">
                <p class="paraCrunch">
        That's everything I had for you today. Thank you so much for taking the time to speak with me today.  
    </p>
                <p class="paraCrunch">
        Thank you so much for taking the time to speak with me today. We are excited to get started and look forward to working with you.  Are there any questions about the program that you have for me at this time?
    </p>
                <apex:inputField value="{!Account.Welcome_Call_Completed__c}"/>
                <p class="paraCrunch">
        Always log your calls in Salesforce!
    </p>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <span style="float:right">
            <apex:commandButton action="{!save}" value="Save" /> &nbsp;
    
            
            <apex:commandLink onclick="return confirm('Are you sure you want to cancel? All changes will be lost!');" action="{!cancel}" value="cancel"/>
        </span>
        <br />
        <br />
    </apex:form>
    <br />
    <script type="text/javascript">
function confirmCancel() {
    return confirm('Are you sure you want to cancel? All changes will be lost!');
}
function addressCopy(b0, b1, b2, b3, s0, s1, s2, s3) {
    // Copy billing fields to shipping fields
    document.getElementById(s0).value = document.getElementById(b0).value;
    document.getElementById(s1).value = document.getElementById(b1).value;
    document.getElementById(s2).value = document.getElementById(b2).value;
    document.getElementById(s3).value = document.getElementById(b3).value;
    // No form submission
    return false;
}
function setColorById(id,sColor) {
    var elem;
    if (document.getElementById) {
        if (elem=document.getElementById(id)) {
            if (elem.style) {
                elem.style.color=sColor;
                return 1;  // success
            }
        }
    }
    return 0;  // failure
}
</script>
</apex:page>

and when I preview my page - I can't see the output fields from my custom object and the text formatting is ugly (see screen shots) 
User-added image
User-added image
Can someone help me identify what I am going wrong?
User-added image