예제 #1
0
 public FieldOption Save(FieldOption fieldOption)
 {
     if (fieldOption.Field != null)
     {
         fieldOption.Field = null;
     }
     return(fieldOption.Id > 0 ? _rep.Update(fieldOption) : _rep.Add(fieldOption));
 }
        public async Task <Field> Update(Field field)
        {
            var filter = Builders <Field> .Filter.Eq("Id", field.Id);

            try
            {
                if (string.IsNullOrEmpty(field.Name))
                {
                    throw new ApplicationException("Name field is required.");
                }

                var fieldToEdit = await Get(field.Id);

                if (fieldToEdit == null)
                {
                    throw new ApplicationException("Unable to find field specified.");
                }

                fieldToEdit.Name         = field.Name;
                fieldToEdit.DefaultValue = field.DefaultValue;

                // Delete field options that were removed
                foreach (FieldOption fo in fieldToEdit.ValueOptions)
                {
                    if (!field.ValueOptions.Contains(fo))
                    {
                        await _fieldOptionRepository.Delete(fo.Id);
                    }
                }

                if (field.ValueOptions != null &&
                    (field.Type == FieldTypes.SingleSelectList ||
                     field.Type == FieldTypes.MultiSelectList ||
                     field.Type == FieldTypes.CheckboxList ||
                     field.Type == FieldTypes.RadioList))
                {
                    List <FieldOption> options = new List <FieldOption>();
                    foreach (FieldOption opt in field.ValueOptions)
                    {
                        if (string.IsNullOrEmpty(opt.Name))
                        {
                            continue;
                        }

                        if (opt.Id == ObjectId.Empty)
                        {
                            options.Add(await _fieldOptionRepository.Add(new FieldOption()
                            {
                                FieldId = field.Id,
                                Name    = opt.Name
                            }));
                        }
                        else
                        {
                            options.Add(await _fieldOptionRepository.Update(opt));
                        }
                    }

                    fieldToEdit.ValueOptions = options;
                }

                await _context.Fields.ReplaceOneAsync(filter, fieldToEdit);

                return(await Get(field.Id));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }