Which methods are changed in migrating wicket from 1.3.6 to 1.4.0? - wicket

I'm migrating wicket from 1.3.6 to 1.4.0. I get syntax error by getModel() and getModelObject() methods. It says they are undefined, so they prevent application from compiling. Which methods should I use instead of them?
This is part of my code:
#SuppressWarnings("unchecked")
public BreadCrumbTrail(String id, IModel model) {
super(id, model);
// Keep a count of the crumbs
int count = 1;
// Get the crumbs
List<Crumb> crumbs = (List<Crumb>) getModelObject();
// Create a repeating view to render the crumbs within
RepeatingView repeating = new RepeatingView("crumbs");
add(repeating);
// Add each crumb
for (final Crumb crumb : crumbs) {
WebMarkupContainer item = new WebMarkupContainer(repeating
.newChildId());
repeating.add(item);
// Create a link from the page held in the crumb
#SuppressWarnings("serial")
Link link = new Link("link", item.getModel()) {
public void onClick() {
setResponsePage(crumb.getPage());
}
};
// Add a title/label to the link
link.add(new Label("title", crumb.getTitle()));
item.add(link);
// Is this the last crumb?
if (count == crumbs.size()) {
// Don't add the normal separator
item.add(new Label("separator", " "));
// Disable the link as this is the current page
link.setEnabled(false);
} else {
// Add the separator
item.add(new Label("separator", " > "));
}
// Up the count of crumbs
count++;
}
}

use getDefaultModelObject() instead
Wicket usually provides a migration guide:
https://cwiki.apache.org/WICKET/migrating-to-wicket-14.html#MigratingtoWicket1.4-Component.getModel%2528%2529andfriendsrenamedtogetDefaultModel%2528%2529andfriends
BTW: wicket 1.5 is also already out

Related

Create WinUI3/MVVM Most Recently Used (MRU) List in Menu Bar

I would like to create a classic "Recent Files" list in my Windows app menu bar (similar to Visual Studio's menu bar -> File -> Recent Files -> see recent files list)
The MRU list (List < string > myMRUList...) is known and is not in focus of this question. The problem is how to display and bind/interact with the list according to the MVVM rules.
Microsoft.Toolkit.Uwp.UI.Controls's Menu class will be removed in a future release and they recommend to use MenuBar control from the WinUI. I haven't found any examples, that use WinUI's MenuBar to create a "Recent Files" list.
I'm using Template Studio to create a WinUI 3 app. In the ShellPage.xaml I added
<MenuFlyoutSubItem x:Name="mruFlyout" Text="Recent Files"></MenuFlyoutSubItem>
and in ShellPage.xaml.c
private void Button_Click(object sender, RoutedEventArgs e)
{
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test1_" + DateTime.Now.ToString("MMMM dd") } );
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test2_" + DateTime.Now.ToString("MMMM dd") } );
mruFlyout.Items.Insert(mruFlyout.Items.Count, new MenuFlyoutItem(){ Text = "C:\\Test3_" + DateTime.Now.ToString("MMMM dd") } );
}
knowing this is not MVVM, but even this approach does not work properly, because the dynamically generated MenuFlyoutItem can be updated only once by Button_Click() event.
Could anybody give me an example, how to create the "Recent Files" functionality, but any help would be great! Thanks
Unfortunately, it seems that there is no better solution than handling this in code behind since the Items collection is readonly and also doesn't response to changes in the UI Layout.
In addition to that, note that because of https://github.com/microsoft/microsoft-ui-xaml/issues/7797, updating the Items collection does not get reflected until the Flyout has been closed and reopened.
So assuming your ViewModel has an ObservableCollection, I would probably do this:
// 1. Register collection changed
MyViewModel.RecentFiles.CollectionChanged += RecentFilesChanged;
// 2. Handle collection change
private void RecentFilesChanged(object sender, NotifyCollectionChangedEventArgs args)
{
// 3. Create new UI collection
var flyoutItems = list.Select(entry =>
new MenuFlyoutItem()
{
Text = entry.Name
}
);
// 4. Updating your MenuFlyoutItem
mruFlyout.Items.Clear();
flyoutItems.ForEach(entry => mruFlyout.Items.Add(entry));
}
Based on chingucoding's answer I got to the "recent files list" binding working.
For completeness I post the detailed code snippets here (keep in mind, that I'm not an expert):
Again using Template Studio to create a WinUI 3 app.
ShellViewModel.cs
// constructor
public ShellViewModel(INavigationService navigationService, ILocalSettingsService localSettingsService)
{
...
MRUUpdateItems();
}
ShellViewModel_RecentFiles.cs ( <-- partial class )
using System.Collections.ObjectModel;
using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Windows.Storage;
using Windows.Storage.AccessCache;
using Windows.Storage.Pickers;
namespace App_MostRecentUsedTest.ViewModels;
public partial class ShellViewModel : ObservableRecipient
{
public ObservableCollection<MRUItem> MRUItems{ get; set;} = new();
// update ObservableCollection<MRUItem>MRUItems from MostRecentlyUsedList
public void MRUUpdateItems()
{
var mruTokenList = StorageApplicationPermissions.MostRecentlyUsedList.Entries.Select(entry => entry.Token).ToList();
var mruMetadataList = StorageApplicationPermissions.MostRecentlyUsedList.Entries.Select(entry => entry.Metadata).ToList(); // contains path as string
MRUItems.Clear(); var i = 0;
foreach (var path in mruMetadataList)
{
MRUItems.Add(new MRUItem() { Path = path, Token = mruTokenList[i++] });
}
}
// called if user selects a recent used file from menu bar list
[RelayCommand]
protected async Task MRULoadFileClicked(int? fileId)
{
if (fileId is not null)
{
var mruItem = MRUItems[(int)fileId];
FileInfo fInfo = new FileInfo(mruItem.Path ?? "");
if (fInfo.Exists)
{
StorageFile? file = await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruItem.Token);
if (file is not null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Path); // store file.Path into Metadata
MRUUpdateItems();
// LOAD_FILE(file);
}
}
else
{
}
}
await Task.CompletedTask;
}
[RelayCommand]
protected async Task MenuLoadFileClicked()
{
StorageFile? file = await GetFilePathAsync();
if (file is not null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Path); // store file.Path into Metadata
MRUUpdateItems();
// LOAD_FILE(file);
}
await Task.CompletedTask;
}
// get file path with filePicker
private async Task<StorageFile?> GetFilePathAsync()
{
FileOpenPicker filePicker = new();
filePicker.FileTypeFilter.Add(".txt");
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(filePicker, hwnd);
return await filePicker.PickSingleFileAsync();
}
public class MRUItem : INotifyPropertyChanged
{
private string? path;
private string? token;
public string? Path
{
get => path;
set
{
path = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(path));
}
}
public string? Token
{
get => token;
set => token = value;
}
public event PropertyChangedEventHandler? PropertyChanged;
}
}
ShellPage.xaml
<MenuBar>
<MenuBarItem x:Name="ShellMenuBarItem_File">
<MenuFlyoutItem x:Uid="ShellMenuItem_File_Load" Command="{x:Bind ViewModel.MenuLoadFileClickedCommand}" />
<MenuFlyoutSubItem x:Name="MRUFlyout" Text="Recent Files..." />
</MenuBarItem>
</MenuBar>
ShellPage.xaml.cs
// constructor
public ShellPage(ShellViewModel viewModel)
{
...
// MRU initialziation
// assign RecentFilesChanged() to CollectionChanged-event
ViewModel.MRUItems.CollectionChanged += RecentFilesChanged;
// Add (and RemoveAt) trigger RecentFilesChanged-event to update MenuFlyoutItems
ViewModel.MRUItems.Add(new MRUItem() { Path = "", Token = ""});
ViewModel.MRUItems.RemoveAt(ViewModel.MRUItems.Count - 1);
}
// MRU Handle collection change
private void RecentFilesChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// project each MRUItems list element into a new UI MenuFlyoutItem flyoutItems list
var i = 0;
var flyoutItems = ViewModel.MRUItems.Select(entry =>
new MenuFlyoutItem()
{
Text = " " + i.ToString() + " " + FilenameHelper.EllipsisString(entry.Path, 65),
Command = ViewModel.MRULoadFileClickedCommand,
CommandParameter = i++
}
);
//// If you want to update the list while it is shown,
//// you will need to create a new FlyoutItem because of
//// https://github.com/microsoft/microsoft-ui-xaml/issues/7797
// Create a new flyout and populate it
var newFlyout = new MenuFlyoutSubItem();
newFlyout.Text = MRUFlyout.Text; // Text="Recent Files...";
// Updating your MenuFlyoutItem
flyoutItems.ToList().ForEach(item => newFlyout.Items.Add(item));
// Get index of old sub item and remove it
var oldIndex = ShellMenuBarItem_File.Items.IndexOf(MRUFlyout);
ShellMenuBarItem_File.Items.Remove(MRUFlyout);
// Insert the new flyout at the correct position
ShellMenuBarItem_File.Items.Insert(oldIndex, newFlyout);
// Assign newFlyout to "old"-MRUFlyout
MRUFlyout = newFlyout;
}

VisualForce Button not returning Selected Ids

I am converting a custom List JS button to support lighting. So, I've made changes to existing class and created a VF page and added that to the list view button. But when I run the functionality nothing seems to happen and debug logs returned Id as 000000.. Pls suggest.
global class AddUserToTeam{
public Opportunity objOpp;
global AddUserToTeam(ApexPages.StandardSetController stdcontroller) {
objOpp = (Opportunity)stdController.getRecord();
system.debug(objOpp );
}
public pagereference addTeam(){
List<Id> opportunityIds = new List<Id>();
opportunityIds.add(objOpp.Id);
system.debug('oppid'+ opportunityIds);
addTeamMember(opportunityIds);
//return new pagereference(url.getsalesforcebaseurl().toexternalform()+'/'+objOpp.Id);
return new PageReference('/006/o');
}
webservice static boolean addTeamMember(List<Id> opptyIds)
{
// some logic to add a user to teams
}
VF
<apex:page standardController="Opportunity" recordSetVar="Opportunities" extensions="AddUserToTeam" action="{!addTeam}">
</apex:page>
[enter image description here][1]
[1]: https://i.stack.imgur.com/2V3vp.png
I fixed the issue, check the below code
global class AddUserToTeam{
public Opportunity objOpp;
public String accIds{get;set;}
global AddUserToTeam(ApexPages.StandardSetController stdcontroller) {
System.debug('Get Selected');
objOpp = stdcontroller.getSelected();
accIds = '';
for(Opportunity acc : objOpp){
accIds += acc.Id + ',';
System.debug('Opp ID : '+accIds);
}
accIds = accIds.removeEnd(',');
}
}
public pagereference addTeam(){
List<Id> opportunityIds = new List<Id>();
opportunityIds.add(accIds );
system.debug('oppid'+ opportunityIds);
addTeamMember(opportunityIds);
return new pagereference(url.getsalesforcebaseurl().toexternalform()+'/'+accIds );
//return new PageReference('/006/o');
}
webservice static boolean addTeamMember(List<Id> opptyIds)
{
// some logic to add a user to teams
}

Wicket - changing panels through a dropdown

I have a dropdown component added on a page. the purpose of this dropdown is to change the type of input form that is rendered. for example, different forms have different required fields, editable fields, etc.
public final class Test extends WebPage
{
CustomPanel currentPanel = new MeRequest("repeater",FormType.MIN);
public Test(PageParameters parameters)
{
add(currentPanel);
DropDownChoice ddc = new DropDownChoice("panel", new PropertyModel(this, "selected"), panels, choiceRenderer);
ddc.add(new AjaxFormComponentUpdatingBehavior("onchange") {
protected void onUpdate(AjaxRequestTarget target) {
System.out.println("changed");
currentPanel = new MeRequest("repeater",FormType.PRO);
target.add(currentPanel);
}
});
add(ddc);
}
i've tried various options with limited results. the only real success has been updating the model, but what i really want to do is change how the components behave.
any thoughts on what i'm missing?
1) If you want to replace one panel with another you may just do the following.
First of all, you should output the markup id of the original panel:
currentPanel.setOutputMarkupId(true);
And then in the ajax event handler write something like that:
protected void onUpdate(AjaxRequestTarget target) {
CustomPanel newPanel = new MeRequest("repeater", FormType.PRO);
currentPanel.replaceWith(newPanel);
currentPanel = newPanel;
currentPanel.setOutputMarkupId(true);
target.addComponent(currentPanel);
}
In this case with every change of dropdown choice you add new panel to the page and you remove old panel from the page.
2) But I would proposed a slightly different approach to your problem. You should move the construction logic of your panel to the onBeforeRender() method:
public class MeRequest extends Panel {
private FormType formType;
public MeRequest(String id, FormType formType) {
super(id);
this.formType = formType;
// don't forget to output the markup id of the panel
setOutputMarkupId(true);
// constructor without construction logic
}
protected void onBeforeRender() {
// create form and form components based on value of form type
switch (formType) {
case MIN:
// ...
break;
case PRO:
// ...
break;
}
// add form and form components to panel
addOrReplace(form);
form.add(field1);
form.add(field2);
// ...
super.onBeforeRender();
}
public void setFormType(FormType formType) {
this.formType = formType;
}
}
Then you'll be able to only change type of the panel in the ajax event:
protected void onUpdate(AjaxRequestTarget target) {
currentPanel.setFormType(FormType.PRO);
target.addComponent(currentPanel);
}
Thus we rebuilt the original panel without recreating it.

Customise Validation summary

I have used html.ValidationSummary to get all errors displayed on top of the page.
This will render list with errors on top of the page.
Example:
<ul>
<li>UserName is invalid</li>
</ul>
I have how ever need to render every item instead of list as custom div with additional html tags inside.
I need every line to be rendered as short example below (this is only one line):
<div>
<div class="right"><a href="#closeError">Close error</div>
<div class="right"><a href="#Update">Update Field</div>
<label>Error:</label> Name on the page is invalid.
</div>
What is your opininon how to achieve this rendering?
I have considered to create html helper where i will take ModelState and get all errors, but not sure this will work...
I have considered to create html helper where i will take ModelState and get all errors, but not sure this will work...
Why wouldn't that work?
public static class ValidationExtensions
{
public static IHtmlString MyValidationSummary(this HtmlHelper htmlHelper)
{
var formContext = htmlHelper.ViewContext.ClientValidationEnabled
? htmlHelper.ViewContext.FormContext
: null;
if (formContext == null && htmlHelper.ViewData.ModelState.IsValid)
{
return null;
}
var sb = new StringBuilder();
var htmlSummary = new TagBuilder("div");
var modelStates = htmlHelper.ViewData.ModelState.Values;
sb.AppendLine("<div class=\"right\"><a href=\"#closeError\">Close error</div>");
sb.AppendLine("<div class=\"right\"><a href=\"#Update\">Update Field</div>");
if (modelStates != null)
{
foreach (ModelState modelState in modelStates)
{
foreach (ModelError modelError in modelState.Errors)
{
var userErrorMessageOrDefault = GetUserErrorMessageOrDefault(modelError);
if (!string.IsNullOrEmpty(userErrorMessageOrDefault))
{
sb.AppendFormat("<label>Error:</label> {0}{1}", htmlHelper.Encode(userErrorMessageOrDefault), Environment.NewLine);
}
}
}
}
htmlSummary.InnerHtml = sb.ToString();
if (formContext != null)
{
formContext.ReplaceValidationSummary = true;
}
return MvcHtmlString.Create(htmlSummary.ToString(TagRenderMode.Normal));
}
private static string GetUserErrorMessageOrDefault(ModelError error)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
{
return error.ErrorMessage;
}
return null;
}
}
and then:
<%= Html.MyValidationSummary() %>

Why is the PagingNavigator not generating the urls?

I have a problem with PagingNavigator in Wicket and I don't understand why am I having it. Here is the thing, I wanted to use a PagingNavigator with a Dataview
dataView = new DataView("pageableTicketsList", provider){
protected void populateItem(final Item item) {
//Somes codes here
};
navigator = new PagingNavigator("navigator", dataView);
dataView.setItemsPerPage(30);
addOrReplace(dataView);
addOrReplace(navigator);
In the html file, I simply have :
<wicket:enclosure child="navigator">
<div class="navigator">
<span wicket:id="navigator" ></span>
</div>
</wicket:enclosure>
When I test in a webBrowser, in fact, I have the pages number shown as :
<< < 1 2 3 4 5 6 7 8 9 10 > >>
BUT any of them are clickable.
I saw in FireBug that the urls are not properly generated like this :
<a href="?wicket:interface=:13:mypage:navigator:navigation:0:pageLink:4:ILinkListener::"><span>1</span>
</a>
Instead, I'm just having
<span>1</span>
I don't get it, what am I doing wrong ?
Here is the code of my provider
public class MyProvider implements IDataProvider {
private List<Ticket> ticketsList;
public MyProvider(TicketService ticketService // and some paramaters){
ticketsList = ticketService.getListBy(//the parameters);
}
public Iterator iterator(int first, int count) {
return ticketsList.subList(first, first + count).iterator();
}
public IModel model(final Object object) {
return new LoadableDetachableModel() {
#Override
protected Object load() {
return (Ticket)object;
}};
}
public int size() {
return ticketsList.size();
}
public void detach() {
}
public List<Ticket> getTicketsList() {
return ticketsList;
}
public void setTicketsList(List<ListTicketsExtranetView> ticketsList) {
this.ticketsList = ticketsList;
}
}
The method size() returns the right value and navigator.isEnabled() returns true
Well, after a whole day of digging, I finally found out where my problem came from :
I have a WebMarkupContainer that was added to my page, if I remove that WebMarkupContainer, the PagingNavigator works fine. There is no dependencies beetween the 2 of them though, I use the WebMarkupContainer to show a message if a list of Tickets is empty or not.
So WHY is the WebMarkupContainer having influence on the PagingNavigator ?
Can you post the code of your class that implements IDataProvider, e.g. SortableDataProvider? If the size() method isn't returning the right value, you might encounter the behaviour you're seeing.
Your code seems right. Did you set anything to disabled with
setEnabled(false);
That has effect on components below that in the hierarchy. If that does not make a difference, try posting some more code.