How to programmatically populate Sitecore items (Add item and fields)?
Asked Answered
H

3

5

I'm now battling with adding items via C# to Sitecore database.

The code below executes correctly, however the items aren't being created.

Also, I noticed, that the item["FieldName"]=value; syntax doesn't actually populate the Fields collection.

And Fields collection on the item seems read only, so I can't just call .Add on it (such method doesn't exist).

So - what is the correct way of creating a child item and populating its fields?

I am using the Master database for both the Sitecore backend and this code.

The code I use below:

   using (new Sitecore.SecurityModel.SecurityDisabler())
   {

        Database db = Factory.GetDatabase(this.Database);

        foreach (var vacancy in Articles.Tables[0].Rows)
        {
            var rootItem = db.GetItem(this.RootItem);
            DataRow dr = (DataRow) vacancy;

            var newItem = rootItem.Add(string.Format("{0} {1}", dr["numericID"], dr["job_name"]),
                                       db.GetTemplate(new ID("{GUID}")));

            newItem.Editing.BeginEdit();
            newItem["Job Title"] = dr["job_name"].ToString();//
            newItem.Editing.EndEdit();
        } 
}

More info: newItem.Template.Fields returns a collection with 100 fields

newItem.Fields returns a FieldCollection with only 9 elements in it.

When I pass through the code newItem["field"].Value = value; it does not increment the newItem.Fields collection count.

Of course the "field" key is consistent with ones present in newItem.Template.Fields[x].Name.

Happy answered 2/2, 2012 at 17:10 Comment(0)
T
6

1) Check some things first f.ex:

assing the template to a variable and check what you get there. and better don't do it by ID rather by path:

var templateItem = db.GetTemplate("yourTemplatePath");

now check whether that is the template you want? make sure it's published (it can always cause some inconsistencies)

2) As to the fields not being 'visible', have you tried: item.Fields.ReadAll()

3) What do you mean by "items not being created"? how would you check that?

4) Also - are you sure that this.Database == "master" ?

Trolly answered 3/2, 2012 at 11:1 Comment(4)
2) Yes, this has helped to pre-populate the Fields collection, I'll let you know how I get along.Happy
3) I didn't see them in the Sitecore Content Editor when using the Master database.Happy
Your suggestions have helped, I was missing the Fields.ReadAll() call :)Happy
Spoko - fajnie że mogłem pomóc :)Trolly
V
4

I would recommend two changes:

(1) The item naming approach:

var newItem = rootItem.Add(ItemUtil.ProposeValidItemName(string.Format("{0} {1}", dr["numericID"], dr["job_name"])), db.GetTemplate(new ID("{GUID}")));

This change will handle invalid characters in the proposed name from your other data source.

(2) The field value setting approach:

newItem.Fields["Job Title"].Value = dr["job_name"].ToString();

This will set the raw value of the field to the provided string.

Valerio answered 2/2, 2012 at 21:52 Comment(4)
Thanks. What would happen if I assigned invalid values (e.g. a text string to an Integer field)? Would I receive a nice exception from Sitecore base code, or just (as in my case) no write would happen?Happy
Fields always contain string valuesOvertly
Thanks for the clever suggestion of ProposeValidName, I was missing that too, however this wasn't a problem in this case. I can only mark one answer as "accepted" though :(Happy
Ok, it would still be worth implementing #1 for safety reasons. Perhaps your data could include in invalid character at some point? Defensive coding FTWValerio
I
2

I would suggest setting the field value as

newItem.Fields["Job Title"].Value = dr["job_name"].ToString();//

Everything else looks ok.

Inconsolable answered 2/2, 2012 at 17:16 Comment(2)
if "job_name" allow null values, you need to check if the value is not null before you convert to string.Ribbentrop
Probably worth mentioning that you can use the shorthand newItem["Job Title"] = "whatever"Mammal

© 2022 - 2024 — McMap. All rights reserved.