How do I query a Drupal Shortcut (8.x/9.x) by its URL or Menu Path? - drupal

We're rolling out an update to an in-house Drupal installation profile, and one of the menu paths that is used frequently is getting changed. Most of our installations reference that menu path in a shortcut (via the "Shortcut" module in core). In an update hook, we'd like to be able to query for those shortcuts and update them.
It feels like this should be straightforward, but for some reason we're finding it difficult to query for shortcuts by their url. We can query them by title, but that seems fragile (since the title could be different between installations, might be different by localization, etc.).
We tried the following, but this lead to the error message 'link' not found:
// This does NOT work.
$shortcuts_needing_update =
\Drupal::entityTypeManager()
->getStorage('shortcut')
->loadByProperties([
'link' => [
'internal:/admin/timeline-management',
],
]);
// This works, but is fragile.
$shortcuts_needing_update =
\Drupal::entityTypeManager()
->getStorage('shortcut')
->loadByProperties([
'title' => 'My shortcut',
]);
Based on the code in \Drupal\shortcut\Entity\Shortcut::baseFieldDefinitions() and \Drupal\shortcut\Controller\ShortcutSetController::addShortcutLinkInline() it's obvious that Shortcut entities have a property called link that can be set like an array containing a uri key, yet it does not seem possible to query by this property even though it's a base field.

Looking at the database, it appears that Drupal stores the URL in a database column called link__uri:
TL;DR That means that this works:
$shortcuts_needing_update =
\Drupal::entityTypeManager()
->getStorage('shortcut')
->loadByProperties([
'link__uri' => 'internal:/admin/old/path',
]
);
Read on if you want to know the subtle reason why this is the case.
Drupal's database layer uses pluggable "table mapping" objects to tell it how to map an entity (like a Shortcut) to one or more database tables and database table columns. The logic for generating a column name for a field looks like this in the default table mapping (\Drupal\Core\Entity\Sql\DefaultTableMapping):
As shown above, if a field indicates it allows "shared" table storage, and the field has multiple properties (uri, title, etc.), then the mapping flattens the field into distinct columns for each property, prefixed by the field name. So, a Shortcut entity with link => ['uri' => 'xyz']] becomes the column link__uri with a value of xyz in the database.
You don't see this often with entities like nodes, which is why this seems strange here. I'm usually accustomed to seeing a separate database table for things like link fields. That's because nodes and other content entities don't usually allow shared table storage for their fields.
How does the mapping determine if a field should use shared table storage? That logic looks like this:
So, the default table mapping will use shared table storage for a field only under specific circumstances:
The field can't have a custom storage handler (checks out here since shortcuts don't provide their own storage logic).
The field has to be a base field (shortcuts are nothing without a link, so that field is defined as a base field as mentioned in the OP).
The field has to be single-valued (checks out -- shortcuts have only one link).
The field must not have been deleted (checks out; again, what is a shortcut without a link field?).
This specific set of circumstances aren't often satisfied by nodes or other content entities, which is why it's a bit surprising here.
We can confirm this by using Devel PHP to ask the table mapping for shortcuts directly, with code like the following:
$shortcut_table_mapping =
\Drupal::entityTypeManager()
->getStorage('shortcut')
->getTableMapping();
$efm = \Drupal::service('entity_field.manager');
$storage_definitions = $efm->getFieldStorageDefinitions('shortcut');
$link_storage_definition = $storage_definitions['link'];
$has_dedicated_storage = $shortcut_table_mapping->requiresDedicatedTableStorage($link_storage_definition);
$link_column = $shortcut_table_mapping->getFieldColumnName($link_storage_definition, 'url');
dpm($has_dedicated_storage, 'has_dedicated_storage(link)');
dpm($link_column, 'link_column');
This results in the following:

Related

Wordpress: Creating a thorough custom post type for recipes

I am currently trying to create a custom post type for recipes. My goal is to include the schema.org/Recipe and or hrecipe microformat and also have the ability to filter for ingredients in the future.
To do this I intend to have an interface with fields for title, photo, description, ingredients and instructions.
My question is: Should I create separate fields for each ingredient and each amount? Or would you say it is sufficient to just create one field for all ingredients? (also keeping the aforementioned microformats in mind).
http://schema.org/Recipe
http://microformats.org/wiki/hrecipe
Having ingredients as a single field is what is expected in both formats you linked to. Querying / filtering based on ingredient name will be slightly more complex...but you should be able to handle it.
There are 3 parts to this answer.
How should you save ingredients in WordPress
How should you allow users to modify the ingredients list
How should you display ingredients publicly
For point 1, you will have to give a bit of thought as to how you save the ingredient list and how you retrieve/display it along with how it is queried. One of the formats indicate you could have properties for each ingredient (still in draft).
You could save an ingredient list as a serialized PHP array, something like this:
$ingredients[]=array('milk','value'=>'125','type'=>'ml');
$ingredients[]=array('sugar','value'=>'1','type'=>'cup');
Since serialized PHP arrays are standardized, you could fairly easily write an WP query that takes it into account.
Keep in mind you will want to have a plan for when the 'value' and 'type' modifiers are set in stone and how to migrate what you saved if they are different.
For point 2, you could create a custom meta box that deserializes the PHP array saved and render individual controls for each ingredient along with controls to allow management (Add, Deletes, Updates).
For point 3....the easiest would be to get the value and manipulate it how you want in the output.

How to use Catalyst to search, select and display entries from my database

I have to use Catalyst in order to create a database and access it through a browser.
I have created a very simple database using DBIx-class and sqlite, just one table and filled it with some records.
I have managed to display the whole table and its rows using Template Toolkit view module and the code below into my controller.
$c->stash(ptm => [$c->model('DB::ptm')->all]);
Now I have created a simple search box in order to search the database and display any entries that match with the keyword, but I don't know how to pass the keyword to my controller nor how to implement the subroutine in order to achieve this.
I have searched for more than three days without finding any solution.
There are two completely different problems here.
Accepting arguments in Catalyst
Performing a search in DBIC
So, starting with the first one. Reading a query string.
$c->request->query_parameters->{field}
Then performing a search. Just call search instead of all and pass a hashref of your columns and values.
$c->model('DB::ptm')->search( { 'name' => $tag } );

Views 3 Relationship Handler

I am trying to write a relationship handler for Views 3 in Drupal 7, but am failing even to begin.
Basically, I have a bunch of nodes of various types all with the same field attached to them. This field is a reference field linking off to a Civicrm contact - but that's not important, as essentially these fields just contain integers.
Now, let's say I have a node of content type 'story', and its reference field contains the integer, oh, let's say 55. In addition, there are nodes of content type 'news' which also contain the reference ID 55.
I want to build a block view, that sits on the story page, that reads in the node's nid as its argument, and then through a relationship it discovers all other nodes that contain the same reference integer as itself.
(In my head, the sql looks something like: SELECT n.nid FROM node n INNER JOIN node n2 ON n.reference = n2.reference [Assuming, for the sake of simplicity, the field data is kept in the node table]).
How do I create a Views handler that caters for this relationship? The only documentation I can find is the views api, which is for version 2 and not 3, and besides is utterly unhelpful. Reading various module's views handlers is not helping either, and views tutorials on the web are almost non-existent.
What are you doing and what is the problem? It sounds like you have everything you need right here...the nid as an argument and the reference field as a relationship. What are your filters set to? and what display type are you using? You could just have the block display some information without sorting, arguments, or relationships and then using the devel module you can change the tpl file for the block to dpm($views) and see what information you have access to.
Let us know what you have configured so far and what your results are if any. Remember that you can use the nid as an argument in the preview, so if the nid is 213 you can type 213 in the preview field (make sure the display is set to the block you are talking about) and see what comes up.
Good luck.

migrating node references

I am working on a project to migrate a website from asp.net to drupal architecture. But the site content is very hierarchal and has a lot of references between entities.
for example: each content belongs to a category, and each category belongs to another category section. Now there may be another level of hierarchy even.
I am planning to make use of migrate module for migrating the database content and linking the migrated nodes via a node reference field.
But i am getting stuck with migrate module as i can't find a way to migrate the node reference field anywhere...
can anyone help me out with this...
Actually, it doesnt seem to be that hard .. in 2012. Yes, you have to keep track of source IDs versus import IDs, but the migrate module does this for you, in a neat little table. You can join that table in your source query, and update the node reference field with the nid of the .. referenced node. Ofcourse, the referenced nodes should have already been imported. If they werent, you can run an run an 'update' later and referenced nids get entered based on the latter imports too. In practice:
$query = Database::getConnection(
'default', 'mysourcedb'
)->select(
'mysourcetable','source'
)->fields('source', array(
'id',
'title',
'whatever'
'rel_rec_id'
)
);
$query->leftJoin('migrate_map_relimport','relmap','relmap.sourceid1=source.rel_rec_id');
$query->addField('relmap','destid1','rel_node_id');
The code above assumes you have a 'mysourcedb' with a 'mysourcetable' in it that refers to a 'rel_rec_id', and theres another import called RelImport that imports the rel table that rel_rec_id is refering to; it should have already run (or will run before you run an additional update). Do a migrate-status once you have the RelImport class to make sure the table exists.
To be able to make joins to the 'migrate_map_relimport' table, make sure map tables are written to the source database, not the drupal database. This is not always necessary, but here it is:
$this->map = new MigrateSQLMap(
$this->machineName,
array(
'id' => array(
'type' => 'int',
'unsigned' => true,
'not null' => true,
'alias' => 'source'
)
),
MigrateDestinationNode::getKeySchema(),
'mysourcedb' // connection to use to write map tables
);
and finally, assign the retrieved rel_node_id to your node reference:
$this->addFieldMapping( 'field_rel_node', 'rel_node_id' );
Yay, it is rocket science .. YMMV
As far as I know, you will not be able to do this entirely within the migrate module. You'll have to run a few queries directly in MySQL.
Essentially, you'll have to create an extra field in each content type to house their legacy ID's and an additional field for each legacy reference (in addition to the actual nodereference field). Load all the data into the content types (leave the nodereference field empty). Then once all of the entities are loaded in, you run mysql queries to populate the nodereference fields based on the legacy IDs and legacy reference fields. Once that's done you can safely delete these legacy fields.
Not the most elegant solution, but I've used it many times.
Caveats:
This is for Drupal 6; Drupal 7's fields implementation is totally different AFAIK.
For very large migrations, you might want to do your legacy field deletions through MySQL.
You might also take a look at the code for the Content Migrate module (more information at https://drupal.org/node/1144136). It's for migrating D6 Content Construction Kit (CCK) content to D7 Fields and it's been integrated with the References module.
It won't do what you need out of the box, as you're coming from an ASP.net site instead of a D6 site, but it may provide some clues.

Anyone familiar in Drupal 6 Services module specifically node.save

I can save/update on regular fields but I'm having trouble saving/updating CCK fields. here's an example node.save() XML request - http://pastebin.com/m5ceca16
I'm assuming your XML data mirrors the node object format.
A CCK field 'field_custom' will be accessible via $node->field_custom. Regardless of type and the limit on number of entries, fields are always arrays. If the CCK field only allows one entry, it is $node->field_custom[0].
The indexes below that level depend on the field type. Most, especially numeric and text fields, are 'value' (eg., $node->field_custom[0] = 'foo'). I've used Nodereference fields which use 'nid', from which I would assume Userreference fields use 'uid'.
The structure of your XML seems correct. I would check the structure of a node object on the site (using a var_dump() or the devel module) to make sure all of your array keys and variable names are correct for your field and field type.
2 things to check:
A var_dump of the results of a node_load() doesn't give you the exact format you should use. Your XML must emulate the input format of the node edit form. So while a var_dump might show you several taxonomy terms in an array, the node edit form may expect the taxonomy terms separated by commas. Off-hand I don't see any fields in your example that this would seem to apply to but I mention it anyway.
Your "changed" timestamp must not be in the future, nor must it be too far in the past. The node will not save if this is off by much. This can be an issue if the clocks on one of the computers isn't very accurate. I had an issue where my services server was about 20 seconds behind my services client so all the updates were getting rejected (the server apparently rejected them on the grounds that they were from the future).

Resources