Many-to-Many entities and NSPopUpButton - core-data

all.
Entities:
[Library {title}] <-->> [Book {title}] <<-->> [Author {name}]
Controllers:
NSArrayController [Library] => {Entity: Library}
NSArrayController [Book] => {Entity: Book, ContentSet: Library, books}
NSArrayController [Author] => {Entity: Author, ContentSet: Book, authors}
NSArrayController [Authors] => {Entity: Author}
Form:
[ NSPopUpButton *]
[ NSTableView **]
[ add ] [ remove ]
* button get content from NSArrayController [Author w/o contentset
option]
** table get content from another NSArrayController [Author
with contentset option set as Library.books]
Question:
how i can add Author into Book.authors from Author entity?
(Use previous authors for any book)

1) set PopUpButton property
{
Content: NSArrayController [Authors], ArrangedObjects
Content Values: NSArrayController [Authors], ArrangedObjects, name
Selected Index: NSArrayController [Authors], selectionIndex
}
2) add
#property (assign) IBOutlet *authorsController, *bookController;
and link it with NSArrayControllers
3) add this code and link with button:
- (IBAction)insertSelectedItem:(id)sender
{
MOAuthor *author = self.authorsController.content[self.authorsController.selectionIndex]; // get current (selected) author
MOBook *book = self.bookController.content[self.bookController.selectionIndex]; // get current guide
[book addAuthorsObject:author]; // add step into guide
NSError *err = nil;
[book.managedObjectContext save:&err]; // save all
}
MOBook, MOAuthor - ManagedObject class created from Entity

Related

How can I access the names of variant products in Shopware 6?

How can I get the name of a variant product via the product repository? So for example t-shirt L. Or only the option.
This is my code:
$cri2 = new Criteria();
$cri2->addFilter(new EqualsFilter('parentId', $itemProductId));
$cri2->addFilter(new EqualsFilter("active", 1));
$cri2->addFilter(new RangeFilter('stock', [ 'gt' => 0 ]));
I need the name of this option:
I believe the confusion is here:
Just note that this is not the name of the variant, it's just it's options concatenated as preview.
You can see inn the picture below that the actual name is null & therefore inherits the parents' name:
If you change the name from the variant product, then it will not be null anymore.
To create an actual name you will have to manually pull its options using associations. Here is an example of a query you might be looking for. After you get the data, just create the name yourself out of the variation data. High chance that this is how Shopware6 does it in the picture provided.
$criteria = (new Criteria()
// loads non-child products
->addFilter(new EqualsFilter('product.parentId', null))
->addAssociations([
'options',
'variation',
'children',
'children.options',
'children.properties',
'children.properties.group'
])
When you want to search for a specific name you can use
$cri2->addFilter(new EqualsFilter('name', 't-shirt L'));
When you want to search for the option name instead you can use
$cri2->addFilter(new EqualsFilter('options.option.name', 't-shirt L'));
When you don't want to search by name, but only what to get the name of a given product:
$product = $this->productRepository->search($cri2, $context)->getFirst();
echo $product->getName();
The finished code is:
$cri = new Criteria();
$cri->addFilter(new EqualsFilter('parentId', "[YOUR PARENT ID]"));
// Add options to associations
$cri->addAssociations([
'options'
]);
// Loop through variant products
foreach ($productRepository->search($cri, $context)->getElements() as &$variantRawItem) {
// Map all options to array
$options = array_map(function ($n) {
return $n->get('translated')['name'];
}, $variantRawItem->get('options')->getElements());
// Create the options title
$optionsTitle = implode(', ', $options);
// $optionsTitle is now e.g.: L, Lila
}

Create New Type of Nav-Menu Item

A site I'm working on has a complicated "mega menu" type navigation. I would like content editors to be able to group menu items by column in the markup. Normally if I want 6 columns I would register 6 menus and name them columns 1-6, however these are dynamic sub-menus that need to be a child of another navigation item inside another menu.
What I'd really like to do is create a new type of nav-menu item (Currently Pages, Links, Categories, as well as my other custom post types and custom taxonomies) where that item would be just for columns. (The fact that I'm using it for columns isn't important here. This could just as easily be dividers, or something else. I just need a new nav-menu item type that I can create special markup with when I'm building the menus.)
Is there a way to create a new nav-menu item type without having to create a custom post type or custom taxonomy that is used only for this purpose?
What I ended up doing for this, was adding a new post type that was hidden everywhere on the site except the nav menus. I then added just a single entry of that post type type, and hid some of the fields.
<?php
function navMenuColumns_init() {
register_post_type('menu_column',
array(
'labels' => array(
'name' => __('Menu Columns'),
'singular_name' => __('Menu Column')
),
'supports' => array('title'),
// Doesn't need to be listed most places as it's not a valid content item on it's own
'public' => false, // Base setting. More specific settings below
'exclude_from_search' => false,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'show_in_nav_menus' => true, // The only thing this is used for
'show_in_admin_bar' => false,
'has_archive' => false,
)
);
$_version = (float)get_option('navMenuColumns_version', 0.0);
if ($_version < 1.0) {
navMenuColumns_install10();
}
add_action('admin_footer', 'navMenuColumns_adminFooter');
}
function navMenuColumns_install10() {
$navMenuPost = wp_insert_post(array(
'post_type' => 'menu_column',
'post_title' => 'Column',
'post_status' => 'publish'
), true);
if (!is_wp_error($navMenuPost)) {
update_option('navMenuColumns_version', 1.0);
}
}
function navMenuColumns_adminFooter() {
?><script>
jQuery(document).ready(function($) {
// Hides most of the fields when editing a Menu Column item.
$('#menu-to-edit').on('click', 'a.item-edit', function() {
var $li = $(this).parents('li.menu-item');
if ($li.find('.item-type').text() == 'Menu Column') {
$li.find('p.description').hide();
$li.find('p.link-to-original').hide();
$li.find('p.field-move').show();
}
});
});
</script><?php
}
add_action('init', 'navMenuColumns_init');
?>
This allows the user to add this as a normal menu item. This won't play well with functions that build the menu markup for you, but if you traverse the menu item and build the markup for you, you can target this post type with custom markup.

Restkit + Core Data: Inserts duplicate values in a UITableView on every app launch

Following AlexEdge Tutorial I have encountered the following behavior. I can provide code as requested since there are many lines and I'm not really sure where to look. Basically, it "works" in the sense that the data is properly loaded into the UITableView, but after stopping and starting up the simulator, it inserts new duplicate rows in each section.
I figured this would have something to do with caching but I am following the above tutorial pretty closely and I've set the identificationAttributes to identify unique records (wouldn't, for example, adding ALL attributes effectively eliminate the possibility that I've not specified a sufficiently unique key, just for debugging purposes?). I've tried changing the Cache name, setting it nil, but it keeps inserting duplicates. Every so often I reset the simulator just to start on a clean slate.
If it matters, I am calling getObjectsAtPath in viewDidLoad as per the tutorial. My understanding of how RestKit worked was that it was okay to do so because it would be smart enough to infer that no updates were necessary as the records are all the same.
Edit
I have set identificationAttributes to an array of two integer attributes that really do determine a unique record.
I also have a managedObjectCache:
// Seal the deal
[managedStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:#"CCTDB.sqlite"];
NSError *error;
NSPersistentStore *persistentStore =
[managedStore
addSQLitePersistentStoreAtPath:storePath
fromSeedDatabaseAtPath:nil
withConfiguration:nil
options:#{
NSMigratePersistentStoresAutomaticallyOption:#YES,
NSInferMappingModelAutomaticallyOption:#YES
}
error:&error];
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
[managedStore createManagedObjectContexts];
managedStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedStore.persistentStoreManagedObjectContext];
EDIT 1
Here is the log output of the second time around
(2013-07-11 03:18:29.961 cocoaclinical[18773:3d07] D restkit.object_mapping:RKPropertyInspector.m:130 Cached property inspection for Class 'EMDisease': {
diseaseId = {
isPrimitive = 0;
keyValueCodingClass = NSNumber;
name = diseaseId;
};
diseaseIdValue = {
isPrimitive = 1;
keyValueCodingClass = NSNumber;
name = diseaseIdValue;
};
name = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = name;
};
subDiseaseId = {
isPrimitive = 0;
keyValueCodingClass = NSNumber;
name = subDiseaseId;
};
subDiseaseIdValue = {
isPrimitive = 1;
keyValueCodingClass = NSNumber;
name = subDiseaseIdValue;
};
}
2013-07-11 03:18:29.975 cocoaclinical[18773:3f03] I restkit.core_data:RKInMemoryManagedObjectCache.m:94 Caching instances of Entity 'EMDisease' by attributes 'diseaseId, subDiseaseId'
2013-07-11 03:18:29.983 cocoaclinical[18773:3f03] T restkit.core_data:RKInMemoryManagedObjectCache.m:127 Cached 31 objects
2013-07-11 03:18:29.984 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMapperOperation.m:231 Asked to map source object {
DiseaseSystemIdMember = 161;
DisplayNameMember = "Acute Lymphocytic Leukemia";
SubDiseaseSystemIdMember = 1886;
} with mapping <RKEntityMapping:0x96c2850 objectClass=EMDisease propertyMappings=(
"<RKAttributeMapping: 0x96ba060 SubDiseaseSystemIdMember => subDiseaseId>",
"<RKAttributeMapping: 0xb58df40 DisplayNameMember => name>",
"<RKAttributeMapping: 0xb58df70 DiseaseSystemIdMember => diseaseId>"
)>
2013-07-11 03:18:29.984 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMappingOperation.m:952 Starting mapping operation...
2013-07-11 03:18:29.985 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:953 Performing mapping operation: <RKMappingOperation 0xb5b7820> for 'EMDisease' object. Mapping values from object {
DiseaseSystemIdMember = 161;
DisplayNameMember = "Acute Lymphocytic Leukemia";
SubDiseaseSystemIdMember = 1886;
} to object <EMDisease: 0xb5b7ee0> (entity: EMDisease; id: 0xb5b7f80 <x-coredata:///EMDisease/t8DD8EE18-C798-468F-9E03-C6A3C724AA772> ; data: {
diseaseId = 161;
name = nil;
subDiseaseId = 1886;
}) with object mapping (null)
2013-07-11 03:18:30.027 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'SubDiseaseSystemIdMember' to 'subDiseaseId'
2013-07-11 03:18:30.028 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'SubDiseaseSystemIdMember to keyPath 'subDiseaseId' -- value is unchanged (1886)
2013-07-11 03:18:30.029 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'DisplayNameMember' to 'name'
2013-07-11 03:18:30.029 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:572 Mapped attribute value from keyPath 'DisplayNameMember' to 'name'. Value: Acute Lymphocytic Leukemia
2013-07-11 03:18:30.030 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'DiseaseSystemIdMember' to 'diseaseId'
2013-07-11 03:18:30.030 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'DiseaseSystemIdMember to keyPath 'diseaseId' -- value is unchanged (161)
2013-07-11 03:18:30.031 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMappingOperation.m:1021 Finished mapping operation successfully...
You do need to set identificationAttributes, generally only one or two attributes though, not everything. Your entities should have some unique identifier.
You also want to add a managedObjectCache to your managed object store. This is the part that allows RestKit to match objects using your identificationAttributes and update the existing items instead of creating new ones.

Drupal views: List of authors of nodes where node.type=abc and node.vocabulary_id=123

In drupal6 using views I want a (block) list of authors (with complete profile fields) of some specific node type AND taxonomy term.id OR vocabulary.id
Summarized query:
Views: type user
Argument: Term ID/Vocabulary ID
Filters: Author of Node type abc
Fields: All Profile/Content Profile Fields
How can I achieve such solution?
I have the same issue. I found that if I filtered by node.type = 'blog' and set fields for the profile fields I was interested in, I could get a list or authors, but there would be duplicates. Setting 'Distinct' to Yes didn't help because it was selecting out distinct nodes, not distinct users.
So I ended up creating a custom block to show this information with some code like this:
<?php
$block['subject'] = t('Bloggers');
// Get a list of blog authors
$result = db_query('SELECT DISTINCT u.uid, u.name FROM {node} n INNER JOIN {users} u ON n.uid = u.uid WHERE n.type = \'blog\'');
$links = array();
while ($blogger = db_fetch_object($result)) {
$link = array();
if (module_exists('profile')) {
profile_load_profile($blogger);
}
if (!empty($blogger->profile_first_name) || !empty($blogger->profile_last_name)) {
$link['title'] = $blogger->profile_first_name . (empty($blogger->profile_first_name) ? '' : ' ') . $blogger->profile_last_name;
}
else {
$link['title'] = $blogger->name;
}
$link['href'] = 'blog/' . $blogger->uid;
$links[] = $link;
}
$block['content'] = theme('links', $links, array('class' => 'flat-links'));
?>
Hope that helps.

populate a comboBox in Griffon App dynamically

I have 2 comboBoxes in my View of Griffon App (or groovy swingBuilder)
country = comboBox(items:country(), selectedItem: bind(target:model, 'country',
value:model.country), actionPerformed: controller.getStates)
state = comboBox(items:bind(source:model, sourceProperty:'states'),
selectedItem: bind(target:model, 'state', value:model.state))
The getStates() in the controller, populates #Bindable List states = [] in the model based on the country selected.
The above code doesn't give any errors, but the states are never populated.
I changed the states from being List to a range object(dummy), it gives me an error MissingPropertyException No such property items for class java.swing.JComboBox.
Am I missing something here? There are a couple of entries related to this on Nabble but nothing is clear. The above code works if I had a label instead of a second comboBox.
I believe that the items: property is not observable and it's only used while the node is being built. You may have better results by setting the binding on the model or by using GlazedLists' EventList.
Model:
#Bindable String country = ""
EventList statesList = new BasicEventList()
Controller:
def showStates = { evt = null ->
model.statesList.clear()
def states = []
if(model.country == "US")
states = ["CA","TX", "CO", "VA"]
else if(model.country == "Canada")
states = ["BC", "AL"]
else
states = ["None"]
edt {model.statesList.addAll(states.collect{it})}
}
View:
def createComboBoxStatesModel() {
new EventComboBoxModel(model.daysList) }
comboBox( items:["USA","Canada","other"], selectedItem: bind(target:model, 'country', value: model.country), actionPerformed : controller.showStates)
comboBox( model: createComboBoxStatesModel(), selectedItem: bind(target:model, 'state', value:model.state))

Resources