Sitecore - Image field in parameter template - sitecore

If I have an image field in a parameter template, what are the steps involved in getting the URL of the image in c#?

#mdresser makes a valid point about what should and should not be a rendering parameter. However, I don't think that Sitecore intentionally made it difficult to use image fields in parameter templates. They simply built the parameter template functionality over the existing key-value pair rendering parameter functionality.
If the name of your image field on the rendering parameters template was BackgroundImage, you could use the following code to get the URL of the selected image:
var imageId = XmlUtil.GetAttribute("mediaid", XmlUtil.LoadXml(this.Parameters["BackgroundImage"]));
MediaItem imageItem = Sitecore.Context.Database.GetItem(imageId);
backgroundImageUrl = MediaManager.GetMediaUrl(imageItem);
If you don't already have a base class for your sublayouts that provides the Parameters property, you will need to also add this:
private NameValueCollection parameters;
public virtual NameValueCollection Parameters
{
get
{
if (this.parameters == null)
{
var parameters = this.Attributes["sc_parameters"];
this.parameters = string.IsNullOrEmpty(parameters)
? new NameValueCollection()
: WebUtil.ParseUrlParameters(parameters);
}
return this.parameters;
}
}

To achieve this you would have to look at how the sitecore image field renders the raw text value into an img tag. However, there is a reason that this doesn't work out of the box with sitecore; parameters templates are designed to define info about how a rendering or sublayout should render. E.g. You could use it to tell a list control to show a certain number of items etc. I'd advise against using rendering parameters for content as this will make content editing very cumbersome. If your aim is to have the content of a particular sublayout defined somewhere other than the page itself, put it into a sub item instead.

You can have a 2 separate functions to retrieve the value of image field in the parameter template that you gave to the sub layout .
First Step : Get the value associated with the parameter of image . Please use below function to retrieve the value .
/// <summary>
/// Returns a specific parameter value
/// Use this for Single-line, multiline text fields, linkfield, Image field etc.
/// </summary>
/// <param name="parameterName"></param>
/// <returns></returns>
public MediaItem GetValueFromRenderingParameter(string parameterName)
{
var item = !string.IsNullOrEmpty(_params[parameterName]) ? _params[parameterName] : string.Empty;
if(item == null)
{
return null ;
}
return Sitecore.Context.Database.GetItem(item);
}
Second step : Create another function where you can use the above mentioned function to retrieve the value of image field and use it appropriately. Here is the code snippet of the same :
Public string RenderImage()
{
Sitecore.Data.Fields.ImageField imageField =GetValueFromRenderingParameter("Image parameter name");
return MediaManager.GetMediaUrl(imageField.MediaItem) ;
}
Hope This Helps .

Related

Sitecore Call Check-List Data in Parameter Template

I have a sublayout assigned "Parameter Template". In the parameter templates, there are some fields such as single-text, rich-text and check-list types. There is no problem when I call the single and rich-text fields in code-behind. But, I don't know how to call the list in the check-list field.
I'd like to get only selected items' information when the sublayout is added.
Firstly read this on parameter templates
https://www.sitecore.net/learn/blogs/technical-blogs/martina-welander-sitecore-blog/posts/2013/07/improving-the-page-editor-experience-part-1-uses-for-parameters.aspx
Then it's useful to setup a base class to handle data sources and parameter templates. You could write your own base class based on this:
https://marketplace.sitecore.net/en/Modules/Sub_Layout_Parameter_Helper.aspx
When you access the parameter values from the sublayout they will be raw values and in your case pipe delimited guids.
This is how to get the value of a parameter:
var sublayout = this.Parent as Sublayout;
var parameters = sublayout.Parameters;
var collection = WebUtil.ParseUrlParameters(parameters);
string images = collection["Images"];
The variable images will contain guids - you'll have to use Getitem() on these to retrieve the actual items selected by splitting the string like this:
var selectedItems = images.split('|');
List<Item> result = new List<Item>();
foreach (var itemId in selectedItems)
{
Guid id = Guid.Empty;
if (Guid.TryParse(itemId, out id))
{
var found = db.GetItem(new ID(id));
if (found != null)
{
result.Add(found);
}
}
}
The list above will now have the selected items specified on the sublayout
The Checklist field type will only store the selected items information, I believe.
You could cast the field to a MultilistField, and then call GetItems() on it. That should give you back the list of selected items.

OpenCart pass data to children module

Basically what i'm trying to do is to pass some data from "parent" controller to the controller of its children module, for example:
header controller
$this->children = array(
'module/newslettersubscribe'
);
newslettersubscribe controller
public function index() {
// Use here data from the header controller
}
Is that even possible to do?
Here the approach is incorrect. You should edit only the slider controller and check whether there is a path variable available in the GET (query string), e.g.:
if (!empty($this->request->get['path'])) { /* ... */ }
If it is you can now extract the categories from it's value (which is e.g. 1_12_36):
if (!empty($this->request->get['path'])) {
$category_ids = explode('_', (string)$this->request->get['path']);
}
Now knowing the category IDs (or the category path) you can display the appropriate images only using whatever code you made up.

tt_address: add categorys of address to the template

Is it somehow possible to add the sub-group of a cetrain group the address is assigned to the html output?
In the template I have ###MAINGROUP### and ###GROUPLIST###. I can't use maingroup, cause it's not the case that the group I need is always the maingroup. And with the grouplist I can't say which group is the sub-group of the one group.
Anyone have an idea how I could do it?
And in addition to that I also need the value of a self created field in the tt_address table.
Edit:
I try it like #lorenz say. What I have so far:
ext_localconf.php:
<?php
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['tt_address']['extraItemMarkerHook'][]
='EXT:txnextaddresssort/class.tx_next_address_sort_addmarkers.php:tx_next_address_sort_addmarkers';
class.tx_next_address_sort_addmarkers.php:
<?php
class tx_next_address_sort_addmarkers {
function extraItemMarkerProcessor(&$markerArray, &$address, &$lConf,
&$pObj) {
$lcObj = t3lib_div::makeInstance('tslib_cObj');
$lcObj->data = $address;
$markerArray['###SORTBEREICH###'] =
$lcObj->stdWrap($address['tx_nextaddresssort_sort_bereich'],
$lConf['tx_nextaddresssort_sort_bereich.']);
}
}
Extentionkey: next_address_sort
All I get is a blank screen, but no errors in apache log
No, there is no possibility to do that.
Yet you can write a custom extension that integrates the extraItemMarkerProcessorhook in tt_address. In ext_localconf.php, add:
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['tt_address']['extraItemMarkerHook'][] ='EXT:myextension/class.tx_myextension_filename.php:tx_myextension_classname';
Then add a file class.tx_myextension_filename.php to your extension.:
class tx_myextension_classname {
public function extraItemMarkerProcessor(&$markerArray, &$address, &$lConf, &$pObj) {
$lcObj = t3lib_div::makeInstance('tslib_cObj');
$lcObj->data = $address;
$markerArray['###MYFIELD###'] = $lcObj->stdWrap($address['myfieldlikeindatabase'], $lConf['myfieldlikeindatabase.']);
return $markerArray;
}
}
This would be an example for getting a field that is in the tt_address table and adding it to the markers so they can be used in a template. It is also stdWrap enabled.
Now, instead of getting a field, you should replace $address['myfieldlikeindatabase'] with a variable that contains the information you need. To receive the data, you can use the TYPO3 database API functions ($GLOBALS['TYPO3_DB']).

Set queryable source on Rendering Parameter Template field

I have a Rendering Parameter template applied to a sublayout. It has a single Droptree field on it, and I want to set the Source of that field to a Sitecore query so I can limit the options available for that field.
Source can be:
query:./*
or
query:./ancestor-or-self::*[##templatename='MyTemplate']/
The query just needs to grab items relative to the content item that we're on. This normally works with Droptree fields in the content editor.
However I'm finding that the query isn't working here because we're in the rendering parameters, so it's not using the content item as it's context.
The query fails and I just get the full Sitecore tree.
I found this can be fixed up for the Datasource field with 'Queryable Datasource Locations' at this link:-
http://www.cognifide.com/blogs/sitecore/reduce-multisite-chaos-with-sitecore-queries/
However I don't know where to start to get this working for other rendering parameter fields.
Any ideas? (I'm using Sitecore 6.6 Update 5)
Unfortunately, the pipeline mentioned in Adam Najmanowicz's answer works for some other types, like Droplink and Multilist, but the pipeline isn't run for Droptree fields.
After looking into this deeper I found that the Source of a Droptree field IS using the wrong context item, as Adam mentioned, but the code comes from the Droptree field itself:-
Sitecore.Shell.Applications.ContentEditor.Tree, Sitecore.Kernel
Utilising the query string code from Adam's answer, we can create a 'fixed' Droptree custom field, that is almost the same as the regular Droptree but will use the correct context item instead.
The code will inherit from the normal Tree control, and only change the way that the Source property is set.
public class QueryableTree : Sitecore.Shell.Applications.ContentEditor.Tree
{
// override the Source property from the base class
public new string Source
{
get
{
return StringUtil.GetString(new string[]
{
base.Source // slightly altered from the original
});
}
set
{
Assert.ArgumentNotNull(value, "value");
if (!value.StartsWith("query:", StringComparison.InvariantCulture))
{
base.Source = value; // slightly altered from the original
return;
}
Item item = Client.ContentDatabase.GetItem(this.ItemID);
// Added code that figures out if we're looking at rendering parameters,
// and if so, figures out what the context item actually is.
string url = WebUtil.GetQueryString();
if (!string.IsNullOrWhiteSpace(url) && url.Contains("hdl"))
{
FieldEditorParameters parameters = FieldEditorOptions.Parse(new UrlString(url)).Parameters;
var currentItemId = parameters["contentitem"];
if (!string.IsNullOrEmpty(currentItemId))
{
Sitecore.Data.ItemUri contentItemUri = new Sitecore.Data.ItemUri(currentItemId);
item = Sitecore.Data.Database.GetItem(contentItemUri);
}
}
if (item == null)
{
return;
}
Item item2 = item.Axes.SelectSingleItem(value.Substring("query:".Length));
if (item2 == null)
{
return;
}
base.Source = item2.ID.ToString(); // slightly altered from the original
}
}
The above code is pretty much the same as the Source property on the base Tree field, except that we figure out the proper context item from the URL if we've detected that we're in the rendering parameters dialog.
To create the custom field, you just need to edit the Web.Config file as described here. Then add the custom field to the core database as described here.
This means that parameters can now have queries for their source, allowing us to limit the available items to the content editor. (Useful for multi-site solutions).
The key here would be to set the Field Editor's context to be relative to the item you are editing instead of the Rendering parameters (that I think it has by default).
So you could have processor:
public class ResolveRelativeQuerySource
{
public void Process(GetLookupSourceItemsArgs args)
{
Assert.IsNotNull(args, "args");
if (!args.Source.StartsWith("query:"))
return;
Item contextItem = null;
string url = WebUtil.GetQueryString();
if (!string.IsNullOrWhiteSpace(url) && url.Contains("hdl"))
{
FieldEditorParameters parameters = FieldEditorOptions.Parse(new UrlString(url)).Parameters;
var currentItemId = parameters["contentitem"];
if (!string.IsNullOrEmpty(currentItemId))
{
Sitecore.Data.ItemUri contentItemUri = new Sitecore.Data.ItemUri(currentItemId);
contextItem = Sitecore.Data.Database.GetItem(contentItemUri);
}
}
else
{
contextItem = args.Item;
}
}
}
hooked as:
<sitecore>
<pipelines>
<getLookupSourceItems>
<processor patch:before="*[#type='Sitecore.Pipelines.GetLookupSourceItems.ProcessQuerySource, Sitecore.Kernel']"
type="Cognifide.SiteCore.Logic.Processors.ResolveRelativeQuerySource, Cognifide.SiteCore" />
</getLookupSourceItems>
</pipelines>
</sitecore>
Together with ResolveQueryableDatasources from Przemek's blog this should solve your problem.

Adding a search box to filter a list of results in Symfony?

I need to put a search box within a list of objects as a result of a typical indexSuccess action in Symfony. The goal is simple: filter the list according to a criteria.
I've been reading the Zend Lucene approach in Jobeet tutorial, but it seems like using a sledge-hammer to crack a nut (at least for my requirements).
I'm more interested in the auto-generated admin filter forms but I don't know how to implement it in a frontend.
I could simply pass the search box content to the action and build a custom query, but is there any better way to do this?
EDIT
I forgot to mention that I would like to have a single generic input field instead of an input field for each model attribute.
Thanks!
I'm using this solution, instead of integrating Zend Lucene I manage to use the autogenerated Symonfy's filters. This is the way i'm doing it:
//module/actions.class.php
public function executeIndex(sfWebRequest $request)
{
//set the form filter
$this->searchForm = new EmployeeFormFilter();
//bind it empty to fetch all data
$this->searchForm->bind(array());
//fetch all
$this->employees = $this->searchForm->getQuery()->execute();
...
}
I made a search action which does the search
public function executeSearch(sfWebRequest $request)
{
//create filter
$this->searchForm = new EmployeeFormFilter();
//bind parameter
$fields = $request->getParameter($this->searchForm->getName());
//bind
$this->searchForm->bind($fields);
//set paginator
$this->employees = $this->searchForm->getQuery()->execute();
...
//template
$this->setTemplate("index");
}
It's important that the search form goes to mymodule/search action.
Actually, i'm also using the sfDoctrinePager for paginate setting directly the query that the form generate to get results properly paginated.
If you want to add more fields to the search form check this :)
I finally made a custom form using the default MyModuleForm generated by Symfony
public function executeIndex {
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
but displaying only a custom field:
<div id="search_box">
<input type="text" name="criteria" id="search_box_criteria" value="Search..." />
<?php echo link_to('Search', '#my_module_search?criteria=') ?>
</div>
Then I created a route named #my_module_search linked to the index action:
my_module_search:
url: my_module/search/:criteria
param: { module: my_module, action: index }
requirements: { criteria: .* } # Terms are optional, show all by default
With Javascript (jQuery in this case) I append the text entered to the criteria parameter in the href attribute of the link:
$('#search_box a').click(function(){
$(this).attr('href', $(this).attr('href') + $(this).prev().val());
});
And finally, back to the executeIndex action, I detect if text was entered and add custom filters to the DoctrineQuery object:
public function executeIndex {
...
// Deal with search criteria
if ( $text = $request->getParameter('criteria') ) {
$query = $this->pager->getQuery()
->where("MyTable.name LIKE ?", "%$text%")
->orWhere("MyTable.remarks LIKE ?", "%$text%")
...;
}
$this->pager->setQuery($query);
...
// Add a form to filter results
$this->form = new MyModuleForm();
}
Actually, the code is more complex, because I wrote some partials and some methods in parent classes to reuse code. But this is the best I can came up with.