delete multiple objects which are inside array in Apex - salesforce

Very new to Apex and never touched java, basically what I am trying to do is delete all records then insert records inside multiple custom objects. Bellow is my code for just the deleting part but I have no idea how to get this working. Once I know how to get it working I can then put it inside a lop etc I just need the basics running first.
List<String> myList = new List<String> {'More_Info_Request__c'};
String foo = myList.get(0);
List<More_Info_Request__c> existing = [SELECT Id From :foo ];
delete existing;
Any help would be amazing

for future me or future human this is how I fixed it:
List<String> objectNames = new List<String> {'More_Info_Request__c', 'Object1__c', 'Object2__c'};
for (String objectName : objectNames) {
List<SObject> existing = Database.query('select id from ' + objectName);
delete existing;
}

Related

Dynamic change of field value using sObject

I'm trying to use sObject to dynamically change Name field objects across while organization.
I've tried using SomeId.getSObjectType().newSObject(SomeId) to create the sObject, but when I try to change the Name field I have error
Variable does not exist: Name
Map<Id, string> idsToUpdate = new Map<Id, string>();
// Put the Id's and associated name values in the map
List<SObject> sObjectsToUpdate = new List<SObject>();
foreach(Id idToUpdate : idsToUpdate.keySet) {
SObject o1 = idToUpdate.getSObjectType().newSObject(idToUpdate);
o1.Name = idsToUpdate.get(idToUpdate);
sObjectsToUpdate.add(o1);
}
update sObjectsToUpdate;
As I can see other posts, this is the way of creation dynamic update of objects.
Any idea why this happens?
Not all objects have a name field, you should check for the existence of the name field before trying to set the field also you must use the put method
Map <String, Schema.SObjectField> fieldMap = o1.getSobjectType().getDescribe().fields.getMap();
if(fieldMap.containsKey('Name')){
o1.put('Name', 'Test');
}

Add image in arraylist

I have to create a WPF app. which collects strings and images in rows. I am not sure if I could use multidimedional array or ArrayList but I cannot figure out how to insert the image into the array. Anyone can help me?
So if you want 1 Image against a variable number of string's
your Image becomes the Key of the Dictionary and the List<string> it's corresponding Value.
public Dictionary<Image, List<string>> MyCollection { get; private set; }
...
// Initialisation
MyCollection = new Dictionary<Image, List<string>>();
// Adding new Row
var tempImage = new Image();
MyCollection.Add(tempImage, new List<string>(){"A", "B", "C"});
// Modifying existing row -- for `Key` tempImage we'll add a string "D" and remove string "A"
List<string> existingValues = MyCollection[tempImage];
existingValues.Add("D");
existingValues.Remove("A");
// Removing rows
MyCollection.Remove(tempImage);
You can download this sample from Here. Hope that clarifies some of the usage ideas. I'd suggest looking at some Simple Examples to get a better understanding of how you can use Dictionary<...> to achieve your requirements.

MVVM database delete Method

I want to DELETE some items from my Model which I generated from the database like that:
db = new TestDBEntities();
foreach (var item in db.Farbe)
{
_model.Add(new Farbe { FarbauswahlNr = item.FarbauswahlNr, Kurztext = item.Kurztext, Ressource = item.Ressource,Vari1 = Convert.ToBoolean(item.Var1) ,Vari2 = item.Vari2 });
}
I'm showing this Model in a RadGridView and deleting by Selecting and Index per Rightcklick on the mouse like this:
public void ExecuteDelete(object obj)
{
farbliste.Model.Remove(SelectedIndex);
ListeAktualisieren();
}
Now the question is how do I Delete something from my Database because if I just Delete from my Model it wont work and that's also not what I want.
Btw some variable are named in German sorry...
you have to save your context. Your context in the first block of code is db.
So:
db = new TestDBEntities();
db.entity.Remove(db.entity.Find(SelectedIndex));
db.SaveChanges();
Entity is the name of your table/object from entity frramework. I would also suggest wraping this is a using block for the db

Export data as C# / VB format to use them in EF Code First's Database Initialization

Some times, sample data is important but boring to generate due to many related tables.
So, in Entity Framework Code First, I think it's an elegant way to insert them in DropCreateDatabaseIfModelChanges::Seed().
But is there a way to export existing data from database back to a string as C# / VB sentences that insert poco objects?
If it works, we may use it to backup data gracefully, or save to multiple .cs by scenes, switch them as needed to better our test, etc.
DATABASE EXPORTS AS THE FOLLOWING CODE:
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander", },
new Student { FirstMidName = "Meredith", LastName = "Alonso", },
new Student { FirstMidName = "Arturo", LastName = "Anand", },
// ...
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
As #Luke suggested in his comment. the best way is to generate Json files for your seed data.
in this article, you can find the easy way to generate your Json from SQL query.
Then all you need is to read them by Newtonsoft.Json
e.g.
var countriesStream = new StreamReader(HostingEnvironment.MapPath("jsonFile.json"));
try
{
countriesList = JsonConvert.DeserializeObject<List<Country>>(countriesStream.ReadToEnd());
}

Apex Trigger Context Variable

Here my code for apex trigger.
trigger LeadTrigger on Lead (after insert)
{
if(Trigger.isInsert){
for(Lead newLead: Trigger.new)
{
//newLead.RecrodTypeId //'Give value of record type id.
//newLead.RecordType.Name //'Null'
}
}
}
Why "newLead.RecordType.Name" returns null?
The lists of objects available in triggers only have values for the fields on the object the trigger is running on. No relationships are traversed, only the IDs of the lookup records are included.
Therefore, to pull in any extra information you need to from related objects needs to be queried for.
You'll want to do something like this:
trigger LeadTrigger on Lead (after insert) {
map<id, RecordType> mapRecordTypes = new map<id, RecordType>();
if(Trigger.isInsert) {
for(Lead newLead: Trigger.new) {
mapRecordTypes.put(newLead.RecordTypeId, null);
}
}
for(RecordType rt : [select Id, Name from RecordType
where Id in : mapRecordTypes.ketSet()]) {
mapRecordTypes.put(rt.Id, rt);
}
for(Lead newLead : Trigger.new) {
string recordTypeName = mapRecordTypes.get(sLead.RecordTypeId).Name;
}
}
This is probably because some of your leads that just got inserted don't have record types associated with them. This is normal. You can enforce that record type selection is mandatory through configuration, if that's what you're looking for.
[EDIT]
Now I think I understand the issue (from your comment). The reason is that since you're in a trigger, the associated RecordType referenced object is not available. The RecordTypeId will always be available since it is literally part of the trigger object as an Id. However, child objects (referenced objects) will not be available to simply reference from within a trigger. To do this you need to create a map of the referenced object in question by doing an additional SOQL call WHERE Id IN: theIdList.
From Apex, not in a trigger, you need to specifically call this field out from your SOQL like this:
List<Lead> leads = [SELECT Id, RecordType.Name FROM Lead];
What just happened there is that the child object, the RecordType in this case, was included in the query and therefore available to you. By default a trigger will not have all of your child objects pre-selected and therefore need to be selected afterwards from within the trigger or class called by the trigger:
List<Id> recIds = new List<Id>();
for(Lead l : leads)
{
recIds.add(l.RecordTypeId);
}
List<RecordType> rt = [SELECT Id, Name FROM RecordType WHERE Id IN :recIds];
Map <Id, String> idRecNameMap = new Map<Id, String>();
for(RecordType r : rt)
{
idRecNameMap.put(r.Id, r.Name);
}
// And finally...
for(Lead l : Trigger.new)
{
String tmpRecordTypeName = idRecNameMap.get(l.RecordTypeId);
}
I did not test this code but I think it look ok. Hope this makes sense.
you can't get extra information on the related objects from this trigger. if you want to get more information you need to make query for other objects.
List<RecordType> records = [SELECT Id, Name FROM RecordType WHERE Id = newLead.RecrodTypeId];
string myname = records[0].name;
but remember that you shouldn't make a query in for loop. so if you wanted to do it in the right way go for Adam's solution.
Put some system debug inside the loop and check your system debug logs for more information
system.debug('lead:' + newLead);
inside the for loop and see what is being passed in. You may find that it is null.
We cant really give you a good answer without knowint the rest of your set up.

Resources