Create New Form not reload after save - dynamics-crm

working good in crm 2011 but not in crm 2013 online
On opportunity Entity create New record form i show only:
1.Some attributes(all other fields/Section/Tabs are hide on form)
2.and an Html button like
function OnFormLoad(){
if(Xrm.Page.ui.getFormType() == 1 ) {
SetRequiredLevelToNone();
createHtmlButton("Save");
HideTabsAndSections()
}
else {
}
}
On click of Html button following function is triggered.
function showWholeForm() {
Xrm.Page.data.entity.save();
}
I want to show all the fields of form after save, means want to reload whole form.
As working in crm 2011

The save method in CRM 2013 will not refresh the page anymore. The new refresh method should be used in this case, as follows:
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
save: Boolean value to be passed as true if data should be saved
after it is refreshed.
successCallback: Function to call when the operation succeeds
errorCallbak: Function to call when the operation fails, that will be passed an object with 2 properties - error code (number) and localized error message (string)
You could find the method documented here: http://msdn.microsoft.com/en-us/library/dn481607(v=crm.6).aspx

I think you should first disable the auto-save if you want consistency with CRM 2011.
function OnSaveDisableAutoSave(eventArgs) {
var saveType = eventArgs.getEventArgs().getSaveMode();
if (saveType == 70 ||saveType == 2)
{ //Disable AutoSave
eventArgs.preventDefault();
}
}
and then
function showWholeForm() {
Xrm.Page.data.refresh(true).then(successCallback, errorCallback);
}

To fix this you can do:
var saved = false;
function onLoad(){
checkIfFormShouldBeReadOnly();
attachEvent();
}
function attachEvent() {
Xrm.Page.data.entity.addOnSave(executeOnSave);
}
function executeOnSave(saveExecution) {
if (!saved) {
saved = true;
Xrm.Page.data.save().then(
function () {
checkIfFormShouldBeReadOnly();
},
function (errorCode, message) {
Xrm.Page.data.refresh();
}
);
}
}

Related

Material Datepicker change month view event

is there any way how to detect that calendar has new month view is loaded, when "yellow buttons" (see screenshot) are used?
You can listen for click events of those buttons on the calendar using Renderer2.
Code from this blog post.
constructor( private renderer: Renderer2g) { }
ngAfterViewInit() {
let buttons = document.querySelectorAll('mat-calendar .mat-calendar-previous-button,' +
'mat-calendar .mat-calendar-next-button');
if (buttons) {
Array.from(buttons).forEach(button => {
this.renderer.listen(button, "click", () => {
console.log("Month changed");
});
})
}
}
You can just use your own header component with whatever buttons and events your want:
<mat-calendar [headerComponent]="headerComponent"></mat-calendar>
And declare a variable headerComponent in the .ts:
public headerComponent = MyCoolHeaderComponent;
You will have to provide your own UI and functionality for the header (in your MyCoolHeaderComponent class).
MatDatepicker component uses DateAdapter service to handle dates, and when you click on next or previous button, a handler runs on MatCalendarHeader component and this handler calls addCalendarMonths method on DateAdapter (if current view is month) so if you patch this function on DateAdapter service TEMPORARILY, you can do anything you like, for example:
in parent component
origAddCalendarMonths: any
constructor(#Optional() private _dateAdapter: DateAdapter<any>) { }
onOpenedStream() {
this.origAddCalendarMonths = this._dateAdapter.addCalendarMonths
this._dateAdapter.addCalendarMonths = (...args) => {
console.log('!!!')
// your logic
return this.origAddCalendarMonths.apply(this._dateAdapter, args)
}
}
onClosedStream() {
this._dateAdapter.addCalendarMonths = this.origAddCalendarMonths
}
ngOnDestroy() {
this.onClosedStream()
}
or if you use MatCalendar instead, you can provide some extended class from DateAdapter in parent component providers to provide that class as DateAdapter for all child of this component (NodeInjector)

array from javascript to controller java in kendo ui

I have a grid in kendo ui with batch editing and I need pass a array to my controller when user clicks update. I have the follow code:
index.jsp:
parameterMap: function(data, type) {
if (type != "read") {
data = data.models;
}
return data;
}
Controller.java:
#Post
#WithoutRoot
public void atualizar(List<MyClassViewModel> vm) {
result.nothing();
}
This way, although the data.models containing an array of objects that were changed, my List returns empty. How can I do that?
Try using kendo.stringify:
parameterMap: function(data, type) {
if (type != "read") {
data = kendo.stringify(data.models);
}
return data;
}
Not sure if this will fix your issue but I'm also using batch: true for my dataSource and this seems to be working for my view models.
You probably also want to check Chrome -> Developer Tools -> Network -> Headers-> Request Payload and see how your data is handed over to the server. Your MyClassViewModel property names should match exactly what you pass from the client.

IE9 and AJAX - List Not Refreshing (ASP.NET and MVC3)

Im new to Web Development and its principles so apologies if my question does not seem clear.
Story So Far......
Im writing an Open Source application to learn ASP.NET MVC3. Now im at the stage where im creating my CRUD controller to allow me to create some new Types. Now I have created a SiteAdmin Controller which holds my Dashboard, with has a View. The View will contain tabs . I have been learning how to handle tabs using the following blog post and JQuery UI
http://ericdotnet.wordpress.com/2009/03/17/jquery-ui-tabs-and-aspnet-mvc/
I have decided to use the AJAX example to handle my tabs, whereby I pass an index parameter to a Controller Action Method called AjaxGetTab . This method (as per the blog post) returns a Partial View for the required Type. Within the Partial View there are Create Controller Action Method's, for e.g. CreateTransactionType (HttpPost), which create new records.
"Stop the waffling what is the problem"
The problem is that my list within the tab on the view doesn't refresh after the Create method is finished. This problem only exists in IE9 (Only IE i have tested) but Chrome and Firefox work, i.e. the list refreshes.
I have checked the Database records exists.
My code is here:
JQuery in Dashboard.cshtml:
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();
getContentTab (1);
});
function getContentTab(index) {
var url='#Url.Content("~/SiteAdmin/AjaxGetTab")/' + index;
var targetDiv = "#tabs-" + index;
var ajaxLoading = "<img id='ajax-loader' src='#Url.Content("~/Content")/ajax-loader.gif' align='left' height='28' width='28'>";
$(targetDiv).html("<p>" + ajaxLoading + " Loading...</p>");
$.get(url,null, function(result) {
$(targetDiv).html(result);
});
}
SiteAdminController AjaxGetTab Method:
/// <summary>
/// AJAX action method to obtain the correct Tab to use.
/// </summary>
/// <param name="index">Tab number</param>
/// <returns>Partial View</returns>
public ActionResult AjaxGetTab(int id)
{
string partialViewName = string.Empty;
object model = null;
//--Decide which view and model to pass back.
switch (id)
{
case 1:
partialViewName = "_TransactionType";
model = db.TransactionTypes.ToList();
break;
case 2:
partialViewName = "_DirectionType";
model = db.DirectionTypes.ToList();
break;
case 3:
partialViewName = "_UserType";
model = db.UserTypes.ToList();
break;
case 4:
partialViewName = "_CurrencyType";
model = db.CurrencyTypes.ToList();
break;
case 5:
partialViewName = "_tabError";
break;
}
return PartialView(partialViewName,model);
}
}
SiteAdminController CreateTransactionType Method:
[HttpPost]
public ActionResult CreateTransactionType(TransactionType model)
{
try
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
model.id = Guid.NewGuid();
model.RecordStatus = " ";
model.CreatedDate = DateTime.Now;
db.TransactionTypes.AddObject(model);
db.SaveChanges();
}
return RedirectToAction("Dashboard");
}
catch
{
return PartialView("_tabError");
}
}
Replace your
$.get(url,null, function(result) {
$(targetDiv).html(result);
});
By:
$.ajax({
type: 'get',
url: url,
cache: false,
success: function(result) {
$(targetDiv).html(result);
}
});
The problem is that IE caches ajax requests, so by setting cache: false in the settings it should work.

Partial View Validation Without JavaScript

I have a partial view in which there is a form. I POST this form using the PRG pattern. I am using the AjaxHelper to create my form. I also need this form to work without javascript. The problem is that when model validation fails, it always changes the url to my partial view.
public ActionResult PostForm(PostFormModel postFormModel)
{
if (ModelState.IsValid)
{
return RedirectToAction("SomewhereElse");
}
else
{
if (Request.IsAjaxRequest())
{
return PartialView("_PostForm")
}
else
{
// What do I do here?
}
}
}
Here's what I have tried:
return PartialView("_PostForm", postFormModel);
This just renders the partial view and doesn't contain any of the parent stuff.
return View("Index", new ParentModel() { PostFormModel = postFormModel });
This actually produces the correct result. It displays the parent view, but the URL is that of the partial http://localhost:22485/Controller/PostForm! I feel like this is really close to the solution. What now?
If you want to change url, you should redirect to another action (using PRG pattern). Insert next code instead of '// What do I do here?':
postModelService.Save(postFormModel); //to Session or to DB
return RedirectToAction("Parent");
New action should look like this:
public ActionResult Parent()
{
var postFormModel = postModelService.Load();
return View("Index", new ParentModel() { PostFormModel = postFormModel });
}
Hope it helps.

ASP.NET MVC "Ajax.BeginForm" executes OnSuccess even though model is not valid

I have a "submit feedback" form which uses "Ajax.BeginForm" to render a partial containing the form elements. The OnSuccess event is triggering even if the ModelState is not valid. Is this normal? I was expecting to be able to do a few postbacks resulting in an invalid model, then when the model is valid and there are no errors then the OnSuccess event would trigger?
I handle this issue with a fairly simple javascript technique:
First setup your OnSuccess like this:
OnSuccess = "UpdateSuccessful(data)"
Then your javascript function like this:
function UpdateSuccessful(data) {
if (data.indexOf("field-validation-error") > -1) return;
// Do your valid stuff here
}
This way, there is no need to mess with your controller, or more importantly, your controller can return the Partial View with the model errors without doing anything weird, ie:
public ActionResult SaveDetails(Project model)
{
if (ModelState.IsValid)
{
model.SaveProject();
}
return PartialView("ProjectForm", model);
}
And in your AjaxOptions:
UpdateTargetId = "FormContents"
Now just make sure you have a div or something with id="FormContents" wherever you want your form displayed.
Is this normal?
Yes, of course. If the server sends HTTP 200 the OnSuccess method is called. The notion of modelstate validity is server side only. As long as your controller action returns some view/partial/json/... the OnSuccess will trigger. If an exception is thrown inside your controller action then the OnError will be triggered instead of OnSuccess.
So in order to handle this case you could have your controller action do something along the lines of:
[HttpPost]
public ActionResult Process(MyViewModel model)
{
if (!ModelState.IsValid)
{
return Json(new { success = false });
}
return Json(new { success = true });
}
and then:
function success(result) {
if (result.success) {
// the model was valid
} else {
// the model was invalid
}
}
Now in the case of invalid model you might want to show the error messages to the user by refreshing the form. What you could do in this case is place your form inside a partial and in the event of an invalid modelstate you would return a partialview from your controller action and in the case of success a json object. So in your success handler you could test:
function success(result) {
if (result.success) {
// the model was valid
} else {
// there were errors => show them
$('#myform_container').html(result);
// if you are using client side validation you might also need
// to take a look at the following article
// http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
// and reattach the client validators to the form as you are
// refreshing its DOM contents here
}
}
You can do the following:
var OnSuccess = function() {
if ($(".validation-summary-errors").length == 0) {
//Your javascript/jquery code goes here
}
}
Slight variation on Luis' answer:
function OnSuccess() {
if ($("span[class='field-validation-error']").length == 0) {
alert("Target Platform saved Successfully.");
}
}
I return a bad request instead of the View to ensure that the ajax call returns onfail and not onsuccess.
In the xhr.statustext you can find the string written in the bad request and manage correctly the onfail event.
Server side:
if (!ModelState.IsValid)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Model not valid");
}
Client side:
$.ajax({
url: '',
method: 'POST'
}).fail(function (xhr) {
alert(xhr.statustext);
});

Resources