dhtmlxGrid : Cliclking header in Big Data grid - dhtmlx

I'd like to maintain page location while click onto header.
But if I'm in page 5 and click onto header then page location changed to 1 page.
(sort is perfect)
I want maintain my page location if I click onto header in page 5, still maintain location
5 page and sorting is perfectly.
I think this is not enough to explain my situation. So I post my development environment
I'm using struts2 and mysql. and here's my javascript.
function fnGridInitSW(){
swgrid = new dhtmlXGridObject('swGridBox');
swgrid.setImagePath("../../../common/img/dhtmlx/grid/");
swgrid.setHeader("SoftWareName, company, version, Install_date");
swgrid.setColumnIds(
"COL_1"
+",COL_2"
+",COL_3"
+",COL_4"
);
swgrid.setInitWidthsP("25,25,25,*");
swgrid.setColTypes("ro,ro,ro,ro");
swgrid.setColSorting("str,str,str,str");
swgrid.attachEvent("onXLS", function(){
$("#swnotfound").hide();
$("#swgridLoading").show();
});
swgrid.attachEvent("onXLE", function(){
$("#swgridLoading").hide();
swgrid.changePage(chPg);
$("#swnotfound").hide();
});
swgrid.init();
swgrid.attachEvent("onBeforePageChanged",function(ind,count){
chPg = count;
if (!swgrid.getRowsNum()){
return false;
};
return true;
});
var mygrid_state = swgrid.getSortingState();
popFnSearch(swgrid.getColumnId(mygrid_state[0]), mygrid_state[1]);
// Custom Sorting
swgrid.attachEvent("onBeforeSorting",function(ind, type, direction) {
popFnSearch(swgrid.getColumnId(ind), direction);
var sInd;
var mygrid_state = swgrid.getSortingState();
if( typeof(mygrid_state[0]) == "undefined" ){
sInd = ind;
}
direction = (mygrid_state[1] == "des") ? "asc": "des";
swgrid.setSortImgState(true,sInd,direction);
return true;
});
}
function popFnSearch(sortC, sortD) {
if( typeof(sortC) == "undefined" ) sortC = swgrid.getColumnId(3);
if( typeof(sortD) == "undefined" ) sortD = "desc";
var params = "/url/Info.do?"&sortC="+sortC+"&sortD="+sortD+"&pageCnt=5";
swgrid.clearAndLoad(params);
}
here's my xml for grid.
<%# page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<rows total_count='<s:property value="%{totalCnt}" />' pos='<s:property value="%{posStart}" />'>
<s:if test="softwareList.size > 0">
<s:iterator value="%{softwareList}" status="index">
<row id="'index<s:property value='%{SW_SEQNO}'/>'">
<cell><s:property value="%{SW_NM}" /></cell>
<cell><s:property value="%{SW_COMPANY}" /></cell>
<cell><s:property value="%{SW_VER}" /></cell>
<cell class="last"><s:property value="%{INST_DT}" /></cell>
</row>
</s:iterator>
</s:if>
</rows>
here's my query
//get total count from softwarelist
<select id="getSoftwareInfoTotCnt" resultClass="Integer" parameterClass = "d">
SELECT IFNULL(COUNT(*), 0)
FROM T_PC_SW_LIST sl
JOIN T_SOFTWARE so ON sl.SW_SEQNO = so.SW_SEQNO
</select>
//get real data from softwarelist
<select id="getSoftwareInfo" resultClass="c" parameterClass = "d">
SELECT
sl.SW_SEQNO
, sl.ASST_SEQNO
, so.SW_NM
, so.SW_COMPANY
, so.SW_VER
, DATE_FORMAT(sl.INST_DT, '%Y-%m-%d') AS INST_DT
FROM T_PC_SW_LIST sl
JOIN T_SOFTWARE so ON sl.SW_SEQNO = so.SW_SEQNO
ORDER BY $sortC$ $sortD$
LIMIT #posStart# , #count#
</select>
If anyone have solution please help me..

You may get the current active page before the sorting started using the getStateOfView() method:
http://docs.dhtmlx.com/doku.php?id=dhtmlxgrid:api_method_dhtmlxgridobject_getstateofview
and then open the needed page after the new sorted data is loaded using the changePage() method:
http://docs.dhtmlx.com/doku.php?id=dhtmlxgrid:api_method_dhtmlxgridobject_changepage

Related

ASP.Net Webforms with SumoSelect

On "Page_Load" I fill a DropDownList with my data source:
lstBoxGrupAcessID.DataTextField = "Description";
lstBoxGrupAcessID.DataValueField = "ID";
lstBoxGrupAcessID.DataSource = new BLLCompany().SelectLstGroupBox(objCompany.CompanyID);
lstBoxGrupAcessID.DataBind();
After this, I need to set the lstBoxGrupAcess with some pre-selected itens ( specific for each company ) ( just for sample, I will select all the itens on the lstBoxGrupAcessID )
foreach (ListItem itm in lstBoxGrupAcessID.Items)
itm.Selected = true;
When I execute the page, I got this erro:
Cannot have multiple items selected in a DropDownList.
The inicialization of SumoSelect in my code is:
<script>
$(document).ready(function () {
var list = $('#<%=lstBoxGrupAcessID.CompanyID%>');
list.SumoSelect({
selectAll: false
});
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
var list = $('#<%=lstBoxGrupAcessID.CompanyID%>');
list.SumoSelect({
selectAll: false
});
}
</script>
The declaration of my DropDownList is:
<asp:DropDownList ID="lstBoxGrupAcessID" runat="server" multiple="multiple" CssClass="form-control"></asp:DropDownList>
You must use asp:ListBox for select multiple items, not Dropdown

Chosen with Ajax in Classic Asp

I'm new to Ajax and Chosen so please bear with me. I'm trying to reload a second select box based on the selection of the first one. All of my select boxes are using the Chosen plugin.
First, this is my JQuery function for chosen.
$(function(){
$('.TeacherName').chosen({ max_selected_options: 1, placeholder_text_multiple: "Select A Teacher"});
$('.Schools') .chosen({ max_selected_options: 1, placeholder_text_multiple: "Select A School" });
});
</script>
Next I load the two boxes from a record-set.
<select class="Schools" name="Schools" id="schoolDrop" style="max-width:210px;" multiple="multiple" onchange="getLocation(this.value);">
<% while not SchoolList.eof%>
<option value="<%=SchoolList("SCHOOL_NUMBER")%>"><%=SchoolList("NAME")%> </option>
<%SchoolList.MoveNext
wend%>
</select>
<select class="TeacherName" name="TeacherName" id="TeacherName" multiple="multiple"style="max-width:150px;">
<option value="0"></option>
<%while not TeacherList.eof%>
<option value="<%=TeacherList("DCID")%>"</option>
<%TeacherList.MoveNext
wend%>
</select>
As you can see I call the Ajax function in an onchange event in the Schools select box.
Next is my Ajax Function.
function getLocation(schoolId)
{
var strURL="SetTeacherAjax.asp?school="+schoolId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('TeacherName').innerHTML=req.responseText;
} else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}//End of Function getLocation
The ajax works if I remove the class selector from the TeacherName drop down.
I've figure this out, so I'll post it as it may help someone else. I needed to add an update statement for Chosen plugin.
enter code here if (req.status == 200)
{
document.getElementById('TeacherName').innerHTML=req.responseText;
$('#TeacherName').trigger('chosen:updated');
} else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
Once I added the
$('#TeacherName').trigger('chosen:updated');
it worked.

How can I implement a dynamic form in TYPO3?

I have created a extension to manage some courses and now I want to add some dynamic to one of my forms. This form contains two select fields. The first select field specify a course category and the second one a course. Currently I get always all categories and all courses no matter which category is selected.
Now I would like that a user can only select a course which belongs to a selected category, but I don't know how I can implement this.
I have tried to use a typeNum and some ajax, but I don't know how I can change the form model with the ajax call and without a page reload.
My template for this form looks like the following:
<f:layout name="Default" />
<f:section name="main">
<div class="sidebar-view">
<a id="form"></a>
<f:form action="list" name="form" object="{form}" section="form">
<fieldset>
<f:render partial="FormErrors" arguments="{field: 'form.category'}" />
<f:form.select class="category" property="category" options="{categoryOptions}" optionValueField="key" optionLabelField="value" prependOptionLabel="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.category')}" />
<f:render partial="FormErrors" arguments="{field: 'form.course'}" />
<f:form.select property="course" options="{courseOptions}" optionValueField="key" optionLabelField="value" prependOptionLabel="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.course')}" />
<f:form.hidden class="id" property="pageId" />
<f:form.submit name="send" value="{f:translate(key: 'LLL:EXT:courses/Resources/Private/Language/locallang_db.xlf:tx_courses_domain_model_form.submit')}" />
</fieldset>
</f:form>
</div>
</f:section>
As you can see it is a simple form with two select fields, a submit button and a hidden field which stores the page id. I don't want to submit the form when the category is changed so I think there is no way to implement this dynamic without ajax.
For this reason I have implemented the following typenum:
obj.ajaxPrototype = PAGE
obj.ajaxPrototype {
typeNum = 0
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type: text/plain
xhtml_cleaning = 0
debug = 0
no_cache = 1
admPanel = 0
}
}
ajaxCall < obj.ajaxPrototype
ajaxCall {
typeNum = 1001
10 < tt_content.list.20.courses_p1
}
After that I have added some javascript (jQuery) to execute a controller action via ajax when the select field is changed:
$(document).ready(function() {
$('.tx-courses select:first-of-type').on('change', function() {
$.ajax({
method: "POST",
url: "index.php?id=" + $('.id').val(),
data: "type=1001&tx_courses_p1[action]=check&tx_courses_p1[form][category]="+$('.category').val(),
success: function(msg) {
alert(msg);
}
});
});
});
Simple action:
/**
* check action
*
* #return void
*/
public function checkAction() {
return 'ajax call fired';
}
If I change the select field I get the message "ajax call fired". So my controller action will be executed and I might implement some "get courses by requested category id" logic and so on now, but how can I update the form from above which will be rendered by my sidebarAction with the ajax call and without a page reload?
Ok, I found a way to get it work.
At first I changed the ontent type of my typeNum from above to json, because I want to work with json.
additionalHeaders = Content-type: application/json
Then I changed my ajax call:
$(document).ready(function() {
var arr;
var ajaxCall = function() {
$.ajax({
method: "POST",
url: "index.php?id=" + $('.id').val(),
data: "type=1001&tx_courses_p1[action]=check&tx_courses_p1[form][category]="+$('.category').val(),
success: function(msg) {
$('.tx-courses .course option:not(:first-child)').remove();
arr = $.map(msg, function(el) { return el });
arr.sort();
$.each(arr, function(i, val) {
$('.tx-courses .course').append('<option value="'+val+'">'+val+'</option>');
});
}
});
};
// init (if someone submitted the form, but forgot to select a category)
ajaxCall();
// someone changed the category
$('.tx-courses .category').on('change', function() {
ajaxCall();
});
});
And my controller action for this ajax request looks as follows:
/**
* check action
*
* #return string
*/
public function checkAction() {
// get arguments
$args = $this->request->getArguments();
// create container for courses which are depended on selected category
$coursesBySelectedCategory = array();
// check if category was posted and category exists
if (isset($args['form']['category']) && $this->courseRepository->categoryExists($args['form']['category'])) {
// get all courses which belongs to this category
$courses = $this->courseRepository->findByCategoryId($args['form']['category']);
} else {
// get all courses
$courses = $this->courseRepository->findAllNotExpiredCourses();
}
// store course names
foreach($courses as $course) {
$coursesBySelectedCategory[] = $course->getName();
}
// remove double entries
$coursesBySelectedCategory = array_unique($coursesBySelectedCategory);
return json_encode($coursesBySelectedCategory);
}
Your feedback is welcome :).

How to Add update panel in MVC 3

I am updating product Quantity by Update button, after clicking on update button page is reloading, instead of reloading that page i want to update that "cartUpdatePanel" table area only by Ajax
My View is
using (Html.BeginRouteForm("ShoppingCart", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table id="cartUpdatePanel" class="table_class" cellpadding="0" cellspacing="0">
#foreach (var item in Model.Items)
{
<tr style="background: #f3f3f3;">
<td>
<input type="submit" name="updatecartproduct#(item.Id)" value="Update Cart" id="updatecartproduct#(item.Id)" />
</td>
</tr>
}
}
My Controller action is, by which i am updating Product Quantity
[ValidateInput(false)]
[HttpPost, ActionName("Cart")]
[FormValueRequired(FormValueRequirement.StartsWith, "updatecartproduct")]
public ActionResult UpdateCartProduct(FormCollection form)
{
if (!_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart))
return RedirectToRoute("HomePage");
//get shopping cart item identifier
int sciId = 0;
foreach (var formValue in form.AllKeys)
if (formValue.StartsWith("updatecartproduct", StringComparison.InvariantCultureIgnoreCase))
{
sciId = Convert.ToInt32(formValue.Substring("updatecartproduct".Length));
break;
}
//get shopping cart item
var cart = _workContext.CurrentCustomer.ShoppingCartItems
.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var sci = cart.Where(x => x.Id == sciId).FirstOrDefault();
if (sci == null)
{
return RedirectToRoute("ShoppingCart");
}
//update the cart item
var warnings = new List<string>();
foreach (string formKey in form.AllKeys)
if (formKey.Equals(string.Format("itemquantity{0}", sci.Id), StringComparison.InvariantCultureIgnoreCase))
{
int newQuantity = sci.Quantity;
if (int.TryParse(form[formKey], out newQuantity))
{
warnings.AddRange(_shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
sci.Id, newQuantity, true));
}
break;
}
//updated cart
cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
var model = PrepareShoppingCartModel(new ShoppingCartModel(), cart, true, false, true);
//update current warnings
//find model
var sciModel = model.Items.Where(x => x.Id == sciId).FirstOrDefault();
if (sciModel != null)
foreach (var w in warnings)
if (!sciModel.Warnings.Contains(w))
sciModel.Warnings.Add(w);
return View(model);
}
How i will achieve to update "cartUpdatePanel" table area after clicking on update button by ajax
Thanx in Advance
Please consider using Ajax.BeginForm helper to create the form. You can use AjaxOptions to specify callback code to capture server output and do whatever you want (including injecting it to a div, table, field set ..)
Using the Ajax.BeginForm is very easy
#using (Ajax.BeginForm(
"name_of_the_action",
new AjaxOptions {
OnSuccess = "processServerResp",
HttpMethod = "POST"},
new {enctype="multipart/form-data"})
){
// rest of the form code
}
Now using javascript, implement processServerResp as a function which takes a single parameter. This parameter will contain what ever values passed from the server to the client. Assuming the server is returning html, you can use the following code to inject it into a container with the id of id_fo_the_div
function processServerResp(serverData){
$(‘#id_fo_the_div’).html(serverData);
// or inject into a table ..
}
You can tap into other interesting features provided by AjaxOptions and do very interesting things.
A good article on Ahax.BeginForm http://www.blackbeltcoder.com/Articles/script/using-ajax-beginform-with-asp-net-mvc
Happy coding

Can I Use PartialViewResult with PagedList and show it in a PartialView

Hi everyone I have a question, Can I use PagedList in a PartialViewResult Action and show the result in a PartialView?
Here is some code
Controller Code:
public PartialViewResult CargosPorProyecto(string id, int? page)
{
var cargos = db.Cargo.Include(i => i.Proyectos).Where(i => i.NumProyecto.Equals(id)).OrderByDescending(i => i.Fecha);
if (Request.HttpMethod != "GET")
{
page = 1;
}
var pageSize = 10;
var pageNumber = (page ?? 1);
var onePage = cargos.ToPagedList(pageNumber, pageSize);
return PartialView("ListaCargosParcial", ViewBag.OnePage = onePage);
}
In my PartialView i put this code to show the pagination
<div class="pagination-right">
<div class="span12">
<%: Html.PagedListPager((IPagedList)ViewBag.OnePage, page => Url.Action("CargosPorProyecto", new { page = page }), new PagedListRenderOptions { LinkToFirstPageFormat = "<< Primera", LinkToPreviousPageFormat = "< Anterior", LinkToNextPageFormat = "Siguiente >", LinkToLastPageFormat = "Última >>" })%>
</div>
</div>
And when i load the page that contains the partialview everything looks good, but when i click in Next ("Siguiente") doesn't load in my partial view.
I hope I explained clearly and thanks for the time.
Regards
You could use AJAX if you want to stay on the same page. For example if you are using jQuery you could subscribe to the click event of the pagination links and then trigger an AJAX request to the corresponding controller action and refresh the partial with the results returned:
$(function() {
$('.pagination-right a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
// refresh the contents of some container div for the partial
// make sure you use the correct selector here
$('#some_container_for_the_partial').html(result);
}
});
// cancel the default action which is a redirect
return false;
});
});

Resources