Create a custom Image Field Type and create a new class for it (or override the default Image Field) to provide the Source path string.
Custom Image Field class:
public class CustomImageField : Sitecore.Shell.Applications.ContentEditor.Image
{
#region Fields
private string _itemId;
private Item _item;
#endregion
#region Properties
public string ItemId
{
get { return _itemId; }
set
{
Assert.ArgumentNotNull(value, "value");
_itemId = value;
}
}
// This is the context item
public Item Item => _item ?? (_item = Client.GetItemNotNull(ItemId));
public new string Source
{
get { return base.Source; }
set
{
if (getCustomMediaPath) // this check is not necessarily required
{
// add custom code to set the path that will be used by the Media Browser dialog
var mediaFolder = "media folder";
var mediaRoot = $"/sitecore/media library/{mediaFolder}";
base.Source = mediaRoot;
}
else
{
base.Source = value;
}
}
}
#endregion
}
In the Sitecore Core DB:
Create a new Image Field item. Field items are located at:
/sitecore/system/Field types
The default Image field is located at:
/sitecore/system/Field types/Simple Types/Image
Custom Fields can be added to:
/sitecore/system/Field types/Custom Field Types
Set the Assembly and Class fields of your custom image field class to make use of that code.
Alternatively you can define a custom prefix that maps to an assembly and namespace and use that shortcut to point to the new Class via the Control field.
config patch for Control prefix:
<configuration xmlns:x="http://www.sitecore.net/xmlconfig/">
<sitecore>
<controlSources>
<source mode="on" namespace="Project.Web.Shell.Applications.ContentEditor" assembly="Project.Web" prefix="CustomFields" />
</controlSources>
</sitecore>
</configuration>
With this configuration the Control field can be set to CustomFields.CustomImageField
Use the new Field
Now you can use this field type (if you made a custom one, otherwise it's just the default Image field) in your templates.
Note on Custom Fields:
Using a new Field Type item will require additional work to get the field to render properly in Experience Editor.
The SitecoreHelper
ends up calling BeginField
, which in turn calls the renderField
pipeline, passing in the RenderFieldArgs
.
The renderField
pipeline has a processor called Sitecore.Pipelines.RenderField.GetImageFieldValue
. You will need to patch in an override of this processor. The Process
method of this processor first checks the FieldTypeKey
of the args. This check will need to be updated to support the new image field type.