![](/img/trans.png)
[英]How to programmatically populate Sitecore items (Add item and fields)?
[英]Sitecore - How do I correctly populate the Item.Fields hashtable with names for the key (not GUIDs)?
這與Sitecore有點奇怪...基本上,我是從Content API訪問一個項目,但它沒有使用基於字段文本的鍵填充Item.Fields哈希表(我想我會稱之為字段名稱),而是帶有GUID。
例如,以下是一些我用來獲取商品的代碼:
var database = global::Sitecore.Configuration.Factory.GetDatabase("master");
var item = database.GetItem("/sitecore/content/Home");
item.Fields.ReadAll(); // edit, per recommendation... does not work
Sitecore.Data.Fields.Field f = item.Fields["SomeText"];
Assert.IsNotNull(f): // This fails
如果設置斷點並進行調試,我可以看到Item.Fields哈希表中有值(實際上是正確的值),但是鍵都是基於GUID而不是“字段名”,因為大多數代碼示例都使用了這個API建議。
編輯:仔細檢查后,DisplayName和Name字段將從API返回為空字符串(請注意,這些在Sitecore中已明確定義,因此仍不確定問題出在哪里)。 看來這些可能與GUID一起用作哈希表的某種鍵。
問題:我在這里做錯什么了嗎? 我已經發布了數據模板和內容項。 顯然已經建立了連接,因為我從API返回結果,甚至返回正確的值,而不是我期望用來引用數據值的鍵。
參考文獻:
來自Sitecore的示例數據的屏幕截圖(注意GUID為鍵):
來自以上鏈接文檔的代碼示例:
訪問“標題”字段:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Fields.Field titleField = home.Fields["title"];
if(titleField!=null)
{
home.Editing.BeginEdit();
titleField.Value = "//TODO: replace with appropriate value";
home.Editing.EndEdit();
}
訪問系統字段“ ArchiveDate”:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item sample = master.GetItem("/sitecore/content/home/sample");
Sitecore.Data.Fields.DateField archiveField =
sample.Fields[Sitecore.FieldIDs.ArchiveDate];
反編譯Sitecore.Kernel.dll可以看到:
public static class FieldIDs
{
// stripped down version
/// <summary>The ID of the 'Archive date' field.</summary>
public static ID ArchiveDate;
static FieldIDs()
{
FieldIDs.ArchiveDate = new ID("{56C15C6D-FD5A-40CA-BB37-64CEEC6A9BD5}");
}
}
如果我理解正確,則您希望Fields集合返回該項目可用的所有字段,即使它們沒有值。 默認情況下,Sitecore將僅返回具有值的字段。
您可以通過在訪問字段集合之前調用ReadAll()
方法來解決此問題。 因此,在您的示例中:
item.Fields.ReadAll();
Sitecore.Data.Fields.Field f = item.Fields["SomeText"];
Assert.IsNotNull(f): // This succeeds
我有相同症狀的問題。 對我而言,根本原因是出版問題。 盡管模板本身已發布,但包含我的模板的文件夾尚未發布。 因此,我可以看到調試器中的字段具有正確的值和ID,但沒有名稱。 解決方案是確保還發布了模板的所有父項。
因此,我最終走了我在問題中提到的路線(這是Sitecore在內部使用的內容,@ technophoria414是Sitecore開發人員的最佳實踐)。
基本上:
namespace MyProject.Core.Data.Sitecore.Fields
{
public static class ContentItem
{
// stripped down version
public static ID DESCRIPTION_TEXT;
static ContentItem()
{
DESCRIPTION_TEXT= new ID("{56C15C6D-FD5A-40CA-BB37-64CEEC6A9BD5}"); // this will be some GUID out of Sitecore
}
}
}
用法將是這樣的:
var query = string.Format("fast:/sitecore/content/HomePageItems//*[@ContentSlug='{0}']", input);
var item = Database.SelectSingleItem(query);
var descriptionText = item.Fields[ContentItem.DESCRIPTION_TEXT].Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.