Need to display first n items from each category in Razor using Umbraco - asp.net-mvc-4

I am new to Umbraco. I have a list of items in a content named Videos. Each item have a specific category. I need to retrieve 'n' number of items from each category. Some one please help. Also am using MixItUp jquery plugin to display the items.
// this will bring up all items from the list
var items = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "videoItem" && x.IsVisible());
// Here am trying to bring 5 items under category "Testimonial"
var allItems = items.Where(x => x.GetPropertyValue("category") == "Testimonial").Take(5);
But I didn't found any output. Please help.

Your second line of code should read:
var allItems = items
.Where(x => x.GetPropertyValue<string>("category") == "Testimonial")
.Take(5);
Rather than simply cast the result to string, this will try and convert the object to the desired type if it isn't already - see here.
If you're using the new ModelsBuilder (which is awesome) you also have the option of strongly typing the whole process.
var items = Model.Content.Children<VideoItem>().Where(x => x.IsVisible());
var allItems = items.Where(x => x.Category == "Testimonial").Take(5);

Related

ASP.Net Core SelectList not displaying selected item

Using ASP.Net core 2.2 in VS 2017 (MVC):
I have a wizard based screen that has a drop down list of Organizations.
When I load a record from the Database, I want to set the select list to the values in the DB.
Spoiler alert: The specified Item is not selected when the page is initially displayed.
When the item is manually selected, and the ‘Next’ button is clicked and then the Prev button is clicked, returning us to the first page, the item is selected just as I intend.
None of the methods below set the ‘Selected’ property of the selected item (“0403”) when loading the Model in the controller for the first display.
The compare in Method 2 never evaluates to true even though I can see the compared values are equal while debugging.
Method 3 does not find the item even though I can see the compared values are equal while debugging
Method 4 does not find the item even though I can see the compared values are equal while debugging
This is all happening in the Controller, so please do not suggest changing the name of the dropdown in the View.
**Org table
ORG ID OrgName**
0004 Org 4
0007 Org 7
0008 Org 8
0403 Org 403
This is my source query:
var orgsQuery = from s in _context.Orgs
orderby s.OrgID
select s;
These are the various ways I have tried building the select List in the Controller:
1).
SelectList oList = new SelectList(orgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
2).
List<SelectListItem> oList = new List<SelectListItem>();
foreach ( var item in OrgsQuery)
{
oList.Add(new SelectListItem()
{
Text = item.OrgName,
Value = item.OrgID,
Selected = (item.OrgID == (string)selectedOrg ? true : false)
});
}
3).
if (selectedOrg != null)
{
oList = new SelectList(OrgsQuery.AsNoTracking(),"OrgID", "OrgName", OrgsQuery.First(s =>
s.OrgID == (string)selectedOrg));
}
else
{
oList = new SelectList(OrgsQuery.AsNoTracking(), "OrgID", "OrgName", selectedOrg);
}
4).
SelectList oList =
new SelectList(_context.Org.OrderBy(r => r.OrgID),
_context.Org.SingleOrDefault(s => s.OrgID == (string)selectedOrg))
Well, assume that selectedOrg type is numeric, than it should be convert to formatted string by following the OrgID format:
var formattedSelectedOrg = String.Format("{0:0000}", selectedOrg);
Or
// if selectedOrg is nullable numeric type
var formattedSelectedOrg = selectedOrg?.ToString("0000");
// if selectedOrg is base numeric type
var formattedSelectedOrg = selectedOrg.ToString("0000");
// if selectedOrg is String type (nullable)
var formattedSelectedOrg = selectedOrg?.Trim().PadLeft(4, '0');
Or
var number;
var formattedSelectedOrg =
String.Format("{0:0000}", Int32.TryParse(selectedOrg?.Trim(), out number) ? number : 0);
So it would be comparable when applied to your codes:
// assume selectedOrg is base numeric type
Selected = item.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
Selected = item.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
Selected = item.OrgID == formattedSelectedOrg
And
// assume selectedOrg is base numeric type
s => s.OrgID == selectedOrg.ToString("0000")
Or
// if selectedOrg is String type (nullable)
s => s.OrgID == selectedOrg?.Trim().PadLeft(4, '0')
Or
// if you prefer to use predefined formatted string
s => s.OrgID == formattedSelectedOrg
Check this out:
Custom numeric format strings
String.PadLeft Method
Also this important briefcase:
Pad left with zeroes
Hope this could helps. Enjoy your coding!

Updating Handles for MatrixBlock "Field Layout Fields" in Craft CMS Migrations

After reading this excellent Medium article, I've been stoked on Migrations in CraftCMS. They've been super useful in importing the same changes across the 10 or so developers who work on our site.
When trying to change the handles on individual fields within block types within matrix blocks (whew) via migrations, I came across a hurdle. The field itself can easily have its "handle" attribute updated, but the columns table for that matrix block's content (matrixcontent_xxxxx) do not get updated to reflect any updated handles. The association between the Matrix Block & its associated Matrix Content table only exists in the info column in the field record for that Matrix Block.
If the Matrix Block's field is updated via the CMS, the change is reflected, so it's gotta be somewhere in Craft's source, but it's not apparent through the Craft CMS Class Reference.
Any ideas?
Edited to add the migration snippet:
public function safeUp()
{
// Strings for labels, etc.
$matrix_block_instructions = "instructions";
$block_label = "Video";
$block_handle = "video";
$field_handle = "video_url";
$field_label = "Video URL";
$field_instructions = "Add a YouTube or Facebook video URL.";
// Fetching the MatrixBlock fields used on the entries themselves
$video_gallery_1 = Craft::$app->fields->getFieldByHandle("handle_1");
$video_gallery_2 = Craft::$app->fields->getFieldByHandle("handle_2");
$video_gallery_3 = Craft::$app->fields->getFieldByHandle("handle_3");
$galleries = [$video_gallery_1, $video_gallery_2, $video_gallery_3];
foreach( $galleries as $gallery ) {
// Fetching the record for this specific MatrixBlock field.
$gallery_record = \craft\records\Field::find()->where(
['id' => $gallery->id]
)->one();
// Fetching the record for this specific MatrixBlockType
$gallery_block_id = $gallery->getBlockTypes()[0]->id;
$gallery_block = \craft\records\MatrixBlockType::find()->where(
['id' => $gallery_block_id]
)->one();
// Assigning standard labels for the MatrixBlockType
$gallery_block->name = $block_label;
$gallery_block->handle = $block_handle;
$gallery_block->update();
// Getting the specific ... 1 ... field to edit
$field_group = \craft\records\FieldLayout::find()->where(
['id' => $gallery_block->fieldLayoutId]
)->one();
$field_layout_field = $field_group->fields[0];
$field = $field_layout_field->field;
$field = \craft\records\Field::find()->where(
['id' => $field->id]
)->one();
// Assigning standard labels for the Label
$field->name = $field_label;
$field->handle = $field_handle;
$field->instructions = $field_instructions;
$field->update();
// Updating the MatrixBlock record with new instructions
$gallery_record->refresh();
$gallery_record->instructions = $matrix_block_instructions;
$gallery_record->update();
}
OK, so my apologies if anyone was stoked on figuring this out, but my approach above was kind of a crazy person's approach, but I've found my own solution.
The key here is that I should have been interacting with craft\fields\MatrixBlock and the craft\fields\PlainText objects, not craft\records\Field objects. There's a method within \craft\services\Fields for saving the field that requires a FieldInterface implemented. This is actually the default classes returned, and I was making more work for myself in the code!
Within that foreach loop, this worked out:
// Fetching the record for this specific MatrixBlock field.
$gallery->instructions = $matrix_block_instructions;
// Update the MatrixBlockType
$gallery_block_id = $gallery->getBlockTypes()[0]->id;
$gallery_block = \craft\records\MatrixBlockType::find()->where(
['id' => $gallery_block_id]
)->one();
$gallery_block->name = $block_label;
$gallery_block->handle = $block_handle;
$gallery_block->update();
// Update the actual field.
$field = $gallery->blockTypeFields[0];
$field->name = $field_label;
$field->handle = $field_handle;
$field->instructions = $field_instructions;
Craft::$app->getFields()->saveField( $field );
Craft::$app->getFields()->saveField( $gallery );
Thanks for looking at this, and sorry for being a crazy person.

How do I iterate through a list of items in a Ext.dataview.List

I'm currently trying to find out how to set items to be selected on a list in ST2.
I've found the following:
l.select(0, true);
l.select(1, true);
which would select the first 2 items on my list. But the data coming from the server is in csv format string with the ids of the items in the list to be selected.
e.g. "4, 10, 15"
So I currently have this code at the moment.
doSetSelectedValues = function(values, scope) {
var l = scope.getComponent("mylist");
var toSet = values.split(",");
// loop through items in list
// if item in list has 'id' property matching whatever is in the toSet array then select it.
}
The problem is I can't seem to find a way of iterating over the items in the list and then inspect the "id" property of the item to see if it matches with the item in the array.
l.getItems()
Doesn't seem to return an array of items. The list is populated via a store with the "id" & "itemdesc" properties. I just want to be able to select those items from a csv string. I've scoured the Api on this and I can't seem to find a way of iterating over the items in the list and being able to inspect its backing data.
the Ext.List's items are not the items you are looking for. The items under the Ext.List object are those:
Ext.create('Ext.List', {
fullscreen: true,
itemTpl: '{title}',
store: theStore,
**items: [item1, item2]**
});
Granted, usually an Ext.List doesn't have items like these. What you are looking for are the Ext.Store items. The Ext.Store items are the exact same items in the same order as presented in the Ext.List.
To iterate over those, and select the corresponding items in the list, do the following:
var s = l.getStore();
var itemIndicesToSelect = [];
for (var i = 0 ; i < s.data.items.length ; i++){
if (arrayContainsValue(toSet, s.data.items[i].data.id)){
itemIndicesToSelect.push(i);
}
}
for (var i = 0 ; i < itemIndicesToSelect.length ; i++){
l.selectRange(itemIndicesToSelect[i], itemIndicesToSelect[i], true);
}
You would have to implement the function arrayContainsValue (one possible solution).
doSetSelectedValues = function(values, scope) {
var l = scope.getComponent("mylist"),
store = l.getStore(),
toSet = values.split(",");
Ext.each(toSet, function(id){
l.select(store.getById(id), true);
});
}

Object collection optimisation

I'm struggling with something I'm sure I should be able to do quite quick with Linq-to-Obj
Have 27 flowers, need a collection of Flower[] containing 5 items split over, roughly 6 records;
List<Flowers[]> should contain 6 Flowers[] entities, and each Flowers[] array item should contain 5 flower objects.
I currently have something like:
List<Flowers[]> flowers;
int counter = 0;
List<Flowers>.ForEach(delegate (Flower item) {
if (counter <= 5){
// add flowers to array, add array to list
}
});
I'm trying to optimise this as it's bulky.
[Update]
I can probably to an array push on objects, removing the items I'v already run through, but is there not an easier way?
var ITEMS_IN_GROUP = 5;
var result = list.Select((Item, Index) => new { Item, Index })
.GroupBy(x => x.Index / ITEMS_IN_GROUP)
.Select(g => g.Select(x=>x.Item).ToArray())
.ToList();
You may also want to try morelinq's Batch

how to programmatically create menu items while creating nodes?

I'm creating some nodes programmatically, thus:
foreach ($titles as $t) {
$n = new stdClass();
$n->type = 'myType';
$n->uid = 1;
$n->title = $t;
$menu = array();
$menu['link_title'] = $t;
$menu['menu_name'] = 'primary-links';
// this attempt at placing the menu item in a particular place in the
// menu hierarchy didn't work:
$menu['parent'] = 'primary-links:867';
$menu['depth'] = 3;
$menu['p1'] = '580';
$menu['p2'] = '867';
$n->menu = $menu;
node_save($n);
}
I've got a menu structure like this:
primary-links
Parent 1
Child 1
Child 2
Parent 2
Child 3
I want the new menu items to appear as children of Child 3. I was able to create menu items at the same time as the nodes, and they appeared in the correct menu, but not in the correct place in the hierarchy. What am I missing?
In drupal 7 you need to set also enabled to 1 (see: menu_node_save()):
$node->menu = array(
'link_title' => $node->title,
'menu_name' => 'main-menu',
'plid' => 0,
'enabled' => 1,
);
I think your over complicating it. In the past when I've programmatically created menu items for nodes, I just set the menu_name, link_title, and plid (parent link id), ie:
$menu['link_title'] = $t;
$menu['menu_name'] = 'primary-links';
$menu['plid'] = 867;
The menu module takes over at some point during the call to node_save and does the rest for you.
~Matt
Also had to add
'description' => ''
to the array otherwise I got an error for Drupal 7