Add tab to the tabpanel on mvc - ext.net

I have a menu and some menu items.when I clcik to menu item I create new panle codebehind and add it to main tabpanel.so far so good ,but it seems for every click on the menu,panel created from the begining,plus,change place of the the tabs.how can I solve this.
here is the my Index.cshtml
<body>
#Html.X().ResourceManager()
#(
Html.X().Viewport()
.Layout(LayoutType.Border)
.Items(
Html.X().Panel()
.Region(Region.West)
.Title("main menu")
.Width(200)
.Collapsible(true)
.Split(true)
.MinWidth(175)
.MaxWidth(400)
.MarginSpec("5 0 5 5")
.Layout(LayoutType.Accordion)
.Items(
Html.X().MenuPanel()
.Collapsed(true)
.Icon(Icon.Note)
.AutoScroll(true)
.Title("menu")
.ID("PNL34")
.BodyPadding(0)
.Menu(menu => {
menu.Items.Add(Html.X().MenuItem().ID("1a").Text("test1").Icon(Icon.Anchor)
.DirectEvents(m => { m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1" ,pnlid="tabpnl10",viewname="Urunler"});
}));
menu.Items.Add(Html.X().MenuItem().ID("2a").Text("test2").Icon(Icon.Anchor)
.DirectEvents(m =>
{
m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1", pnlid = "tabpnl11", viewname = "Siparisler" });
}));
})
)
,
Html.X().TabPanel()
.ID("TabPanel1")
.Region(Region.Center)
.Title("E-TICARET")
.MarginSpec("5 5 5 0")
))
and codebehind controller
public ActionResult AddTab(string conid,string pnlid,string viewname)
{
var cmp = this.GetCmp<Panel>(pnlid);
var cmp2 = this.GetCmp<TabPanel>(conid);
if (cmp.ActiveIndex==-1)
{
var result = new Ext.Net.MVC.PartialViewResult
{
ViewName = viewname,
ContainerId = conid,
RenderMode = RenderMode.AddTo,
WrapByScriptTag = false
};
cmp2.SetActiveTab(pnlid);
return result;
}
else
{
return null;
}
}

This is not going to work.
if (cmp.ActiveIndex == -1)
In WebForms it is retrieved from the Post data. There is no a WebForms-like Post in MVC. You should send all the required information with a request.
Also if you don't need a tab to be rendered if it is already exists, just stop a request. You can determine on client if a tab is already there or not.

Related

Silverstripe 4 PaginatedList get Page-number - Link (Backlink)

In Silverstripe 4 I have a
DataObject 'PublicationObject',
a 'PublicationPage' and
a 'PublicationPageController'
PublicationObjects are displayed on PublicationPage through looping a PaginatedList. There is also a Pagination, showing the PageNumbers and Prev & Next - Links.
The Detail of PublicationObject is shown as 'Dataobject as Pages' using the UrlSegment.
If users are on the Detail- PublicationObject i want them to get back to the PublicationPage (the paginated list) with a Back - Link.
Two situations:
The user came from PublicationPage
and
The User came from a Search - Engine (Google) directly to the
DataObject- Detail.
I have done this like so:
$parentPage = Page::get()->Filter(array('UrlSegment' => $request->param('pageID')))->First();
$back = $_SERVER['HTTP_REFERER'];
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']))) {
if (strtolower(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) != strtolower($_SERVER['HTTP_HOST'])) {
// referer not from the same domain
$back = $parentPage->Link();
}
}
Thats not satisfying.
Question:
How do i get the Pagination - Link ( e.g: ...publicationen?start=20 ) when we are on the Detail - DataObject? How can we find the Position of the current Dataobject in that paginatedList in correlation with the Items per Page? (The Page- Link This Dataobject is on)
<?php
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\View\Requirements;
use SilverStripe\Core\Convert;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\ORM\PaginatedList;
use SilverStripe\Control\Director;
use SilverStripe\ORM\DataObject;
use SilverStripe\ErrorPage\ErrorPage;
use SilverStripe\Dev\Debug;
use SilverStripe\Dev\Backtrace;
class PublicationPageController extends PageController
{
private static $allowed_actions = ['detail'];
private static $url_handlers = array(
);
public static $current_Publication_id;
public function init() {
parent::init();
}
public function detail(HTTPRequest $request)
{
$publication = PublicationObject::get_by_url_segment(Convert::raw2sql($request->param('ID')));
if (!$publication) {
return ErrorPage::response_for(404);
}
// HERE I WANT TO FIND THE POSITION OF THE DATAOBJECT IN THE PAGINATEDLIST OR RATHER THE PAGE - LINK THIS DATAOBJECT IS IN
//$paginatedList = $this->getPaginatedPublicationObjects();
//Debug::show($paginatedList->find('URLSegment', Convert::raw2sql($request->param('ID'))));
//Debug::show($paginatedList->toArray());
$parentPage = Page::get()->Filter(array('UrlSegment' => $request->param('pageID')))->First();
$back = $_SERVER['HTTP_REFERER'];
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']))) {
if (strtolower(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) != strtolower($_SERVER['HTTP_HOST'])) {
// referer not from the same domain
$back = $parentPage->Link();
}
}
static::$current_Publication_id = $publication->ID;
$id = $publication->ID;
if($publication){
$arrayData = array (
'Publication' => $publication,
'Back' => $back,
'SubTitle' => $publication->Title,
'MetaTitle' => $publication->Title,
);
return $this->customise($arrayData)->renderWith(array('PublicationDetailPage', 'Page'));
}else{
return $this->httpError(404, "Not Found");
}
}
public function getPaginatedPublicationObjects()
{
$list = $this->PublicationObjects()->sort('SortOrder');
return PaginatedList::create($list, $this->getRequest()); //->setPageLength(4)->setPaginationGetVar('start');
}
}
EDIT:
is there a more simple solution ? than this ? :
public function detail(HTTPRequest $request)
{
$publication = PublicationObject::get_by_url_segment(Convert::raw2sql($request->param('ID')));
if (!$publication) {
return ErrorPage::response_for(404);
}
//*******************************************************
// CREATE BACK - LINK
$paginatedList = $this->getPaginatedPublicationObjects();
$dO = PublicationObject::get();
$paginationVar = $paginatedList->getPaginationGetVar();
$sqlQuery = new SQLSelect();
$sqlQuery->setFrom('PublicationObject');
$sqlQuery->selectField('URLSegment');
$sqlQuery->setOrderBy('SortOrder');
$rawSQL = $sqlQuery->sql($parameters);
$result = $sqlQuery->execute();
$list = [];
foreach($result as $row) {
$list[]['URLSegment'] = $row['URLSegment'];
}
$list = array_chunk($list, $paginatedList->getPageLength(), true);
$start = '';
$back = '';
$i = 0;
$newArray = [];
foreach ($list as $k => $subArr) {
$newArray[$i] = $subArr;
unset($subArr[$k]['URLSegment']);
foreach ($newArray[$i] as $key => $val) {
if ($val['URLSegment'] === Convert::raw2sql($request->param('ID'))) {
$start = '?'.$paginationVar.'='.$i;
}
}
$i = $i + $paginatedList->getPageLength();
}
$back = Controller::join_links($this->Link(), $start);
// END CREATE BACK - LINK
//*****************************************************
static::$current_Publication_id = $publication->ID;
$id = $publication->ID;
if($publication){
$arrayData = array (
'Publication' => $publication,
'Back' => $back,
'MyLinkMode' => 'active',
'SubTitle' => $publication->Title,
'MetaTitle' => $publication->Title,
);
return $this->customise($arrayData)->renderWith(array('PublicationDetailPage', 'Page'));
}else{
return $this->httpError(404, "Not Found");
}
}
You can simply pass the page number as a get var in the URL from the PublicationPage. The detail() method can then grab the get var and if there's a value for the page number passed in, add it to the back link's URL.
In the template:
<% loop $MyPaginatedList %>
Click me
<% end_loop %>
In your controller's detail() method:
$pageNum = $request->getVar('onPage');
if ($pageNum) {
// Add the pagenum to the back link here
}
Edit
You've expressed that you want this to use the page start offset (so you can just plug it into the url using ?start=[offset]), and that you want an example that also covers people coming in from outside your site. I therefore propose the following:
Do as above, but using PageStart instead of CurrentPage - this will mean you don't have to re-compute the offset any time someone clicks the link from your paginated list.
If there is no onPage (or pageOffset as I've renamed it below, assuming you'll use PageStart) get variable, then assuming you can ensure your SortOrder values are all unique, you can check how many items are in the list before the current item - which gives you your item offset. From that you can calculate what page it's on, and what the page offset is for that page, which is your start value.
public function detail(HTTPRequest $request)
{
$publication = PublicationObject::get_by_url_segment(Convert::raw2sql($request->param('ID')));
$paginatedList = $this->getPaginatedPublicationObjects();
// Back link logic starts here
$pageOffset = $request->getVar('pageOffset');
if ($pageOffset === null) {
$recordOffset = $paginatedList->filter('SortOrder:LessThan', $publication->SortOrder)->count() + 1;
$perPage = $paginatedList->getPageLength();
$page = floor($recordOffset / $perPage) + 1;
$pageOffset = ($page - 1) * $perPage;
}
$back = $this->Link() . '?' . $paginatedList->getPaginationGetVar() . '=' . $pageOffset;
// Back link logic ends here
//.....
}

Desperately need Xamarin.IOS modal MessageBox like popup

Coding in Xamarin IOS. I have a drop down list type popup, where, if The end user types in a new value, I want to ask a yes/no question: Do You want to add a new row?
The control is inside a UIStackView, which is inside a container UIView, which is in turn inside another which is presented via segue. Xamarin demanded a UIPopoverController, which I implemented. Here is The code I have so far:
using System.Threading.Tasks;
using Foundation;
using UIKit;
namespace PTPED_Engine
{
public enum MessagePopupType
{
YesNo = 1,
OKCancel = 2,
OKOnly = 3
}
public enum PopupResultType
{
OK = 1,
Cancel = 2,
Yes = 3,
No = 4
}
public static class AlertPopups
{
static NSObject nsObject;
public static void Initialize(NSObject nsObject)
{
AlertPopups.nsObject = nsObject;
}
public static Task<PopupResultType> AskUser(UIViewController parent, UIView V, string strTitle, string strMsg, MessagePopupType mpt)
{
using (UIPopoverController pc = new UIPopoverController(parent))
{
// pc.ContentViewController
// method to show an OK/Cancel dialog box and return true for OK, or false for cancel
var taskCompletionSource = new TaskCompletionSource<PopupResultType>();
var alert = UIAlertController.Create(strTitle, strMsg, UIAlertControllerStyle.ActionSheet);
// set up button event handlers
if (mpt == MessagePopupType.OKCancel)
{
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(PopupResultType.OK)));
alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(PopupResultType.Cancel)));
}
if (mpt == MessagePopupType.YesNo)
{
alert.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(PopupResultType.Yes)));
alert.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(PopupResultType.No)));
}
if (mpt == MessagePopupType.OKOnly)
{
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, a => taskCompletionSource.SetResult(PopupResultType.OK)));
}
// show it
nsObject.InvokeOnMainThread(() =>
{
pc.PresentFromRect(V.Bounds, V, UIPopoverArrowDirection.Any, true);
});
return taskCompletionSource.Task;
}
}
}
}
and I invoke it as follows:
LookupCombo.Completed += async (object sender, CompletedEventArgs e) =>
{
C1AutoComplete AC = (C1AutoComplete)sender;
if (AC.Text.Trim() != "")
{
string sColName = AC.AccessibilityIdentifier.Trim();
var ValuesVC = (List<Lookupcombo_Entry>)AC.ItemsSource;
var IsThisAHit = from Lookupcombo_Entry in ValuesVC
where Lookupcombo_Entry.sDispVal.ToUpper().Trim() == e.value.ToUpper().Trim()
select Lookupcombo_Entry.sMapVal;
if (!IsThisAHit.Any())
{
string sTitle = "";
string sFull = _RM.GetString(sColName);
if (sFull == null) { sFull = "???-" + sColName.Trim(); }
sTitle = " Add New " + sFull.Trim() + "?";
string sPPrompt = "Do you want to add a new " + sFull.Trim() + " named " + AC.Text.Trim() + " to the Database?";
var popupResult = await AlertPopups.AskUser(CurrentViewController(), V, sTitle, sPPrompt, MessagePopupType.YesNo);
}
}
};
CurrentViewController is defined like this:
private UIViewController CurrentViewController()
{
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
return vc;
}
This does nothing. It hangs The user interface.
This should be built in, but it is only built in in Xamarin.Forms, which I do not want to use.
I have no problem in doing this stuff with an await, but this is simply not working. Can anyone help?
Thanks!
You can just use the ACR UserDialogs library:
https://github.com/aritchie/userdialogs
This is a solution I provided a few years ago, I think it is an ugly hack, compared to your elegant approach. You did not say what part does not work exactly, that might help spot the problem.
Here is my solution from a few years back:
iphone UIAlertView Modal

'IObservable<SyncProgress>' does not contain a definition for 'CombineLatest'

I just took this code snippet from realm which fits my requirement .
var session = realm.GetSession();
var uploadProgress = session.GetProgressObservable(ProgressDirection.Upload, ProgressMode.ReportIndefinitely);
var downloadProgress = session.GetProgressObservable(ProgressDirection.Download, ProgressMode.ReportIndefinitely);
var token = uploadProgress.CombineLatest(downloadProgress, (upload, download) =>
{
return new
{
TotalTransferred = upload.TransferredBytes + download.TransferredBytes,
TotalTransferable = upload.TransferableBytes + download.TransferableBytes
};
})
.Throttle(TimeSpan.FromSeconds(0.1))
.ObserveOn(SynchronizationContext.Current)
.Subscribe(progress =>
{
if (progress.TotalTransferred < progress.TotalTransferable)
{
// Show spinner
}
else
{
// Hide spinner
}
});
But CombineLatest method is not available inside IObservable interface in Xamarin provided .Net subset.
But given I took this directly from real websites it is supposed to work .

PagedList.Mvc ellipsis button does not work

I am using PagedList.Mvc for paging in my MVC 5 app.
Question: The ellipsis button, which is after page#10 in screen shot below, does not do anything when clicked. Is that how its supposed to be, or I can make the ellipsis button work so clicking it would display the next set of pages?
The html helper being used in the View for displaying this pager is as below.
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, SearchText = ViewBag.SearchText }))
The solution that worked is to hide the ellipsis button.
SOLUTION
This solution involves hiding the ellipsis button. For this, you would need to make sure that the property of DisplayEllipsesWhenNotShowingAllPageNumbers under PagedListRenderOptions class is set to false, since its true by default. Its this setting that causes the pager to show the ellipsis button.
The code snippet given below will go into your View or PartialView html, and you will need to change some of the custom parameters like sortOrder and action name etc.
Hide Ellipsis button when Pager is ajaxified
#Html.PagedListPager(Model,
page => Url.Action("GetOrderDetails", new { page, sortOrder = ViewBag.CurrentSort,
, command = "paging", PageSize = ViewBag.PageSize }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new PagedListRenderOptions { DisplayEllipsesWhenNotShowingAllPageNumbers = false},
new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "gridTable",
OnBegin = "OnBegin", OnSuccess = "OnSuccess" }))
Hide Ellipsis button when Pager is non-ajaxified
#Html.PagedListPager(Model, page => Url.Action("Index", new { page,
sortOrder = ViewBag.CurrentSort, command = "paging", PageSize = ViewBag.PageSize}),
new PagedListRenderOptions { DisplayEllipsesWhenNotShowingAllPageNumbers = false })
ANOTHER SOLUTION
Download the source code from GitHub at https://github.com/troygoode/PagedList and open the solution in Visual Studio.
In HtmlHelper.cs class add the following 2 methods.
private static TagBuilder PreviousEllipsis(IPagedList list, Func<int, string> generatePageUrl, PagedListRenderOptions options, int firstPageToDisplay)
{
var targetPageNumber = firstPageToDisplay - 1;//list.PageNumber - 1;
var previous = new TagBuilder("a")
{
InnerHtml = string.Format(options.EllipsesFormat, targetPageNumber)
};
previous.Attributes["rel"] = "prev";
if (!list.HasPreviousPage)
return WrapInListItem(previous, options, "PagedList-skipToPrevious","disabled");
previous.Attributes["href"] = generatePageUrl(targetPageNumber);
return WrapInListItem(previous, options, "PagedList-skipToPrevious");
}
private static TagBuilder NextEllipsis(IPagedList list, Func<int, string> generatePageUrl, PagedListRenderOptions options, int lastPageToDisplay)
{
var targetPageNumber = lastPageToDisplay + 1;// list.PageNumber +1;
var next = new TagBuilder("a")
{
InnerHtml = string.Format(options.EllipsesFormat, targetPageNumber)
};
next.Attributes["rel"] = "next";
if (!list.HasNextPage)
return WrapInListItem(next, options, "PagedList-skipToNext", "disabled");
next.Attributes["href"] = generatePageUrl(targetPageNumber);
return WrapInListItem(next, options, "PagedList-skipToNext");
}
In same HtmlHelper.cs, replace an existing method of PagedListPager with following code. There are only 2 changes in this code and these are the 2 lines inserted just before the commented line of //listItemLinks.Add(Ellipses(options));. There are 2 places in the method where this line appeared in original code, and these have been commented and replaced by calls to the new methods defined in above code snippet.
///<summary>
/// Displays a configurable paging control for instances of PagedList.
///</summary>
///<param name = "html">This method is meant to hook off HtmlHelper as an extension method.</param>
///<param name = "list">The PagedList to use as the data source.</param>
///<param name = "generatePageUrl">A function that takes the page number of the desired page and returns a URL-string that will load that page.</param>
///<param name = "options">Formatting options.</param>
///<returns>Outputs the paging control HTML.</returns>
public static MvcHtmlString PagedListPager(this System.Web.Mvc.HtmlHelper html,
IPagedList list,
Func<int, string> generatePageUrl,
PagedListRenderOptions options)
{
if (options.Display == PagedListDisplayMode.Never || (options.Display == PagedListDisplayMode.IfNeeded && list.PageCount <= 1))
return null;
var listItemLinks = new List<TagBuilder>();
//calculate start and end of range of page numbers
var firstPageToDisplay = 1;
var lastPageToDisplay = list.PageCount;
var pageNumbersToDisplay = lastPageToDisplay;
if (options.MaximumPageNumbersToDisplay.HasValue && list.PageCount > options.MaximumPageNumbersToDisplay)
{
// cannot fit all pages into pager
var maxPageNumbersToDisplay = options.MaximumPageNumbersToDisplay.Value;
firstPageToDisplay = list.PageNumber - maxPageNumbersToDisplay / 2;
if (firstPageToDisplay < 1)
firstPageToDisplay = 1;
pageNumbersToDisplay = maxPageNumbersToDisplay;
lastPageToDisplay = firstPageToDisplay + pageNumbersToDisplay - 1;
if (lastPageToDisplay > list.PageCount)
firstPageToDisplay = list.PageCount - maxPageNumbersToDisplay + 1;
}
//first
if (options.DisplayLinkToFirstPage == PagedListDisplayMode.Always || (options.DisplayLinkToFirstPage == PagedListDisplayMode.IfNeeded && firstPageToDisplay > 1))
listItemLinks.Add(First(list, generatePageUrl, options));
//previous
if (options.DisplayLinkToPreviousPage == PagedListDisplayMode.Always || (options.DisplayLinkToPreviousPage == PagedListDisplayMode.IfNeeded && !list.IsFirstPage))
listItemLinks.Add(Previous(list, generatePageUrl, options));
//text
if (options.DisplayPageCountAndCurrentLocation)
listItemLinks.Add(PageCountAndLocationText(list, options));
//text
if (options.DisplayItemSliceAndTotal)
listItemLinks.Add(ItemSliceAndTotalText(list, options));
//page
if (options.DisplayLinkToIndividualPages)
{
//if there are previous page numbers not displayed, show an ellipsis
if (options.DisplayEllipsesWhenNotShowingAllPageNumbers && firstPageToDisplay > 1)
listItemLinks.Add(PreviousEllipsis(list, generatePageUrl, options, firstPageToDisplay));
//listItemLinks.Add(Ellipses(options));
foreach (var i in Enumerable.Range(firstPageToDisplay, pageNumbersToDisplay))
{
//show delimiter between page numbers
if (i > firstPageToDisplay && !string.IsNullOrWhiteSpace(options.DelimiterBetweenPageNumbers))
listItemLinks.Add(WrapInListItem(options.DelimiterBetweenPageNumbers));
//show page number link
listItemLinks.Add(Page(i, list, generatePageUrl, options));
}
//if there are subsequent page numbers not displayed, show an ellipsis
if (options.DisplayEllipsesWhenNotShowingAllPageNumbers && (firstPageToDisplay + pageNumbersToDisplay - 1) < list.PageCount)
listItemLinks.Add(NextEllipsis(list, generatePageUrl, options, lastPageToDisplay));
//listItemLinks.Add(Ellipses(options));
}
//next
if (options.DisplayLinkToNextPage == PagedListDisplayMode.Always || (options.DisplayLinkToNextPage == PagedListDisplayMode.IfNeeded && !list.IsLastPage))
listItemLinks.Add(Next(list, generatePageUrl, options));
//last
if (options.DisplayLinkToLastPage == PagedListDisplayMode.Always || (options.DisplayLinkToLastPage == PagedListDisplayMode.IfNeeded && lastPageToDisplay < list.PageCount))
listItemLinks.Add(Last(list, generatePageUrl, options));
if(listItemLinks.Any())
{
//append class to first item in list?
if (!string.IsNullOrWhiteSpace(options.ClassToApplyToFirstListItemInPager))
listItemLinks.First().AddCssClass(options.ClassToApplyToFirstListItemInPager);
//append class to last item in list?
if (!string.IsNullOrWhiteSpace(options.ClassToApplyToLastListItemInPager))
listItemLinks.Last().AddCssClass(options.ClassToApplyToLastListItemInPager);
//append classes to all list item links
foreach (var li in listItemLinks)
foreach (var c in options.LiElementClasses ?? Enumerable.Empty<string>())
li.AddCssClass(c);
}
//collapse all of the list items into one big string
var listItemLinksString = listItemLinks.Aggregate(
new StringBuilder(),
(sb, listItem) => sb.Append(listItem.ToString()),
sb=> sb.ToString()
);
var ul = new TagBuilder("ul")
{
InnerHtml = listItemLinksString
};
foreach (var c in options.UlElementClasses ?? Enumerable.Empty<string>())
ul.AddCssClass(c);
var outerDiv = new TagBuilder("div");
foreach(var c in options.ContainerDivClasses ?? Enumerable.Empty<string>())
outerDiv.AddCssClass(c);
outerDiv.InnerHtml = ul.ToString();
return new MvcHtmlString(outerDiv.ToString());
}
Then, rebuild the code and copy over the dlls to your bin folder. After this you will find that the ellipsis button is enabled, and will take you to the page just before the first page of current set of page numbers, or the page just after this current set. I tested this and it worked.

MOSS 2007: Adding Filter to ListView web part

I have been dropped into a sharepoint 2007 project, and i have relatively little experience with altering existing webparts.
My first task is to add a filter to two out of three columns in a list view. My Lead Dev suggests trying to add a jquery combo-box filter, and another dev suggests extending the web part and overriding some of the functionality.
What i think is a good option is to change the context menu for the list view headers, so that instead of "Show Filter Choices" bringing up a standard dropdownlist that only responds to the first letter, it would have a jquery combobox. And maybe if the business requests it, change the wording of that option.
My question to you is, what would be a good path to take on this? Also, what resources are there besides traipsing around books and blogs are there to guide an sp newbie to do this?
Thanks.
How about something like this:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
$(document).ready(function()
{
jQuery.extend(jQuery.expr[':'], {
containsIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0"
});
$("table.ms-listviewtable tr.ms-viewheadertr").each(function()
{
if($("td.ms-vh-group", this).size() > 0)
{
return;
}
var tdset = "";
var colIndex = 0;
$(this).children("th,td").each(function()
{
if($(this).hasClass("ms-vh-icon"))
{
// attachment
tdset += "<td></td>";
}
else
{
// filterable
tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' /></td>";
}
colIndex++;
});
var tr = "<tr class='vossers-filterrow'>" + tdset + "</tr>";
$(tr).insertAfter(this);
});
$("input.vossers-filterfield")
.css("border", "1px solid #7f9db9")
.css("width", "100%")
.css("margin", "2px")
.css("padding", "2px")
.keyup(function()
{
var inputClosure = this;
if(window.VossersFilterTimeoutHandle)
{
clearTimeout(window.VossersFilterTimeoutHandle);
}
window.VossersFilterTimeoutHandle = setTimeout(function()
{
var filterValues = new Array();
$("input.vossers-filterfield", $(inputClosure).parents("tr:first")).each(function()
{
if($(this).val() != "")
{
filterValues[$(this).attr("filtercolindex")] = $(this).val();
}
});
$(inputClosure).parents("tr.vossers-filterrow").nextAll("tr").each(function()
{
var mismatch = false;
$(this).children("td").each(function(colIndex)
{
if(mismatch) return;
if(filterValues[colIndex])
{
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
if($(this).is(":not(:containsIgnoreCase('" + val + "'))"))
{
mismatch = true;
}
}
});
if(mismatch)
{
$(this).hide();
}
else
{
$(this).show();
}
});
}, 250);
});
});
});
It will need to be added to the page via a content editor web part.

Resources