Apex Lookup Value copy to second Object - salesforce

I have a trigger that moves the values from one object to another, but am stuck on how to move the values of the lookup fields from one to the other. what is the syntax? If you could show me the Company and the Chair_Rep ones that would be great!
<Lead> newLeadsList= new List<Lead>();
for (integer i=0; i<newContacts.size(); i++) {
if (newContacts[i].createlead__c == TRUE && oldContacts[i].createlead__c == FALSE ) {
newLeadsList.add(new Lead(
firstName = newContacts[i].firstName,
lastName = newContacts[i].lastName,
***Company = newContacts[i].account.name,***
Status = 'identified',
LeadSource = newContacts[i].leadsource ,
Product_Interest__c = 'CE',
//ContactLink__c = newContacts[i].ID,
Title = newContacts[i].title,
Email = newContacts[i].email,
//***Chair_Rep__c = newContacts[i].Chair_Rep__c***
Phone = newContacts[i].Phone,
MobilePhone = newContacts[i].MobilePhone,
// Address = newContacts[i].MailingAddress,
//Website = newContacts[i].Website,
nickname__c = newContacts[i].Nickname__c

Lookup fields should contain references (IDs) on records.
Is 'Company' a standard Lead field in your code?
***Company = newContacts[i].account.name,***
If so, then it's a Text(255) type field, which cannot be used as lookup.
If you need to make a lookup on a Contact's account record, then you can create a custom Lookup field on Lead with reference to Account. And then you could try this code (assuming ContactCompany is that custom lookup field :
ContactCompany__c = newContacts[i].AccountId
or
ContactCompany__c = newContacts[i].Account.Id
Chair_Rep__c and newContacts.Chair_Rep__c should be lookup fields on same object. Then this
Chair_Rep__c = newContacts[i].Chair_Rep__c
or this should work
Chair_Rep__c = newContacts[i].Chair_Rep__r.Id

Related

How to get next id for ID generation strategy = GenerationType.TABLE

Is there an easy way to get the next id of an object which use id generation strategy GenerationType.TABLE and a custom database table? My problem is that allocation size is not 1 (which is fine - optimization), but this way JPA doesn't update the sequence table on every object creation. So I'm wondering is there a way to hit next sequence ( I need it for different operation) and next time new object is created it should use next sequence as well. So id which I will use for different purpose will be skipped next time a new object is created.
Example of the mapping:
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TestIdGenerator")
#GenericGenerator(
name = "TestIdGenerator",
strategy = "enhanced-table",
parameters = {
#Parameter(name = "table_name", value = "sequences"),
#Parameter(name = "segment_column_name", value = "key_column_txt"),
#Parameter(name = "segment_value", value = "test_id"),
#Parameter(name = "value_column_name", value = "next_id"),
#Parameter(name = "increment_size", value = "20"),
#Parameter(name = "optimizer", value = "pooled-lo")
}
)
#Column(name = "test_id")
#EqualsAndHashCode.Include
#ToString.Include
private Integer id;
I'm using SequenceStyleGenerator (Hibernate 5).
How about just invoking the same code that Hibernate does? Something like this:
Integer nextValue = (Integer) session.getSessionFactory()
.unwrap(SessionFactoryImplementor.class)
.getRuntimeMetamodels()
.getMappingMetamodel()
.findEntityDescriptor(MyEntity.class)
.getIdentifierGenerator()
.generate(session, null)

How to insert all Picklist values as Active in already inserted picklist field through metadata api

I have the following code...but When i am inserting multi values to picklist field through metadata api all values are inserted but as inactive value only last value is inserted as active and this last active value make the all prior values as inactive.Please help.
MetadataService.CustomObject customObj;
customObj = new MetadataService.CustomObject();
MetadataService.MetadataPort service = createService();
MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = objectName +'.'+ fieldName;
customField.label = fieldLabel;
customField.type_x = fieldType;
//Create the valueSet for picklist type
MetadataService.ValueSet picklistValueSet = new MetadataService.ValueSet();
//For each ValueSet, we have either ValueSetValuesDefinition or ValueSettings and some other attributes
MetadataService.ValueSetValuesDefinition valueDefinition = new MetadataService.ValueSetValuesDefinition();
List<MetadataService.CustomValue> values = new List<MetadataService.CustomValue>();
MetadataService.CustomValue customValue1 = new MetadataService.CustomValue();
//Adding "Default" value as one picklist value in the newly created picklist
customValue1.fullName = valFullName ;
customValue1.description = '';
customValue1.isActive =TRUE;
customValue1.default_x = FALSE;
customValue1.label = valLabel;
values.add(customValue1);
//It will be list of CustomValue
valueDefinition.value = values;
valueDefinition.sorted = false;
//set the valueSetDefinition
picklistValueSet.valueSetDefinition = valueDefinition;
//Set the valueSet for picklist type
customField.valueSet = picklistValueSet;
That is not possible, you have to take the manual step to activate the picklist values inserted

MVC Model is using values for old table entries, but new entries return NULL

I have an interesting little problem. My controller is assigning values to the properties in my model using two tables. In one of the tables, I have some entries that I made a while ago, and also some that I've just added recently. The old entries are being assigned values correctly, but the new entries assign NULL even though they're in the same table and were created in the same fashion.
Controller
[HttpPost]
[Authorize]
public ActionResult VerifyReservationInfo(RoomDataView model)
{
string loginName = User.Identity.Name;
UserManager UM = new UserManager();
UserProfileView UPV = UM.GetUserProfile(UM.GetUserID(loginName));
RoomAndReservationModel RoomResModel = new RoomAndReservationModel();
List<RoomProfileView> RoomsSelectedList = new List<RoomProfileView>();
GetSelectedRooms(model, RoomsSelectedList);
RoomResModel.RoomResRmProfile = RoomsSelectedList;
RoomResModel.GuestId = UPV.SYSUserID;
RoomResModel.FirstName = UPV.FirstName;
RoomResModel.LastName = UPV.LastName;
RoomResModel.PhoneNumber = UPV.PhoneNumber;
return View(RoomResModel);
}
GetUserProfile from the manager
public UserProfileView GetUserProfile(int userID)
{
UserProfileView UPV = new UserProfileView();
ResortDBEntities db = new ResortDBEntities();
{
var user = db.SYSUsers.Find(userID);
if (user != null)
{
UPV.SYSUserID = user.SYSUserID;
UPV.LoginName = user.LoginName;
UPV.Password = user.PasswordEncryptedText;
var SUP = db.SYSUserProfiles.Find(userID);
if (SUP != null)
{
UPV.FirstName = SUP.FirstName;
UPV.LastName = SUP.LastName;
UPV.PhoneNumber = SUP.PhoneNumber;
UPV.Gender = SUP.Gender;
}
var SUR = db.SYSUserRoles.Find(userID);
if (SUR != null)
{
UPV.LOOKUPRoleID = SUR.LOOKUPRoleID;
UPV.RoleName = SUR.LOOKUPRole.RoleName;
UPV.IsRoleActive = SUR.IsActive;
}
}
}
return UPV;
}
The issue I see is that this database has a somewhat poor design, and that particular record fell into the trap of that poor design. Consider that you have two ID's on that table:
SYSUserProfileID
SYSUserID
That's usually an indication of a bad design (though I'm not sure you can change it), if you can, you should merge anything that uses SYSUserID to use SYSUserProfileID.
This is bad because that last row has two different ID's. When you use db.Find(someId) Entity Framework will look for the Primary Key (SYSUserProfileID in this case) which is 19 for that row. But by the sounds of it, you also need to find it by the SYSUserID which is 28 for that row.
Personally, I'd ditch SYSUserID if at all possible. Otherwise, you need to correct the code so that it looks for the right ID column at the right times (this will be a massive PITA in the future), or correct that record so that the SYSUserID and SYSUserProfileID match. Either of these should fix this problem, but changing that record may break other things.

How do I make a mutableArrayValue that I can access through a relationship?

I've added a to-many relationship called listItems between my entities Person and ListItem in my data model, and then successfully added objects to a given Person using
let personSelectedListItems = person.mutableSetValue(forKey: "listItems")
personSelectedListItems.addObjects(from: selectedListItems)
print("personSelectedListItems after addObjects contains \(personSelectedListItems)")
Where selectedListItems is an array of objects of type ListItem. The print statement gives:
personSelectedListItems after addObjects contains Relationship 'listItems' on managed object (0x6080000d2050) <PersonMO: 0x6080000d2050> (entity: Person; id: 0xd000000000040002 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/Person/p1> ; data: {
age = Ky;
firstName = Uykyu;
image = <89504e47 0d0a1a0a 0000000d 49484452 000002cc 00000333 08020000 003d00d3 35000000 01735247 4200aece 1ce90000 001c>;
isVisited = 0;
lastName = Kuyuy;
listItems = (
"0xd000000005140000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p325>",
"0xd000000005680000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p346>",
"0xd0000000023c0000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p143>"
);
locationCity = Uyk;
locationState = You;
notes = "";
phoneNumber = "";
score = nil;
}) with objects {(
<ListItemMO: 0x6000000b6c20> (entity: ListItem; id: 0xd000000005140000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p325> ; data: {
category = Meta;
isSelected = 1;
listItem = "Similar values";
listItemStatus = 1;
listItemWeight = 1;
people = (
"0xd000000000040002 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/Person/p1>"
);
}),
<ListItemMO: 0x6000000af900> (entity: ListItem; id: 0xd000000000080000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p2> ; data: {
category = Appearance;
isSelected = 1;
listItem = Attractive;
listItemStatus = 3;
listItemWeight = 1;
people = (
"0xd000000000040002 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/Person/p1>"
);
}),
<ListItemMO: 0x6000000b27e0> (entity: ListItem; id: 0xd0000000023c0000 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/ListItem/p143> ; data: {
category = Behavior;
isSelected = 1;
listItem = "Good grammar";
listItemStatus = 1;
listItemWeight = 1;
people = (
"0xd000000000040002 <x-coredata://1350DE85-4F65-462A-9C36-1EEE3D5298CD/Person/p1>"
);
})
)}
This is good, because I want to have these objects created for each Person, but it's bad because it's an unordered set that I'm seemingly not able to access. I'd like for it to be a mutable array so I can access each object at an index, but when I do
let personSelectedListItems = person.mutableArrayValue(forKey: "listItems")
personSelectedListItems.addObjects(from: selectedListItems)
print("personSelectedListItems after addObjects contains \(personSelectedListItems)")
I get this error message:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSManagedObjects of entity 'Person' do not support -mutableArrayValueForKey: for the property 'listItems''
Which is puzzling, since I don't know why mutableSetValueForKey: was was supported but the array version wasn't. I'd really like to be able to access the objects through the relationship, ideally through dot notation. What is the best way to go about this?
Core Data to-many relationships are always represented by sets. Part of the support for this is that NSManagedObject implements mutableSetValue(forKey:), which is one of the documented ways to access the relationship. Since to-many relationships are sets, NSManagedObject does not support mutableArrayValue(forKey:), as that error message indicates.
If you want an ordered relationship, mark it as ordered in the data model editor, and then you can use NSOrderedSet. It's still not an array but it does have ordering.
Both #Wain and #TomHarrington pointed me in the right direction on this, but here's what the answer to my question was (after some searching and tinkering):
First and foremost, I needed to mark the to-many relationship as 'ordered' in the Data Model Inspector of my data model file. The second thing was to change
let personSelectedListItems = person.mutableSetValue(forKey: "listItems")
personSelectedListItems.addObjects(from: selectedListItems)
print("personSelectedListItems after addObjects contains \(personSelectedListItems)")
to
let personSelectedListItems = person.mutableOrderedSetValue(forKey: "listItems")
personSelectedListItems.addObjects(from: selectedListItems)
print("personSelectedListItems after addObjects contains \(personSelectedListItems)")
so that mutableOrderedSetValue would reflect the ordered nature of the relationship. After that, I had a returned set that was in order. Hurray! But now how do I access and change those individual objects through the relationship? That brings me to the third thing - I had to downcast the set to my class (called ListItemMO). To grab the first object in the ordered set and then change a property through the relationship, it looks like this:
if let listItemSet = personVar.listItems?.object(at: 0) as? ListItemMO {
listItemSet.listItemStatus = 0
}

Google App Engine - Get from repeated StructuredProperty

I have the following structures:
class UserOther(ndb.Model):
other_type = ndb.StringProperty(indexed = True)
other_data = ndb.StringProperty(indexed = False)
class User(ndb.Model):
name = ndb.StringProperty(default = "NULL", indexed = False)
email = ndb.StringProperty(default = "NULL", indexed = False)
active = ndb.BooleanProperty(default = True)
others = ndb.StructuredProperty(UserOther, repeated = True)
updated_at = ndb.DateTimeProperty(auto_now = True)
How can I use an User key id and a string for other_type(like "job") to get and be able to edit that information. I tried using the ancestor parameter, but perhaps I didn't do that correctly.
user_key = ndb.Key("User", user_id)
user = user_key.get()
other = UserOther.query(UserOther.other_type == "job", ancestor = user_key).get()
So if i print my user looks like this :
1425436064.0User(key=Key('User', 5171003185430528), active=True, email=u'NULL', name=u'NULL', others=[UserOther(other_data=u'0', other_type=u'job'), UserOther(other_data=u'0', other_type=u'times_worked'), UserOther(other_data=u'0', other_type=u'times_opened')], updated_at=datetime.datetime(2015, 3, 6, 10, 35, 24, 838078))
But if I print the job variable it is
1425436759.0None
You've misunderstood how to query for structured properties. The UserOther entity doesn't live on its own, it's part of the relevant User entity, so that's what you need to query.
The documentation explains exactly how to do this, but in summary you would do:
job = User.query(User.others.other_type == "job").get()
What I would do is get the user (by id) and then filter the 'others' in code:
user = User.get_by_id(user_key_id)
for other in user.others:
if other.other_type == 'job':
print other.other_data # do edits

Resources