+ Start a Discussion
Bob.390672021994282E12Bob.390672021994282E12 

How to Call a Constructor

I have a method and a constructor. I know how to call a method but not a constructor. I would think that it would be like the below. Any suggestions? I want to place my generaterandomstring into my object name. Everytime the record saved it would insert the logic for the constructor in the name

public PageReference PCR() {

         Object__c newObject;
        
         object = [select id, Name, number__c from Object__cwhere id = :object.id];

    //     newObject.name =  RandomNumbersMethod();
         newObject.name = generateRandomString();
                 insert newObject;


}

My Method

public double RandomNumbersMethod()
{
return Math.random() * 10;
}

My Constructor 

public String generateRandomString(Integer len) {
 
    final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    String randStr = '';

    while (randStr.length() < len) {
       Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), 62);
       randStr += chars.substring(idx, idx+1);
    }
    return randStr;
  
}
Best Answer chosen by Bob.390672021994282E12
Peter Thurston 12Peter Thurston 12
newObject.name = generateRandomString();
should be:
newObject.name = generateRandomString(<insert the length of the random string you want here>);
so something like:
newObject.name = generateRandomString(10); // should return a 10 character random string

All Answers

RamuRamu (Salesforce Developers) 
The below article might help

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_constructors.htm
Bob.390672021994282E12Bob.390672021994282E12
Actually I read it, didnt make sense in this case senario. There is very little documentaion in regards to consructors. 
Peter Thurston 12Peter Thurston 12
I'm pretty sure you just need to pass in the Integer [len] parameter that generateRandomString(Integer len) is expecting...  I don't see a defined constructor without parameters, which is what you're calling on newObject...
Bob.390672021994282E12Bob.390672021994282E12
Could you possible provide an example of how to do that Bryan Revelant Sent from my smart phone
Peter Thurston 12Peter Thurston 12
newObject.name = generateRandomString();
should be:
newObject.name = generateRandomString(<insert the length of the random string you want here>);
so something like:
newObject.name = generateRandomString(10); // should return a 10 character random string
This was selected as the best answer
Bob.390672021994282E12Bob.390672021994282E12
Haha, I know it was something simple 

Thanks