Silverstripe Sessions or URL Parameters - session

I'm trying to figure out how to pass a value from my .ss page to my controller for a custom search filter that I've built. The idea is you click on this image or a form button and then the page will set a session variable and refresh itself. Upon page load the page loads different information depending on what it reads in the session variable. I can accomplish the same thing with URL Parameters but there are no examples online that I could find that would show me how to do this.
Basically I have this as my php:
class ArticleHolder_Controller extends Page_Controller {
public function ValidateType(){
if(isset($_SESSION['mySearchTag']) && !empty($_SESSION['mySearchTag'])) {
$tag = $_SESSION['mySearchTag'];
}
else{
$tag='News';
}
$filter = $this::get()->filter('Filters:PartialMatch', $tag)->First();
if ($filter == NULL){
return NULL;
}
else{
$_SESSION['mySearchTag']=$tag;
return $this->PaginatedPages();
}
}
public function PaginatedPages(){
$paginatedItems = new PaginatedList($this->filterArticles($_SESSION['mySearchTag']), $this->request);
$paginatedItems->setPageLength(3);
return $paginatedItems;
}
public function filterArticles($tag){
return ArticlePage::get()->filter('category:PartialMatch', $tag)->sort('Date DESC');
}
}
my .ss looks like this:
<% if ValidateType() %>
<ul>
<% loop $PaginatedPages %>
<li>
<div class="article">
<h2>$Title</h2>
<h3>$Date</h3>
<img class="indent" src="$Photo.link" alt="image"/>
<p class="indent">$Teaser</p>
</div>
</li>
<% end_loop %>
</ul>
<% include Pagination %>
<% else %>
<p>SORRY NO RESULTS WERE FOUND</p>
<% end_if %>
This code works as is. What I cannot figure out how to now add a clickable button on .ss page that will reload the page and set a session variable value.
If I can achieve this with url parameters then that can work too, I just need to know how to set them in the .ss page and how to retrieve them in the php.

Create a SetFilter function that will take the URL parameter ID and set it to your session variable:
public function SetFilter() {
if($this->request->param('ID')) {
$_SESSION['mySearchTag'] = $this->request->param('ID');
}
return array();
}
Make sure your SetFilter function is added to the $allowed_actions of your controller:
static $allowed_actions = array (
'SetFilter'
);
This function is called by your page link followed by /SetFilter/[your-filter].
In your template you would create a link to create this filter like so:
Filter articles by example

Related

Send parameter from Spring MVC controller to jsp code

I'm trying to send the variable average review from controller to view and show a number of stars equal with average review.
The problem is that I don't know how to loop through received variable and java code doesn't recognize that variable. I tried with a foreach from JSTL, but there is no list of objects; I want a classic for loop.
Here is my controller:
#RequestMapping(value = "/viewDetails", method = RequestMethod.GET)
public ModelAndView viewProductDetails(HttpServletRequest request) {
int productID = Integer.parseInt(request.getParameter("id"));
// irrelevant code goes here
double averageReview= reviewDAO.getAverageReview(productID);
modelAndView.addObject("averageReview",averageReview);
return modelAndView;
}
This is my view page, where I tried to loop:
<p>
<c:set var = "averageReview" scope = "session" value ="${averageReview}"/>
<% for(int i=0;i< ${averageReview}; i++){ %>
<span class="glyphicon glyphicon-star"></span>
<% } %>
</p>
How about this?
<c:forEach var = "i" begin = "0" end = "${averageReview}">
<span class="glyphicon glyphicon-star"></span>
</c:forEach>

How to get image url in .ascx?

I have an image field in Sitecore from which I need its url. In code behind I have one item:
Item contactSlide = itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact");
In the .ascx it looks like this:
<div class="contact-section grid-padding-big" style="background-image: url(img/bg.jpg)">
I need to replace img/bg.jpg with the url of the image field of the item.
In repeaters I normally have a method in the code behind for this:
public string GetImageUrl(Item item)
{
Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)item.Fields["Bild"]);
if (imgField.MediaItem != null)
{
string mediaUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
return mediaUrl;
}
return "";
}
And in the .ascx I call it like this:
<div style="background-image:url(<%# GetImageUrl((Sitecore.Data.Items.Item) Container.DataItem) %>)"></div>
This works when using this method while in repeaters. But now I have a single item. How can I pass the item to the method to get its image url? Or is there another way to do this?
You can use code in a .ascx within <%= and %>, so you could simply do this:
<div style="background-image:url(<%= GetImageUrl(itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact")) %>)"></div>
You can also define a method in your code behind to directly get the url from the item you have already resolved:
public string GetBackgroundImageUrl()
{
Item contactSlide = itemHelper.GetItemByPath("/sitecore/content/AMM/Resources/Slides/Slide Contact");
return this.GetImageUrl(contactSlide);
}
And call this in the .ascx:
<div style="background-image:url(<%= GetBackgroundImageUrl() %>)"></div>

MVC:replacing HTML.ActionLink with ahref

Earlier I had ActionLink
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId,fleetId=Model.SelectedFleet.ID}) %>
on my page..and it is working fine. But now my requirement is it must check if some there is some data in FooEntity then it redirect to another view otherwise it should display an alert message..
so i changed ActionLink to ahref and thinking to use $.ajax call with it..but my action AddRace is written accordingly ActionLink. but now i'm using ahref so i want to make ajaxcall which will return some boolean and based on that i'll redirect or show alert. I need to re-write AddRace Action. I'm pretty new to MVC so confuse in changing my AddRace action.
ahref:
<a href="#" onclick='checkFleetAddedandScroing()'>Add Race</a>
Action is:
public ActionResult AddRace(Guid eventId, Guid fleetId)
{
try
{
var model = new RaceModel { EventID = eventId, FleetID = fleetId, IsAddPHRFBFactors = IsAddPhrfbFactors(eventId, fleetId) };
SetFleetsInViewBagForAddRace(eventId);
return View(model);
}
catch (Exception ex)
{
throw;
}
}
Please suggest me how to do it....
You need to use the same parameters.
<a href="#" onclick='checkFleetAddedandScroing("<%= Url.Action("AddRace",
new {eventId = Model.EventId,fleetId=Model.SelectedFleet.ID} %>")'>Add Race</a>
EDIT:
You don't even need to do an a tag.
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId,fleetId=Model.SelectedFleet.ID},
new {onclick="return myFunction()"}) %>
<script type="text/javascript">
function myFunction() {
return confirm("Click no to cancel the navigation, otherwise click yes");
}
</script>
Then you would do your ajax call in the javascript function and return false when you want to cancel redirect.

SilverStripe get half of image width/height

how can I get calculate with image height and width? I am trying to center an image like described in the first answer:
How to make an image center (vertically & horizontally) inside a bigger div
That's what I have tried so far:
<% control ProfileImage %>
<% if getOrientation = 1 %>
<img src="$URL" style="margin-left: -{$Width/2)}px" class="portrait"/>
<% else_if getOrientation = 2 %>
<img src="$URL" class="landscape"/>
<% end_if %>
<% end_control %>
The output of the decisive line is:
<img src="/assets/Uploads/picture.jpg" style="margin-left: -{154/2)}px" class="portrait"/>
Then I tried to write an own function:
class Profile extends Page{
//...
function GetHalfWidth(){
return ($this->ProfileImage->Width)/2;
}
//...
}
But I get the following error when I try to view the page in the frontend:
[Notice] Trying to get property of non-object
To get at the width of your image in the model you can change your function to read:
function GetHalfWidth() {
$width = $this->obj('ProfileImage')->Width;
return $width / 2;
}
However, if you are trying to reference that method form within the control loop of ProfileImage you'll need to 'jump out' and use $Top.GetHalfWidth
I would think a better way to handle it would be to define it as a method of your ProfileImage, if ProfileImage was subclassed from Image...
In Profile.php
<?php
class Profile extends Page {
...
public static $has_one = array(
'ProfileImage' => 'Profile_Image'
);
...
}
class Profile_Controller extends Page_Controller {
...
}
class Profile_Image extends Image {
function GetHalfWidth() {
$width = $this->Width;
return $width / 2;
}
}

How can I get access to a variable in a View which was created in a Controller?

How can I get access to a variable in a View which was created in a Controller?
Either put the variable into the Model that you are using for your View
Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
and
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
although hopefully you'll be using Razor :)
You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.
You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.
In your controller:
ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;
In your view:
<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Resources