getting a list in MVC from Umbraco - list

I have Umbraco Document types MyContent and MyContentList. MyContentList has a list view of MyContent. In the partial View I have
#inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentModels.MyContentList>
#using ContentModels = Umbraco.Web.PublishedContentModels;
#{
Layout = "";
}
#Html.Partial("~/Views/Partials/MyView.cshtml",
new MyProject.Models.MyContentList()
{
Target = #Umbraco.Field("ContentTarget").ToString(),
Items = ???
}
How do I get the list of items from Umbraco and pass it in my MVC?
Thanks

Make sure you've loaded the Umbraco.Web namespace so the extension method can be used:
#using Umbraco.Web
Then you can try something like the following:
#foreach(var item in Model.Content.Children<ContentModels.MyContent>()){
// do something here
}
Also review the documentation on our.umbraco.com here:
https://our.umbraco.com/documentation/Reference/Querying/IPublishedContent/Collections

Related

Sitecore 8: Change of datasource template for a sublayout

I have a doubt regarding the change of datasource template of a sublayout. Now, there are two sublayouts: Sub1 and Sub2 which are having Template1 as their datasource template. Until the time I discovered that i need a different datasource template for Sub1, i had already created many items of sublayouts Sub1 and Sub2.
Template2 will now replace Template1 as datasource template for sublayout Sub1.
Now, i have to change the template of all those items that were created with sublayout as Sub1.
The problem is I have to manually change each item's template via content editor--> Configure-->Change Template technique, which is very cumbersome. Is there any other way to change the template of all those items at once ?
I suggest you to install Sitecore PowerShell Extensions and to change the template using the Sitecore PowerShell Console.
$master = [Sitecore.Configuration.Factory]::GetDatabase("master");
$entryTemplate = $master.Templates["your path to template Sub2"];
cd master:\Content\Home\Sub1FolderItems\;
//path to sub1 folder items
Get-ChildItem -recurse | ForEach-Object { if ($_.TemplateName -eq "Sub1") { $_.ChangeTemplate($entryTemplate) } };
There is another way - if you have Sitecore Rocks installed, you can multi-select all the items, right click and select Change Template - no code, and pretty quick unless your content items are in many different places.
As #SitecoreClimber suggested, the best approach to do this is to install Sitecore PowerShell Extensions and fix this with PowerShell. If you don't have admin access or you are not allowed to install PowerShell extensions to your machine, you can use the following .NET code to achieve what you want. Just replace the values of ID variables with the IDs of your templates and sublayouts:
// replace with the first template's ID
ID template1ID = new ID("{A0F73C76-DD4D-4037-90D4-48B616397F5D}");
// replace with the second template's ID
ID template2ID = new ID("{43A1EBB0-CABB-4682-9F5B-7765D7FB0E29}");
// replace with your sublayout's ID
ID sublayout2ID = new ID("{1C6094FA-4539-48E4-A24A-104787641A88}");
Database masterDatabase = Factory.GetDatabase("master");
TemplateItem template2Item = masterDatabase.GetTemplate(template2ID);
// Set to your RootItem
Item rootItem = masterDatabase.GetItem("{756B23C8-1C0F-41AC-9273-B18FDA047925}");
using (new SecurityDisabler())
{
foreach (Item child in rootItem.Axes.GetDescendants())
{
RenderingReference[] renderings = child.Visualization.GetRenderings(Sitecore.Context.Device, true);
IEnumerable<RenderingReference> sublayout2Renderings =
renderings.Where(x => x.RenderingID == sublayout2ID);
foreach (RenderingReference rendering in sublayout2Renderings)
{
if (!string.IsNullOrEmpty(rendering.Settings.DataSource))
{
Item datasourceItem = masterDatabase.GetItem(rendering.Settings.DataSource);
if (datasourceItem != null)
{
if (datasourceItem.TemplateID == template1ID)
{
datasourceItem.ChangeTemplate(template2Item);
}
}
}
}
}
}

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.

Prestashop api - How to get the current cart contents

I'm new to Prestashop, I cant find examples anywhere of how to get the current cart contents. I can get a list of all carts, but how do I get the current users cart?
it is easy and simple. I am considering you are using PS 1.5.x
In controllers other than cart controller
$cart = new Cart($this->context->cookie->id_cart);
or in an class
$context = new Context();
$cart = new Cart($context->cookie->id_cart);
Now the $cart is an object, and it has all the current cart data.
You can also get the cart products by calling getProducts like below
$cartProducts = $cart->getProducts();
Hope this will help.
Please note that code is not tested and is just a sample code for your idea.
Thank you
For PS 1.4.X you can get using getProducts()
$product_array = $this->getProducts();
print_r($product_array);
Example :
public function getSubTotal() {
$product_array = $this->getProducts();
foreach($product_array as $product_item) {
$sub_total += $product_item['price'] * $product_item['cart_quantity'];
}
return $sub_total;
}

SiteCore 6.5: Getting control parameters

When adding controls to a content node via the Presentation -> Layout Details -> Edit, you are allowed to add "Parameters" to the controls. How do you get those parameters from code?
I'm using the forms for web marketers and I want to pass in parameters to the form control and have access to them from custom field controls.
Here is a function to get a parameter:
private string Params(string key)
{
string rawParameters = Attributes["sc_parameters"];
NameValueCollection parameter = WebUtil.ParseUrlParameters(rawParameters);
if (parameter.HasKeys())
return parameter[key];
return "";
}
You need to add it to you sublayout .cs file and it should work.
I was able to do this using
Sitecore.Form.Core.Renderings.FormRender frm = ((Sitecore.Form.Core.Renderings.FormRender)((Sitecore.Form.Web.UI.Controls.BaseControl)this).Form.Parent);
NameValueCollection parameters = Sitecore.Web.WebUtil.ParseUrlParameters(frm.Parameters);
string val = parameters["my_param"];
It's ugly, but it works.

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.