How can a field value of a Component be overridden using Event Handler? When I have the code snippet below, there is no error while saving the Component. But content changes done by the Event hanlder is not reflected back in the Component. I expect the single value field "size" to have "blabla..." as the value.
// Call to Subscribe the events
EventSystem.Subscribe<Component, SaveEventArgs>(ComponentSaveInitiatedHandler,
EventPhases.Initiated);
private void ComponentSaveInitiatedHandler(Component component,
SaveEventArgs args, EventPhases phases)
{
if (component.Schema.Title == "XYZ")
{
ItemFields Fields = new ItemFields(component.Content, component.Schema);
SingleLineTextField textField = (SingleLineTextField)Fields["size"];
textField.Value = "blabla...";
}
}
You need to update the Content property with the XML string, as follows:
ItemFields Fields = new ItemFields(component.Content, component.Schema);
SingleLineTextField textField = (SingleLineTextField)Fields["size"];
textField.Value = "blabla...";
component.Content = Fields.ToXml();
Related
I was trying out the newly released xamarin shell. Basically, I am trying out how to map the route to a dynamically generated page. I noticed the RegisterRoute has an overload that requires an object of type RouteFactory. I created a demo class for this:
class NavMan : RouteFactory
{
private readonly string title;
public NavMan(string title) : base()
{
this.title = title;
}
public override Element GetOrCreate()
{
return new ContentPage
{
Title = "tit: " + title,
Content = new Label { Text = title }
};
}
}
Now, in the App.cs I create a register a demo route:
Routing.RegisterRoute("batman", new NavMan("I am batman"));
I have tried several variations of setting up the Shell object. I mostly get blunt null pointers and need to guess what to change.
As of now, my App class's constructor has the following code:
var sea = new Shell();
var theItem = new FlyoutItem
{
IsEnabled = true,
Route = "batman"
};
sea.Items.Add(theItem);
sea.CurrentItem = theItem;
MainPage = sea;
This gives me a blunt null pointer too. All I am trying for now is to display the page of route "batman". Even a flyout or tab isn't mandatory.
Update
While not the aim, I at least got the app opening with the following:
var sea = new Shell();
Routing.RegisterRoute("batman", new NavMan("I am batman"));
var theItem = new ShellContent {
Title = "hello 20",
Route = "batman2",
Content = new ContentPage {
Content = new Button {
Text = "Something shown",
Command = new Command(async () => await Shell.Current.GoToAsync("//batman"))
}
}
};
sea.Items.Add(theItem);
sea.CurrentItem = theItem;
MainPage = sea;
On clicking the button, it now shows me the following exception and never calls the GetOrCreate function.
System.Exception: <Timeout exceeded getting exception details>
Update 3
Basically, I am looking for a way to bind a route to ShellContent in a way that it simply displays I mention the route property and it displays a page in the route. It doesn't make sense that I need to mention a route AND mention a content template for the page. The route is already mapped to a page.
Table has one date field. I have two form name as formA and formB ,formA has textbox and button. formB has grid with date field.
So my question is if I enter date in textbox and clicked the button of formA, entered date should be assign in grid of formB. I added table datasource of both forms. Please help me out on this.
Although behavior described by you seems to be not so standard in terms of AX, I would suggest you to use dialog form as a FormA (rather than regular form). That way you respect best practices and desired behavior is achieved easier.
Create class extending RunBase class with date field:
class FormADialog extends RunBase
{
DialogField fieldDate;
TransDate transDate;
}
Here is how we construct form controls:
protected Object Dialog()
{
Dialog dialog = super();
fieldDate = dialog.addField(extendedTypeStr(TransDate), 'Date');
return dialog;
}
The following method will retrieve values from Dialog:
public boolean getFromDialog()
{
transDate = fieldDate.value();
return super();
}
Processing logic goes here:
public void run()
{
FormBTable formBTable;
ttsbegin;
select firstOnly forUpdate formBTable;
formBTable.Date = transDate;
formBTable.write();
ttscommit;
}
The only missing thing is entry point for dialog class (represents FormA):
public static void main(Args _args)
{
FormADialog formADialog = new FormADialog();
FormDataSource formDataSource;
if (formADialog.prompt())
{
formADialog.run();
// FormB should contain menu item for dialog class for the following code
if (args && args.record() && args.record().dataSource())
{
formDataSource = args.record().dataSource();
formDataSource.research();
}
}
}
Now clicking on dialog button will update grid.
If you insist on use of approach with two regular forms. I will think of linkActive() method at the datasource of the second form. Take a look at
Tutorial Form Dynalink. A record change in the parent form notifies the child form, making it call the linkActive method which in turn calls the executeQuery method at the child table datasource.
Another approach could be as follows.
For passing parameters from one form to another a special class Args is usually used.
Initiator form prepares data for transfer within clicked() method of button control:
void clicked()
{
Args args;
FormRun formRun;
args = new Args();
args.parm(dateField.text());
args.name(formStr(FormB));
formRun = classFactory.formRunClass(args);
formRun.init();
formRun.run();
formRun.wait();
super();
}
Receiving endpoint should listen at init() method of FormB:
public void init()
{
Date passedValue;
super();
// check presence
if (element.args())
{
passedValue = str2Date(element.args().parm(), 123);
}
}
Take a look at axaptapedia.com article to see how we can pass complex set of parameters within custom made class.
I need to get the latest text set in the custom control by javascript. When i tried to get the selected text from server control, it is always returning the default text & not the modified text. How to retain the latest value set by the javascript in servercontrol? Below is the complete code for your reference..
ServerControl1.cs
[assembly: WebResource("ServerControl1.Scripts.JScript1.js", "text/javascript")]
namespace ServerControl1
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl
{
public List<string> ListItems
{
get
{
return ViewState["items"] as List<string>;
}
set
{
ViewState["items"] = value;
}
}
public string Text
{
get
{
return (FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor).InnerText;
}
set
{
((FindControl("middleDiv").FindControl("anchorID") as HtmlAnchor)).InnerText = value;
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextContainer.ID = "middleDiv";
HtmlAnchor selectedTextAnchor = new HtmlAnchor();
selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextAnchor.ID = "anchorID";
selectedTextAnchor.HRef = "";
selectedTextContainer.Controls.Add(selectedTextAnchor);
HtmlGenericControl unList = new HtmlGenericControl("ul");
foreach (string item in ListItems)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlAnchor anchor = new HtmlAnchor();
anchor.HRef = "";
anchor.Attributes.Add("onclick", "updateData()");
anchor.InnerText = item;
li.Controls.Add(anchor);
unList.Controls.Add(li);
}
selectedTextContainer.Controls.Add(unList);
Controls.Add(selectedTextContainer);
ChildControlsCreated = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string resourceName = "ServerControl1.Scripts.JScript1.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(ServerControl1), resourceName);
}
}
}
JScript1.js
function updateData() {
var evt = window.event || arguments.callee.caller.arguments[0];
var target = evt.target || evt.srcElement;
var anchor = document.getElementById("anchorID");
anchor.innerText = target.innerText;
return false;
}
TestPage Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> items = GetDataSource();
ServerControl1.ListItems = items;
ServerControl1.Text = "Select ..";
}
}
protected void ClientButton_Click(object sender, EventArgs e)
{
string selectedText = ServerControl1.Text;
}
The server won't get your client changes unless you POST the changes to him. Your HtmlAnchors are being rendered in HTML as <a> controls, and these type of controls won't POST anything to the server.
You're going to need an <input> control to input the changes into the server (that's why they're called input controls after all). I suggest an <input type=hidden> to hold the value of the anchor.innerText and keeps its state.
Your Javascript function needs to be modified so it updates the anchor.innerText AND updates the hidden input value as well. This way when the page gets posted back to the server you can retrieve the updated and client-modified value from the hidden field.
First you need to define as private fields your selectedTextAnchor and the hiddenField you are going to insert. This is because you need to access them in your CreateChildControls method as well as in the getter and setter of yout Text property. Much in the way the partial designer classes define the controls you want to have available in code-behind.
ServerControl.cs
private HtmlAnchor selectedTextAnchor;
private HtmlInputHidden hiddenField;
In the CreateChildControls method you need to insert the hidden field.
You'll notice I removed the use of ClientIDMode.Static. Using that mode would make your client controls to have the same fixed IDs and Javascript might get confused when you have multiple copies of your ServerControl in a page, and thus losing the reusable purpose of a custom control.
Instead, you need to provide your Javascript function with the ClientID's of the controls it needs to modify. The key here is that you need to attach your controls to the Control's hierarchy BEFORE you try to get their ClientID's.
As soon as you do this.Controls.Add(dummyControl), you're making dummyControl to become a part of the Page and its dummyControl.ClientID will be suddenly changed to reflect the hierarchy of the page you're attaching it into.
I changed the order at which your controls are attached to the Control's collection so we can grab their ClientID's at the time we build the onclick attribute and pass the parameters so your Javascript function knows which anchor and hiddenField to affect.
ServerControl.cs
protected override void CreateChildControls()
{
base.CreateChildControls();
// Instantiate the hidden input field to include
hiddenField = new HtmlInputHidden();
hiddenField.ID = "ANCHORSTATE";
// Insert the hiddenfield into the Control's Collection hierarchy
// to ensure that hiddenField.ClientID contains all parent's NamingContainers
Controls.Add(hiddenField);
HtmlGenericControl selectedTextContainer = new HtmlGenericControl("div");
// REMOVED: selectedTextContainer.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextContainer.ID = "middleDiv";
selectedTextAnchor = new HtmlAnchor();
// REMOVED: selectedTextAnchor.ClientIDMode = System.Web.UI.ClientIDMode.Static;
selectedTextAnchor.ID = "anchorID";
selectedTextAnchor.HRef = "";
selectedTextContainer.Controls.Add(selectedTextAnchor);
// Insert the selectedTextContainer (and its already attached selectedTextAnchor child)
// into the Control's Collection hierarchy
// to ensure that selectedTextAnchor.ClientID contains all parent's NamingContainers
Controls.Add(selectedTextContainer);
HtmlGenericControl unList = new HtmlGenericControl("ul");
foreach (string item in ListItems)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlAnchor anchor = new HtmlAnchor();
anchor.HRef = "";
// The updateData function is provided with parameters that will help
// to know who's triggering and to find the anchor and the hidden field.
// ClientID's are now all set and resolved at this point.
anchor.Attributes.Add("onclick", "updateData(this, '" + selectedTextAnchor.ClientID + "', '" + hiddenField.ClientID + "')");
anchor.InnerText = item;
li.Controls.Add(anchor);
unList.Controls.Add(li);
}
selectedTextContainer.Controls.Add(unList);
}
Note the use of the keyword this in the updateData function, it'll help us to grab the object that is triggering the action. Also note that both Id's are passed as strings (with single quotes)
The Javascript function would need to be modified so it updates the anchor and the hidden input field.
JScript1.js
function updateData(sender, anchorId, hidFieldId) {
// Update the anchor
var anchor = document.getElementById(anchorId);
anchor.innerText = sender.innerText;
// Update the hidden Input Field
var hidField = document.getElementById(hidFieldId);
hidField.value = sender.innerText;
return false;
}
The last thing to do is change the way you are setting and getting your Text property.
When you GET the property you need to check if it's a Postback, and if it is, then you want to check if among all the info that comes from the browser there is your HiddenInputField. You can grab all the info coming from the client right at the Request object, more specifically, in the Request.Form.
All enabled input controls on your page will be part of the Request.Form collection, and you can get their values by using Request.Form[anyInputControl.UniqueID]. Note that the key used for this object is the UniqueID, NOT ClientID.
Once you get your client-modified value from the hidden input, you assign its value to the selectedTextAnchor, otherwise it'll go back to the original "Select..." text.
When you SET the property, you just need to assign it to the selectedTextAnchor.
In both GET and SET you need to call EnsureChildControls(), which will actually call your CreateChildControls() to make sure that your selectedTextAnchor and hiddenField controls are instantiated before you try to get some of their properties. Pretty much the same way that it's done in Composite Controls.
ServerControl.cs
public string Text
{
get
{
EnsureChildControls();
if (this.Page.IsPostBack)
{
string HiddenFieldPostedValue = Context.Request.Form[hiddenField.UniqueID];
// Assign the value recovered from hidden field to the Anchor
selectedTextAnchor.InnerText = HiddenFieldPostedValue;
return HiddenFieldPostedValue;
}
else
{
return selectedTextAnchor.InnerText;
}
}
set
{
EnsureChildControls();
selectedTextAnchor.InnerText = value;
}
}
This way you can have a control that recognizes the changes made in client. Remember that server won't know any change in client unless you notice him.
Another approach would be to notice the server everytime you click a link through an ajax request, but this would require a whole new different code.
Good luck!
I wish to populate a drop down box with each possible SeriesChartType so that my users may choose an appropriate chart type.
How can I iterate through the SeriesChartType collection (it's in the namespace System.Web.Ui.DataVisualization.Charting) and return each possible option so I can add it to the drop down box?
Thanks.
This worked for me in VB - I had to instantiate a new instance of the SeriesChartType which allowed me to use the [Enum].GetNames Method.
I was then able to add them to the drop down box as shown:
Dim z As New SeriesChartType
For Each charttype As String In [Enum].GetNames(z.GetType)
Dim itm As New ListItem
itm.Text = charttype
ddl_ChartType.Items.Add(itm)
Next
Thanks to everyone for your answers. mrK has a great C alternative to this VB code.
foreach (ChartType in Enum.GetValues(typeof(System.Web.UI.DataVisualization.Charting))
{
//Add an option the the dropdown menu
// Convert.ToString(ChartType) <- Text of Item
// Convert.ToInt32(ChartType) <- Value of Item
}
If this isn't what you're looking for, let me know.
You could bind data in the DataBind event handler:
public override void DataBind()
{
ddlChartType.DataSource =
Enum.GetValues(typeof(SeriesChartType))
.Cast<SeriesChartType>()
.Select(i => new ListItem(i.ToString(), i.ToString()));
ddlChartType.DataBind();
}
and then retrieve the selected value in the SelectedIndexChanged event handler like this:
protected void ddlChartType_SelectedIndexChanged(object sender, EventArgs e)
{
// holds the selected value
SeriesChartType selectedValue =
(SeriesChartType)Enum.Parse(typeof(SeriesChartType),
((DropDownList)sender).SelectedValue);
}
Here's a generic function:
// ---- EnumToListBox ------------------------------------
//
// Fills List controls (ListBox, DropDownList) with the text
// and value of enums
//
// Usage: EnumToListBox(typeof(MyEnum), ListBox1);
static public void EnumToListBox(Type EnumType, ListControl TheListBox)
{
Array Values = System.Enum.GetValues(EnumType);
foreach (int Value in Values)
{
string Display = Enum.GetName(EnumType, Value);
ListItem Item = new ListItem(Display, Value.ToString());
TheListBox.Items.Add(Item);
}
}
How can I add a set of dynamic images and then add event handlers to each that trigger a different event?
My scenario is that I have a remote service that grabs a set of data (ArrayCollection) that has a className, classID and classDescription. I would like the images to have event handlers that trigger a new panel display that would show the "classDescription" for the particular class that is clicked. My problem is figuring out how to retrieve the proper set of data and adding the images properly to the panel.
From your Array Collection create a value object, a class or an interface making sure the properties names are identical and create the relevant accessors for it
public class DataObject
{
protected var _classDescription:String;
public function get classDescription():String
{
return _classDescription;
}
public function set classDescription(value:String):void
{
_classDescription = value;
}
}
When you retrieve your object form your ArrayCollection, you can loop thru the object's properties to assign them to your value object
var dataObj:DataObject = new DataObject();
for each ( var prop:String in collectionObject )
if( dataObj.hasOwnProperty(prop) )
dataObj[prop] = collectionObject[prop] ;
This object should extend Sprite so that you can add your image as a child and dispatch a mouse event. In the images container, the value object would add a MouseEvent listener and the listening function could be something like this:
private function mouseClickHandler(event:MouseEvent ):void
{
var target:YourValueObject = event.currentTarget as YourValueObject;
trace ( target.classDescription );
}