I'm trying to do a Dynamic List of a SObject gutted from an ID. My goal is SEND a SObject info via mail. (Opportunity, Case...)

From a list of selected records, I send by argument their IDs with this Javascript Button:

  var url = parent.location.href;
  var records = {!GETRECORDIDS($ObjectType.Opportunity)};
  if (records[0] == null) {
    alert("Please select at least one record.");
  } else if (records.length > 10) {
    alert("Please select less than 10 records.");
  } else {
    alert("Selected: " + records.length + " records.");
    sforce.apex.execute("myClass ","myMethod",{idArrays:records});
  parent.location.href = url;

And this is my Class Code:

global class myClass {

  WebService static void myMethod(list <String> 
    ID myId = Id.valueOf(idArrays[0]);
    // In this case, mySObject return SObject Opportunity
    Schema.sObjectType mySObject = myId.getSObjectType(); 

    List<mySObject> lSelected = new List<mySObject
    lSelected = Database.query('SELECT Name, Account.Name FROM ' + mySObject + ' WHERE id = :idArrays');
    for (mySObject ms :lSelected){
      //Here call another class with ms records.
      clsSendEmail.testMail(address, subject, body);

Can I use List like that? Or how. If I try to do:

    List<SObject> lSelected = new List <SObject>();
    lSelected = Database.query('SELECT.......');
    for (SObject ms :lSelected){
        clsSendEmail.testMail(address, subject, body); 
//if here try to get ms.Name... or some data, returns Error: 'Field expression not allowed for generic SObject'

Thank you!

  • 2
    You can get a value using the SObject.get method. So in you case String name = (String) ms.get('Name'); will give you the name; the field will have to have been included in the query too.
    – Keith C
    Sep 26, 2015 at 22:26

1 Answer 1


The first option won't work because you can't use a variable as a type parameter, even if the variable holds a SObjectType.

How were you retrieving the name in the second option? ms.Name won't compile, because not all Sobjecy types have a name field, but md.get ("name") should work so long as the passed in object has one.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.