How to assign a value to an Orchard ContentPickerField from code? - c#-4.0

I am working on an Orchard site that needs to be able to use some customized forms to create new content items.
To handle this I'm using a controller to display a form and then trying to create the new content items on post back by populating the dynamic items and then sending them through the ContentManagerService's Create() function.
This is working ok until I got to the content picker field I have as part of my content item.
In my project I have a content type of Question Record that has a SubmittedBy field that is a Content Picker Field.
Here is what I can see in the immediate window while processing the post back:
> dynamic q = _questionService.NewQuestion("Why doesn't this work?");
{Custom.Website.Models.Question}
base {Orchard.ContentManagement.ContentPart}: {Custom.Website.Models.Question}
IsNew: true
OriginalQuestion: "Why doesn't this work?"
Summary: null
> q.QuestionRecord
{Orchard.ContentManagement.ContentPart}
base {System.Dynamic.DynamicObject}: {Orchard.ContentManagement.ContentPart}
ContentItem: {Orchard.ContentManagement.ContentItem}
Fields: Count = 5
Id: 0
PartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentPartDefinition}
Settings: Count = 0
TypeDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypeDefinition}
TypePartDefinition: {Orchard.ContentManagement.MetaData.Models.ContentTypePartDefinition}
Zones: {Orchard.UI.ZoneCollection}
> q.QuestionRecord.SubmittedBy
{Orchard.ContentPicker.Fields.ContentPickerField}
base {Orchard.ContentManagement.ContentField}: {Orchard.ContentPicker.Fields.ContentPickerField}
ContentItems: null
Ids: {int[0]}
The ContentItems property is read-only and the Ids when assigning a new int[] to the Ids array I get a System.ObjectDisposedException with the message: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
Are there any workarounds to get this value set in code or do I need to create my own property to store the related content item ids? It would be very helpful to have the admin interface of the ContentPickerField also available.
Thanks.

If you have a reference to the ContentPickerField, you can assign it a value using the Ids property.
In example (assuming your content type has a part called Question which has a field called SubmittedBy):
var submittedByField = ((dynamic)q.ContentItem).Question.SubmittedBy;
sbmittedByField.Ids = new[] { submittedById };
As Bertrand mentioned, the format to access a content field is: contentItem.PartName.FieldName.
If you attached a field to a type directly via the admin, the part name has the same name as the type name, hence contentItem.TypeName.FieldName (where TypeName is actually the name of the implicitly created part).

Related

Kentico Document Get Page Meta Data Custom Page Type

When trying to retrieve DocumentPageTitle and DocumentPageDescription using GetStringValue() on a custom page type TreeNode, the result is always coming back as the default value (in this case an empty string) passed into the method.
I'm able to successfully retrieve other column values as well as standard document properties such as DocumentName, DocumentID and AbsoluteURL, but not the document meta properties.
The respective fields in the Meta tab of document/page do have values and are being successfully rendered in the by default such as <meta name="description" content=".." />
// returns empty string
string documentPageDescription = DocumentContext.CurrentDocument.GetString("DocumentPageDescription", string.Empty);
// returns empty string
TreeNode document = parameters[0] as TreeNode;
string documentPageDescription = document.GetStringValue("DocumentPageDescription", string.Empty);
I've tried setting option Inherits fields from page type to "Page (menu item)", but that did not help.
Does the custom page type need to inherit from something specifically or have a specific setting activated to access these values? Or if what I think is a TreeNode in fact isn't, how could I get the TreeNode from this object that has the properties listed before available?
Thank you for any help you can provide.
ValidationHelper.GetString(CMS.DocumentEngine.DocumentContext.CurrentDocument.GetValue("DocumentPageDescription"), string.Empty)
Two things to check, one, are you sure the meta data is available on the page you are pulling? Two, is your API actually pulling all the data for that page?
I've used these in my test and both returned the metadata.
var page = DocumentHelper.GetDocuments().Path("/Articles/Coffee-Beverages-Explained").FirstObject;
Response.Write(page.GetStringValue("DocumentPageDescription", string.Empty));
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
TreeNode tn = tree.SelectNodes().OnCurrentSite().Path("/Articles/Coffee-Beverages-Explained").FirstObject;
Response.Write(tn.GetStringValue("DocumentPageDescription", string.Empty));
The DocumentPageTitle and DocumentPageDescription were coming back as null when the custom page type document/page was inheriting from parent/global values.
I was able to use the following to get the properties when not inheriting, while falling back to the parent value when inheriting was taking place:
string documentPageTitle = document.GetStringValue("DocumentPageTitle", DocumentContext.CurrentTitle);
This approach came from the following issue on Kentico DevNet.
Thank you for your help and suggestions, it's appreciated.

Orchard - Insert content item to Content Type programmatically

I have problem to insert content item to Content type. In Orchard administration I created custom content type with fields: name, surname, date etc...
But inserting new content items I must do in controller method programmatically. I tried this, buth this no work:
var item = this._services.ContentManager.New("Zadosti");
item.Name.Value = "Some dummy usage of this product"; // I can not access name field
this._services.ContentManager.Create(item);
You probably attached the fields directly to the custom "Zadosti" content type?
What Orchard in that case does is attaching the fields to a part named exactly the same as the type, it doesnt ever attach the fields to the content type itself (dont let the dashboard fool you!)
Therefore you can access the field as following:
var item = this._services.ContentManager.New("Zadosti");
// 'Zadosti' in here is the name of your part, which is
// the same as your content type name
item.Zadosti.Name.Value = "Some dummy usage of this product";
this._services.ContentManager.Create(item);

Can't set Orchard field values unless item already created

I seem to be having a problem with assigning values to fields of a content item with a custom content part and the values not persisting.
I have to create the content item (OrchardServices.ContentManager.Create) first before calling the following code which modifies a field value:
var fields = contentItem.As<MyPart>().Fields;
var imageField = fields.FirstOrDefault(o => o.Name.Equals("Image"));
if (imageField != null)
{
((MediaLibraryPickerField)imageField).Ids = new int[] { imageId };
}
The above code works perfectly when against an item that already exists, but the imageId value is lost if this is done before creating it.
Please note, this is not exclusive to MediaLibraryPickerFields.
I noticed that other people have reported this aswell:
https://orchard.codeplex.com/workitem/18412
Is it simply the case that an item must be created prior to amending it's value field?
This would be a shame, as I'm assigning this fields as part of a large import process and would inhibit performance to create it and then modify the item only to update it again.
As the comments on this issue explain, you do need to call Create. I'm not sure I understand why you think that is an issue however.

Sharepoint 2010 Metadata fields Key, Value

I'm currently working with Sharepoint 2010 and Sharepoint API on creating a document library with some existing document lists.
I have created a WinForm that loops through a given doc lists and then add them to diffrent document libraries depending on 'Type(A metadata field)' of the document. Type is determined by reading the "Metadata fields" for the specific document. Metadata fields are read by creating Hashtable of SPFields
Question
When document metadata field is read to determin the 'Type', I have realised that the Metadatafield 'Type'(Key) actually pulls out as 'Type+TaxHTField0' and value for the Key pulls out as value|GUID
So for example if my Metadata field is called Doc_x0020_Type when it returns from the API it comes out as Doc_x0020_TypeTaxHTField0 the value for this should be just 'products' but it comes out as
products|21EC2020-3AEA-1069-A2DD-08002B30309D
Is there a setting we can set in sharepoint to eleminate adding extra charaters and GUID to both Key and Value for metadata fields?
Below is what I've done to rectify the issue, but wondered if it's a setting we can set in sharepoint
public String GetLibrary(Hashtable itemProperties)
{
String typeMetaField = "Doc_x0020_TypeTaxHTField0";
String sKey = String.Empty;
foreach (DictionaryEntry deEntry in itemProperties)
{
sKey = deEntry.Key.ToString();
if (sKey == typeMetaField){
_type = deEntry.Value.ToString();
string[] value = _type.Split('|');
_type = value[0].Trim();
}
}
return GetDocumentLibrary(_type);
}
This is by design.
If you add a taxonomy field to your own contenttype (for instance named 'MyTaxField') SharePoint will autogenerate a hidden 'Notes' field that contains the label and the guid of the values you select in the UI.
This is quite helpful when using SPSiteDataQuery since it will return empty values for taxonomy fields that allow multiple values (works with single value taxonomy fields though).
The only way to get the taxonomy values is to have a for the hidden field named 'MyTaxFieldTaxHTField0'.
But as you have discovered, this field might not be formatted as youd like :).
I have not tested this, but did you check if your contenttype contains a field called "Doc_x0020_Type" (possible of type TaxonomyFieldValue(Collection))?

Get SPListItem in another format

I want to get different Rows from an SPListItem. I'll show you my problem with an example.
This code
Console.WriteLine(SPItemName["Created By"]);
or
Console.WriteLine(SPItemName["Created By"].ToString);
returns "8;UserName" (8 is the User ID).
If I look up the row in SharePoint Designer, i can choose even a format for this data field.
So i could get the html code of this field.
How to set the format (like html code or text) of a datafield in c#?
thanks
Use Either SPFieldLookupValue
If you need just the username, use SPFieldLookupValue to seperate id from value:
var userValue = new SPFieldLookupValue(SPItemName["Created By"] as string)
Then you can:
userValue.LookupValue to return UserName
userValue.LookupId to return Id
Or SPFieldUserValue
Or better yet, you can create SPFieldUserValue object to access any other user properties like email, login name, etc..
SPFieldUserValue objUserFieldValue = new SPFieldUserValue(web, SPItemName["Created By"].ToString());
Afterwards you can use:
objUserFieldValue.User.LoginName;
objUserFieldValue.User.Name;
objUserFieldValue.User.ID;
objUserFieldValue.User.Groups;
objUserFieldValue.User.Roles;
objUserFieldValue.User.Email;
objUserFieldValue.User.Sid;
objUserFieldValue.User.UserToken;
http://www.sharepointkings.com/2009/04/spfielduservalue-and.html
Note: to create SPFieldUserValue you must pass reference to web, that's because SharePoint has to get additional user information from user information list to construct SPFieldUserValue object.

Resources