Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Dan 3 posts 28 karma points
    Jul 12, 2014 @ 17:36
    Dan
    0

    Set value of Umbraco.DropDown programatically

    Hi, Looking for some assistance in setting a Dropdown value programatically, I was under the impression for a simple Umbraco.DropDown data type I'd just be able to do the following..

    ContentService c = new ContentService();
    IContent myContent = c.GetById(1054);
    
    myContent.SetValue("status", "Reserved"); // 'status' being the alias for my Umbraco.DropDown data type, 'reserved' being an available prevalue option I've set up on the data type
    
    c.SaveAndPublishWithStatus(myContent);
    

    A member picker, and text field which I'm also updating during the same bit of logic work without a hitch - however the dropdown doesn't seem to work at all.

    I would expect the drop down value to have changed from 'Available' to 'Reserved' however when I review the content in the backoffice the dropdown has been reset to the default (no) value.

    Thought this would be quite straight forward (and apologies if I've missed something silly..) but starting to pull my hair out with it a little now, any help would be greatly appreciated!

    Thanks

  • Dan 3 posts 28 karma points
    Jul 12, 2014 @ 21:39
    Dan
    5

    After discovering the DataTypeService, and realising that I needed the internal Id of the prevalue rather than the string value I'd assigned it.. I've put together the following solution - unsure if I've done it 'right' but works for me..

    ContentService c = new ContentService();
    
    // Fetch the content I'm updating..
    IContent myContent = c.GetById(1054);
    
    // I need to find the Id of the 'Reserved' prevalue option on the Status data type I created
    DataTypeService dts = new DataTypeService();
    
    // Get an instance of the status editor
    var statusEditor = dts.GetAllDataTypeDefinitions().First(x => x.Name == "Status");
    
    // Now we can fetch the pre-values collection, and use linq to find the Id for the 'Reserved' option
    int preValueId = dts.GetPreValuesCollectionByDataTypeId(statusEditor.Id).PreValuesAsDictionary.Where(d => d.Value.Value == "Reserved").Select(f => f.Value.Id).First();
    
    myContent.SetValue("status", preValueId); // Finally update the status with the new Id.
    
    
    c.SaveAndPublishWithStatus(kit); // All done, save and publish
    

    Hope this helps someone get on the right track - feel free to comment with amends if I've done anything daft.

  • M N 125 posts 212 karma points
    Mar 11, 2017 @ 22:54
    M N
    5

    Thank you Dan,

    Very helpful. Added this to my own helpers. Modified slightly so it will pull the Property on the Content node by the Alias, then get the data type guid from the Property.. Function for anyone that needs, saving/publishing left outside of this routine.

        public static void SetDropDownValue(IContent editableNode, string propAlias, string val)
        {
            // Grab data type service
            IDataTypeService dts = ApplicationContext.Current.Services.DataTypeService;
    
            //find the property on the content node by its alias
            Property prop = editableNode.Properties.FirstOrDefault(a => a.Alias == propAlias);
    
            if (prop != null)
            {
                //get data type from the property
                var dt = dts.GetDataTypeDefinitionById(prop.PropertyType.DataTypeDefinitionId);
    
                //get the id of the prevalue for 'val'  
                int preValueId = dts.GetPreValuesCollectionByDataTypeId(dt.Id).PreValuesAsDictionary.Where(d => d.Value.Value == val).Select(f => f.Value.Id).First();
    
                editableNode.SetValue(propAlias, preValueId); 
    
            }
        }
    

    Usage, in the context of the original post by Dan

    ContentService c = new ContentService();
    IContent myContent = c.GetById(1054);
    SetDropDownValue(myContent, "status",  "Reserved); 
    c.SaveAndPublishWithStatus(myContent);
    
  • Jez Reel R. Maghuyop 3 posts 33 karma points
    Dec 28, 2014 @ 16:19
    Jez Reel R. Maghuyop
    0

    This is the answer that I've been looking for! thank god someone posted it in here I can't find anything on the net.

    did you find the way just by using the Name instead of the Id?

  • Casper Andersen 126 posts 508 karma points
    Jul 29, 2015 @ 09:24
    Casper Andersen
    0

    After many weeks of searching, i found this thread and this was 100% the solution i needed. Thank you so much!

  • Casper Andersen 126 posts 508 karma points
    Jul 29, 2015 @ 09:24
    Casper Andersen
    0

    Could you by any chance set your own answer as the correct one, since that makes it easier for people to find.

  • Sam 26 posts 137 karma points c-trib
    Nov 04, 2015 @ 21:00
    Sam
    0

    This is very complicated really.

    What I have done is made a custom property editor for 'Dropdown' which just stores the selected value as a string.

    Then I can set or retrieve the value just as a string without having to translate it.

  • Nicholas Westby 2054 posts 7103 karma points c-trib
    Nov 04, 2015 @ 21:27
    Nicholas Westby
    0

    I believe the decision to store drop down values as ID's rather than as the text value makes sense. That way, if you ever need to rename a drop down value, you only have to do that in one place (rather than on every content node that made use of that drop down).

    I would not recommend replacing the built-in drop down property editor with a custom one just to change the storage mechanism.

  • Lev Nuznyy 19 posts 122 karma points
    Nov 23, 2015 @ 08:11
    Lev Nuznyy
    0

    Hello, I use a similar method has been said above but I have an error overload

    enter image description here

  • Lev Nuznyy 19 posts 122 karma points
    Nov 23, 2015 @ 09:00
    Lev Nuznyy
    0

    Solved a problem since, but still an interesting opportunity there is another way

    var myService = ApplicationContext.Current.Services.DataTypeService;
    
  • Arjan 21 posts 91 karma points
    Dec 21, 2015 @ 11:49
    Arjan
    0

    note that once the proprty is set using the string value, you need to reset it manually through the backoffice, otherwise using the preValueId still doesn't work :(

  • David Armitage 510 posts 2081 karma points
    May 21, 2017 @ 14:22
    David Armitage
    2

    Hi Guys,

    Here are some useful methods a wrote. Sure they will come in handy....

    public static int GetDataTypeId(string dataTypeName)
            {
                var dataTypeService = ApplicationContext.Current.Services.DataTypeService;
                var allTypes = dataTypeService.GetAllDataTypeDefinitions();
                return allTypes.First(x => dataTypeName.InvariantEquals(x.Name)).Id;
            }
    
    public static PreValueCollection GetPreValues(string dataTypeName)
            {
                int dataTypeId = GetDataTypeId(dataTypeName);
                var dts = ApplicationContext.Current.Services.DataTypeService;
                var preValues = dts.GetPreValuesCollectionByDataTypeId(dataTypeId);
                return preValues;
            }
    
    public static List<SelectListItem> PreValuesToSelectList(string dataTypeName)
            {
                return (from x in GetPreValues(dataTypeName).PreValuesAsDictionary
                        select new SelectListItem
                        {
                            Text = x.Value.Value,
                            Value = x.Value.Id.ToString()
                        }).ToList();
            }
    
    
    public static string GetPreValueString(string preValueId)
            {
                int Id;
                if(int.TryParse(preValueId, out Id))
                {
                    return library.GetPreValueAsString(Id);
                }
    
                return string.Empty;
            }
    
  • Mihir Ajmera 32 posts 145 karma points
    Aug 09, 2019 @ 10:47
    Mihir Ajmera
    0

    Hi All,

    I do the same scenario in Umbraco version 8.1.0 so, How I can bind selected value in content node value and display in the back office?

    var registrationContent = _contentService.Create(model.FullName, 1497, "registration"); registrationContent.SetValue("jobTitle", model.JobTitle);

    I try with the above case not I can`t assign a selected value using surfacecontroller method in MVC.

    Anyone have about then please give a solution so I can implement this case in my custom form.

  • Ben Margevicius 1 post 22 karma points
    Jan 09, 2020 @ 22:18
    Ben Margevicius
    1

    I know it's late. But with Umbraco 8.4 I had to set the value to a Json Array of the value. Even if DDL can only select one value.....

    var dataType = dataTypeService.GetDataType("Email Newsletter - Dropdown");
                        ValueListConfiguration prevalues = (ValueListConfiguration)dataType.Configuration;
                        var selectednewslettervalue = prevalues.Items.Where(a => a.Value == model.SelectedEmailNewsletterOption).Select(a => a.Value).ToArray();
                        if (selectednewslettervalue.Count() > 0)
                        {
                            var s = JsonConvert.SerializeObject(selectednewslettervalue);
                            evt.SetValue("emailNewsletter", s);
                        }
    
  • M N 125 posts 212 karma points
    Aug 09, 2019 @ 14:46
    M N
    0

    Have only kicked the tires with U8, have you saved the new content? U7 - one of these?

    _contentService.Save(registrationContent);
    _contentService.SaveAndPublishWithStatus(registrationContent, 0, true);
    
  • David Armitage 510 posts 2081 karma points
    May 30, 2020 @ 05:34
    David Armitage
    1

    Hi Guys,

    For Umbraco 8 here is an example of my insert method also populating the dropdown field.

    var content = _contentService.Create(reviewObject.Email, reviewObject.ParentId.Value, "umb8srReview");
                        if (content != null)
                        {
                            content.SetValue("firstName", reviewObject.FirstName);
                            content.SetValue("lastName", reviewObject.LastName);
                            content.SetValue("email", reviewObject.Email);
    
                            //###############
                            //THIS IS THE DROPDOWN FIELD
                            content.SetValue("rating", JsonConvert.SerializeObject(new[] { reviewObject.Rating }));
                            //###############
    
                            content.SetValue("review", reviewObject.Review);
                            content.SetValue("approved", reviewObject.Approved);
                            content.SetValue("reviewDate", reviewObject.ReviewDate);
                            content.SetValue("relatedId", reviewObject.RelatedId);
                            content.SetValue("memberId", reviewObject.MemberId);
                        }
    
                        _contentService.SaveAndPublish(content);
    

    Simply wrap this around your value.

    JsonConvert.SerializeObject(new[] { "your-value-here" })
    

    Hope this helps someone.

    Regards

    David

  • Andrew Bright 84 posts 244 karma points
    Aug 24, 2023 @ 10:28
    Andrew Bright
    0

    Having a similar issue on Umbraco 10 essentially if a dropdown value is not set then I want to apply a default value which seems to be fine but not seeing the update value reflected in media section unless the page is refreshed:

     // If the reviewEvery property isn't set, set the default to "12 months"
                          SaveEventExtension.SetDropdownValues(media.Properties.FirstOrDefault(f => f.Alias == "reviewEvery"),
                                "Review Frequency", "12 months", _dts);
    
    if (string.IsNullOrWhiteSpace(property?.GetValue()?.ToString()))
                {
                    IDataType? preValueSource = dts.GetDataType(dataType);
                    ValueListConfiguration? preValues = (ValueListConfiguration?)preValueSource?.Configuration;
                    ValueListConfiguration.ValueListItem? listValue = preValues?.Items?.Find(item => item.Value == value);
    
                    property?.SetValue(
                        JsonConvert.SerializeObject(new[]
                        {
                            listValue.Value
                        })
                    );
    
                }
    
Please Sign in or register to post replies

Write your reply to:

Draft