CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: [Lead__c] - foreign-keys

I am getting an error message when I try to instert a custom object into an exisiting lead object.
List<Lead> leads =[select Id from Lead where Email =:lead.Email ];
if(leads.size()>0)
{
Lead existing_lead = new Lead(Id = leads[0].id);
social_account.Lead__c = existing_lead.Id; //social_account is a custom object that
//has a child relationship to lead.
//ie lead is a parent of social_accounts.
update existing_lead;
insert social_account; //if there is an existing lead with same same email,
//i'd like to insert new social_account to an exsiting lead.
}
I am getting this error:
554 System.DmlException: Update failed. First exception on row 0 with id 00Q3000000WW3isEAD; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: []
Class.ProcessContact.handleInboundEmail: line 81, column 9
External entry point
even if I comment out the 'update existing_lead', i get a similar error message.
554 System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: [Lead__c]
Class.ProcessContact.handleInboundEmail: line 82, column 9
External entry point
I would appreciate any suggestions.
regards

This error means that the Lead record has been converted to a Contact. Once converted, the Lead record cannot be updated. The Lead object has an IsConverted property that you can check to see if it has been converted. If IsConverted is true, ConvertedContactId will hold the contact ID of the new Contact record.
Lead Object reference

You cannot update converted Lead by default, but after Sprint 16 release, there is possibility, just you need to setup few things.
-From Setup, enter User Interface in the Quick Find box, then select User Interface then select Enable "Set Audit Fields upon Record Creation" and "Update Records with Inactive Owners" User Permissions.
-From Setup, enter Profiles in the Quick Find box, then select Profiles. Select the profile and then select Set Audit Fields upon Record Creation.
Here you can find more information's about this.

Related

Acumatica - Creating Custom Usr Field on Purchase Orders for Weight Total

I am trying to add a new field through the customization browser to the Purchase Orders screen (PO301000). I created the field through the New Field button and edited the Data Access slightly to provide a default parameter for the field. Here is the code in the Data Access:
[PXDBDecimal]
[PXDefault(TypeCode.Decimal, "0.0")]
[PXUIField(DisplayName="Weight Total")]
This field will be used to calculate the total weight of the purchase order and I would like it to be stored in the database.
I get this error when publishing:
An error while publishing the database item POOrder
with the message:
Nullable object must have a value.
I have tried changing the PXDBDecimal to a PXDBQuantity. This has to be done through the customization browser and not the database itself because this project will be going on a SaaS hosted site where I do not have access to the database. I have also tried creating the field through the DAC only and I receive this error when trying to open the page:
Invalid column name 'UsrWeightTotal'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UsrWeightTotal'.
When reviewing the project xml for the POOrder table entry in the customization I found there were some extra/missing attributes required for a column type of decimal.
There was a MaxLength property and no DecimalLength property. I compared it to adding a new field of type decimal and looked at the project xml to come up with the following:
<Table TableName="POOrder">
<Column TableName="POOrder" ColumnName="UsrWeightTotal" ColumnType="decimal" AllowNull="True" DecimalPrecision="6" DecimalLength="19" IsNewColumn="True" IsUnicode="True" />
</Table>
I bet the error was complaining about the missing DecimalLength value (as a result was null but required for the publish process).

How to manage related fields and permissions in Odoo 8?

This question started here: How to manage security with One2many fields in Odoo?. But now, I have simplified the problem and the question is not the same one.
The environment and the problem are the same:
class mother(models.Model):
_name = 'mother'
name = fields.Char(string='Name', size=64, required=True)
is_a_good_mother = fields.Boolean(string='Is a good mother?')
#api.multi
def write(self, vals):
_logger.info('I DO NOT KNOW WHY WHEN CREATING A CHILD THIS ORM '
'METHOD IS BEING EXECUTED, RECEIVING THE KEY '
'is_a_good_mother')
return super(mother, self).write(vals)
class child(models.Model):
_name = 'child'
mother_id = fields.Many2one(comodel_name='mother',
string='Mother', ondelete='cascade')
has_a_good_mother = fields.Boolean(
string='Does the child have a good mother?',
related='mother_id.is_a_good_mother',
related_sudo=True)
I have a menu option which opens a form of Child. This form is auto-generated by Odoo.
The problem
I have an user who can create and modify children, but not mothers. When this user creates the child, a security error raises telling that the user belongs to a group which cannot modify the Mother model. This is due to the line related='mother_id.is_a_good_mother', if I remove it, and the I create a new child, the ORM write method of Mother is not called.
So if B has a related child pointing to any field of A, and you create a new record of B, ORM write method of A is called.
I have a security group my_group, with read 1 create 1 write 1 unlink 1 in B and read 1 create 0 write 0 unlink 0 in A. As an user of this group cannot write A, he gets an error when creating a B record.
How can I avoid this error? I have tried with related_sudo=True, but it did not work, may be I did not use it well.
Can anyone help me?
A related field value is stored in the original field of the "mother" object. So when you try to change it on the "child" object, that's where Odoo updates it behind the scenes. If the user making the change doesn't have a permission to change the "mother" object, an exception will be raised.
You need to make sure that users who don't have permissions to change the target object can't set/change the value of related fields pointing to the object. You can do this for example by making it readonly (readonly=True).

How to check status of invitation?

For each User I want to display his invitation status:
"Invitation Sent" or "Invitation Accepted"
Currently I just check if a field encrypted_password in Users table contains anything.
If it is not - then a user did not registered (accepted an invitation) yet but it was sent to him (otherwise this user's record would not exist in DB)
Is there a more elegant way to do it?
Yes you should take a
is_registered:boolean
column in user table which contains default value "false". Now you just have to do is when user get registered that time you just change value to "true".
when ever you want to check is user registered? just do
#user.is_registered? or current_user.is_registered?
this returns true/false

How to avoid MIXED_DML_OPERATION error in Salesforce tests that create Users

Sometimes in Salesforce tests you need to create User objects to run part of the test as a speciifc type of user.
However since the Salesforce Summer 08 update, attempts to create both User objects and normal objects (such as Accounts) in the same test lead to the following error:
MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: Account
Note that the error doesn't happen when you run the tests from Eclipse/Force.com IDE, but it does happen when you deploy to Salesforce and then run the tests from within Salesforce.
How do I re-write my tests to avoid this error?
Here's a simple example of a test that causes the error:
static testMethod void test_mixed_dmlbug() {
Profile p = [select id from profile where name='(some profile)'];
UserRole r = [Select id from userrole where name='(some role)'];
User u = new User(alias = 'standt', email='standarduser#testorg.com',
emailencodingkey='UTF-8', lastname='Testing',
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username='standarduser#testorg.com');
Account a = new Account(Firstname='Terry', Lastname='Testperson');
insert a;
System.runAs(u) {
a.PersonEmail = 'test#madeupaddress.com';
update a;
}
}
Not many Salesforce people on here yet, I guess.
I found a solution, I don't know why it works, but it works.
All parts of the test that access normal objects need to be wrapped in a System.runAs that explicitly uses the current user, like this:
User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) {
// put test setup code in here
}
So, the example text_mixed_dmlbug method given in the question, would become:
static testMethod void test_mixed_dmlbug() {
User u;
Account a;
User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) {
Profile p = [select id from profile where name='(some profile)'];
UserRole r = [Select id from userrole where name='(some role)'];
u = new User(alias = 'standt', email='standarduser#testorg.com',
emailencodingkey='UTF-8', lastname='Testing',
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username='standarduser#testorg.com');
a = new Account(Firstname='Terry', Lastname='Testperson');
insert a;
}
System.runAs(u) {
a.PersonEmail = 'test#madeupaddress.com';
update a;
}
}
Then the MIXED_DML_OPERATION errors stop happening.
It seems like you've found a workaround. I just wanted to try and clear up why you where getting this error.
I think you are running into this issue (per http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects.htm):
sObjects That Cannot Be Used Together in DML Operations
Some sObjects require that you perform DML operations on only one type per transaction. For example, you cannot insert an account, then insert a user or a group member in a single transaction. The following sObjects cannot be used together in a transaction:
* Group1
* GroupMember
* QueueSObject
* User2
* UserRole
* UserTerritory
* Territory
Important The primary exception to
this is when you are using the runAs
method in a test.
In addition, the Summer 08 Release notes (that link is a PDF) say:
In previous releases, in a single
transaction that involved triggers,
you could perform DML operations on
more than one type of sObject, for
example, you could insert an account,
then insert a user. As of Summer
'08, you can only perform DML
operations on a single type of sObject
from the following list of sObjects.
For example, you cannot insert an
account, then insert a user, or update
a group, then insert a group
member.
Group
GroupMember
QueueSObject
User
UserRole
UserTerritory
Territory
In addition, User and Territory now
support the insert and update DML
operations, and UserRole
now supports the insert, update delete
and upsert DML operations.
Apex DML operations are not supported
on the following sObjects:
AccountTerritoryAssignmentRule
AccountTerritoryAssignmentRuleItem
UserAccountTeamMember
This behavior is actually documented in the salesforce documentation: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_dml_non_mix_sobjects.htm?SearchType. Read where it say "Important
The primary exception to this is when you are using the runAs method in a test"
Just found this in the documentation:
Other Uses of runAs
You can also use the runAs method to perform mixed DML operations in your test by enclosing the DML operations within the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations.
So it looks like the RunAs workaround is not a workaround but is assumed by Salesforce as the only way of going by the mixed DML issue.
Hope this helps
Reference
This error is so common when attempting to create user and other objects records in a single transaction in apex.
Workaround in apex class/trigger : use future method for creating user when encountered the error
Workaround in test class : don't try creating a new user data, instead use ))>
code-snippet at -
https://thesalesforcedev.blogspot.com/2019/07/mixeddmloperation-dml-operation-on.html

Django : Setting a generic (content_type) field with a real object sets it to None

Update 3 (Read This First) :
Yes, this was caused by the object "profile" not having been saved. For those getting the same symptoms, the moral is "If a ForeignKey field seems to be getting set to None when you assign a real object to it, it's probably because that other objects hasn't been saved."
Even if you are 100% sure that it was saved, check again ;-)
Hi,
I'm using content_type / generic foreign keys in a class in Django.
The line to create an instance of the class is roughly this :
tag = SecurityTag(name='name',agent=an_agent,resource=a_resource,interface=an_interface)
Where both agent and resource are content_type fields.
Most of the time, this works as I expect and creates the appropriate object. But I have one specific case where I call this line to create a SecurityTag but the value of the agent field seems to end up as None.
Now, in this particular case, I test, in the preceding line, that the value of an_agent does contain an existing, saved Django.model object of an agent type. And it does.
Nevertheless, the resulting SecurityTag record comes out with None for this field.
I'm quite baffled by this. I'm guessing that somewhere along the line, something is failing in the ORM's attempt to extract the id of the object in an_agent, but there's no error message nor exception being raised. I've checked that the an_agent object is saved and has a value in its id field.
Anyone seen something like this? Or have any ideas?
====
Update : 10 days later exactly the same bug has come to bite me again in a new context :
Here's some code which describes the "security tag" object, which is basically a mapping between
a) some kind of permission-role (known as "agent" in our system) which is a generic content_type,
b) a resource, which is also a generic content_type, (and in the current problem is being given a Pinax "Profile"),
and c) an "interface" (which is basically a type of access ... eg. "Viewable" or "Editable" that is just a string)
class SecurityTag(models.Model) :
name = models.CharField(max_length='50')
agent_content_type = models.ForeignKey(ContentType,related_name='security_tag_agent')
agent_object_id = models.PositiveIntegerField()
agent = generic.GenericForeignKey('agent_content_type', 'agent_object_id')
interface = models.CharField(max_length='50')
resource_content_type = models.ForeignKey(ContentType,related_name='security_tag_resource')
resource_object_id = models.PositiveIntegerField()
resource = generic.GenericForeignKey('resource_content_type', 'resource_object_id')
At a particular moment later, I do this :
print "before %s, %s" % (self.resource,self.agent)
t = SecurityTag(name=self.tag_name,agent=self.agent,resource=self.resource,interface=self.interface_id)
print "after %s, %s, %s, %s" % (t.resource,t.resource_content_type,type(t.resource),t.resource_object_id)
The result of which is that before, the "resource" variable does reference a Profile, but after ...
before phil, TgGroup object
after None, profile, <type 'NoneType'>, None
In other words, while the value of t.resource_content_type has been set to "profile", everything else is None. In my previous encounter with this problem, I "solved" it by reloading the thing I was trying to assign to the generic type. I'm starting to wonder if this is some kind of ORM cache issue ... is the variable "self.resource" holding some kind proxy object rather than the real thing?
One possibility is that the profile hasn't been saved. However, this code is being called as the result of an after_save signal for profile. (It's setting up default permissions), so could it be that the profile save hasn't been committed or something?
Update 2 : following Matthew's suggestion below, I added
print self.resource._get_pk_value() and self.resource.id
which has blown up saying Profile doesn't have _get_pk_value()
So here's what I noticed passing through the Django code: when you create a new instance of a model object via a constructor, a pre-init function called (via signals) for any generic object references.
Rather than directly storing the object you pass in, it stores the type and the primary key.
If your object is persisted and has an ID, this works fine, because when you get the field at a later date, it retrieves it from the database.
However -- if your object doesn't have an ID, the fetch code returns nothing, and the getter returns None!
You can see the code in django.contrib.contenttypes.generic.GenericForeignKey, in the instance_pre_init and __get__ functions.
This doesn't really answer my question or satisfy my curiosity but it does seem to work if I pull the an_agent object out of the database immediately before trying to use it in the SecurityTag constructor.
Previously I was passing a copy that had been made earlier with get_or_create. Did this old instance somehow go out of date or scope?