I am working on revamping a sites' paging system, and I have run into something simple I can't seem to solve. I am trying to show pages (1 2 3 4 5) at a time, and when the user gets to page 5, the list changes to something like (4 5 6 7 8). How could I do this using a cfloop? Here is a sample of my code:
<cfloop from="1" to="#totalPages#" index="i">
<cfoutput><a class="paging" href="?start=#(i*25)-24#">#i#</a></cfoutput>
</cfloop>
At the moment it shows pages 1 - 54 all at once. Any tips?
Heres my code
<cfset curPage = Int(start / 25) + 1>
<cfloop from="1" to="#totalPages#" index="i">
<cfif i is curPage>
<div class="page current">#i#</div>
<cfelse>
<cfif totalPages lte 5 or i is 1 or i is totalPages or (i gt curPage - 3 and i lt curPage + 3) or ((curPage is 1 or curPage is 2) and i lt 6) >
<div class="page">#i#</div>
<cfelse>
<cfif i is 2 or i is totalPages - 1>
<div class="more">...</div>
</cfif>
</cfif>
</cfif>
</cfloop>
What this code does is it shows the first 5 pages, then an ellipsis, then the last page. As you page through it, it will always show the link to the first and last page, plus 2 page before and after the current page.
Screenshots: Page 1 and page 10
You should be able to easily modify this to work exactly how you want it. (I happen to not like when all of the links change at once the way you described)
There is a great open source pagination library that will solve your problem. I can't say enough good things about it because I wrote it. Shameless, I know. Anyways:
http://www.dopefly.com/projects/pagination/
Check out the docs, they are very complete and helpful. In your code, printing the page numbers are as simple as calling #pagination.getRenderedHTML()#. It is pretty customizable so that you can change the numbers that are printed and you can style the output however you like.
How about:
<cfloop from="#url.startpage#" to="#url.startpage+4#" index="i">
<cfif i LE totalpages>
<cfoutput><a class="paging" href="?start=#(i*25)-24#">#i#</a></cfoutput>
</cfif>
</cfloop>
Of course you would need to add "startpage" to your url and manipulate it appropriately. So your first link would be startpage=1 but your last would be startpage=4 (if I understand your question correctly).
Related
I' am finding it difficult to understand this. How can I limit the results to 50 only. Let say if in the directory I have 1000 files, how can I limit it so that only 50 files are looped over.
<cfdirectory action="list" directory="#ExpandPath('/downloaded/')#" name="listRoot" filter="*.xml" recurse="false" sort="datelastmodified asc">
<cfoutput>
<cfloop query="listRoot" from="1" to="50" index="i">
....
</cfloop>
</cfoutput>
When I run the above code I get the following error message
Attribute validation error for tag CFLOOP.
If you review the complete error message, it contains the answer (emphasis mine):
It has an invalid attribute combination: from,index,query,to. Possible combinations are:
Required attributes: 'query'. Optional attributes: 'endrow,startrow'.
...
Required attributes: 'from,index,to'. Optional attributes: 'step'.
The code is attempting to mix two different types of loops: query loop and from/to loop. That is not a valid combination. You can either use a query loop OR a from/to loop, but not both.
Having said that, since the goal is to display the output, there is really no need for the cfloop. Just use cfoutput with the "startRow" and "maxRows" attributes:
<cfoutput query="listRoot" startRow="1" maxRows="50">
#name#<br>
</cfoutput>
As mentioned in the other answer, recent versions of CF also support for ...in loops:
<cfscript>
for (row in listRoot) {
writeOutput("<br>Debug: name value = "& row.name );
}
</cfscript>
You can access specific rows in a query with:
query[columnName][rowIndex]
In order to do a from to loop instead of an each loop, go:
<cfoutput>
<cfloop from="1" to="50" index="i">
#listRoot["name"][i]#<br>
</cfloop>
</cfoutput>
I have a query as below which
<cfquery name="qryGetXXX" datasource="#sDataSource#">
SELECT COUNT(*) AS TotalCount,Quality.Qualitydesc
FROM QualityCheck INNER JOIN Quality
ON QualityCheck.QualityID = Quality.qualityID
WHERE DATEDIFF(d,DueDate,GETDATE()) >= 90
GROUP BY quality.qualityDesc
</cfquery>
will result in
1) *total count* 21 *QualityDesc* IO
2) *total count* 1 *QualityDesc* Max
3) *total count* 1 *QualityDesc* Min
4) *total count* 1 *QualityDesc* Other
5) *total count* 3 *QualityDesc* Reg
In order to get the first row I am using,
<cfif #qryGetXXX.RecordCount# gt 0 >
<cfloop query="qryGetXXX" startrow="1" endrow="1">
<cfset XXXTimeTotal =#qryGetXXX.TotalCount# >
</cfloop>
<cfelse>
<cfset XXTotal = 0 >
</cfif>
which is checking for the first the recordcount of the whole query but is there any way I can check whether the first row (i.e. startrow 1 and endrow 1) is has a value and then if the startrow 2 and endrow 2 has a value and so on? Can I put the results in an array and will that be easier?
Frank,
You are correct, i am new to coldfusion, hence all the confusion.The query provides me with the results i.e i have the result set as explained above, however i cannot figure out a way to check every row individually. For example i have to check if there are results for the first row and if it does i have to pass that value to my output, and if doesnot i have to put in no value was entered or '0'. I need to do this for the five rows and there will always only be 5 rows of results, which is why i was using start and endrow, however start and endrow donot allow me the flexibility to check for empty row values. In essence i would like to check the row as something like below.
<!--- check the first row of resuslt i.e. Max values ---!>
<cfif startrow1.endrow1 gt 0 >
<cfset nIOCount =#qryGetXXX.TotalCount# >
<cfelse>
<cfset nIOCount = '0'>
</cfif>
<!--- then check the second row resuslts Max ---!>
<cfif startrow2.endrow2 gt 0 >
<cfset nMaxCount =#qryGetXXX.TotalCount# >
<cfelse>
<cfset nMaxCount = '0'>
</cfif>
<!---Output the values---!>
Totals
<tr>
<th>IO</th>
<td>#nIoCount#</td>
</tr>
<tr>
<th>Max </th>
<td>#nMaxCount#</td>
</tr>
<tr>
I know i cannot reference startrow and endrow as i want, so i am looking for a way to reference each row individually in the result set some other way. Any suggestions?
thanks
That query/code is rough (I rendered it to something I could work with).
Your query: (if yours works just leave it as is (I'm making two assumptions below)).
<cfquery name="test" datasource="#sdatasource#">
select count(a.*) as totalcount, a.qualitydesc
from quality a, qualitycheck b
where a.qualityid = b.qualityid
and datediff(d,a.duedate,getdate()) >= 90
group by a.qualitydesc
</cfquery>
Then do your check if and sets like this: (instead of an array I did a struct (making more assumptions as well)).
<cfset totals = structnew()>
<cfif test.recordcount>
<cfoutput query="test">
<cfif test.totalcount neq "">
<cfset StructInsert( totals, test.QualityDesc, test.totalcount )>
<cfelse>
<cfset xxtotal = 0>
</cfif>
</cfoutput>
</cfif>
In fact, you can skip that nested if statement and for the xxtotal and do something else out of the loop leaving you with tighter code that looks like this:
<cfset totals = structnew()>
<cfif test.recordcount>
<cfoutput query="test">
<cfset StructInsert( totals, test.QualityDesc, test.totalcount )>
</cfoutput>
</cfif>
So if these are your targets:
1) totalcount 21 QualityDesc IO
2) totalcount 1 QualityDesc Max
3) totalcount 1 QualityDesc Min
4) totalcount 1 QualityDesc Other
5) totalcount 3 QualityDesc Reg
Then your looped values will look like this and any missing values or whatever will be bypassed (again you will need to do some checking down stream)...
totals.IO = 21
totals.Max = 1
totals.Min = 1
totals.Other = 1
totals.Reg = 3
Let me know if this helps and makes sense.
(Summary from comments...)
If you mean some of the descriptions, like "IO", are not included in query results at all, then that is what I suspected earlier. Since you are using an INNER join, the query will only return counts for descriptions that exist in both tables. If you want to include all descriptions, even if there is no match in "QualityCheck", you need to use an OUTER join instead. For example:
SELECT Quality.Qualitydesc
, COUNT(QualityCheck.QualityID) AS TotalCount
FROM Quality LEFT JOIN QualityCheck
ON QualityCheck.QualityID = Quality.qualityID
AND DATEDIFF(d,DueDate,GETDATE()) >= 90
GROUP BY quality.qualityDesc
Though as I mentioned on another thread, how you construct the filter can negatively impact the query's performance. See What makes a SQL statement sargable? for details and alternatives.
Side note, while you provided a lot of detail here, you omitted the most important part: .. the actual goal ;-) You will get faster and more accurate responses if you clearly summarize what you are trying to do first, then include the code.
The Golden Rule: Imagine You're Trying To Answer The Question
The XY Problem
How to Ask
I have a column(cse_dept) where it has integers , I would only like to show the columns where it equals 12 or 39.
Is there a way to do this?
<cfif (#GetCurrentUser.cse_dept# eq '12'39') >
<h1>test</h1>
</cfif>
It does not show me a error it just doesn't work the way I would like it.
You can use listFind. If the value of GetCurrentUser.cse_dept is 12 or 39 listFind will return the a number greater than 0
<cfif listFind('12,39', GetCurrentUser.cse_dept)>
<h1>test</h1>
</cfif>
listFind is case sensitive in case you were searching for something other than numbers. If you need a case-insensitve search you can use listFindNoCase
Alternatively you could check for each value separately
<cfif GetCurrentUser.cse_dept EQ 12 OR GetCurrentUser.cse_dept EQ 39>
<h1>test</h1>
</cfif>
If you want to check if GetCurrentUser.cse_dept is 12 or 39 for any result in your query you can do
<cfif listFind(valueList(getCurrentUser), 12) OR listFind(valueList(getCurrentUser), 39)>
<h1>test</h1>
</cfif>
There are a few ways to do this:
Method 1 - Query of Queries
<cfquery name="q1" dbtype="query">
select count(*) records
from GetCurrentUser
where cse_dept in (12,39)
</cfquery>
<cfif q1.records gt 0>
do something
</cfif>
Method 2 - List Functions
<cfif ListFind(ValueList(GetCurrentUser.cse_dept), 12)
+
ListFind(ValueList(GetCurrentUser.cse_dept), 39) gt 0>
do something
</cfif>
Method 3 - Array Functions
<cfif ArrayFind(GetCurrentUser['cse_dept'], 12)
+
ArrayFind(GetCurrentUser['cse_dept'], 39) gt 0>
do something
</cfif>
Method 2 is very similar to Matt's second suggstion. One difference is the use of a ValueList function. The second is that instead of using "or", I added the function results together. The results are the same.
Method 3 is probably the fastest. However, depending on where those numbers 12 and 39 come from, Method 1 might be a better approach.
I'm in Coldfusion 8. I have a table that is produced by a loop. Very complex code but I put some of it here:
<cfloop array = #qrep.getColumnList()# index = "col">
<cfset l = l + 1>
<cfif l EQ tindx - 1>
<cfset prevcol= col>
</cfif>
<cfif linefold GT 0>
<cfset lmod = i%linefold>
<cfelse>
<cfset lmod = 1>
</cfif>
<!--- printing detail --->
<cfif l LE m AND repdetail NEQ 'n'>
<td class = "repsubthead"> Subtotal:
<b>#qrep[col][currentrow]#</b></td>
</cfif>
<!--- printing totals only; row labels --->
<cfif repdetail EQ 'n' AND l EQ tindx >
<cfset frowarr[footrow] = qrep[col][currentrow]>
<cfset footrow_1 = footrow - 1>
<cfif footrow EQ 1>
<td style = "font-size: 13px" > #qrep[col][currentrow]#</td>
<cfelseif frowarr[footrow] NEQ frowarr[footrow_1] >
<td style = "font-size: 13px;"> #qrep[col]currentrow]#</td>
<cfelse>
<cfset testrow = footrow>
<td class = "repsubthead" style = "padding-top: 10px"> Total #qrep[prevcol] currentrow]# </td>
</cfif>
.... lots more before we get to end of loop
This part of the code prints out a row label for each row. Further in the program there is a similar loop to print out the value for the row. Everything is working fine except for one problem I can't trace. An extra row is being inserted in one spot, with no data in it. Part of the table is here:
State: CT
AVS 25.00
COMB 15.00
Email2010 15.00
REF 75.00
STRLST01 22.00
extra row inserted here, height much smaller than other rows
STRLST04 50.00
Total CT 202.00
I have copied this table to a Libre Office document and zoomed in on the bad row. It is definitely there, and it contains a blinking item that looks like this: '
I cannot delete this item from the row in Libre Office, although I am able to delete the entire row. The blinking thing disappears when I put my cursor in another row.
I have checked both STRLST01 and STRLST04 in my MySQL database, and they seem fine, with no anomalies. I cannot find anywhere in my code where I would be inserting an extra row (altho admittedly the code is very complicated).
Has anyone seen something like this? Does anyone have a clue what might be causing this?
Just a shot in the dark here... but try sanitizing your table content. For example:
#htmlEditFormat(qrep[col][currentrow])#
This would be to rule out that the TR in "STRLST01" isn't getting processed as <TR>. I've seen dynamic tables like this one go haywire because the content gets interpreted as HTML.
MC
What is the generated HTML? Looking at the actual generated output rather than the rendered output could help you find if it's bad data being dumped into another row or if it's a bug in your HTML generation routine.
If it's an odd special character in your data, the HTMLEditFormat() or XMLFormat() functions should find it and deal with it. Or at least make it easier to troubleshoot.
It's a bit of tricky question, however, my page for most rated bands displays the band logos in order of how high they have been rated. My only problem is i want to count through the records by using a cfloop from 1 to 10 and because it is split in to two columns, have one counting 1 through to 9 and the other 2 through to 10, each of them with steps of two.
Can anybody help me with this? If i've confused just mention it and ill try to clarify exactly what i mean.
<DIV class="community_middle">
<cfoutput query="top10MostRated">
<cfloop from="2" to="10" index="i" step="2">
<DIV class="communityContent">
#chr(i)#
<IMG src="logo/#top10MostRated.Logo#" alt="#top10MostRated.Name#" width="100%" height="100%"></IMG>
</DIV>
<BR/>
</cfloop>
</cfoutput>
</DIV>
If you're looking to do odd/even lists separately, then you can use the currentrow property of the query combined with the modulo operator (%) to work out if the row is odd or even:
<cfloop query="topBands>
<cfif topBands.currentRow % 2 = 1>
<!--- do your odd number output here --->
</cfif>
</cfloop>
<cfloop query="topBands>
<cfif topBands.currentRow % 2 = 0>
<!--- do your even number output here --->
</cfif>
</cfloop>
I think these answers address your side-by-side part of your question but does not explain the "same image" issue. Their code is written correctly but does not explain the reason.
Your code:
<IMG src="logo/#top10MostRated.Logo#"
alt="#top10MostRated.Name#"
width="100%" height="100%"></IMG>
... would be fine if you were only inside a <cfloop query = "top10MostRated"> or <cfoutput query = "top10MostRated"> block. The reason is because inside these types of blocks CF is smart enough to know you want the data for the current row. It would be the same as:
<IMG src="logo/#top10MostRated.Logo[top10MostRated.currentRow]#"
alt="#top10MostRated.Name[top10MostRated.currentRow]#"
width="100%" height="100%" />
Because you're nesting the to/from cfloop inside a <cfoutput query = ""> block, you are getting unexpected results. Your existing code is always asking for the record provided by your outer loop. Hence you see the same image 5 times. (using any of the fine examples provided will help you get out of this) but, you can remove the query from your cfoutput and simply ask CF to show you the value for the correct row in your loop using your index (you set your index to "i") so the below would show you the image that corresponds to your loop.
<IMG src="logo/#top10MostRated.Logo[i]#"
alt="#top10MostRated.Name[i]#"
width="100%" height="100%" />
It sounds like what you'd like to get is a collection of even-numbered records and a collection of odd-numbered records. In Coldfusion 10 or Railo 4, you can use groupBy() from Underscore.cfc to split up your query result into manageable sub-sets, like so:
_ = new Underscore();// instantiate the library
groupedBands = _.groupBy(topBands, function (val, index) {
return index % 2 ? "odd" : "even";
});
This returns a struct with two elements odd and even, each containing an array of records which are odd or even. Example result:
{
odd: [{name: "Band one"}, {name: "Band three"}],
even: [{name: "Band two"}, {name: "Band four"}]
}
Splitting your results into logical sub-sets makes the code more readable:
<cfoutput>
<cfloop from="1" to="5" index="i">
<div class="left">#groupedBands.odd[i].name#</div>
<div class="right">#groupedBands.even[i].name#</div>
</cfloop>
</cfoutput>
You'll also be able to use those sub-sets in other places on your page if you need to.
Note: I wrote Underscore.cfc
Ben Nadel has a post exactly for this. Link here
A breakdown for this is
<cfloop query="top10MostRated">
<cfif top10MostRated.CurrentRow MOD 2>
<!--- Add to the "odd list" --->
<cfelse>
<!--- Add the record to the "even list" --->
</cfif>
</cfloop>
Then you'll have 2 lists oddList and evenList. Then it's just a matter of displaying them.
I'd do it a different way. The objective is to have records 1 and 2 side by side and I don't see that in #barnyr's answer.
<cfoutput>
<cfloop from="2" to="topbands.recordcount + 1" index = "i" step="2">
#topbands.fieldname[i-1]#
<cfif i lte topbands.recordcount>
#topbands.fieldname[i]# <br />
</cfif>
</cfloop>
</cfoutput>