I have several custom folder types such as Year Folder or Quarter Folder. When the user creates a folder of this type he enters the name and selects an item from a dropdown (year etc.). 90% of the time the name is identical to the value of the dropdown so I am going to use JavaScipt to populate the Name feild in the new item form with a token. If the user doesn't change the token, I will use an ItemAdding event receiver to replace the token value with the value from the dropdown.
However, I have run into a problem. I can't actually chnage the "Name" feild.
properties.AfterProperties["Name"];
doesn't exist. The internal name of "name" is FileLeafRef but if try to access it, I get an error that it is read only.
So is it possible to change the "Name" propertie in ItemAdding event receiver?
I have also attempted to cancel the creation of the item in ItemAdding event receiver and create my own new item. The code is below
public void createItem(SPItemEventProperties properties)
{
try
{
SPList list = properties.List;
SPWeb web = properties.Web;
string url = properties.AfterUrl;
SPFolder folder = web.GetFolder(url);
SPContentType type = list.ContentTypes[properties.AfterProperties["ContentType"].ToString()];
if (checkIfFolder(type)) // checks if current item is a folder
{
string name = replaceTokens(properties); // returns the new name that will be used
SPItem newItem = list.Items.Add(url, SPFileSystemObjectType.Folder, name);
foreach (DictionaryEntry entry in properties.AfterProperties)
{
System.Diagnostics.Debug.WriteLine(entry.Key.ToString() + " " + entry.Value.ToString());
if (entry.Key.ToString() != "FileSystemObjectType")
{
newItem[entry.Key.ToString()] = entry.Value.ToString();
}
}
this.EventFiringEnabled = false;
newItem.Update();
this.EventFiringEnabled = true;
}
}
catch (SPException spEx)
{
// file already exists?
//if (spEx.ErrorCode == -2130575257)
// return false;
//else
// throw spEx;
}
}
This code executes and no errors are generated. However, no new item is created either. What is wrong?