How to get id of invisible element in fragment? - sapui5

I have a Dialog in fragment:
<core:FragmentDefinition
xmlns="sap.m"
xmlns:f="sap.ui.layout.form"
xmlns:core="sap.ui.core">
<Dialog title="{i18n>AddNewItem}" resizable="true" draggable="true">
<content>
<MessageStrip
id="failMsg"
visible="false"
text="{i18n>SensorTypesCreateFail}"
type="Error"
showIcon="true"/>
</Dialog>
</core:FragmentDefinition>
As in UI5 doc:
Retrieving a control instance when the fragment is not part of a view:
When no fragment ID was given: myControl = sap.ui.getCore().byId("myControl")
When a fragment ID myFrag was given: myControl = sap.ui.core.Fragment.byId("myFrag", "myControl")
If there is no visible="false", I can get this MessageStrip by sap.ui.getCore().byId("failMsg").
But I found that with visible="false", id of MessageStrip is sap-ui-invisible-failMsg, I failed to found proper API to get it.
Of course I can use sap.ui.getCore().byId("sap-ui-invisible-failMsg"), but I am not sure whether this ID will change after I deploy it to FLP, and as #schnoedel said in another question:
Beware that the prefixes like -- and --- used by the framework may change in the future. Thats why it's recommended to use the public api functions the framework supplies like byId() and createId().
So, is there any better way to get it?
Update:
Change my code from:
this[dialogName] = sap.ui.xmlfragment("namespace." + dialogName, this);
this.getView().addDependent(this[dialogName]);
To
this[dialogName] = sap.ui.xmlfragment(dialogName, "namespace." + dialogName, this);
this.getView().addDependent(this[dialogName]);
And now my id is sap-ui-invisible-dialogName--failMsg...

It depends on what you want to achieve after getting the ID. If you just want to change a property you could do it without any ID via a Model.
For that you can assign a Model field (i.e. baseModel>/visable) to the visable property and once it should be changed you change the model and via two way binding it updates the control.
code to change a model:
this.getView().getModel("nameOfUrModel").setProperty("property", "value")
for more information about this just check the walkthrough tutorial on
https://sapui5.hana.ondemand.com/
And if you for whatever reason really need the ID:
https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.core.Fragment.html
here you find the command:
sap.ui.core.Fragment.byId(sFragmentId, sId)
It should be able to return the Control your using
Hope that helps
Eric

You were very close to the solution. After adding dialogName for the fragment ID in its creation, you just have to call the API ...:
sap.ui.require(["sap/ui/core/Fragment"], Fragment => Fragment.byId(dialogName, "failMsg"));
... to get the control instance as mentioned here.
However, regardless whether you provided a fragment ID or not, you can easily ignore the render prefix "sap-ui-invisible-" at any time - Meaning that you could've also been able to get the control instance via sap.ui.getCore().byId("failMsg") instead of sap.ui.getCore().byId("sap-ui-invisible-failMsg") even if the control is invisible.

Related

SAPUI5 - How to change the table in the same View?

situation:
2 diferent tables, 1 view;
want to achieve:
I've got to change the table when I change the selectedKey in a select.
I already tried to create fragments with each table and call the one I want when I change the select.
fragment1 - table 1
fragment2 - table 2
select - oEvent (onChangeSelect) - getSelectedKey - if(key === 1) - call fragment1, if(key === 2) - call fragment2, but it gives me an error.
I don't know if this is correct and I'm not finding any infos related online.
If someone can show some links or give me just an idea on how can I do this, it would be perfect.
You could use the concept of binding to achieve this without coding. assume you have something like that in your view:
<Select><!-- ... --></Select>
<core:Fragment ... /><!-- table 1 -->
<core:Fragment ... /><!-- table 2 -->
First, add a model to your app, which will contain the information about the status of the app (which of the fragments is visible currently). Easiest way is to start with an empty JSON model. If you are familiar with manifest.json config, add it there. if not, you could add this in your Components init method:
this.setModel(new JSONModel(), "config");
This way, the new empty model is available under the name "config" in all the views of the app.
Now, we will add a visibility flag, which will control the visibility of your fragments (tables), and can be changed by the select:
<Select selectedKey="{config>/selectedFragmentKey}">
<core:Item key="" text="Please choose one" />
<core:Item key="showFragment1" text="Show Fragment 1" />
<core:Item key="showFragment2" text="Show Fragment 2" />
</Select>
This new version will store the key of the selected item in the config model in the path /selectedFragment. Add visibility flag to fragments (tables):
<!-- table 1 is only visible if "Show Fragment 1" was selected -->
<Table visible="{= ${config>/selectedFragmentKey} === 'showFragment1'}" .../>
<!-- table 2 is only visible if "Show Fragment 2" was selected -->
<Table visible="{= ${config>/selectedFragmentKey} === 'showFragment2'}" .../>
and you're done.
Main lesson here: learn to use bindings.
If I understood the question correctly, you have a selection control (which has 2 entries), and a table in the view. Based on the selection item, you want to display ONE of the tables at any given point of time. I am also assuming here, that the tables are purely used in the current view only & not really a "re-useable" thing - which gets used in different places of the app (which then renders the use of fragments an overkill).
I am assuming, both tables are bound (although to different data sets).
In that case, consider using the "visible" property of the appropriate table to "false".
Remember - all UI components, including tables inherit from sap.ui.core.Control - which has the "visible" property.
In API reference for table : https://sapui5.hana.ondemand.com/#/api/sap.ui.table.Table%23methods/Summary
If you scroll down to "Borrowed from:" section, you will see the "setVisible" and "getVisibe" methods.
So, in the event fired during selection change, you can grab the table control & set the visibility using the aforementioned methods.
Alternatively, you can also set an expression binding directly on the table control in XML, which evaluates to "true" or "false" (perhaps using a formatter).
Let me know if you need further info on this.
Best Regards,
Gopal Nair.

Mask input for sap.m.Date(Time)Picker

With the sap.m.DateTimePicker, it's possible for a user to either select a value from the drop-down list or enter it manually. I'm wondering if there's a way to add a mask to the manual input box that matches the valueFormat of the DateTimePicker.
I know there's a sap.m.MaskInput as well, so maybe there's a way to combine the two elements.
There is a new private module named sap.m.MaskEnabler which the sap.m.InputBase (i.e. DateTimePicker) is supposed to make use of.
(MaskEnabler) should be applied to the prototype of a sap.m.InputBase.
The mask feature is currently enabled only in sap.m.TimePicker (v1.54). According to this commit message, however, the same feature will arrive to the Date(Time)Picker as well:
This change prepares for refactoring of DatePicker and TimePicker so the
common code of both pickers can be moved to a new common control that
they may extend.
Therefore, if it's not urgent, and depending on your project, I'd not create a new custom control and then throw it away once the mask feature has arrived.
I'll update my answer when it's available.
Until then (and even afterwards), you can still guide the user to enter the data in the correct format via OData binding type sap.ui.model.odata.type.DateTime:
<DateTimePicker
value="{
path: 'myODataModel>myDateTime',
type: 'sap.ui.model.odata.type.DateTime',
constraints: {
isDateOnly: true,
displayFormat: 'Date'
}
}"
minDate="{...}"
maxDate="{...}"
/>
In contrast to formatter, type allows us to keep two-way data binding.
The entered value is automatically intercepted from updating the model data when...
It could not be parsed due to an invalid format (fires parseError)
It could be parsed but the constraints were violated (fires validationError)
If you enable handling UI messages
additionally, the framework will then take care of creating the appropriate
message for the user:
Example: https://stackoverflow.com/a/48482544
I think the only way to combine the two sap.m.DateTimePicker and sap.m.MaskInput is to develop your own control . Documentation : https://sapui5.hana.ondemand.com/#/topic/91f1703b6f4d1014b6dd926db0e91070.
Another way is to just use the Placeholder of the DateTimePicker Input field. This does not provide the same functionality as a MaskInput, but helps the user which valueFormat is expected in the input when entering it manually.
If you have a binding in your input box, you could set the type in the binding to eg. sap.ui.model.type.Date. This way you get some automatic formatting when field validation is triggered. There are other types available and you could inherit from sap.ui.model.SimpleType to code your own.

SAPUI5: How to create a control hierarchy?

I hope you can help me with this. After reading all the documentation several times, googling for days, etc I don't find the way to do what i'm going to explain in a clean way, and in think I'm missing something because it's a really basic scenario.
I'm working with oData models, in this case 2 named models, "Model1", "Model2". Now what I want is to show a "parent" ComboBox based on an oData path, and a table that changes its items depending on the selection, in other words.
Model1 { //JSON representation of the data.
Accounts:[
"account 1": {invoices: ["invoice1", "invoice2", "invoice3"]},
"account 2": {invoices:["invoice4", "invoice5"]}
]
}
Combo Box:
<... items={Model1>/Accounts} /> -- This works and shows Account 1, and Account2.
Table
<Table... items="{Model1>Invoices}">
..
<items>
....
</items>
</Table>
What I want is the table to change it's context to the account selected on the ComboBox. The point is that this works, but the first time it loads the view, as there is no account selected, it calls the wrong odata path MYSERVICE/Invoices, instead of doing nothing, as the Account is not set yet, and the path for the invoices, once selected the account, shoud be MYSERVICE/Account('Account1')/Invoices for example.
I know I can achieve this with code, but I'm sure there must be a clean way to do this.
Seriously, this is driving me crazy.
Thanks for your help.
Are you sure that
items="{Model1>Invoices}"
triggers odata call? Because this is a relative path (without leading slash), normally it should not do the call.
What you can do:
Handle ComboBox selectionChange event;
In this event handler, create a path that you will bound the table to. In your case the path could look like this: "/Account(Account1)" - "/{EntitySetName}({KEY})". You can make use of createKey method of ODataModel2;
Set the table's context using the path:
oTable.bindObject({
path: sPath,
model: "Model1",
parameters: {
$expand: "Invoices"
}
});
Once the context is set, the relative binding will start working automatically and table will get the "Invoices"
I assume that the Account and Invoices are linked via navigation property and one-to-many cardinality, that's why the $expand parameter will load the corresponding invoices.

Waiting for sap.ui.table.Table rendered after bound model has changed

I have sap.ui.table.Table which rows are bound to an JSONModel.
var oListModel = new sap.ui.model.json.JSONModel();
//oTable created here (sap.ui.table.Table)
oTable.setModel(oListModel);
oTable.bindRows("/");
When the table is rendered, i.e. the DOM is created for this table, i need to reference to the DOM to pass the DOM elements (table rows) to a library which will make them draggable.
My problem is: How do i know when the DOM for the table is created after the model has been changed and the table is rerendered? I didnt find any listener. The view controller's listener onAfterRendering() didn't help me.
The model is filled with data after a XMLHTTPRequest is successful. When i set the model in the success handler of the xht request and try to access the DOM elments directly afterwards they don't exist yet.
Thank you for your help!
You can add an event delegate
var oMyTable = new sap.ui.table.Table();
oMyTable.addEventDelegate({
onAfterRendering: function() {
$table = this.getDomRef() ....
}
});
a better way is to extend the control see Using addDelegate to extend a control to use third party functionality
UPDATE
the example in that blog doesn't work anymore fixed here
I had a similar issue recently where i had to access an element after a smartform (where the element is present) rendered onto the view. I posted my query here as well as my final solution (based on the accepted answer of #Dopedev). I am using XML views - including nested XML views - here however and the onAfterRendering didn't help for me as well.
I guess you could look at this solution - like it's mentioned in the accepted answer, it may not be an optimal solution, but it sure works. In my case there is not much of a performance issue with the binding of the DOMNodeInserted since it is being called in the onAfterRendering of the nested view that consists of only the smartform with an immediate unbinding upon finding.
The condition if (id === "yourtableid") { } should be enough to identify and pass on. Since you have a table and thus several child nodes, unbinding is imperative at this point.
Mutation Observer is the preferred method but i guess you may need to check the browser compatibility table at the end of the page to see if it matches your requirements. There is an example here. I have used Mutation Observer (outside of a SAPUI5/openUI5 environment) earlier and found it very convenient(and performant) to listen to DOM insert events. In fact the sap.ui.dt package consists of MutationObserver.js

Set class or ID on <h:inputHidden> in JSF

I'm trying to set a class or id parameter on a <h:inputHidden> in JSF. The code looks like this:
<h:inputHidden value="#{getData.name}" class="targ" />
But in the browser, the class isn't set:
<input type="hidden" name="j_idt6" value="j_idt6">
I need to set a class to this parameter, because I have a JavaScript autocomplete function for a <h:inputText> that sets a value in the hidden input, which needs to be passed in the next page.
Any ideas? Thanks!
I know it's a little bit late, but it can help someone in the future.
As inputHidden shows nothing in the browser there's no sense to allow it to have a class.
You can use the Id but as the Id could change as you change the component parents using it would bring some headache.
I'd suggest as a workaround, you can give it a parent so you can manipulate it by javascript.
Exemple:
JSF
<h:panelGroup styleClass="someCssClass">
<h:inputHidden id="someId" value="someValue" />
</h:panelGroup>
Javascript (using jQuery, you could use pure javascript also)
$('.someCssClass input[type=hidden]').val('yourNewValue');
None of these answers here satisfied my needs (need the PrimeFaces component, need class not ID, wrapping is too much work), so here's what I came up with:
Use pass-through attributes: https://www.primefaces.org/jsf-2-2-pass-through-attributes
Use pass:hidden-class="blah" (in my case, it's xmlns:pass up top)
Use [attribute=value] selector:
https://www.w3schools.com/cssref/sel_attribute_value.asp
document.querySelector multiple data-attributes in one element
That basically boils down to using something like this (because h:inputHidden becomes a regular input): document.querySelector("input[hidden-class=" + blah + "]")
Please, see similar question - How can I know the id of a JSF component so I can use in Javascript
You can sed "id" property, but in final html code it can be not the same, but composite: for example, if your input with id="myhidden" is inside form with id="myform", final input will have id="myform:myhidden".
In the end, I used a standard HTML <input type="hidden"> tag, as I had no advantages for using the JSF one. If you're trying to set a value in a hidden input with JavaScript, I recommend using this workaround.