Scout Eclipse check for dirty fields - valuechangelistener

When you try to close Swing application and you change same value in field, application ask you if you want to save changes.
My first question is why RAP application doesn't ask same question ?
Second and more important question is how to force validation of fields change and how to manipulate this.
for example :
I have table with rows and some fields below table. If I click on row some value is entered in fields. I can change this value and click button save.
I would like to force change validation on row click. So if changes ware applied and if I click on row, application should warn me that some changes are not saved.
But I should be able to manipulate what is change and what is not. For example if table on row click fill some data if fields this is not change, but if I entered value is same fields this is change.
I discovered method
checkSaveNeeded();
But it does nothing. (if I change values or not)
I see that every field has mathod
#Override
public final void checkSaveNeeded() {
if (isInitialized()) {
try {
propertySupport.setPropertyBool(PROP_SAVE_NEEDED, m_touched || execIsSaveNeeded());
}
catch (ProcessingException e) {
SERVICES.getService(IExceptionHandlerService.class).handleException(e);
}
}
}
so I should manipulate changes throw m_touched ?
How is this handled in Scout ?
ADD
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form, and way to set fields dirty or not.
I look here and here, but all it describes is how values is stored for popup messages and dot how to fire this messages (validation).

My first question is why RAP application doesn't ask same question ?
I am not sure to know which message box you mean but it should be the case.
There are several questions about unsaved changes and form lifecycle in the Eclipse Scout Forum. I think you can find them with Google.
I have also taken the time to start to document it in the Eclipse Wiki:
Scout Field > Contribution to unsaved changes
Form lifecycle
I think you should implement execIsSaveNeeded() in the corresponding field. The default implementation in AbstractTableField uses the state of the rows, but you can imagine the logic you want.
#Order(10.0)
public class MyTableField extends AbstractTableField<MyTableField.Table> {
#Override
protected boolean execIsSaveNeeded() throws ProcessingException {
boolean result;
//some logic that computes if the table field contains modification (result = true) or not (result = false)
return result;
}
//...
I hope this helps.
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form.
Are you speaking from this message box that appears when the user clicks on Cancel in the form?
There is no specific function that you can call for that. But you can check the beginning of the AbstractForm.doCancel() function. It is exactly what you are looking for.
I have rewritten it like this:
// ensure all fields have the right save-needed-state
checkSaveNeeded();
// find any fields that needs save
AbstractCollectingFieldVisitor<IFormField> collector = new AbstractCollectingFieldVisitor<IFormField>() {
#Override
public boolean visitField(IFormField field, int level, int fieldIndex) {
if (field instanceof IValueField && field.isSaveNeeded()) {
collect(field);
}
return true;
}
};
SomeTestForm.this.visitFields(collector);
MessageBox.showOkMessage("DEBUG", "You have " + collector.getCollectionCount() + " fields containing a change in your form", null);
I have changed the Visitor to collect all value fields with unchanged changes. But you can stick to the original visitField(..) implementation. You cannot use P_AbstractCollectingFieldVisitor because it is private, but you can have a similar field visitor somewhere else.
I am looking for a way to set fields dirty or not.
As I told you: execIsSaveNeeded() in each field for some custom logic. You can also call touch() / markSaved() on a field to indicate that it contains modifications or not. But unless you cannot do otherwise, I do not think that this is the correct approach for you.

Related

How to make Date Editable while using Glass mapper

Today i am facing one issue which has following requirement.
Date should be Editable.
Date should be in particular format.
My Code is like below which is not working.
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
I have tried following approach but throwing "DateParameters" namespace error.
#Editable(item, x=> x.Start_Date, new DateParameters { Format = "MMMM dd,yyyy"})
Also i have learner following thing but how can i achieve this ?
To make a field editable takes two parameters, this has been used to make the Date field editable. The first parameter instructs Glass.Mapper which field to make editable, the second parameter then specifies what the output should be when the page is not in page editing mode. This allows you to control the output of the field when in the two different modes.
Can anybody help me ?
For Experience editor mode, this works for me in razor view:
#Editable(model => model.SomeDateField, new { Format = "dd-MM-yyyy" })
Sitecore 8.2 though, with Glass 4.4.
What you want to do is to provide the default format but keep things the same for the main glass stuff. Like so:
foreach(var item in Model)
{
<div>#Editable(item, x => x.Start_Date, x=>x.Start_Date.ToString("MMMM dd,yyyy"))</div>
}
This will make the date a normal date when editing, but allow you to format it for the final page.
Usually in this case i use different code for "Normal View" and "Experience Editor", so for normal view you need only to display the date with format without making it editable, and on experience editor you need only to edit the date field the author will not care about the date format with experience editor, so your code will be like this :
foreach(var item in Model)
{
{
#if (Sitecore.Context.PageMode.IsExperienceEditorEditing)
{
<div>#Editable(item, x => x.Start_Date)</div>
}
else
{
<div>#item.Start_Date.ToString("MMMM dd,yyyy")</div>
}
}
}
I have tried that as well but it is throwing an error like below
**Value cannot be null. Parameter name: objectToSwitchTo
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Common.Switcher2.Enter(TValue objectToSwitchTo)
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression1 field, Expression1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer)**
Any help on this ?

Sitecore|WFFM| Custom Error Message with details| on Same Page with Form

I have a Web Form for Marketer set up done for one of my Pages.
I have Custom Submit Action written for it as shown below in the code snippet -
public class **CustomFormSubmit : ISaveAction**
{
public void Execute(ID formid, AdaptedResultList fields, params object[] data)
{
try
{
**//var returnValue= Custom Logic to save form data // returns true or false**
}
catch (Exception ex)
{
Logger.Log(ex.Message + ":" + builder, ExceptionCategory.Error);
throw;
}
}
In my above Web form - Success Mode is - SuccessMode/Redirect and I have a success Page configured for it.
My requirement in above scenario is to keep user on the same Page(with Form) if returnValue is false . (as shown in above code snippet)
Can anyone Please guide me in the above scenario as - how to keep user on the same Page with values filled in the form so that user can submit it again.
Product Details - 7.2 rev. 141226 , Web Forms for Marketers 2.4 rev.140117
To add further details -
I am not sure how can I go back to my page instead of the redirection in case if return is false in the above code snippet.
As soon the submit button is clicked the above function- Execute- gets called.
How do I go back to the Page - Do I need to override any function or customize something.
If any exception comes while saving data- then the control goes back to the same Page with all values filled by user retained -with the Save Action Failed Message which is configured in Sitecore .
So my requirement will be to go to to the form as happening in case of Exception when false comes as return value while saving data and to put customised Error Messages which might change each time, so not statically configured ,rather a dynamic one.
Thanks!
Saurabh
One option will be to redirect to the original page with the Form on.
Enable your form to populate the fields via Query String using the ReadQueryString property, via Presentation Details of the Form Renderer:
So on false of your Save Action you create a collection of query strings with the name of each Field, as it appears in the Form, followed by the User's value.
The code below will loop through all your fields and arrange them into a QueryString with its FieldName and Value;
string urlOfForm = HttpContext.Current.Request.Url.AbsolutePath;
var queryString = new StringBuilder("?");
foreach (AdaptedControlResult field in fields)
{
queryString.Append(string.Format("{0}={1}&", field.FieldName, field.Value));
}
urlOfForm = urlOfForm + queryString;
HttpContext.Current.Response.Redirect(urlOfForm);
Sitecore will then automatically populate the appropriate fields with the values, achieving your requirement.
EDIT
I have found that most Exceptions thrown will take the user back to the Form with their values populated. You can then pass in the cause of the failure to write to your CRM. See below for Example
if (submitFailed)
{
throw new Exception("The email address entered already exists in our System");
}
The complexity then comes in dynamically swapping out the Save Action Failed Message to show this Exception Message. All posts I find about custom Save Action Message state the only real approach is to redirect via your Custom Save Action to a different page showing a different message. Which is not suitable to your requirements.
I have found the pipeline Args you are going to need to patch FormSubmitFailedArgs and SubmitFailedArgs. The Former will need the following change
public FormSubmitFailedArgs(ID formID, AdaptedResultList fields, ID actionFailed, Exception ex)
: base(formID, actionFailed, ex)
{
this.Fields = fields;
this.ErrorMessage = ex.Message;
}
and the Latter will need
public SubmitFailedArgs(ID formID, ID actionFailed, string errorMessage, Exception innerException)
{
this.FormID = formID;
this.ActionFailed = actionFailed;
this.ErrorMessage = innerException.Message;
this.InnerException = innerException;
}
Location and Styling of Submit Message:
You need to find the FormRender sublayout file, this is defaulted to website\sitecore modules\Web\Web Forms for Marketers\Control\SitecoreSimpleFormAscx.ascx inside there you will find a compont called SubmitSummary this renders out the submit message so move it to where you require.
Also note it references the CssClass scfSubmitSummary this is what you will need to target to change the styling of the Message. This Answer is already REALLY long so I won't give a blow by blow how to change the styling of that class, see here for example - http://www.awareweb.com/awareblog/10-1-13-wffmguide
Pipeline Patching
I've dug in deeper, in order to use the custom Args we created for using the exception error message you will need to control the Pipeline which ultimately uses those Args, this is the processor Sitecore.Form.Core.Pipelines.FormSubmit.FormatMessage, Sitecore.Forms.Core in the <errorSubmit> Pipeline.
From my investigation it shouldn't take much effort then its a matter of patching it, you can modify if the Sitecore.Forms.config directly or use patch:instead from a config file within the App_Config/Includes folder - see here for more info.
One option would be to create a Custom Form Verification Action. You could save the data here, although it would be better to verify the data against your API here and then save the data in custom save action, simply since this seems more logical as to how WFFM was meant to function.
using Sitecore.Data;
using Sitecore.Form.Core.Controls.Data;
using Sitecore.Form.Core.Submit;
using System;
using System.Collections.Generic;
namespace Custom.WFFM
{
public class CustomVerificationStep : BaseCheckAction
{
public string FailedMessage { get; set; }
public override void Execute(ID formid, IEnumerable<ControlResult> fields)
{
// Call your API
// You have access to the fields, so you can pass them through as parameters to your if needed
bool flag = ServiceAPI.ValidateUserData(param1, param2, etc);
if (!flag)
{
throw new Exception(string.Format(this.FailedMessage ?? "There was an error while verifying the data against the service call"));
}
}
public override ActionState QueryState(ActionContext context)
{
return ActionState.DisabledSingleCall;
}
}
}
Create the corresponding Verification Action under /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Form Verification:
You can change the error message by setting it in the Parameters field as <FailedMessage>Custom Failed Error Message</FailedMessage>.
And then add your verification step to your form:
If you need a different error message per form then you can set the error message to display from the Error Messages tab.
The user will then be returned to the same without any of the save actions being called and the form fields still filled in.

Search Dialogs in Epicor

Hopefully someone here is familiar with creating customizations in Epicor 9. I've posted this to the Epicor forums as well, but unfortunately that forum seems pretty dead. Any help I can get would be much appreciated.
I've created a customization on the Order Entry form to display and store some extra information about our orders. One such field is the architect on the job. We store the architects in the customer table using a GroupCode of AR to distinguish them from regular customers. I have successfully added a button that launches a customer search dialog and filters the results to only display the architects (those with GroupCode AR). Here's where the problems come in. I have two questions:
1: On the customer search, there is a customer type field that defaults to a value of Customer. Other choices are < all>, Suspect, or Prospect. How can I make the search form default to < all>?
2: How do I take the architect (customer) I select through the search dialog and populate its CustID into the ShortChar01 field on my Order Entry customization? Here's the code I have:
private void SearchOnCustomerAdapterShowDialog()
{
// Wizard Generated Search Method
// You will need to call this method from another method in custom code
// For example, [Form]_Load or [Button]_Click
bool recSelected;
//string whereClause = string.Empty;
string whereClause = "GroupCode = 'AR'";
System.Data.DataSet dsCustomerAdapter = Epicor.Mfg.UI.FormFunctions.SearchFunctions.listLookup(this.oTrans, "CustomerAdapter", out recSelected, true, whereClause);
if (recSelected)
{
System.Data.DataRow adapterRow = dsCustomerAdapter.Tables[0].Rows[0];
// Map Search Fields to Application Fields
EpiDataView edvOrderHed = ((EpiDataView)(this.oTrans.EpiDataViews["OrderHed"]));
System.Data.DataRow edvOrderHedRow = edvOrderHed.CurrentDataRow;
if ((edvOrderHedRow != null))
{
edvOrderHedRow.BeginEdit();
edvOrderHedRow["ShortChar01"] = adapterRow["CustID"];
edvOrderHedRow.EndEdit();
}
}
}
When I select a record and click OK, I get an unhandled exception.
I think the problem you are/were having is that you aren't adding the CustNum to the Sales Order first. In my mind I would do it this way first, but there is might be ChangeCustomer BO method in oTrans that you could call to make sure everything defaults correct.
EpiDataView edvOrderHed = ((EpiDataView)(this.oTrans.EpiDataViews["OrderHed"]));
if (edvOrderHed.HasRow)
{
edvOrderHed[edvOrderHed.Row].BeginEdit();
edvOrderHed[edvOrderHed.Row]["CustNum"] = adapterRow["CustNum"];
edvOrderHed[edvOrderHed.Row]["ShortChar01"] = adapterRow["CustID"];
edvOrderHed[edvOrderHed.Row].EndEdit();
}
Hope that is helpful, even if late.

cfwheels - removing unused composite key pairs

I've got an issue with a nested property that uses a composite key.
When I'm editing a model that has multiple instances of nested properties (with a composite key) and want to update it to have fewer by leaving them blank, cfWheels does not remove the ones that are not used anymore, and maintains the old value. Is there a way of forcing the deletion of these without calling delete on the nested model?
I've been doing by deleting all nested properties, and then update() creates the records that are needed, but the big issue with that is that when I have code in between that fails, It just deletes the items, which as you know can be very very bad.
In your init call to nestedProperties(), try adding the allowDelete option:
nestedProperties(association="comments", allowDelete=true);
Then if a model within that collection has a property called _delete that is set to true, CFWheels will delete that record.
I'm not sure of your model because you don't include any details in your question, but you could probably run a beforeValidationOnUpdate callback that checks criteria on the nested models and sets _delete = true when the record needs to be deleted.
For example:
// Post.cfc
component extends="Model" {
function init() {
hasMany("comments");
nestedProperties(association="comments", allowDelete=true);
beforeValidationOnUpdate("removeBlankComments");
}
private function removeBlankComments() {
if (StructKeyExists(this, "comments") && IsArray(this.comments)) {
for (local.i = 1; local.i < ArrayLen(this.comments); local.i++) {
if (!Len(this.comments[local.i].message)) {
this.comments[local.i]._delete = true;
}
}
}
}
}
Not sure if this will give you any problems with the nested composite key. Sometimes nested properties are a little kludgy with "special" cases.
i think you forgot to mention allowDelete attribute in nestedProperties by defalut allowDelete is set as false in wheels and does not delete the composite key form table. you have to set it true.
for example in model you have to do some thing like this.
<cfset hasMany(name="campaignlanguages",shortcut="languages", dependent="deleteAll") />
<cfsetnestedProperties(associations="campaignlanguages",allowDelete="true")/>
you can find more details here

Can't access a new field programmatically on a template in Sitecore

my question is basically the same as #Bob Black's Cannot access sitecore item field via API but I agree with #techphoria414 that the accepted solution is not necessary and in my case does not work.
In my own words, I have a template Departure that I have been using for about a year now creating and updating items programmatically. I have added a new field Ship to the template. When I create a new item the field comes up as null when I try to access it using departure.Fields["Ship"]. If I step over the line causing the exception then after calling departure.Editing.EndEdit() I can then see the Ship field if I call departure.Fields.ToList(). If I add the template to a content item via the Sitecore GUI I can see the field and use it, and if I look at a content item which is based on the template I can see the new field too. So it is only when I access the template/item programmatically that it is null.
I have sitecore running on my local machine with a local sqlserver, and publish to my local machine.
Here is my code
String ship = "MSDisaster";
foreach (Language language in SiteLanguages)
{
departure = departure.Database.GetItem(departure.ID, language);
departure.Editing.BeginEdit();
try
{
departure.Fields["StartDate"].Value = GetSitecoreDateString(xDep, "StartDate");
departure.Fields["EndDate"].Value = GetSitecoreDateString(xDep, "EndDate");
departure.Fields["Guaranteed"].Value = xDep.SelectSingleNode("./Guaranteed").InnerText;
departure.Fields["Status"].Value = xDep.SelectSingleNode("./Status").InnerText;
departure.Fields["Currency"].Value = ConvertLanguageToCurrency(language);
departure.Fields["Market"].Value = ConvertLanguageToMarket(language);
departure.Fields["TwinSharePrice"].Value = GetPrice(xDep, "twn", language);
departure.Fields["SinglePrice"].Value = GetPrice(xDep, "sgl", language);
if (!String.IsNullOrEmpty(ship))
departures.Fields["Ship"].Value = ship;
}
catch (Exception ex)
{
departure.Editing.CancelEdit();
log.Error(ex);
throw ex;
}
departure.Editing.EndEdit();
}
So, how do I get the field be picked up?
Thanks,
James.
Firstly do you see the field in the web database in the sitecore administration.
If you do the item has the fields, you then should check the template assigned on the item and double check that the field is actually called "ship" and check the case as ive seen this as an issue before.
Also check the security on the item and field just in case anyone changed anything.
Next try and get the data from the item but instead of using the field name, use the field ID.
Let me know how you go?
Chris
Sorry Chris, StackOverflow, and the others who looked at my questions. It was a stupid typo. It's even there in my question
departure.Fields["SinglePrice"].Value = GetPrice(xDep, "sgl", language);
if (!String.IsNullOrEmpty(ship))
departures.Fields["Ship"].Value = ship;
}
departure is the item I am working on, departures is the collection it belongs to... doh.
So what is the protocol here? Do I delete my question now because it isn't really going to help anyone code better?
James.