Example #1
0
        /// <summary>
        /// Saves the current post edit model.
        /// </summary>
        /// <param name="api">The current api</param>
        public void Save(Api api)
        {
            var newModel = false;

            // Get or create post
            var post = Id.HasValue ? api.Posts.GetSingle(Id.Value) : null;

            if (post == null)
            {
                post     = new Piranha.Models.Post();
                newModel = true;
            }

            // Map values
            Mapper.Map <EditModel, Piranha.Models.Post>(this, post);

            // Check action
            if (Action == SubmitAction.Publish)
            {
                post.Published = DateTime.Now;
            }
            else if (Action == SubmitAction.Unpublish)
            {
                post.Published = null;
            }

            // Remove old categories
            post.Categories.Clear();

            // Map current categories
            if (!String.IsNullOrWhiteSpace(SelectedCategories))
            {
                foreach (var str in SelectedCategories.Split(new char[] { ',' }))
                {
                    var categoryName = str.Trim();

                    var cat = api.Categories.GetSingle(where : c => c.Title == categoryName);
                    if (cat == null)
                    {
                        cat = new Piranha.Models.Category()
                        {
                            Title = categoryName
                        };
                        api.Categories.Add(cat);
                    }
                    post.Categories.Add(cat);
                }
            }
            if (newModel)
            {
                api.Posts.Add(post);
            }
            api.SaveChanges();

            this.Id = post.Id;
        }