5

When the standard Name field of an object is set as Text, it shows a weird behavior if left empty. It is not possible to mark it as required or non-required, but when editing a record from its standard edit page, the field is required:

Required Name field

No problem so far: the field is required in any case. The problem arises when it comes to insertion from code. If we insert a record from code:

CustomObject__c r = new CustomObject__c();
insert r;

... we get no error. Instead, the record is inserted with the short, 15-character Id copied into its Name field. What I would expect is an exception with the same error that we've got in the standard edit page.

This problem does not occur with custom fields: if a custom field is marked as required, it will be so both in the standard edit page and from code.

I did not find any mention to this on documentation. Is this behavior new in Spring'14? Has any of you found this same problem before?

1
  • 5
    No, this is not new behaviour, its been this way for as long as I can remember :-) May 23, 2014 at 10:29

2 Answers 2

5

It has always worked with this. I've been writing Salesforce code over 3 years now. If you don't give it a name through code, it defaults it to it's ID.

The UI will require a user to input a String, but why does the code really need to force it to? The developer is the one creating the code and so then knows what should be acceptable.

If you really want to force the developer to not leave the name blank, create a validation rule. Have the validation rule check to see if the Id and Name field are the same, or the Name is blank. In either of those cases have it error.

TL;DR; This functionality has been around for years. Nothing has changed.

1
  • The UI will require a user to input a String, but why does the code really need to force it to? The developer is the one creating the code and so then knows what should be acceptable. That's true, but the same rule could be applied to any other required field. It's a special behavior, only for this field, so it implies a little incoherence. Of course there must be technical reasons for this, just like @crmprogdev points out, but in any case from a developer making use of this, it looked as a weird behavior. May 26, 2014 at 7:00
0

If you do this from the UI, the text for Name is a look-up based on the ContactID (or UserID as the case may be). In Apex, you're getting the ID directly. That's the difference you're seeing between the two. In the UI, it's a display issue. In Apex, its an issue of making certain you have the correct Contact or User. When you query, you can always get the Contact.Name or User.Name for later display.

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.