Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement missing forms selectpart and options #7281

Merged
merged 5 commits into from
Oct 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Forms/Assets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[
{
"generateSourceMaps": false,
"inputs": [
"Assets/scss/SelectOptionsEditor/selectOptionsEditor.scss"
],
"output": "wwwroot/Styles/selectOptionsEditor.css"
},
{
"inputs": [
"Assets/js/SelectOptionsEditor/selectOptionsEditor.js"
],
"output": "wwwroot/Scripts/selectOptionsEditor.js"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
function initializeSelectOptionsEditor(elem, data, defaultValue, modalBodyElement) {

var previouslyChecked;

var store = {
debug: false,
state: {
options: data,
default: defaultValue
},
addOption: function () {
if (this.debug) { console.log('add option triggered') };
this.state.options.push({ text: '', value: '' });
},
removeOption: function (index) {
if (this.debug) { console.log('remove option triggered with', index) };
this.state.options.splice(index, 1);
},
getOptionsFormattedList: function () {
if (this.debug) { console.log('getOptionsFormattedList triggered') };
return JSON.stringify(this.state.options.filter(function (x) { return !IsNullOrWhiteSpace(x.text) }));
}
}

var selectOptionsTable = {
template: '#select-options-table',
props: ['data'],
name: 'select-options-table',
methods: {
add: function () {
store.addOption();
},
remove: function (index) {
store.removeOption(index);
},
uncheck: function (index) {
if (index == previouslyChecked) {
$('#customRadio_' + index)[0].checked = false;
store.state.default = null;
previouslyChecked = null;
}
else {
previouslyChecked = index;
}
},
getOptionsFormattedList: function () {
return store.getOptionsFormattedList();
}
}
};

var selectOptionsModal = {
template: '#select-options-modal',
props: ['data'],
name: 'select-options-modal',
methods: {
getOptionsFormattedList: function () {
return store.getOptionsFormattedList();
},
showModal: function () {
$(modalBodyElement).modal();
},
closeModal: function () {
var modal = $(modalBodyElement).modal();
modal.modal('hide');
}
}
};

new Vue({
components: {
selectOptionsTable: selectOptionsTable,
selectOptionsModal: selectOptionsModal
},
data: {
sharedState: store.state
},
el: elem,
methods: {
showModal: function () {
selectOptionsModal.methods.showModal();
}
}
});

}

function IsNullOrWhiteSpace(str) {
return str === null || str.match(/^ *$/) !== null;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.select-options-table {
.courier {
font-family: Courier New, Courier, monospace;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Forms.Models;
using OrchardCore.Forms.ViewModels;

namespace OrchardCore.Forms.Drivers
{
public class SelectPartDisplayDriver : ContentPartDisplayDriver<SelectPart>
{
private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
deanmarcussen marked this conversation as resolved.
Show resolved Hide resolved
};

private readonly IStringLocalizer S;

public SelectPartDisplayDriver(IStringLocalizer<SelectPartDisplayDriver> stringLocalizer)
{
S = stringLocalizer;
}

public override IDisplayResult Display(SelectPart part)
{
return View("SelectPart", part).Location("Detail", "Content");
}

public override IDisplayResult Edit(SelectPart part)
{
return Initialize<SelectPartEditViewModel>("SelectPart_Fields_Edit", m =>
{
m.Options = JsonConvert.SerializeObject(part.Options ?? Array.Empty<SelectOption>(), SerializerSettings);
m.DefaultValue = part.DefaultValue;
});
}

public async override Task<IDisplayResult> UpdateAsync(SelectPart part, IUpdateModel updater)
{
var viewModel = new SelectPartEditViewModel();

if (await updater.TryUpdateModelAsync(viewModel, Prefix))
{
part.DefaultValue = viewModel.DefaultValue;
try
{
part.Options = String.IsNullOrWhiteSpace(viewModel.Options)
? Array.Empty<SelectOption>()
: JsonConvert.DeserializeObject<SelectOption[]>(viewModel.Options);
}
catch
{
updater.ModelState.AddModelError(Prefix + '.' + nameof(SelectPartEditViewModel.Options), S["The options are written in an incorrect format."]);
}
}

return Edit(part);
}
}
}
17 changes: 17 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Forms/Models/SelectPart.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using OrchardCore.ContentManagement;

namespace OrchardCore.Forms.Models
{
public class SelectPart : ContentPart
{
public SelectOption[] Options { get; set; }
public string DefaultValue { get; set; }
}

public class SelectOption
{
public string Text { get; set; }

public string Value { get; set; }
}
}
4 changes: 4 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Forms/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ static Startup()
TemplateContext.GlobalMemberAccessStrategy.Register<FormInputElementPart>();
TemplateContext.GlobalMemberAccessStrategy.Register<LabelPart>();
TemplateContext.GlobalMemberAccessStrategy.Register<InputPart>();
TemplateContext.GlobalMemberAccessStrategy.Register<SelectPart>();
TemplateContext.GlobalMemberAccessStrategy.Register<TextAreaPart>();
TemplateContext.GlobalMemberAccessStrategy.Register<ButtonPart>();
}
Expand Down Expand Up @@ -53,6 +54,9 @@ public override void ConfigureServices(IServiceCollection services)
services.AddContentPart<InputPart>()
.UseDisplayDriver<InputPartDisplay>();

services.AddContentPart<SelectPart>()
.UseDisplayDriver<SelectPartDisplayDriver>();

services.AddContentPart<TextAreaPart>()
.UseDisplayDriver<TextAreaPartDisplay>();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace OrchardCore.Forms.ViewModels
{
public class SelectPartEditViewModel
{
public string Options { get; set; }
public string DefaultValue { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
@using OrchardCore.Forms.ViewModels
@model SelectPartEditViewModel

<script asp-src="~/OrchardCore.Forms/Scripts/selectOptionsEditor.min.js" debug-src="~/OrchardCore.Forms/Scripts/selectOptionsEditor.js" asp-name="selectOptionsEditor" at="Foot" depends-on="vuejs, vuedraggable"></script>
<style asp-src="~/OrchardCore.Forms/Styles/selectOptionsEditor.min.css" debug-src="~/OrchardCore.Forms/Styles/selectOptionsEditor.css"></style>

<script at="Foot">
initializeSelectOptionsEditor(document.getElementById('@Html.IdFor(m => m)'), @Html.Raw(Model.Options), '@Model.DefaultValue', document.getElementsByClassName('@Html.IdFor(m => m)-ModalBody'));
</script>

<script type="text/x-template" id="select-options-table">
<table class="table table-bordered table-sm select-options-table">
<thead class="thead-light">
<tr>
<th scope="col">@T["Option Text"]</th>
<th scope="col">@T["Value"]</th>
<th scope="col" colspan="3">@T["Default?"]</th>
</tr>
</thead>
<draggable v-model="data.options" :tag="'tbody'">
<tr v-for="(option, index) in data.options" :key="index">
<td>
<input type="text" class="form-control" v-model="option.text" placeholder="@T["Enter the text"]" />
</td>
<td>
<input type="text" class="form-control courier" v-model="option.value" placeholder="@T["Enter a value"]" />
</td>
<td class="text-center align-middle">
<div class="custom-control custom-radio ml-2">
<input type="radio" class="custom-control-input" :id="'customRadio_' + index" name="@Html.NameFor(m => m.DefaultValue)" v-bind:value="option.value" v-model="data.default" v-on:click="uncheck(index)">
<label class="custom-control-label" title="@T["Set as default"]" v-bind:for="'customRadio_' + index"></label>
</div>
</td>
<td class="text-center">
<a v-on:click="remove(index)" href="javascript:void(0)" title="@T["Remove element from list"]" class="btn">
<i class="fas fa-times"></i>
</a>
</td>
<td class="text-center"><div class="btn cursor-move"><i class="fas fa-arrows-alt"></i></div></td>
</tr>
</draggable>
<tfoot>
<tr>
<td class="col-sm-12 text-center" colspan="5">
<a v-on:click="add()" class="btn btn-light w-100 btn-sm"><i class="fas fa-plus small"></i> @T["Add an option"]</a>
<input class="form-control content-preview-text" id="@Html.IdFor(m => m.Options)" name="@Html.NameFor(m => m.Options)" type="hidden" v-bind:value="getOptionsFormattedList()" />
</td>
</tr>
</tfoot>
</table>
</script>

<script type="text/x-template" id="select-options-modal">
<div class="modal fade @Html.IdFor(m => m)-ModalBody text-left" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">@T["Edit Data"]</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="select-options-textarea">@T["Options"]</label>
<textarea id="select-options-textarea" name="select-options-textarea" rows="8" class="form-control" v-bind:value="JSON.stringify(data.options)" v-on:input="data.options = JSON.parse($event.target.value)"></textarea>
<span class="hint">@T["A JSON representation of the allowed values, e.g. {0}", "[ { text: 'First option', value: 'option1' }, { text: 'Second option', value: 'option2' } ]"]</span>
</div>
<div class="form-group">
<label for="options-default-value">@T["Default value"]</label>
<input id="options-default-value" name="options-default-value" class="form-control" type="text" v-model="data.default" />
<span class="hint">@T["(Optional) The value to assign to the select field."]</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-submit" v-on:click="closeModal()">@T["OK"]</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">@T["Cancel"]</button>
</div>
</div>
</div>
</div>
</script>

<div id="@Html.IdFor(m => m)" class="form-group">
<label asp-for="Options">@T["Options"]</label>
<a href="javascript:void(0)" v-on:click="showModal" class="float-right" title="@T["Edit Data"]"><i class="fas fa-edit"></i></a>
<select-options-table :data="sharedState"></select-options-table>
<select-options-modal :data="sharedState" v-on:reload-data="reloadData()"></select-options-modal>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@using OrchardCore.Forms.Models
@model ShapeViewModel<SelectPart>
@{
var formElementPart = Model.Value.ContentItem.As<FormElementPart>();
var formInputElementPart = Model.Value.ContentItem.As<FormInputElementPart>();
var elementId = formElementPart.Id;
var fieldName = formInputElementPart.Name;
var fieldId = !string.IsNullOrEmpty(elementId) ? elementId : !string.IsNullOrEmpty(fieldName) ? Html.GenerateIdFromName(fieldName) : default(string);
deanmarcussen marked this conversation as resolved.
Show resolved Hide resolved
var fieldValue = Model.Value.DefaultValue;
var fieldClass = "form-control";
deanmarcussen marked this conversation as resolved.
Show resolved Hide resolved

if (ViewData.ModelState.TryGetValue(fieldName, out var fieldEntry))
{
fieldValue = fieldEntry.AttemptedValue;
deanmarcussen marked this conversation as resolved.
Show resolved Hide resolved
if (fieldEntry.Errors.Count > 0)
{
fieldClass = "form-control input-validation-error";
}
}
}
<select id="@fieldId" name="@fieldName" class="@fieldClass">
@foreach(var option in Model.Value.Options)
{
<option value="@option.Value" selected="@(option.Value == fieldValue ? "selected" : null)">@option.Text</option>
}
</select>
Loading