How to get a reference to the currently edited item when inside a custom field in Sitecore

感情迁移 提交于 2020-01-17 03:21:31

问题


In Sitecore I have created a custom field (via this recipe: http://sdn.sitecore.net/Articles/API/Creating%20a%20Composite%20Custom%20Field/Adding%20a%20Custom%20Field%20to%20Sitecore%20Client.aspx) The field is for use in the content editor. The custom field has a menuitem attached (the little textbutton rendered just above the field) The custom field work as expected and the menuitem hooks into code in the custom field class as it should. However, the logic I need to implement for the menuitem requires that I get a reference to the item that is currently being edited by the user in the content editor.

However, to my surprise this doesn't work:

Sitecore.Context.Item

This does not give me the item that the user is currently editing, but instead the "content editor" item, which is always the same. I would think there would simply be a property of some object in the API, but I can't find it.


回答1:


If you are following this article then you will have defined a property on your control..

public string ItemID { get; set;}

.. this will be populated with the ID for the item you are editing. You should be able resolve the Item object from this ID using something like:

Sitecore.Data.Database.GetDatabase("master").GetItem(ItemID)

.. if you are just looking just for the value of the field you are editing you can use the base.Value field.




回答2:


The best place to ask this would be on the developer forum, you should get a good response on there.

Though, taking a look through the Sitecore code, it looks like this might be what you want. Try reading it from the ViewState:

public string ItemID
{
    get
    {
        return base.GetViewStateString("ItemID");
    }
    set
    {
        Assert.ArgumentNotNullOrEmpty(value, "value");
        base.SetViewStateString("ItemID", value);
    }
}



回答3:


Stephen Pope is right, though there are more properties that you can 'automagiacally' retrieve from Sitecore. Some properties, just like ItemID are put on the field via reflection. There's also the ItemVersion and Source that can be useful for your custom controls.

If you're intereseted, take a peek inside the class Sitecore.Shell.Applications.ContentEditor.EditorFormatter, and especially its method SetProperties:

ReflectionUtil.SetProperty(editor, "ItemID", field.ItemField.Item.ID.ToString());
ReflectionUtil.SetProperty(editor, "ItemVersion", field.ItemField.Item.Version.ToString());


来源:https://stackoverflow.com/questions/8148279/how-to-get-a-reference-to-the-currently-edited-item-when-inside-a-custom-field-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!