This setup has multiple custom objects that have related Contacts. Set up also includes multiple record types (Contacts object), based on the respective custom objects. When creating a new Contact from each of these custom objects, I want to be able to set the default record type accordingly.
2 Answers
From your question I understand that contact appears as related list on many object and whenever a user click on the new contact button on the related list you want to open a new contact form w/o going to the recordType selection page.
You would need to add a custom button of type list on the contact object and the link in the custom button should look something like this
/003/e?fieldID={!customObject__c.Name}&fieldId_lkid={!CustomObject__c.Id}&retURL=%2F{!CustomObject__c.Id}&RecordType=yourRecordTypeId
Replace the fieldId in the above URL with the DOM id of the custom object look up field. To get the DOM id, open the contact form, right click on the custom object look up field, select inspect element and when the console opens get the id of the html element.
To the get the recordType id, go to contact obejct, recordType and select the recordType you want to populate, you will get the Id from the URL.
Next step will be to replace the standard 'New COntact' button with your custom button. Go to the custom object page layout, scroll down to the related list section and add the custom button in the related list.
repeat the same steps for all the objects.
RecordType can be fetched as:
List<RecordType> recordTypeList = [select Id, Name, SobjectType, FROM RecordType where SobjectType='Account' ]; // Fetch all RecordType on sObject Account
Select one of the required recordType.
You need to insert recordType while creating new record of object as:
Account acc = new Account(recordTypeId=recordTypeList[0].id, name='TestRecord');
insert acc;
This will cause error if there will no record So you should first check list size then insert
.