$(function () { pageContext.i18n.modTalk = 'moderation talk'; pageContext.i18n.replyToComment = 'Reply'; pageContext.i18n.modTalkEmpty = 'moderation talk is empty'; pageContext.url.getModTalk = "/comments/%25ID%25/listModTalk.json"; pageContext.url.possibleCommentRecipients = "/comments/%ID%/possibleRecipients.json"; pageContext.url.commentEdit = '/comments/%25ID%25/edit.html'; pageContext.url.commentView = '/comments/%ID%/view.html'; pageContext.i18n.commentVisibility = { 'full': 'Viewable by all users', 'op': 'Viewable by the original poster', 'mod': 'Viewable by moderators', 'opAndMod': 'Viewable by moderators and the original poster', 'other': 'Advanced visibility', 'dialogTitle': 'Comment visibility', 'selectGroups': 'Visible to groups', 'selectOther': 'Other recipients', 'selectOriginalPoster': 'Original poster', 'selectModerators': 'Moderators', 'selectAssignees': 'Asked to answer users' }; pageContext.i18n.commentMenuLabels = { 'comment-edit': 'comments.menu.edit', 'comment-delete': 'comments.menu.delete', 'comment-convert': 'comments.menu.convert' };pageContext.i18n.answer= { bestAnswer: 'Best Answer', controlBar : { accept: 'Accept', unaccept: 'Unaccept', acceptCommand: 'Accept this answer as correct', cancelAcceptedCommand: 'Remove this answers accepted status' } }; window.croles = { u: false, op: false, m: false, og: false, as: false, ag: false, dc: false, doc: false, eo: false, ea: false }; tools.init({ q: { e: false, ew: false, eo: false, r: false, ro: false, d: false, dow: false, fv: false, c: false, co: false, p: false, tm: false , ms: false, mos: false }, n: { f: false, vf: false, vfo: false, vr: false, vro: false, c: false, co: false, vu: false, vd: false, w: false, wo: false, l: false }, c: { e: false, eo: false, d: false, dow: false, ta: false, tao: false, l: false }, a: { e: false, ew: false, eo: false, d: false, dow: false, a: false, aoq: false, ao: false, tc: false, tco: false, p: false, tm: false }, pc: croles }, { tc: true, nsc: true }); commandUtils.initializeLabels(); }); Skip to Content
0

How can I set a required field in a form

Mar 23, 2017 at 12:14 PM

116

avatar image
Former Member

Hello,

i have a form in a page and i want set any fields to mandatory fields. In the first step I set metadata property with nullable = "false".

<Property Name="Id" Type="Edm.String" Nullable="false" />
<Property Name="title" Type="Edm.String" Nullable="false"/>

and in the second step in the form in View

<Label text="Id" 
	labelFor="Id"
	required="true"/>
<Input value="{appointments>Id}"
	id="Id"
	required="true"
	placeholder="set a Id"/>

<Label text="Title"
	labelFor="title"
	required="true"/>
<Input value="{appointments>title}"
	id="title"
	required="true"
	placeholder="Set a Title"/>

but if the fields are empty and i click the submitbutton. The form will still be delivered successfully

10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

2 Answers

Best Answer
Ulrich Block
Mar 23, 2017 at 12:25 PM
0

The challenge here is the "required" property at a label not causing a check. Instead it just indicates with an asterix to the user, that he needs to fill out the form: https://sapui5.hana.ondemand.com/explored.html#/entity/sap.m.Label/properties

I guess you do not have a HTML body like:

<form ...>
<input .../>
<button type="submit"><button>
<form>

I assume that instead an AJAX request is done with jQuery. In such a case you could implement a check before sending the AJAX request.

The easiest way would be a fieldgroup and a for loop like:

var aControls = sap.ui.getCore().byFieldGroupId("yourFieldGroupId");

for (var i = 0, iLength = aControls.length; i < iLength; i++) {
    ...
}

In the loop you could set the error state of the input field to error instead of sending an AJAX call.

Show 1 Share
10 |10000 characters needed characters left characters exceeded
Former Member

the view and the controller work very well, but just the required field not work. Do i need something write in onSave function?

this is my view

<mvc:View
	controllerName="timeTrackertimeTracker.controller.Calendarform"
	xmlns="sap.m"
	xmlns:l="sap.ui.layout"
	xmlns:forms="sap.ui.layout.form"
	xmlns:core="sap.ui.core"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:semantic="sap.m.semantic"
	xmlns:smartfield="sap.ui.comp.smartfield"
	xmlns:smartform="sap.ui.comp.smartform"
	xmlns:me="sap.me">
	
	<semantic:FullscreenPage
		id="page"
		title="{i18n>addPageTitle}"
		showNavButton="true"
		navButtonPress="onNavBack">
		<semantic:content>
			<forms:SimpleForm 
				editable="true" 
				layout="ResponsiveGridLayout" 
				id="form">
				<forms:content>
					<Label text="Id" 
					labelFor="Id"
					required="true"
					/>
					<Input value="{appointments>Id}"
						id="Id"
						required="true"
						placeholder="set a Id"/>
						
<!--					<Label text="ProjectNumber" />
					<Input value="{appointments>/projectnumber}"
						id="projectnumber"
						placeholder="set a projectnumber"/>
					-->
					
					<Label text="Title"
						labelFor="title"
						required="true"/>
					<Input value="{appointments>title}"
						id="title"
						required="true"
						placeholder="Set a Title"/>
					
					<Label text="Description"
					id="description"/>
					<TextArea value="{appointments>description}" 
						id="textarea"
						placeholder="Set your description"/>
					
					<Label text="Starttime"/>
					<DateTimePicker
					id="startime"
					required="true"
					value="{appointments>starttime}"
					width="100%"
					placeholder="Set Starttime in Form YYYY-MM-DD HH:MM:SS"
					class="sapUiTinyMarginBottom" />
					
					<Label text="Endtime"/>
					<DateTimePicker
					id="endtime"
					required="true"
					value="{appointments>endtime}"
					width="100%"
					placeholder="Set EndTime in Form YYYY-MM-DD HH:MM:SS"
					class="sapUiTinyMarginBottom" />


<!--					<Label text="Billable" 
						labelFor="flag"/>
					<Input value="{appointments>flag}"
						id="flag"
						placeholder="set a flag in true or false"/>-->
						
					 <Label labelFor="flag" text="Billable" />
					 <VBox id="flag" binding="{appointments>flag}">
						<RadioButton  text="true"/>
						<RadioButton  text="false"/>
					</VBox>
								
					<Label text="resttime"/>
					<Input type="Number"
						id="resttime"
						value="{appointments>resttime}"
						placeholder="please enter only a Number"/>


				</forms:content>
			</forms:SimpleForm>


		</semantic:content>
		<semantic:saveAction>
			<semantic:SaveAction id="save"  press="onSave"/>
		</semantic:saveAction>
		<semantic:cancelAction>
			<semantic:CancelAction id="cancel" press="onCancel"/>
		</semantic:cancelAction>
	</semantic:FullscreenPage>


</mvc:View>

this is my controller

sap.ui.define(['sap/ui/core/mvc/Controller', 
	'timeTrackertimeTracker/controller/BaseController', 
	'sap/ui/model/json/JSONModel', 
	"sap/m/MessageToast",
	"sap/ui/model/odata/ODataModel",
	"sap/ui/core/routing/History"
	],




    	function(Controller, BaseController, JSONModel, MessageToast, ODataModel, History) {
    	"use strict";


    	//Global variables
    	//var _oController, oModel, oView;
    	
    	return BaseController.extend("timeTrackertimeTracker.controller.Calendarform", {
    	/*var Calendarcontroller = BaseController.extend("timeTrackertimeTracker.controller.Calendarform", {*/
    	
		/* =========================================================== */
		/* lifecycle methods                                           */
		/* =========================================================== */
		onInit: function() {
				//Store controller reference to global variable
				this.getRouter().getRoute("Calendarform").attachPatternMatched(this._onRouteMatched, this);
		}, 


		/* =========================================================== */
		/* event handlers                                              */
		/* =========================================================== */
		
		_onRouteMatched: function() {
			// register for metadata loaded events
			var oModel = this.getModel("appointments");
			oModel.metadataLoaded().then(this._onMetadataLoaded.bind(this));
		},
		
		_onMetadataLoaded: function () {
			// create default properties
			 var oProperties = {
				Id: "Id" + parseInt(Math.random() * 1000)
/*				duration: "",
				resttime: "",
				title: "",
				starttime: "",
				endtime: "",
				Description: ""*/
			};


			// create new entry in the model
			this._oContext = this.getModel("appointments").createEntry("/appointments", {
				properties: oProperties,
				success: this._onCreateSuccess.bind(this)
			});


			// bind the view to the new entry
			this.getView().setBindingContext(this._oContext, "appointments");
		},
		
		onSave: function() {
			// bind the view to the new entry
			this.getModel("appointments").submitChanges();
		}, 
		
		_onCreateSuccess: function (oEvent) {
			// navigate to the new product's object view
			this.getRouter().navTo("AppointmentsList", true);
	
			// unbind the view to not show this object again
			this.getView().unbindObject();
			
			// show success messge
			var sMessage = this.getResourceBundle().getText("newObjectCreated", [ oEvent.Id ]);
			MessageToast.show(sMessage, {
				closeOnBrowserNavigation : false
			});
		},


		onCancel: function() {
			this.onNavBack();
			//this.getView().getModel("appointments").deleteCreatedEntry(this._oContext);
		},
		
		
		/**
		 * Event handler for navigating back.
		 * It checks if there is a history entry. If yes, history.go(-1) will happen.
		 * If not, it will replace the current entry of the browser history with the worklist route.
		 * @public
		 */
		onNavBack : function() {


/*			var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.navTo("AppointmentsList");*/
			
			var oHistory = History.getInstance(),
				sPreviousHash = oHistory.getPreviousHash();


			// discard new product from model.
			this.getModel("appointments").deleteCreatedEntry(this._oContext);


			if (sPreviousHash !== undefined) {
				// The history contains a previous entry
				history.go(-1);
			} else {
				// Otherwise we go backwards with a forward history
				var bReplace = true;
				this.getRouter().navTo("AppointmentsList", {}, bReplace);
			}
		}
    	});
     
    /*	return Calendarcontroller;*/
     
    });

0
Akhilesh Upadhyay Mar 24, 2017 at 10:57 AM
0

"required" property will helps only to show the "*" on UI.

onSave function you can write like below,

var oModel = this.getModel("appointments");
var bValid = true;
var id = oModel.getProperty("/Id"); // or may be instead of only "/Id" you may need to pass bindingpath + "/Id"
if(id == ""){
  bValid = false;
}
//.... for every required field you can put a check like above

// check first if bValid is true else you can show message
if(bValid){
  this.getModel("appointments").submitChanges();
}

hope this help.

Share
10 |10000 characters needed characters left characters exceeded