Add IF statement to JSP - html

I am trying to add an if statement to following code, but it keeps throwing errors. What am I doing wrong?
<%
int countOnRows = 0;
int i;
countOnRows= Integer.parseInt(formFields.getValue("broughtBack"));
if (countOnRows = 0) {
<h2>No data available - check back later </h2>
}
for( i=1; i<=countOnRows; i++ )
{ %>
<div class="a_report">
<h2>Dealer Sales Report</h2>
<h3>Sales Results as of July 2014 - <%=formFields.getValue("dealerName"+i)%>, Dealer <span class="dlr_info"># <%=formFields.getValue("dealerNo"+i)%></span></h3>
<div class="body_copy"><span class="print">[ print this report ]</span>
:
: table with table data in report here
:
<% } %>
</div>

It is not Java code:
if (countOnRows = 0) {
<h2>No data available - check back later </h2>
}
change it into:
if (countOnRows == 0) {
%> <h2>No data available - check back later </h2> <%
}
I also changed if (countOnRows = 0) into if (countOnRows == 0)
You should read about using JSTL and EL, it's better than using Java code inside JSP pages.

Related

if else statement is not being treated as code inside #foreach - 2sxc v11 DNN 9.8

I'm currently learning 2sxc and am building a directory app as my initial project.
I'm trying to use the following code in a list view to change the way an item is displayed based on the Boolean "UpgradedListing"
#foreach(var listing in AsList(Data)) {
<div #Edit.TagToolbar(listing)>
if(listing.UpgradedListing == 'true'){
<strong>#listing.ListingName</strong<br/>
<a href='mailto:#listing.Email'>#listing.Email</a>
<hr/>
} else {
#listing.ListingName<br/>
<a href='mailto:#listing.Email'>#listing.Email</a>
<hr/>
}
</div>
}
the resulting output looks like this:
if(listing.UpgradedListing == 'true'){ Techmedics Ltd office#techmedics.co.nz
} else { Techmedics Ltd
office#techmedics.co.nz
}
if(listing.UpgradedListing == 'true'){ Solutions Online NZ Ltd enquiries#solutions-online.co.nz
} else { Solutions Online NZ Ltd
enquiries#solutions-online.co.nz
}
in other words the if else isn't being seen as code.
Can any one explain why this is?
You just need an # symbol in front of the first if, so
#if(listing.UpgradedListing == 'true'){
Also you've got a typo, your closing strong tag is missing its right >
And 'true' is not the same as true (boolean). 2sxc will know and return a boolean for .UpgradedListing (if you have it set AS a boolean field... if you have it as a string, then you need == "true"
and you can also move the stuff that doesn't change outside the if/else to make it more readable...
#foreach (var listing in AsList(Data))
{
// here you can still write C# without an #
// because it's still in code-mode
var x = 7; // this still works here
<div #Edit.TagToolbar(listing)>
<!-- here Razor switches to HTML because we had a Tag around it -->
<!-- so we need to really introduce the code-mode again -->
#if (listing.UpgradedListing)
{
<strong>#listing.ListingName</strong><br />
}
else
{
#listing.ListingName<br />
}
<a href='mailto:#listing.Email'>#listing.Email</a>
<hr />
</div>
}

Unable to add row dynamically in loop inside table in Razor

I want to display 3 Cells in a row and then create row <tr> dynamically for remaining cells. When I searched for this logic, I am getting same answer from multiple articles about using modulo and it seems working for evryone but I'm not getting desired output. What am I missing here?
Code:
<table>
#for (var i = 0; i < deliveryProvider.DeliveryTagInfo.DeliveryProviderTagList.Count; i++)
{
var deliveryTag = deliveryProvider.DeliveryTagInfo.DeliveryProviderTagList[i];
if ((i%3) == 0) //Create new row for 4th item
{
#:<tr>
}
<td>
<div class="input-element checkbox">
#Html.CheckBoxFor(x => x.DeliveryProviderList[j].DeliveryTagInfo.IsDeliveryTagSelectedList[i], new
{
name = deliveryTag,
id = deliveryTag
})
<label for="#deliveryTag">
<span></span>#deliveryTag</label>
</div>
</td>
if ((i%3) == 0)
{
#:</tr>
}
}
</table>
Output:
Expected Output:
Test1
ALCOHOL SPILLABLE COLD_BAG
HOT_BAG HEAVY SIZE
Test2
abc pqr xyz
Some of the problem code is in your closing tag.
if ((i%3) == 0)
{
#:</tr>
}
On your first iteration, i%3 is == 0, so you put a closing tag on your first statement. Essentially you are only creating <tr> tags on every third one.
Here is an example of how you could remedy this:
var listCount = 11;
for (var i = 0; i < listCount; i++)
{
if (i%3 == 0)
{
#:<tr>
}
//Add Checkboxes
//Closing Tag
if (((i+1) % 3 == 0 )|| i == listCount - 1)
{
#:</tr>
}
}
Closing tag Explained...
For the first condition of the closing tag:
(i+1) % 3 == 0 )
Since the item has been added, we check to see if it is the third one- by using i+1, we will know how many items
are in the row and we can close it if it is.
For the second condition:
i == listCount - 1
We also need to account for if it is the last item. If the list only has 2 items for example, we still need to close the row.

How to Provide Breadcrumbs for Page with dynamic Parameters?

I found a Grails framework for generating Breadcrumbs here. It does generate breadcrumbs based on a static definition in a breadcrumbs.xml file where it defines the hierarchies of the crumbs:
<map>
<nav id="homeCrumb" matchController="samplePages" matchAction="homeBreadCrumbPage">
<!-- levels navigation -->
<nav id="itemsLevel1Crumb" matchController="samplePages" matchAction="level1BreadCrumbPage">
<nav id="itemsLevel2Crumb" matchController="samplePages" matchAction="level2BreadCrumbPage">
<nav id="itemsLevel3Crumb" matchController="samplePages" matchAction="level3BreadCrumbPage">
<nav id="showItemCrumb" matchController="samplePages" matchAction="itemDetailsBreadCrumbPage"/>
</nav>
</nav>
</nav>
<nav id="simple1Crumb" matchController="samplePages" matchAction="simpleBreadCrumb"/>
<nav id="simple2Crumb" matchController="samplePages" matchAction="simpleBreadCrumbWithAttr"/>
<!-- levels navigation -->
</nav>
</map>
This file is evaluated and printed by a taglib:
class BreadCrumbTagLib {
static def log = LogFactory.getLog("grails.app.breadCrumbTag")
def breadCrumb = { attrs , body ->
def manager = BreadCrumbManager.getInstance()
def uri = request.getRequestURI()
def context = request.getContextPath()
def controller = params.controller
def action = params.action
def attrTitle = attrs.title
def attrLink = attrs.link
// if controller and action are missing from params try to get them from request url
if (!controller && !action && uri && context && uri.indexOf(context) != -1) {
def uriParams = uri.substring(uri.indexOf(context) + (context.length() + 1), uri.length())
def uriArray = uriParams.split('/')
if (uriArray.size() >= 2 ) {
controller = uriArray[0]
action = uriArray[1]
}
}
def crumbs = manager.getBreadCrumbs(controller, action)
if (crumbs) {
out << '<div class="breadcrumb"><ul>'
def size = crumbs.size()
crumbs.eachWithIndex { crumb, index ->
out << '<li>'
// override title and link of breadcrumb on current page (i.e. last bread crumb in hierarchy)
// if name, link attributes are supplied
if (index == size - 1) {
if (attrTitle)
crumb.title = attrTitle
if (attrLink)
crumb.link = attrLink
}
// set title to undefined if not found, associated
// renderer if present can overwrite it
if (!crumb.title)
crumb.title = "undefined"
if (crumb.title && crumb.title.size() > 40)
crumb.title = crumb.title.substring(0, 40) + "..."
if (crumb.viewController && crumb.viewAction) {
def content = g.include(controller:crumb.viewController, action:crumb.viewAction, breadcrumb:crumb, params:params)
out << content
} else if (crumb.viewTemplate) {
def content = g.include(view:crumb.viewTemplate, breadcrumb:crumb, params: params)
out << content
} else if (crumb.linkToController && crumb.linkToAction && (size - 1 > index)){
out << "${crumb.title}"
// if crumb has a link and its not the last vread crumb then show link else
// just show the text
} else if (crumb.link && (size - 1 > index)){
out << "${crumb.title}"
} else {
out << "${crumb.title}"
}
out << "</li>"
// do not print for last bread crumb
if (size - 1 > index)
out << "<li>ยป</li>"
}
out << "</ul></div>"
}
}
}
Problem: When I have a structure where I need some params which are not fix.
Example: I am in the third level of navigation lets say
A1 / A2 / A3
In my case A2 should open a page like user/show/1234 where 1234 is the id of the user to show. The problem is that I cannot add 1234 hard coded in the breadcrumbs.xml file because this id changes depending on which user you want to show.
How can I handle this when an intermediate breadcrumbs link needs dynamic parameters?
After thinking about it some more, I realized it may be better not to use the HttpSession. If you use a session-scoped service instead it will be easier to unit test the breadcrumb code.
First, create a session-scoped service to maintain the user's navigation history.
class NavigationHistoryService {
static transactional = false
static scope = "session"
def history = [:]
public List push(String controller, String action, Map params) {
def crumb = [
action: action,
params: params]
history.controller = crumb
return history
}
In your controllers inject the service and use it to keep track of where the user has been. Then add the history as part of what's returned by the action's model:
class CompanyController {
def navigationHistoryService
def show() {
navigationHistoryService.push('company', 'show', params)
...
[crumbs: navigationHistoryService.history]
}
}
Finally, use the history in your GSP to render the crumbs.
<ol class="breadcrumb">
<li><g:link controller="company" action="${crumbs.company.action}" params="${crumbs.company.params}">SOMETHING</a></li>
</ol>
It looks like your breadcrumbs are in the format CONTROLLER/ACTION/ID. If that's so, the information you need is already available in your GSP via the webRequest property. Here's an example using Twitter Bootstrap breadcrumbs:
<ol class="breadcrumb">
<li>${webRequest.controllerName}</li>
<li>${webRequest.actionName}</li>
<li class="active">${webRequest.id}</li>
</ol>
You'd still have to set up the hrefs to something meaningful. A more robust approach would be something like this...
<g:set var="crumbs" value="${[webRequest.controllerName, webRequest.actionName, webRequest.id].findAll { it != null }}.collect { [label: it, active: false] }" />
<% crumbs.last().active = true %>
<ol class="breadcrumb">
<g:each in="${crumbs}">
<li class="${it.active ? 'active' : ''}">${it.label}</li>
</g:each>
</ol>
Embedding Groovy code into GSP via the <% %> tags is not recommended, but something like this could be done in a TagLib. This approach can handle breadcrumbs of 1-3 parts in length. It adjusts according to the current URI.
use simple by blade view
<ul class="breadcrumb" style="padding-right: 20px">
<li> <i class="fa fa-home"></i> <a class="active" href="{{url('/')}}">Home</a>
{{--<i class="fa fa-angle-right"></i>--}}
</li> <?php $link = url('/') ; ?>
#for($i = 1; $i <= count(Request::segments()); $i++)
<li>
#if($i < count(Request::segments()) & $i > 0)
<?php $link .= "/" . Request::segment($i); ?>
<a class="active" href="<?= $link ?>">{{Request::segment($i)}}</a>
{{--{!!'<i class="fa fa-angle-right"></i>'!!}--}}
#else {{Request::segment($i)}}
#endif
</li>
#endfor
</ul>

Problems with getting an image to show in a paged list

I have the following code, and it displays the listed text and the pagination at the bottom all fine. But when I try to get the images from the child page into the list it errors for me. Any ideas why?
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "SiteLayout.cshtml";
}
<div role="main" id="main">
<div id="blogPageFeatures">
<!-- loop through all of the child pages (blog posts) and grab data to output as a summary -->
#{
var pageSize =3;
var page =1;int.TryParse(Request.QueryString["page"],out page);
var items =Model.Content.Children().Where(x => x.IsDocumentType("BlogArticle")).OrderByDescending(x => x.CreateDate);
var totalPages =(int)Math.Ceiling((double)items.Count()/(double)pageSize);
if(page > totalPages)
{
page = totalPages;
}
else if(page <1)
{
page =1;
}
}
#foreach(var item in items.Skip((page -1)* pageSize).Take(pageSize))
{
<a href="#item.Url">
<!-- The next image line is where it errors -->
<img src="#Umbraco.Media(item.Children.blogArticleImage).Url">
<h2>#item.Name</h2>
<p class="blogTileDate">#item.CreateDate.ToString("dd/MM/yy")</p>
</a>
}
<div class="clearfix"></div>
<!-- Pagination START -->
#if(totalPages >1)
{
<div class="pagination">
<ul>
#if(page >1)
{
<li>Prev</li>
}
#for(int p =1; p < totalPages +1; p++)
{
var active =(p == page)?" class=\"active\"":string.Empty;
<li#(Html.Raw(active))>
#p
</li>
}
#if(page <totalPages)
{
<li>Next</li>
}
</ul>
</div>
}
<!-- Pagination END -->
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
You are getting Model.Content.Children, which is a strongly typed collection of IPublishedContent objects. You are then calling item.Children.blogArticlImage, which is not going to work, as you're trying to get the a property on the children of the item, not a property of the item itself. You're also trying to use dynamic syntax, which won't work on the strongly typed objects. Try changing your image code to:
<img src="#Umbraco.TypedMedia(item.GetPropertyValue<int>("blogArticleImage")).Url">
That should do te trick, one thing to note is that if an item doesn't have an image set, or the image that has been selected has been deleted, it'll throw an error. A more robust approach would be something like this:
var imageSrc = "ADD DEFAULT IMAGE PATH HERE";
var media = Umbraco.TypedMedia(item.GetPropertyValue<int>("blogArticleImage"));
if (media != null && !string.IsNullOrEmpty(media.Url))
{
imageSrc = media.Url;
}
<mig src="#imageSrc">

For loop over ResultSet#getFetchSize() in JSP doesn't produce any HTML

I have the following code:
<%
for (int i = 0; i < rs.getFetchSize(); i++) {
System.out.print("test");
//blah
%>
<div id="Test<%= out.print(i) %>">
<div class="<%= oddOrEven(i)%>Header">
<div class="<%= oddOrEven(i)%>A">Test<% out.print(i);%></div>
<div class="<%= oddOrEven(i)%>B">
//Stuff here
Odd or Even simply responds with the word odd or even based on the number i passed to it, that should make my css style alternate between grey colors.
When I compile the page it works, but this part is totally omitted and doesn't appear in the source. Can someone help me get this working?
The ResultSet#getFetchSize() doesn't return the amount of returned records as you seemed to expect. It just returns the configured fetch size. It may for instance just return 0 depending on the JDBC driver configuration and semantics.
Just use ResultSet#next() the usual way to move the cursor to the next row.
for (int i = 0; rs.next(); i++) {
That said, writing Java code in a JSP file is officially discouraged since a decade. I'd suggest to work on that part as well.
How about this:
<%
for(int i = 0; i < rs.getFetchSize(); i++)
{
%>
<div id="Test<%= i%>">
<div class="<%= oddOrEven(i)%>Header">
<div class="oddOrEven(i)A">Test<%= i%></div>
<%
}
%>
You are missing a last curly brace which will complete the for loop
Also you do not need to provide ... out.println() ... <%= %> will do that for you