Orchard - how to access taxonomy field of a custom content type programmatically - orchardcms

I have a custom content type called Store, which has a Brands taxonomy field. A Store can have multiple Brands associated with it.
I have been tasked with building an import/export routine that allows the user to upload a CSV file containing new Stores and their associated Brands.
I can create the Stores other fields OK, but can't work out how to set the taxonomy field?
Can anyone tell me how I access the Taxonomy field for my custom content type?
Thanks in advance.

OK so (as Bertrand suggested), using the Import/Export feature might be a better way to go, but as a relative noob on Orchard I don't have the time to spend looking at it and couldn't find a good tutorial.
Below is an alternative approach, using the TaxonomyService to programatically assign Terms to a ContentItem.
First of all, inject the ContentManager and TaxonomyService into the constructor...
private ITaxonomyService _taxonomyService;
private IContentManager _contentManager;
public MyAdminController(IContentManager contentManager, ITaxonomyService taxonomyService)
{
_contentManager = contentManager;
_taxonomyService = taxonomyService;
}
Create your ContentItem & set the title
var item = _contentManager.New("MyContentType");
item.As<TitlePart>().Title = "My New Item";
_contentManager.Create(item);
Now we have a ContentItem to work with. Time to get your taxonomy & find your term(s)...
var taxonomy = _taxonomyService.GetTaxonomyByName("Taxonomy Name");
var termPart = _taxonomyService.GetTermByName(taxonomy.Id, "Term Name");
Add the terms to a List of type TermPart...
List<TermPart> terms = new List<TermPart>();
terms.Add(termPart);
Finally, call UpdateTerms, passing in the ContentItem, terms to assign and the name of the field on the ContentItem you want to update...
_taxonomyService.UpdateTerms(item, terms.AsEnumerable<TermPart>(), "My Field");
Hope this helps someone. Probably me next time round! : )

Related

How to get source list types of particular list/record field?

Here is I have two entity custom fields with list/record type,
custom_dev_j15 entity field has a custom source list (eg: one, two, three, four, etc)
custom_qa_v93 entity field has a standard source list as an object (eg: customer )
I've two vendor entity custom fields as stated in screenshots of question,
custentity473 --> customer is selected as list source
custentity474 --> custom_dev_j15_m_list as selected as list source ( which is custom list)
Here is snippet that i used to get the options of these fields,
// Snippet
var fieldDetails = {};
var record = nlapiCreateRecord("Vendor");
var field = record.getField("custentity473");
var selectoptions = field.getSelectOptions();
for ( var i in selectOptions) {
var Option = {
id : selectOptions[i].getId(),
label : selectOptions[i].getText()
}
Options.push(Option);
}
fieldDetail["options"] = Options;
But my need is to get source list information like name of the list source (customer or custom_dev_j15_m_list) via suitescript
any idea on how to get this information?
Thanks in advance
I'm not sure I understand this question for what you're trying to do.
In NetSuite almost always, you accommodate to the source list types because you know that's the type, and if you need something else (e.g. a selection which is a combination/or custom selection you'll use a scripted field)
Perhaps you can expand on your use case, and then we can help you further?

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 CMS update record directly in database

I have got list of content items , for each content items I need to add a meta keyword and descriptions. I am using VandelayIndustries module for this. I have got list of keywords and descriptions along with the contentItemId .I can find out the published ContentItem from ContentItemVersionRecord.
Is there a way I can directly insert record in Vandelay_Industries_MetaRecord table with Id as ContentItemId and keywords and Descriptions.
You will need to create an import method. Your ContentItems should have a MetaPart. You can achieve this either by going to Content Definition in the Orchard dashboard or by modifing the ContentType in the migrations.
ContentDefinitionManager.AlterTypeDefinition("MyContentType",
type => type
.WithPart("MetaPart"));
Create a method that iterates thru the csv file and will add the entries:
foreach(var entry in listFromFile) {
var item = _contentManager.Get(entry.Id).As<MediaPart>();
item.Key = entry.Key;
item.Description = entry.Description;
}
And that's it.

Sharepoint Custom List with TimeStamp Field

I'm making a custom SharePoint List. I need a TimeStamp Field, but the only available type, by default, is DateTime.
Any help?
I think you would need to create a custom field type so that you can control the display of a DateTime type and validation etc - see this blog post for more info
I had the same problem in Sharepoint 2010 and solved it. Posting in case someone else finds this useful :)
To achieve this one must use the "Calculated" columntype.
From GUI:
Create new column
Pick type "Calculated".
Select "Created" column and add to formula.
Save.
From code:
As far as I can tell, there is two options to achieve this:
Access the "Created" and either set it's ShowInDisplayForm property to true or add the column to a view (for example the DefaultView).
Create a calculated column that points to the "Created" column, just as the GUI-example does. The trick is to set the "Formula" & the "OutputType" properties.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["test"];
string fieldName = list.Fields.Add("Timestamptest", SPFieldType.Calculated, false);
SPFieldCalculated field = list.Fields[fieldName] as SPFieldCalculated;
field.Formula = "=Created";
field.OutputType = SPFieldType.DateTime;
field.ShowInEditForm = false;
field.Update();
list.Update();
SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add(field);
defaultView.Update();
}
}
});

Accessing SPLIstItem properties in SharePoint

I'm trying something very simple - accessing my SharePoint list's items and their properties.
However, SPListItem.Properties count is zero for all normal lists. Everything works as expected for document and pages libraries. So, if the list items are based on document type, all is good. If they are based on item, properties are not returned.
I've tried in two environments, with new sites created from OOTB publishing templates, with new lists which are based on OOTB content types etc. Always the same thing.
Right amount of SPListItems is always returned. Title and Name are fine. It's just that the .Properties hashtable is totally empty.
In desperation, I wrote a web part that outputs the following (ugly!) diagnostics.
foreach (SPList list in SPContext.Current.Web.Lists)
{
foreach (SPListItem item in list.Items)
{
Label label = new Label();
label.Text = "Name: " + item.Name + "Property count: " + item.Properties.Count;
this.Controls.Add(label);
}
}
The only observation is that it works exactly as I described earlier. I just share the code to show that this is the most basic operation imaginable.
Here is sample output - I've added the line breaks for readability ;-)
Name: Test Property count: 0
Name: default.aspx Property count: 21
Obviously item "Test" is an item based list item and default.aspx is a page.
Has anyone ever encountered anything like this? Any ideas?
item["FieldName"] is the canonical way to get a value of a metadata column in a SharePoint list. If you need to get the list of available fields for a SharePoint list, check the parent SPList object's Fields property which is a collection of the fields in this list. Each of those field objects will have a property called InternalName and that is what you should use to access its value when you are working with an instance of SPListItem.
Are you trying to get the field Values? Sadly, they are not strongly typed:
string ModifiedBy = (string)item["Author"];
To get the proper names of the fields (they have to be the internal names), go to the List and then List Settings. You will find the List of Columns there. Click on any Column Name to go to the Edit Page, and then look at the URL in the Address Bar of your Browser. At the very end, there should be a parameter "Field=Editor" or similar - that's your internal field name.
If you wonder why a field like "Test Field" looks strange, that is because Sharepoint encodes certain characters. A Space would be encoded to x0020 hence the Internal Name for "Test Field" is "Test_x0020_Field".
In order to get the proper field type to cast to:
string FieldType = item["Author"].GetType().FullName;
(The Intermediate Window in Visual Studio is tremendously helpful for this!)
I have found the following extension to the SPListItem class to be very helpful.
internal static class SharePointExtensions
{
internal static Dictionary<string, object> PropertiesToDictionary(this SPListItem item)
{
// NOTE: This code might be temping - but don't do it! ...itdoes not work as there are often multiple field definitions with the same Title!
// return item.Fields.Cast<SPField>().ToDictionary(fld => fld.Title, fld => item[fld.Title]);
Dictionary<string, object> dict = new Dictionary<string, object>();
var fieldNames = item.Fields.Cast<SPField>().Select(fld => fld.Title).Distinct().OrderBy(sz => sz).ToArray();
foreach (fieldName in fieldNames)
dict.Add(sz, item[fieldName]);
return dict;
}
}
with it you can simply do:
item.PropertiesToDictionary()
...and you will have a nice Linq dictionary object that will work just the way you'd expect. Is it a little heavy-weight / low-performance? Sure. Are most people willing to make that trade-off? I think so...
Do you run SPListItem.Update() or .SystemUpdate() after setting the properties?
If you want to get an object out of a SPField of a SPListItem you've got to do like this:
SPField field = ((SPList)list).Fields.GetField("FieldName");
object fieldValue = field.GetFieldValue(((SPListItem)item)[field.Title].ToString());
The ListItem.Properties hashtable will be empty unless you assign to it.
SPListItem item = properties.ListItem;
item.Properties["Key"] = "value";
int total = item.Properties.Count;
Answer:
"total == 1"
SPList yourList = web.Lists["Your list name"];
string sColumnValue = oSPListItem[yourList.Fields["yourSiteColumn display
name"].InternalName].ToString();

Resources