Appframe Knowledge Base


50 hits
4

Miscellaneous razor functions

Site language: @Language → EN
Localize string: @Localize("hello") → hello
Breadcrumb: @Breadcrumb() → Web > Web 4 > Razor documentation
Link to another page on the site: @Link("login") → Article not found: login
Start a HTML element: @Begin("li") → 
End a HTML element: @End("li") → 
HTML-encode a string: @HtmlEncode("<") → <
URL-encode a string: @UrlEncode("?") → "%3f"
Javascript-encode a string: [" '] → "\" and \u0027"

User-info: Login → @User.ShortName
                Name → @User.FullName
                Authenticated → @User.IsAuthenticated

razor web · Perma link post comment Posted by: Peter Øren (23-aug-2013)

3

How to get access information about current user

var login = af.userSession.login;
var name = af.userSession.name; // Surname, Firstname
var emailAdress = af.userSession.email;
var currentDomain = af.userSession.domain;

common web · Perma link post comment Posted by: Jarl Erik Schmidt (10-mai-2012)

3

Web-Templating: data-templating="item-list" or data-templating="current-item"

<!--   Databinding attributes:

	data-object-id="dsRecords" (defining the scope)

   	data-templating="item-list" (will look for data-item-template and then render 
	 one copy of the relevant template per record)
	data-templating="current-item" (will look for data-item-template and render one copy 
	 of the relevant template for current record only)

   	data-item-template="default" (root element for the default item template)
	data-item-template="current-item"
	data-item-template="current-item-edit"
	data-item-template="new-item-edit"
	data-item-template="no-data" (rendered if there are no data returned from database)
	data-add-class-if="test:className" //test must be a javacript condition: data.fieldName === 'Test':MyClass
	data-remove-class-if="test:className" //test must be a javacript condition: data.fieldName === 'Test':MyClass
	
	
   	data-field="FieldName"	(used in elements to bind data)
   	data-datepicker="date" / "datetime" / "time"
	data-attr="src:/file/db/Persons/dsPersons/<%=PrimKey%>/<%=ImageCRC%>" 
	data-attr="href:/persons?<%=ID%>"
	
   	data-action="save" (used in button elements: click button will save record to database)
   	data-action="cancel" 
   	data-action="delete" 
   	data-action="edit" 
   	data-action="new" (used in button elements: set dataobject.currentRow to -1 and fire beginEdit)
   	data-action="clear"  (used in dropdowns to clear fieldvalue)
   	data-action="done"  (saves if dirty, cancel if not dirty)
	data-action="next" 
	data-action="previous" 

   	data-show-newitem (in item-list: allways shows UI for new record, if not present or "false"
	you will need to use an action to show new record UI)
	
	data-edit-focus (used in current-item-edit and new-item-edit for choosing a specific element that should have focuse when entering edit mode)
	
	functions:
	data-template-function (used if custom template is needed. Return name of custom template and this will be used insated of current active template. Must be located on rootelement)
	data-function (can be used on any element and will be executed for each row-rendering)
--->

<!-- Simple bound list of items (all records using same template)-->
<div data-templating="item-list" data-object-id="dsPersons">
  <div data-item-template="default">
    <h4 data-field="Name"></h4>
	<span data-field="Address"></span>
	<br>
	<span data-field="ZipCode"></span>
	<span data-field="City"></span>
  </div>
</div>

<!-- Simple bound list of items, highlighting current-item by introducing a second template -->
<div data-templating="item-list" data-object-id="dsPersons">
  <div data-item-template="default">
    <h4 data-field="Name"></h4>
	<span data-field="Address"></span>
	<br>
	<span data-field="ZipCode"></span>
	<span data-field="City"></span>
  </div>
  <div data-item-template="current-item" class="active">
    <h4 data-field="Name"></h4>
	<span data-field="Address"></span>
	<br>
	<span data-field="ZipCode"></span>
	<span data-field="City"></span>
  </div>
</div>

<!-- Simple bound list of items, editing current-item -->
<div data-templating="item-list" data-object-id="dsPersons">
  <div data-item-template="default">
    <h4 data-field="Name"></h4>
	<span data-field="Address"></span>
	<br>
	<span data-field="ZipCode"></span>
	<span data-field="City"></span>
  </div>
  <div data-item-template="current-item" class="active">
    <h4 data-field="Name"></h4>
	<input type="text" data-field="Address"></input>
	<br>
	<input type="text" data-field="ZipCode"></input>
	<input type="text" data-field="City"></input>
  </div>
</div>

If you need a list of editable items: put inputs in the "default" template.

If you want a popup form for editing, make a "current-item-edit" template with a bootstrap
modal element (you need to trigger the edit by calling the beginEdit on the dataobject.

To trigger an edit, use a button with data-bind="edit"

If you would like to allways show a "new blank record" (enabling the user to input a new item)
just set the "data-show-newitem" attribute (in the data-list root element).

dataobject web web-templating · Perma link post comment Posted by: Sigmund Lunde (07-nov-2014)

Robert Vinkovic :
Solution, not the only one but the only one I have managed to make work: parent div must have data-list="manual-edit" with 2 child divs one with data-item-template="read-only" and one with "edit" (22-jan-2015)
Peter Butt :
(23-feb-2015)
Martin Vaaden :
Tried using data-remove-class-if some time ago, but seems like it's not in use any more (?) Seems like data-add-class-if will add class if check == true and remove if check == false (12-jun-2015)
3

Web-Templating: data-field, data-attr, src, href, crop , null-image, ratio, file upload

<!-- Simple bound form-->
<div data-object-id="dsPersons">
    <h4 data-field="Name"></h4>
	<input type="text" data-field="Address"></input>	
	<button data-action="save" class="btn btn-default">Save</button>
	<button data-action="cancel" class="btn btn-default">Save</button>
</div>

<!-- Binding image to img
	 - data-attr="src:url"
	 - data-null-image: will use this image when data is null
-->
<img class="img-responsive thumbnail pull-left" 
	 data-attr="src:/file/db/info/dsKommentarer/Bilde/<%=PrimKey%>/<%=Bilde%>?height=35" 
	 data-null-image="/static/graphics/camera-icon.svg">

<!-- Binding url anchor
	 - data-attr="href:url"
-->
<img class="img-responsive thumbnail pull-left" 
	 data-attr="href:/file/db/info/dsKommentarer/Bilde/<%=PrimKey%>/<%=Bilde%>?height=35" >

<!-- Binding crop with save
	data-crop: enables crop for img. If empty, filestore will be used. If not the value should be varbinary field from table.
	data-ratio: sets the crop ratio (width/height)
	-->
<img data-object-id="dsPerson" 
		data-crop="Bilde" 
		data-ratio="1" 
		data-attr="src:/file/db/brukerinfo/dsPerson/Bilde/<%=PrimKey%>/<%=Bilde%>" 
		data-null-image="/static/graphics/camera-icon.svg" >

<!-- Binding fileuploader: Provides drag & drop and fileupload
     - data-object-id
	 - data-upload
-->
<div data-upload class="file-upload-control col-xs-12" data-object-id="dsFiler" id="arkivUploader">
	<!-- put your markup here -->
</div>

<!--Upload link to trigger filechooser-->
<a href="#" class="pull-right text-muted" data-upload-target="arkivUploader">velg fil(er) for opplast...</a>




dataobject web web-templating · Perma link post comment Posted by: Sigmund Lunde (09-nov-2014)

3

Web-Templating: Lookup, lookup-bindings

<!-- To connect a lookup to an input add attribute   
	data-lookup-id="idOfYourLookup" and 
	data-lookup-bindings="field1=field2, field3=field4" 
	field1 and field3 are fields in base (host/target) data-object
	field2 and field4 are fields in lookup data-object  -->
	
<input type="tel" 
		class="form-control" 
		data-field="PostCode" 
		data-lookup-id="lookupPostCode"
		data-lookup-bindings="Postcode=Postcode, Location=Location">
		
<!--  To define a lookup add attributes as shown below. -->
<div id="lookupPostCode"
		data-templating="lookup"
		data-object-id="dsPostCodes"  
	 	data-lookup-width="400"
		data-display-fields="Postcode, Location">  <!-- creates lookup markup automatically -->
</div>
<!-- If you don't like the instant search (automatic search after 3 charachters) add attribute data-disable-instant -->

<!-- If you would like to use your own custom markup leave out the data-display-fields and provide a template instead-->
<div data-templating="lookup"
		id="lookupPostCode"
	 	class="list-group"
		data-object-id="dsPostCodes" 
	 	data-lookup-width="400"
		data-disable-instant
		data-limit-to-list="true"> <!-- Remove this attribute to get automatic search after 3 charchters -->
	<div data-item-template="default">
		<div class="list-group-item">
			<span data-field="Postcode"></span>,
			<span data-field="Location"></span> 
			<span data-field="Country"></span>
		</div>
	</div>
</div>

<!-- If you would like to have the lookup unbound you should leave out the data-lookup-bindings and data-field attributes -->
<input type="tel" 
		class="form-control" 
		data-lookup-id="lookupPostCode">
		
<div id="lookupPostCode"
		data-templating="lookup"
		data-object-id="dsPostCodes"  
	 	data-lookup-width="400"
		data-display-fields="Postcode, Location">  <!-- creates lookup markup automatically -->
</div>
<!--In order to get the selected value you need to use event in javascript-->
<script>
af.article.getUnboundCustomDropdown("lookupPostCode").attachEvent("onRecordSelected",function(pRow){
});
</script>
<!-- Custom items -->
<div id="lookupHosts"
        data-templating="lookup"
        data-display-fields="HostName, Title"
        data-lookup-items="myTestItems"  
        data-object-id="dsMyTestItems"><!--dsMyTestItems should not be defined as dataobject, must be named unique-->
</div>
<script>
/*function that returns static items as json*/
function myTestItems(){
    return [{HostName:"HostName 1", Title:"Title 1"},{HostName:"HostName 2", Title:"Title 2"}]
}
</script>

dataobject web web-templating · Perma link post comment Posted by: Sigmund Lunde (18-des-2014)

D. Young Hoang :
I am going through the Certification Program using Appframe.Core v4.30.0.19024 and data-lookup-bindings is no longer working. After looking into the js source code, looks like it has been updated to data-value-bindings. I used data-value-bindings and it worked. In addition to that the JS console will throw a warning message if the data type of the first field/column from the lookup's data object does not match with the input data type. To fix that, I need to set the data-display to the selected field. i.e.: <input data-field="CustomerID" type="number" class="form-control" id="Orders_CustomerID" data-lookup="dsCustomers" data-display="ContactID" data-value-bindings="CustomerID=ContactID"> (05-okt-2017)
3

Using Rest API to execute a procedure in Pims

Example of how to use the RestAPI to execute a procedure in Pims: function execProcOnAPI(){ var vData = { "Timeout": 30, "AwaitResult": true, "@DocumentType": "AA", "@Title": "Sample Doc", "@DocGroup": "Administrative", "@FacilityID":"A", "@OriginatorCompany":"AOGD", "@Discipline": "A", "@NewDocumentID":"", "@AddSheetNo":false, "@ContractNo":null, "@WorkPackID":null, "@SubProjectID":null, "@System":null, "@Area":null, "@PONumber":null }; jQuery.ajax({ url: "https://api.pimsdevhosting.com/procedure/dcsCreateNewDocumentID/call", data: JSON.stringify(vData), contentType: "application/json", dataType: "json", type: "POST", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("UserName" + ":" + "Password")); }, success: function(resultData) { //here is your json. console.log(resultData); }, error : function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); }, timeout: 120000 }); }

rest api web · Perma link post comment Posted by: Johnny Vik (10-jun-2015)

3

Using Rest API to return result a API resource

Example of how to retrieve documents in Pims Document Control function getDocuments(){ jQuery.ajax({ url: "https://api.pimsdevhosting.com/dcs/documents/?take=100", type: "GET", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("Username" + ":" + "Password")); xhr.setRequestHeader("Accept","application/json"); }, success: function(resultData) { //here is your json. console.log(resultData); }, error : function(jqXHR, textStatus, errorThrown) { }, timeout: 120000, }); }

rest api web · Perma link post comment Posted by: Johnny Vik (10-jun-2015)

D. Young Hoang :
for sorting results, add parm ?order=["Title","OtherField"] or ?order=[{"desc":"Title"},{"asc","OtherField"}] This is important for paging since skip 0 or no skip does not implement row_number() causing the final results to skew... issue https://www.pims.no/issues/issue?43709 (03-jul-2018)
1

How to set background color on cell in afGrid

gridMyGrid.attachEvent("onFormatCellValue", function(pCell) {
	pCell.css.backgroundColor = "#f00";
});

components web · Perma link post comment Posted by: Jan Henrik H. Meling (27-nov-2012)

1

Using af.controls.Dialog - Showing an article or an external page in a dialog

var vDialog = new af.controls.Dialog({
    overlay: { clickCloses: true }, // does what you'd expect
    buttons: { close: true }, // enables the close button in the header
    title: "Omega", width: 1200, height: 650,
    content: "http://www.omega.no/",
    destroyOnClose: true // will dispose of the dialog after it closes

});

vDialog.show();

common web · Perma link post comment Posted by: Jan Henrik H. Meling (14-mai-2012)

1

Execute a stored procedure and output html for each row in razor

@{
	var vProcedureCall = ProcedureCall("astp_Some_Procedure");
	var vDataSet = vProcedureCall.Execute();
}

<ul>
@foreach (var vRow in vDataSet[0])
{
	<li>@HtmlEncode(vRow["Column1"])</li>
}
</ul>

razor web · Perma link post comment Posted by: Peter Øren (15-jan-2013)

Arild Røksund :
Should vCategories be vDataSet ? (17-feb-2015)
Peter Øren :
Yes (23-feb-2015)
1

How to use the appframe confirm dialog

af.controls.confirm({
                title: "title",
                message: "message",
                buttons: ["Yes", "No"],
				escape: 1,
                callback: function(index) {
                    if (index === 0) {
						//your code
                    }
                }
            });

components web · Perma link post comment Posted by: Peter Øren (14-jan-2013)

1

How to make a URL column into a link to that url

gridSomething.attachEvent("onFormatCellValue", function(pCell) {
    if (pCell.fieldName === "URL") {
        var vEscapedURL = af.common.htmlEscape(pCell.dataRow.URL);
        pCell.value = '<a href="' + vEscapedURL  + '">' + vEscapedURL + '</a>';
    }
});

components web · Perma link post comment Posted by: Jan Henrik H. Meling (21-okt-2013)

1

Repeater / Template Syntax

<!-- Everything inside <% %> is JavaScript, so you can use variables and if statements.
     If you want to use values from the current row, you can use the variable "row".
     If you want to have logic based on the row index, "i" is the zero based index.
     If you want to have logic based of the previous or next row, "data" is the array of rows. -->

<%if (row.SomeBitField === true) {%>
	<p>The variable is true</p>
<%} else {%>
	<p>The variable is not true</p>
<%}%>

<!-- Normally if you just want the escaped value of a field, you use this syntax: -->

<p><%=MyFieldName%></p>

<!-- If you need to replace something or process the value, you need to prefix the field name
     with "row.", as the un-prefixed version is only a shorthand that escapes for you.
     Make sure you escape the value before outputting it when using row.FieldName: -->

<p><%=af.common.htmlEscape(row.SomeField.replace("foo", "bar"))%></p>
<p><%=af.common.stringifyValue(row.FieldA || row.FieldB)%></p>

components web · Perma link post comment Posted by: Martin Vaaden (11-jun-2014)

1

Declarative Bound Filter Panel

<!--Declartive Filter Panel is an extension to declartive databinding. Look at related kb articles for declartive binding-->
<!--Currently you need to specify an empty edit-template (compability issue)-->


<!-- Each filter section requires [data-filter-type] (multiple, single or search) and [url-pos].  -->
<!-- Depending on data-filter-type optional attributes are: 
       action (search), 
       data-filter-default (multiple), 
       data-filter (multiple and single), 
       data-filter-field(multiple and single)  
-->

<!-- If you have data-filter-type="search" you specify the data-filter-for to specify related textbox and action (remove or search)  and specify action (remove. search) -->
<!--If you have data-filter-type="single" or "multiple" and data is dynamically rendered you need to specify [data-filter-field] attribute to the field that will be used when filtering. -->
<!--If you have data-filter-type="single" or "multiple" and you are going to use static data,  [data-filter] attribute is required on the subelements. This will be used to filter related dataobjects. -->


<!--Specify all dataobjects that will be included in filterpanel using the [data-filter-target] attribute -->
<div data-filter-target="dsIssues,dsInvolved,dsIssueType,dsAreas,dsSeverity,dsCategory,dsActionsAssigned,dsToBeClosed, dsToBeVerified,dsToBeReviewed,dsStarred,dsAwaitingResponse">

<!--Example of [data-filter-type="search"] -->
	<h4>Free text</h4>
	<div class="input-group">
		<input type="text" name="search" id="search" class="form-control" placeholder="Search for..." data-filter-type="search" url-pos="0">
		<span class="input-group-btn">
			<button class="btn btn-default" name="removeBtn" type="button" data-filter-for="search" action="remove"><span class="glyphicon glyphicon glyphicon-remove"></span></button>
			<button class="btn btn-default" name="searchBtn" type="button" data-filter-for="search" action="search"><span class="glyphicon glyphicon-search"></span></button>
		</span>
	</div>

<!--Example of [data-filter-type="mulitple"] and static list-->
	<div data-filter-type="multiple" url-pos="1" data-filter-default="Closed IS NULL">
        <div class="checkbox">
            <label><input type="checkbox" data-filter="1=1">
                <span>Include Closed</span>
            </label>
        </div>
		<div data-item-template="edit"></div>
    </div>


<!--Example of [data-filter-type="single"] and static list-->
	<h4>Filters</h4>
	<div class="list-group" data-filter-type="single" url-pos="2">
		<a class="list-group-item data-filter-default" data-filter="" >All Issues</a>
		<a class="list-group-item" data-filter="Status = 'Awaiting Response'">Awaiting response</a>
		<a class="list-group-item" data-filter="(Status IN('Completed','Cancelled','Duplicate') AND Closed IS NULL)">To be closed</a>
		<a class="list-group-item" data-filter="(Status = 'Action Assigned' AND Closed IS NULL)">Actions assigned</a>
		<a class="list-group-item" data-filter="(Status = 'To Be Reviewed')">To be reviewed</a>
		<a class="list-group-item" data-filter="AreaResp = SUSER_SNAME()">Area resp is me</a>

		<a class="list-group-item" style="display:none;" data-filter="(AwaitingResponseFromMe > 0)">Awaiting response from me (<span data-object-id="dsAwaitingResponse" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="(ToBeClosedBy=SUSER_SNAME() AND Status IN('Completed','Cancelled','Duplicate') AND Closed IS NULL)">To be closed by me (<span data-object-id="dsToBeClosed" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="(OpenActionsAssignedToMe > 0)">Actions assigned to me (<span data-object-id="dsActionsAssigned" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="(AreaRespIsMe = 1 AND Status = 'To Be Reviewed')" >To be reviewed by me (<span data-object-id="dsToBeReviewed" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="(ToBeVerifiedBy = SUSER_SNAME() AND Verified IS NULL And Closed IS NOT NULL)" >To be verified by me (<span data-object-id="dsToBeVerified" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="Involved = 1">My Involvement (<span data-object-id="dsInvolved" data-field="IssueID"></span>)</a>
		<a class="list-group-item" style="display:none;" data-filter="Starred = 1">Starred (<span data-object-id="dsStarred" data-field="IssueID"></span>)</a>
	</div>


<!--Example of [data-filter-type="multiple"] and dynamic list-->
	<h4>Issue Type</h4>
    <div data-filter-type="multiple" url-pos="3" data-object-id="dsIssueType" data-list="manual-edit" data-filter-field="IssueType">
        <div class="checkbox" data-item-template="read-only">
            <label><input type="checkbox">
                <span data-field="IssueType"></span>
            </label>
        </div>
		<div data-item-template="edit"></div>

    </div>


<!--Example of [data-filter-type="multiple"] and dynamically rendered list -->
	<h4>Area</h4>
    <div data-filter-type="multiple" url-pos="4" data-object-id="dsAreas" data-list="manual-edit" data-filter-field="Area">
        <div class="checkbox" data-item-template="read-only">
            <label ><input type="checkbox" >
                <span data-field="Area"></span>, <span data-field="AreaRespFirsName"></span> (<span data-field="IssueID"></span>)
            </label>
        </div>
		<div data-item-template="edit"></div>
    </div>


<!--Example of [data-filter-type="single"] and dynamically rendered list-->
	<h4>Category</h4>
	<div data-object-id="dsCategory" url-pos="5" data-filter-field="Category" data-filter-type="single">
		@Render("Repeater", ID:"repCategories")
	</div>



<!--Example of [data-filter-type="multiple"] and dynamically rendered list-->
	<h4>Severity</h4>
    <div data-filter-type="multiple" url-pos="6" data-object-id="dsSeverity" data-list="manual-edit" data-filter-field="SeverityLevel">
        <div class="checkbox" data-item-template="read-only">
            <label ><input type="checkbox" >
                <span data-field="SeverityLevel"></span> (<span data-field="IssueID"></span>)
            </label>
        </div>
		<div data-item-template="edit"></div>
    </div>

</div>

<script>
      $(function(){
                 new af.url.DataFilter();
       });
</script>

web web-templating · Perma link post comment Posted by: Peter Øren (28-jul-2014)

1

Date date-picker web-templating

<!-- To activate the datepicker use an input with type="text" and add attribute data-datepicker -->

<input type="text" 
		data-field="StartDato"
		data-datepicker="date/datetime"  
		data-startmode="years/months/dates" 
		data-format="Short Date">

<!-- data-startmode is optional, default is dates, you can set it to years or months -->
<!-- data-format is optional, default for date is "Short Date" and default for datetime is "General Date Short Time" -->

web web-templating · Perma link post comment Posted by: Sigmund Lunde (19-des-2014)

1

Select, web-templating, add options from datasource

<!-- 
	To create options in a select element use data-options="dataSource" and specify data-option-text="field" (and data-option-value if different from data-option-text)
-->
<select class="form-control" 
	data-field="Categories"
	data-options="dsCategories"
	data-option-text="Category">

	<!-- Generated options (from data-options datasource) will not replace any options allready in your markup -->
	<option class="text-muted">(choose a category)</option>	
</select>

dataobject web web-templating · Perma link post comment Posted by: Peter Øren (23-des-2014)

1

Change file in a filetable with web4


HTML:
<div class="modal fade" id="fileupload">
	<div class="modal-dialog">
        <div class="modal-content" style="min-height:300px;">
			<div class="modal-header">
                <h4 class="modal-title">Change file</h4>
            </div>
            <div class="modal-body">
                    <input id="fileInput" name="fileInput" type="file" /><br />
                    <button type="button" class="btn btn-default btn-lg fileChange" data-inputfileid="fileInput">Upload File</button> <!-- inputfileid it used to know where the file input is. -->
            </div>    
        </div>    
	</div>
</div>	    


JS:


//**** Edit file without edit and upload plugin (update File)
function ChangeFile(pFileInputID) {
    var pFileInput = $('#' + pFileInputID);
    console.log(pFileInput[0]);
    var vFileUploader = new af.components.Uploader({
		url: "/file/upload/" + af.article.id + "/dsFiles/" + dsFiles.currentRow("PrimKey")
	});
	
    var hideIndicator = af.controls.working("Uploading file...");
	
	vFileUploader.upload(pFileInput[0], function() {
	     	dsFiles.refreshCurrentRow();
	        hideIndicator();
	        $('#fileupload').modal('hide');
	});
}

$('.fileChange').click(function() {
    ChangeFile($(this).data('inputfileid'));
});

web · Perma link post comment Posted by: Erik Skagen Vindenes (16-apr-2015)

0

How to use the filter object in javascript

// some variables to be used as part of filter criteria
var vCurrentMonday = new XDate(+$("#weeks").val()),
	vOrderItem = $("#orders").val();

// defining the filter object
dsTimesheet.setParameter("filterObject", {
	type: "group", mode: "and", items: [
		{ type: "expression", column: "WeekStarting", operator: "equals", valueType: "datetime", value: vCurrentMonday },
		{ type: "expression", column: "OrderItemTemplate", operator: "equals", valueType: "string", value: vOrderItem }
	]
});

// refresh the data source to get data using the filter
dsTimesheet.refreshDataSource();

// Alternatively you can build the filter string yourself,
// but then you need to make sure you escape and format the values properly
dsTimesheet.recordSource.setFilterString("WeekStarting = '" + af.common.formatByMask(vCurrentMonday, "sql_date_time") + "' AND OrderItemTemplate = '" + vOrderItem.replace(/'/g, "''") + "'");

components dataobject web · Perma link post comment Posted by: Torgeir Fredriksen (29-nov-2012)

0

Using af.controls.Dialog - Create via code with custom buttons and content

var vContent = $('<label style="display: inline-block; padding: 10px 20px 20px 20px;">First name:<input style="display: block;"></label>');
var vDialog = new af.controls.Dialog({
    overlay: { clickCloses: true }, // does what you'd expect
    buttons: { close: true }, // enables the close button in the header
    title: "My Test Dialog",
    content: vContent,
    destroyOnClose: true, // will dispose of the dialog after it closes
    buttonbar: [
        { text: "I have entered my first name", highlight: true,
            click: function() {
                alert("Your name is: " + $(vDialog.getElement()).find("label > input").val());
                vDialog.close();
            }
        },
        { text: "Get me out of here", click: function() { vDialog.close(); } }
    ]
});

vDialog.show();

components web · Perma link post comment Posted by: Jan Henrik H. Meling (14-mai-2012)

0

Using af.common.localStorage to save UI state

/* If localStorage is not supported by your browser,
   the settings will be kept in memory and reset on reload.
   If you need to check if your settings will be persisted,
   you can use this command to test for support: */

af.common.localStorage.isPersisted();
// > true

/* When getting a setting and the value does not exist
    you can specify a default value as the second parameter
    and that value will be returned if no data is in the localStorage */

af.common.localStorage.get("mySetting", "myDefaultValue");
// > "myDefaultValue"

/* Values that are stored in localStorage gets stored per article
    by reading the af.article.id value, so make sure this is correct */

af.common.localStorage.set("mySetting", "someOtherValue");
// > undefined

/* You can also remove individual keys */

af.common.localStorage.remove("mySetting");
// > true

/* Or you can clear everything beeing stored for the active article */

af.common.localStorage.clear();
// > undefined

common web · Perma link post comment Posted by: Jan Henrik H. Meling (14-mai-2012)

0

How to show busy indicator

// Shows a "busy" indicator and returns a function that hides it:
var hideIndicator = af.controls.working("Doing lengthy operation...");

// Normally you'd call hideIndicator() in the complete/error function
// of jQuery.ajax, pCallBack/pOnError in af.data.execProcedure, etc.
// Here we just call it after 3000 milliseconds:

var afterWorkComplete = function() {
	hideIndicator();
}

setTimeout(afterWorkComplete, 1000);

common web · Perma link post comment Posted by: Jarl Erik Schmidt (10-mai-2012)

0

How to recursively clone a value in JavaScript

//used to copy/clone a value (supports values/arrays/objects)
//note : if you know the type you should use copyArray/copyObject instead
var firstValue = 'test',
	newValue = af.common.copyValue(firstValue);

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to recursively clone an object in JavaScript

// Used for making a copy/clone of an existing object
var firstObject = { id: "myObject", title: "test" },
	newObject = af.common.copyObject(firstObject);
// newObject will now be a clone of firstObject
// The function clones recursively, so be careful to
// not pass in objects that have a reference to them selves.

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to recursively clone an array in JavaScript

// Used for making a copy/clone of an existing array
var firstArray = ["A", "B", "C"],
	newArray = af.common.copyArray(firstArray);
// newArray will now be a clone of firstArray
// The function clones recursively, so be careful to
// not pass in arrays that have a reference to them selves.

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to create an empty object that does not inherit from anything in JavaScript

//Called without any parameters creates a totally empty object
// (even without the Object prototype if your browser supports it)
var vEmptyObject = af.common.createObject();
// vEmptyObject.hasOwnProperty will not be present here in modern browsers

// You can also create an object based on another object
var vOtherObject = { foo: 1, bar: 2 };
af.common.createObject(vOtherObject);
// Returns an object with the keys and values of the object passed in

// Can also be used to make an array into an object
var vArray = ["a", "b", "c"];
af.common.createObject(vArray);
// Returns the array as an object {0: "a", 1: "b", 2: "c"}

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

Show sharing dialog

var myshareDialog = new af.controls.ShareDialog({
    panes: ["Reader", "Editor", "Manager"],
    searcher: searchfunction,
    callback: callbackfunction,
    readOnly: false //true/false
});

myshareDialog.show();

components web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to create a buttonbar

/*
Buttonbar control settings:
container: null, // Container to attach to on initialization (optional)
initialize: true, // Initialize now
dock: "bottom", // specify where to dock (top or bottom)
type: "normal", // normal or slim (35px or
localize: false, // localize inputted strings automatically
definition: null // Array of button definitions (required before initialize):

Definition settings:
id: "someUniqueID", // (optional) if you need to name the button for some reason (we use this for PLUpload's shim)
type: "button", // "button", "label" or "custom" (will ignore "highlight" and "click" attributes when "custom")
text: "Close", // Will only be used when type is "button" or "label"
className: null, // when set, this class will be applied to the button (only applies for type button)
icon: false, // when true, a span will be prepended in addition to the text (use class to specify icon, only works for type button)
position: "left", // left/right/center
highlight: true, // true/false - true will make a hilighted button
display: true, // false to have button be hidden on init
disabled: false, // true to have button be disabled on init
custom: null, // html string, selector, or element to attach
click: function () { this.close(); }
*/

//Create buttonbar
var vButtonBar = new af.controls.ButtonBar({
	definition: [
		{ text: "OK", highlight: true, click: onOK },
		{ text: "Cancel", click: onCancel }
	]
});
//will return a buttonBar that has an Ok and Cancel button which will trigger functions onOk/onCancel when clicked
//Attach the buttonBar to your dialog
dlgMyDialog.setButtonBar(vButtonBar);

//Optionally you can define and set a buttonbar definition object directly on the dialog instead
dlgMyDialog.setButtonBar([
	{ text: "OK", highlight: true, click: onOK },
	{ text: "Cancel", click: onCancel }
]);

web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to remove item from an array at a specified index

var myArray = [1,2,3,4,5]; //[1, 2, 3, 4, 5]

af.common.arrayRemoveAt(myArray,2,3);
//Removes items 3 and 4 from the array [1, 2, 5]

af.common.arrayRemoveAt(myArray, 1);
// Removes item at position 1 from the array [1, 5];

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to prompt user with a short message

//Display notification (click the notification text to close)
af.controls.notify('Mail sent!');
// notify returns a function which you can call at a later point to close the notification

//Display notification for a certain duration
setTimeout(af.controls.notify('This message will be displayed for 3 seconds.'), 3000);

components web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

Formatting a string in JavaScript like you would in .NET with String.Format

//Format string
var vRecord = 7,vTotalRecords=10;
af.common.formatString("Viewing record {0} of {1}", vRecord, vTotalRecords);
//Returns Viewing record 7 of 10

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to get number of rows

//will return the number of rows available / loaded
//it will not return the total number of rows the table/view contains
//if you want the total number of rows, you need to set maxRecords to -1 and reload first
ds.getDataLength();

// ds.getData() is a heavy operation, so if you are going to iterate over a limited number of rows,
// use ds.getDataLength() and ds.getData(index) for much better performance.

components dataobject web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to format dates and numbers

//----- Format as date -----

//Format dates using default format
af.common.format(new Date(),{type:'date'});
//Returns date formatted as dd-MMM-yyyy (i.e 10-apr-2013)

//Format dates using custom format
af.common.format(new Date(),{type:'date',format:'dd-MM-yy'});
//Returns date formatted as dd-MM-yy (i.e 10-04-13)

//Format date including time (UTC is used by default if not specified)
af.common.format(new Date(),{type:'date',format:'dd-MM-yy hh:mm'});
//Returns UTC date and time formatted as dd-MM-yy hh:mm (i.e 10-04-13 04:41)

//Format date including time and not using UTC format (UTC is used by default if not specified)
af.common.format(new Date(),{type:'date',format:'dd-MM-yy hh:mm',utc:false});
//Returns non-UTC date formatted as dd-MM-yy hh:mm (i.e 10-04-13 04:41)


//----- Format as filesize (specified in byte) note: only supports up to 1000 TB -----

af.common.format('1.2345',{type:'filesize',decimals:2});
//Returns 1.23 B

af.common.format('1024',{type:'filesize',decimals:2});
//Returns 1 KB (decimals will not be shown when 0 is returned for all decimals, so 1.00 but will be shown as 1)

af.common.format('1048576',{type:'filesize'});
//Returns 1 MB


//----- Format strings -----

// Can be used to format strings that for example have been translated
af.common.format("Record {0} of {1}", vIndex + 1, vTotal);
// Calling when vIndex = 0 and vTotal = 100 returns:
// "Record 1 of 100"

common web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to set field value on current row

//Set value of a field in the current row
ds.currentRow(vFieldName, vNewValue);

components dataobject web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to get current row's data

//Get the whole current row as an object
ds.currentRow();

//Get value of a specific field in the current row
ds.currentRow("SomeField");

components dataobject web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to get current row index

//Get current Index
ds.getCurrentIndex();

components dataobject web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to set current row index

//Set Current Index
ds.setCurrentIndex(vIndex);

components dataobject web · Perma link post comment Posted by: Øystein Kaldestad (12-apr-2013)

0

How to make buttons float to right in Toolbar

/* Not recommended, but if you really want to: */
ul#toolbarMain.afToolbar.Horizontal {
	li.group, li.item, li.separator {
		float: right;
	}
}

components web · Perma link post comment Posted by: Jan Henrik H. Meling (10-apr-2013)

0

How to make tabs float to right in TabBar

/* Not recommended, but if you really want to: */
#tabsDetail > label.afTabPage { float: right; }

web · Perma link post comment Posted by: Jan Henrik H. Meling (10-apr-2013)

0

Listen for changes on a field

// The listener is attached to the data object, and will not be
// triggered when the current index is changed.

dsStuff.attachEvent("onFieldChanged", function (pField) {
	if (pField.name === "FieldName") {
		// Do stuff
	}
});

components dataobject web · Perma link post comment Posted by: Jarl Erik Schmidt (20-feb-2013)

0

Show and hide Form items

// Hide single item
formSomething.getFields('InputOne').hide();

// Hide multiple items
formSomething.getFields(['InputOne', 'InputTwo', ..., 'InputOneHundred']).hide();

// Show single item
formSomething.getFields('InputOne').show();

// Hide multiple items
formSomething.getFields(['InputOne', 'InputTwo', ..., 'InputOneHundred']).show();

components web · Perma link post comment Posted by: Jarl Erik Schmidt (19-feb-2013)

0

How to use prompt in Appframe

	af.controls.prompt({
            title: "Add Period",
            message: "Enter period for monthly points",
            defaultValue: ((new Date()).getFullYear() * 100) + (new Date()).getMonth()+1,
            callback: function(pPeriod) {
				af.article.procedures.procAddMontlyPoints.execute({"Period": pPeriod}, function (e,res){
					alert("Montly points added");
				}, "", true);
            }
        });

components web · Perma link post comment Posted by: Peter Øren (29-jan-2013)

0

Search a record source using a query parameter and output html for each row in razor

@{
	var vRecordSource = RecordSource("aviw_Some_View");
	string vSearch = @QueryString.RawValue("query");
	vRecordSource.SelectColumns.Add("Column1");
	if(vSearch != null && vSearch != ""){
		vRecordSource.WhereClause = "SearchColumn LIKE '%" + vSearch.Replace("'", "''") + "%'";
	}
	vRecordSource.OrderByColumns.Add("Column1",eDescAsc.Asc);
	vRecordSource.MaxRecords = -1;
	var vData = vRecordSource.GetData();
}
@if(vData.Count > 0){
	<ul>
	@foreach (var vRow in vData)
	{
		<li>@HtmlEncode(vRow["Column1"].ToString())</li>
	}
	</ul>
}

razor web · Perma link post comment Posted by: Peter Øren (15-jan-2013)

0

How to trigger loading of data object

dsMyDataObject.refreshDataSource();

components dataobject web · Perma link post comment Posted by: Peter Øren (05-okt-2012)

0

Ho to use a DropdownBase sub-class instance

var vComboBox = new af.controls.ComboBox({
    dropdown: null // Replace null with a reference to an instance of a dropdown
});

/*
// Example code to replace the combobox into the dom
$($0).replaceWith(vComboBox.getElement())
*/

components web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

How to make a custom af.controls.DropdownBase sub-class

function DropdownForm(pOptions) {
    var priv = {
        options: new af.common.Options({
            defaults: { width: null, height: null, fields: null },
            passed: pOptions
        })
    };
    priv.initControl = function initControl() {
        priv.control = new af.controls.Form({ fields: priv.options.fields });
    };
    af.controls.DropdownBase.call(this, priv); // Call base class passing our instance and priv
}
DropdownForm.prototype = new af.controls.DropdownBase(DropdownForm);

/*
// Example usage
var vDropdownForm = new DropdownForm({
    fields: [
        { FieldName: "Test", Editor: "Textbox" }
    ]
});

vDropdownForm.show($0);
*/

web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

How to make a custom af.controls.Form editor type

(function (scope) {
    "use strict";
    var af = scope.af;

	function CustomEditor(pForm, pData) {
		this.inputSelector = "a"; // Uses valHooks to interface with afComboBox
		this.getInput = function() {
			var that = this;
			if (!that.listBox) {
				that.listBox = new af.controls.ComboBox({
					input: CustomEditor.prototype.getInput.call(this),
					dropdown: CustomDropdown
				});
			}
			return CustomEditor.prototype.getInput.call(this);
		};
		af.controls.Form.InputBase.apply(this, arguments);
	}
	CustomEditor.prototype = new af.controls.Form.InputBase();

}(this));

web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

Using af.common.runTemplate - Generating html with data using a template

/* Calling af.common.runTemplate passing a template and an object containing the data you want
   in your template and/or an object of custom handlers that should be run when the templates
   is replacing the field having that name. Values in the data object get escaped, while the
   return values of any custom handlers do not. Custom handlers are used instead of data if present. */

var vTemplate, vResult, vData = { ID: "TheDivId", Text: "A test text string" };
vTemplate = '<span id="<%=ID%>"><%=Text%> - <a href="<%=Link%>">Click me</a></span>';

vResult = af.common.runTemplate(vTemplate, vData, {
    Link: function(data) {
		// Note: passing data from database into a javascript link like this
		// could result in XSS security holes if not escaped. Be careful!
		return "javascript:alert('" + data.Text + "');";
    }
});

common web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

Using af.common.unFormatByMask - Parsing a date by using a format mask

/* Calling the af.common.unFormatByMask function, passing a date string and format mask
   will try to parse the date string into a date object using the passed format mask. */

var vDateString =  "Saturday the 6th of October 2012 at 09:30:00";

af.common.unFormatByMask(vDateString, "dddd 'the' dS 'of' MMMM yyyy 'at' HH:mm:ss");
// Returns a date object: Sat, 06 Oct 2012 09:30:00 GMT

common web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

How to format dates and numbers using a mask

var vDate = new XDate(2012, 9, 6, true);

/* Calling the af.common.formatByMask, passing a date and a format string,
   will look for the format alias in af.userSession and use that if present. */

af.common.formatByMask(vDate, "Short Date");
// Returns: "06.10.2012" (or whatever the short-date format is for your culture)


/* Calling the af.common.formatByMask function, passing a date and format string
   which is not in af.userSession will just use the provided format string. */

af.common.formatByMask(vDate , "dddd 'the' dS 'of' MMMM yyyy");
// Returns: "Saturday the 6th of October 2012"


/* Calling the af.common.formatByMask, passing a number and a format alias,
   will look for the format alias in af.userSession and use that if present. */

af.common.formatByMask(0.53, "%");
// Returns: "53%"

af.common.formatByMask(1.25e6, "123.12k");
// Returns: "1.25M"

af.common.formatByMask(5123.24, "1 234.1");
// Returns: "5 123,2"

common web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)

0

How to get all the values of an object as an array

/* Calling the af.common.getObjValues function on an object will return all its values as an array.
   The order of the values is the order they were added to the object. */

af.common.getObjKeys({ a: 1, b: 2, c: 3 });
// Returns: [1, 2, 3]

common web · Perma link post comment Posted by: Jan Henrik H. Meling (05-okt-2012)