Error on update from 2.3 to 2.8 and 2.7? I'm using drupal commerce 2.3 and want to update to commerce 2.8.

I just copied the files to the new folder and get the error:

PHP Fatal error:  Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272

Fatal error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206): Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171): Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182): Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72): Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118): Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php on line 272
Drush command terminated abnormally due to an unrecoverable error.                                           [31;40m[1m[error][0m
Error: Uncaught Error: Class 'CommerceGuys\Addressing\AddressFormat\FieldOverride' not found in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php:272
Stack trace:
#0 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(206):
Drupal\commerce_store\Entity\Store::baseFieldDefinitions(Object(Drupal\Core\Entity\ContentEntityType))
#1 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityFieldManager.php(171):
Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions('commerce_store')
#2 C:\www\crypto-excel\core\lib\Drupal\Core\Entity\EntityManager.php(182):
Drupal\Core\Entity\EntityFieldManager->getBaseFieldDefinitions('commerce_store')
#3 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(72):
Drupal\Core\Entity\EntityManager->getBaseFieldDefinitions('commerce_store')
#4 C:\www\crypto-excel\core\lib\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem.php(118):
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenc in
C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php, line 272

But when I go to :
 C:\www\crypto-excel\modules\contrib\commerce\modules\store\src\Entity\Store.php

This file is just there.

I tried the same to goto commerce 2.7, but then same error applies.

Somebody any suggestion?

I just copied the files to the new folder

That's not how to update a Drupal 8 project - you need to use Composer.

Run composer update in your project root, and the old version of the address library (commerceguys/addressing), which is causing your current problem, will be upgraded alongside the modules.


load files to the public files dir via admin panel? I was wondering if I could get some advice on best practice on loading images directly to the public files DIR - without FTP access?

My site lives on cloud hosting, and I have no FTP access, my code pushes go through git, but my files dir is not included in the git repo.
I have to load a couple images that are not part of any content type to the public files dir, and don't know if there is a module for that, or what other best practices may be.
I can put a support ticket in if I have to, but I'd like to see if I can get around that if it's possible

Thanks!

Since my user case was only one image, I ended up putting the file in the theme folder.
for future and larger number file loads I'll be using the media module


Language selector for Apache Solr search form How can I do something like this with Apache Solr in Drupal 7?

This will be the front page of my site, and depending on the language the user chooses, he will be redirected to the language-specific subdomain of my site with the respective search results:

en.mysite.com/search/search=type+here&lang=en
es.mysite.com/search/search=type+here&lang=es
jp.mysite.com/search/search=type+here&lang=jp

Of course, only results with the user's language should be shown.

The Solr Multilingual module should do what you appear to want.

  ... provides a way to offer language-specific searches for different
  languages at once on multilingual websites ...

I'm using the not-yet-released 7x dev version with some success.  A registered-user's primary language selection, or override from a drop-down in the site-wide menu sets a $var which I carry through to the Solr search module, language-specific content, and Drupal language overlays for standard markup, etc.


Managing custom aliases on translated content We have a Drupal 8 site with translated content, and using the Pathauto module. The issue we are running into is that when we un-check the "Generate automatic URL alias" on, say, the Chinese node, because the content editors want to customize that URL, that applies to all the other languages of that node, and path aliases are no longer automatically generated.

Ideally, we would like to separately control how to generate path aliases for each language a node is using, whether automatic or custom. The Pathauto_i18n module looks like it might be helpful, but it's woefully unfinished for Drupal 8 and I don't think we have the resources to finish it on our own right now.

Is there something else I am missing?

I had to create a custom path based on a field. I was able to use hook_pathauto_pattern_alter(). If you need custom path per node then this should work. You will need to add a field. It can be a plain text field.
Pathauto conditions. Here is an example of the hook. code review for hook_pathauto_pattern_alter


Why is Drupal 7 loading the wrong .js file? There is a very strange bug that is happening on one of our client websites, and we have been unable to figure out what's going on. It's a tough one.

The Issue

In simple terms, Drupal is loading the wrong JavaScript file. We have a custom theme for the site. In the theme's .info file there is this line:

scripts[] = script/script.js

A couple of weeks ago we updated the .info file. The original .info file contained:

scripts[] = script/script-min.js

The script and script-min files are completely different files, and the server should be loading the script.js file.

Here is the behavior we are witnessing:

When we flush theme cache, Drupal reads in the .info file and loads script.js
After cron runs (every 5 minutes) Drupal will randomally decide to load script-min.js
If we check the database, the system table shows that Drupal has cached script-min.js

It should be noted that nothing in the code is loading script-min.js. We have grepped through and cannot find where Drupal would even be trying to load the file from. The script-min.js file exists in the script directory along-side the script.js file, but nowhere is it referenced.

Our Setup

Acquia Cloud Hosting w/ Git and PHP 5.3+
3 environments (dev, stage, production)
Production environment has two web servers, a balancer, varnish and MySQL. Web servers use Gluster file system to sync files
This issue does not appear to show up on our dev/stage servers

What we've tried

None of these fixes worked:

Rebuilding registry
Removing script-min.js file
Targeting web server IPs to rule out an issue with the dual-server setup
Clearing all caches
Clearing Varnish cache

Why we need help

We have been trying to diagnose this issue for nearly two weeks now, and we've run out of the obvious ideas. Our main theory right now is that their might be an issue with the two web servers, but from all of our testing, it doesn't appear to be the case... But does make the most sense.

We are aware that we could probably get the server to use the right JS file by just using drupal_add_js instead of the .info method, but we really want to know why the server is loading a file that we are not telling it to.

EDITS

These modules implement hook_cron() on the site:
acquia_agent,
acquia_spi,
ctools,
dblog,
field,
googleanalytics,
node,
scheduler,
system,
update,
xmlsitemap_node,
xmlsitemap,
xmlsitemap_engines

I have already checked, and during cron, the drupal_clear_js_cache, system_rebuild_theme_data, and drupal_theme_rebuild functions are not hit. My original assumptions had to do with those functions, but if they are not running during cron, they are probably not the issue.

We think the issue might be related to this bug report: http://drupal.org/node/1765812

Turns out the issue was with a rogue server that was hitting our site. The old web server was hitting our database and caching the old files.

It was hard to find because the two servers had the same hostname for some reason.


basic xml source migration problem I am attempting to figure out how to write a simple migration from an XML source that is located on a separate URL.

I have tried a number of different configurations for the selector and so far nothing has worked. The migration and source example are below.

migration:

id: xml_test
label: xml test importer
migration_group: p_migrate
dependencies:
  enforced:
    # List here the name of the module that provided this migration if you want
    # this config to be removed when that module is uninstalled.
    module:
      - p_migrate
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: simple_xml
  urls:
    - 'http://localhost:8888/test/source.xml'
  item_selector: /root/row
  fields:
    -
      name: title
      label: title
      selector: root/row/title
process:
  #  nid and vid commented out will allow them to autoincrement. Safe as long
  #    as nothing else is referencing them.
  #  nid: nid
  #  vid: vid
  #  type: type
  title: title

destination:
  plugin: 'entity:node'
  default_bundle: article

Source:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <row>
    <title>Lorem ipsum</title>
  </row>
  <row>
    <title>Feeds Migrate is awesome!</title>
  </row>
</root>

This is the error I am currently getting:
Invalid argument supplied for foreach() SimpleXml.php:79
Invalid argument supplied for foreach() SimpleXml.php:79

I found the problem. I needed to add the id configuration to the source:

ids:
    title:
      type: string

I also changed the selector back to: title


Adding a wrapper to contain tables using grouping field in views / display suite I'm using a table to display fields data in views 3. Within this i've got a field selected to group these items which produces a heading and then a table for each group. All good up to this point.
The issue i'm trying to solve is a way to manipulate all these tables - so i'd like to add a container, with an id to style accordingly.
I'm able to access the wrapper for the whole via https://api.drupal.org/api/views/theme%21views-view.tpl.php/7
and the template for the table which in my instance is views-bootstrap-table-plugin-style.tpl.php (which allows me to markup for each table)
What i'm looking is where the loop occurs for the grouped field so i can put a wrapper round the loop. Any suggestions?

EDIT: here is a grab of my view https://www.dropbox.com/s/a2mb85m1lo2oxr4/views-display.png
The region i am trying to wrap is below the exposed filters form.
I am using Display Suite > Views Displays to layout the view with exposed filters and views content in the left column and the map as an attachment in the right column.

EDIT: removing the view having its template defined via DS Views has given a result with markup with a .view-content wrapper around the tables (which is good) but isn't entirely helpful as i still need to split the view into two columns (which is why i was using DS).

https://www.dropbox.com/s/7aukgjkkux2xycs/views-display-no-ds.png

Whilst creating a custom template to do this by modifying an existing DS template and making a region specifically for my grouped table seems the quickest way to solve this, it certainly seems a bit messy as this will need to be done for every time i set to use grouped fields.

You can add classed to your regions within Display suite:

Add CSS classes to regions
Now that you have defined regions you can define custom CSS classes for them.

Go to Administration > Structure > Display Suite > CSS Classes (admin/structure/ds/classes)
Enter custom class names in the fields "CSS classes for regions” (one per line). You can provide a human friendly class name by using a pipe ("|”), e.g.,:

class_name_1
class_name_2|Class two
extravagant|Extravagant
subtle_emphasis|Subtle emphasis

Click "Save”
Go to Administration > Structure > Display Suite (admin/structure/ds/layout) and choose "manage display” for the desired entity.
Choose the tab "Custom classes” to assign the classes to the regions
Click the tab "Extra classes for regions”. Assign the defined classes to the regions.
Click "Save”
You can check the source code of your web page to see the new classes and start styling them in your CSS.

From Manage displays.

You can use above steps to add a class to your Display Suite region. Depending on how Views renders the View, explore the DOM to see if you need to select additional classes.


How to give ranking to content? I have created a content type named Ranking and also created a field rank this content. If I give rank 1,2,3 and so on.

Content should display according to rank, the content with rank 1 should show at first position and so on.

Any idea how to perform this?

Note: I'm using the Views module.

You can achieve your requirement by following below steps.

Create view of Ranking content type.
Add fields you want to show to your listing.
Now add sort criteria of field rank this content with selecting Ascending operation.


Is there any online tutorial explains how can I map the requested URL to actions' code in drupal 7? I'm beginner to Drupal 7. As I know, when the user request for example the URL: (www.example.com/node/123) then the Node module will responsible on responding to this request. How can I create a simple php function in my custom module so that it can respond to a specific request generated from my custom page or my custom form submission? for example: www.example.com/mymodule/blablabla?

You are looking for hook_menu(), you will need to implement this hook on your custom module to register path in drupal.

  Define menu items and page callbacks.

  This hook enables modules to register paths in order to define how URL
  requests are handled. Paths may be registered for URL handling only,
  or they can register a link to be placed in a menu (usually the
  Navigation menu). A path and its associated information is commonly
  called a "menu router item". This hook is rarely called (for example,
  when modules are enabled), and its results are cached in the database.

Since you are beginner, First I would suggest you to learn about hook system for drupal.

Checkout this answer for detailed use of hook_menu.


Issue with Workbench setting I'm creating workflow for my Drupal 7 site. On this site we installed Workbench, Workbench Access, Workbench Moderation and Workbench Media. I'm following this setting, but still having 2 issues with Workbench.

1) My drafts are not showing on "My Drafts" tab. It only show if I give the permission "Bypass content access control", which I dont want to do that.

2) I wanna hide "All Recent Content" on My Content tab. Currently, it how Logout page, and Thank you for creting an account page, which I dont wanna show these too.

Nobody can give you this answer, check your permissions against what is typical in the documentation page you listed. Have you checked this page selecting the given Role you want to examine:

  If non-administrative users encounter access denied (403) errors or
  fail to see notifications about moderation states, the "Check
  permissions" tab can help you determine what permissions are missing.
  Visit:

  Admin > Configuration > Workbench > Workbench Moderation > Check
  Permissions

The My Content page in Workbench Moderation is a View. You can customize its filters or conditions to meet your needs -- but be careful it's provided by the Workbench module so if you update the module you will likely loose your changes to the View unless you implement your changes using hook_views_default_alter.


How to use Services to create new node with Entity Reference field? I am able to create a new node with body field, but when I try to set the value for my entity reference field, I get

  {"form_errors":{"field_drawing][und":"An illegal choice has been
  detected. Please contact the site administrator."}}

I am sending a structure similar to the working body field, but with 'target_id' instead of 'value':

'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 123
        }
    ]
}

123 is the nid of an existing node. What would cause an 'illegal choice' response?

I figured out the solution from comments on this issue.

To set the field via services, you can set the field's widget type to "autocomplete" and instead of just sending the nid, send a string with the title of the referenced node, a space, and the nid inside parenthesis.

'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 'Title of Node (123)'
        }
    ]
}


Ajax error on node form edit page I'm trying to ajaxify part of node form. I have a hook_form_alter that adds extra ajax property to a widget of select field. The problem I'm facing is the callback method / function, which is not fired when change is happening.

So this is my form_alter code which resides in accountancy_invoice/accountancy_invoice.module:

function accountancy_invoice_form_node_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_invoice_form') {

    $form['accommodation'] = array(
      '#type' => 'container',
      '#prefix' => '
Dave
',
      '#attributes' => array(
        'class' => 'user-full-name',
      ),
    );

    $form['field_invoice_customer']['widget']['#ajax'] = array(
      'callback' => 'Drupal\accountancy_invoice\Form\AjaxifyForm::customerValues',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
      )
    );

  }
}

This is my AjaxifyForm class which resides in accountancy_invoice/src/Form/AjaxifyForm.php:

namespace Drupal\accountancy_invoice\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;

class AjaxifyForm {
  public static function customerValues(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#user-full-name', 'Bryan'));
    $title = "Example Dialog";
    $content = "foo bar content";
    $options = array();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
    return $response;
  }
}

It doesn't really matter at the moment what this ajax should do. For testing purposes I just want to change name from Dave to Bryan in #user-full-name and display sample dialog box.

In the console, each time ajax is triggered I got an error:

This is complete error message (it's trimmed in the screenshot):
↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /node/add/invoice?ajax_form=1↵StatusText: OK↵ResponseText: TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given, called in /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 441 in Drupal\Core\Form\FormState->setError() (line 1093 of /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Form/FormState.php).

This is a generic issue that will show for various reasons, often because of a bug in the code handling the server response. Look in your server logs for more information as to what has happened.


When to use different vocabularies vs. one big hierarchical vocabulary with parent terms Context: I'm developing a website (a directory of things) with a content type "product" that relies on an extensive list with actually two levels: say "productname" and "productvariation". In real life this could be "fruits" or "beer" for the first level "productname" and then "strawberrys", "apples", "peaches" or "stout", "wheat" or "lager" for the second level "productvariation". There won't be a third level as all variations will go on that second level even if they are a subcategory of one variation. It's important that the content type can hold unlimited values of "productnames" (first level) and subsequently unlimited values of "variations" from the selected "productnames".

I want easy editing for the people who will maintain this site. I'm thinking conditional field architecture: User selects one ore more products (radiobuttons or checkboxes)and then the appropriate (select) lists of variations appear for further selecting.

Right now I'm thinking the first level as different vocabs but I don't know if this is the right way?

I haven't found a way to display the vocabs as a list (like a term reference field) so I'm doubting my draft. Is the above a misconception and i should use just one vocabulary?

Thanks in advance!

In the general term you should think on your requisites for these three things, and the pros/cons of the options provided by Drupal core/contrib to accomplish them:

How to create and maintain the hierarchy of terms
How to pick terms from the hierarchy when creating/editing products
How to filter products with a criteria based on this hierarchy (views or programatically filtering)

The way you decide to go for the 1st point (one hierarchical vobcabulary or two related vocabularies) determines the options available to solve the other two points.

When using one hierarchical vocabulary, the most important thing IMO is to preserve the lineage: when classifying a product as strawberry, also classify it as a fruit. This is very helpful to cleanly address the 3rd point without frustration, neither with inelegant approaches.
Drupal core doesn't provide a way to preserve the lineage when creating entities. There're several modules out there that ensures it. The most powerful, Hierarchical Select.

Also, editing the hierarchy of terms via the core interface is a bad UX when you go above a few dozens of terms. To improve this there're modules like Taxonomy Manager.

Lastly, eventually you may face scale problems if the vocabulary is huge.

OTOH, using two vocabularies brings other pros/cons.

On the pros side:

Configuring different fields in each of the vocabularies. For example, in the first level vocabulary (usually called family) a boolean field indicating whether the product is perishable, and a image field in the second level vocabulary for a photo of the variation.
Preserving the lineage is not an issue, since you are selecting values in two different field/widgets that you enforce to be required.

On the cons:

You're on your own with two independent vocabularies/fields that needs to be dependant somehow. You may want to create entity reference fields from parent to child, or the other side. You also need a dependant selector widget, eventually you want this widget to work also in views exposed filters,...

The Reference field option limit is great for this setup. It is a bit hard to get how it works, and it has some issues (specially I remember problems with i18n) but it does it pretty nice.

In conclusion:

None of both approaches works 100% out of the box
In the one-vocab approach you want to solve the lineage problem
Two vocabularies is more versatile
Two vocabularies is harder to setup


Sort the products by SKU when seeing order details I have an Ubercart commerce website in Drupal 7.

I'm trying to sort the products listed inside a given completed order by the SKU value.

This is the link: /admin/store/orders/1 or /admin/store/orders/300

I tried to edit uc-order--admin.tpl.php but it did not work. I tried everything but nothing works. Maybe I'm doing it wrong.

I'm new to theming and templating so the code I wrote or the place I did might have been wrong also.

Any ideas on how to sort the products by the values in the SKU field in an order that was already placed?

Inside uc-order--admin.tpl.php I added the following code:

$order_output = array();
$order_info = new stdClass();
$order_id = '';

$array_key_modifier = 0;
foreach ($products as $product) {
    // organize products by sku
    // make an array with stuff I need
    // sku => array(item,model,price,quantity,subtotal)
    // then sort keys by alphabetical value, output to table
    $array_key = '';
    if (!isset($order_output[$product->model])) {
        $array_key = $product->model;
    } else {
        $array_key = $product->model . $array_key_modifier;
        $array_key_modifier++;
    }

    $order_output[$array_key] = array("title" => $product->title, "model" => $product->model,
        "price" => $product->price, "quantity" => $product->qty, "subtotal" => $product->total_price);
    //  "price");
    $order_info = $product->order; // each product has complete built in order info. Maintain a reference to it
    $order_id = $product->order_id;

    if (!empty($product->data['attributes'])):
        $order_output[$array_key]["attributes"] = $product->data['attributes'];
    endif;
}

ksort($order_output);

uc-order--admin.tpl.php is the "default admin notification template". In other words, the email sent to admins to notify them about a new order.

You can change the order of the products listed in the order view page by implementing hook_tapir_table_alter()

I have not used this code in production, and do not know what effect it will have on other pages/processes, so test it thoroughly:

function YOUR_MODULE_NAME_tapir_table_alter(&$table, $table_id) {
  if ($table_id == 'uc_op_products_view_table') {
    $sorted_rows = array();
    foreach ($table['#rows'] as $key => $row) {
      if (!empty($row['#entity']->model)) {
        $sku = $row['#entity']->model;
        $new_key = $sku . '_' . $key;
      }
      else {
        $new_key = $key;
      }
      $sorted_rows[$new_key] = $row;
    }
    if ($sorted_rows && ksort($sorted_rows)) {
      $table['#rows'] = $sorted_rows;
    }
  }
}


Write complex access control in a reusable way We deal with nodes representing humans with two important properties: mother and father.

Your parents as well as your aunts and uncles should get extra permissions, like to see you in a certain view mode, or to see your private images.

Where should I place this complex access control in a way that I can easily call it in several controllers and hooks?

Is there a name for the kind of feature I'm going to program?

If there's no better idea, I would go with a validation. We could put the access control in a validator that we use like this:

$errors = $family_access_validator->validate($node);
if (count($errors) > 0) {
    throw new AccessDeniedHttpException();
}

However, I'm not sure whether this is the correct approach. When we use validation, we are always interested in the message why the data is rejected. Here, we are only interested in OK or not OK.

For access control on routes, you can write a service which implements AccessInterface.  At its simplest, this is just a class placed in a module's src/Access folder with a single method public function access(AccountInterface $account), returning a flavour of AccessResult.  Then you simply register your class in the module's services.yml, annotate the route to use that access checker and Drupal will do the rest.  Relevant documentation

The documentation suggests that if the route being access-checked has an upcasted parameter like {node}, then you can add $node to function's arguments - i.e. public function access(AccountInterface $account, Node $node) and it will be automatically supplied.  I haven't actually tried that part myself though.  Assuming it works, you can then access the node's fields as normal in order to compare the entity ids of the mother/father fields with the user to which the $account belongs.

I'm not sure if there are similar ways to automatically invoke this same access check for displaying entities with different view modes, but at the end of the day it is just a service like any other, so you could always request it from the container or inject it into whatever other controllers / services / hooks you need.  In these contexts you will of course have to 'manually' supply the current user $account and relevant $node to check.


How to Add Block with Page on the same view? Initially, I have displayed the contents in the Block on View. Now I am trying to display Taxonomy Term in the Page ,with Block on the same view.

There is a ADD button in the View, if I add the page for Taxonomy Term in that view, It's showing the same content information for the Page.

How do I add Taxonomy Term for Page and Content for Block on the same View.

Please anyone help me how to sort out this problem.

In Views, click on +Add button and select Attachment. (This part is optional, if you have a view block already created you can just attach that).

Make your attachment look like your block.

Now go to your page view in the FOOTER add Global: View area and select your attachment or block.


Setting up permissions My cars data is as the following:

id    make        no         parent
1     bmw         NULL          0
2     bmw         bmw987        1
3     bmw         bmw654        1
4     ferrari     NULL          0
5     ferrari     ferrari987    4
6     ferrari     ferrari654    4

(Note: I am using two tables for above data. This is just to get an idea of data.)

I am creating permissions to book cars as:

Book bmw; the user will have permission to book bmw987 and bmw654 means
children of BMW
book bmw987; the user will have permission to book bmw9987 only.
Book ferrari; the user will have permission to book all Ferrari cars.

In my car booking portal, I have 100's of cars and many makes. When I used hook_permission() and loop through all available cars to create book permission on each car, it pollutes my permission page (admin/people/permission) and believe me handling these many permission will faint Admin.

Is there any other alternative to handle such huge permission?

I think you should try something like this

function mymodule_menu() {
  $items['example/car/%'] = array(
    'title' => 'Example RSS feed',
    'page callback' => 'example_feed',
    'access arguments' => 'mymodule_abc_view',
    'type' => MENU_CALLBACK,
    );
    return $items;
}

function mymodule_abc_view() {
    return 'TRUE after checking something';
}

your URL should pass the car id or something to check the permission.


Add comma in between the Tags Display in Drupal 7 Can any one help me how to add comma inbetween the tags in drupal 7.

I have inspect the code  for the following tags

Tags: Test bha

the code for this is

Tags:&nbsp;

                Test
                bha

I have used used the following code to add the comma inbetween the tags

              function fold__field_tags($variables) {

                   $output = '';

              // Subtract 1 from count to match $delta which starts at 0
               $count = (count($variables['items']) - 1);

              // Render the label, if it's not hidden.
              if (!$variables['label_hidden']) {
             $output .= '
' . $variables['label'] . ':&nbsp;
';
                 }

           // Render the items.
          $output .= '
';
          foreach ($variables['items'] as $delta => $item) {
          $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
          $output .= '
' . drupal_render($item) . '
';
         // If this is not the last item, print a comma and space
         if($delta < $count) {
          $output .= ', ';
         }
         }
       $output .= '
';

    // Render the top-level DIV.
      $output = '
' . $output . '
';

      return $output;

    }

Can Anyone help me where i made a mistake.

For anyone who needs to do this in the future:

div.field-name-field-tags div.field-items div:after {
  content: ", ";
}

div.field-name-field-tags div.field-items div:last-child:after {
  content: "";
}


change the page title of user page the html title of the user pages are the user id and the website name. Is there a way to instead change the user id to the user name?

ie.

[user id] | website name >>> [user: name] | website name

For a no-code solution try the page title module, which allows you to override page titles all over the site, with the use of tokens to improve flexibility.


When creating a content type programmatically, is there a way to add tuples (e.g. pairs) of fields? In Drupal 7, I'd like to create a Person content type. A person may have multiple profiles - an administrator should be able to select which profile will be considered the primary one. So, that means that I need a tuple consisting of:

A textarea, for the profile text
A checkbox, indicating that this is the primary profile
A textbox, for naming this particular profile

I need functionality to behave like that of any of the lists: I can click "Add another Item", and a set of all three of these fields will appear.

I have a vague idea of how this can be executed, but it involves using the form API to add fields before the form renders each time, as well as the necessary AJAX behavior. This seems a bit overcomplicated, since this would also necessitate creating an additional DB table to hold these tacked-on fields.

Is there a relatively simple way of doing this solely through hook_install()?

The profile2 might fit your bill:

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)


Join a user field to a profile2 field in a view What I am trying to do is to join fields that are a user type (e.g. image, and username) to Profile2 fields.
In the example I want to join:

teacher name (teacher profile2)
teacher date (teacher profile2)
username (drupal registration)

What I mean by Drupal registration is the fields used to register an account.

If you have to the display profile fields using the Views module, then follow these steps:

Add "User:profile" under "RELATIONSHIPS".
Select "Profile types" in which type you have your fields to be display (teacher name, teacher date), as you may have more than one profile types.
You can add the selected profile fields under "Fields".


Drush MAMP not working I'm running with a big problem for hours now and it's driving me crazy, maybe one of you already know the answer.

Drush seems to not want to work on my OSX (10.8.5) with MAMP (3.0.5). When I execute $ drush pmi I get the following output:

Command pm-info needs a higher bootstrap level to run - you will need[error]
to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'pmi' could not be executed.                       [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  7.28
 Site URI              :  http://default
 Database driver       :  mysql
 Database hostname     :  127.0.0.1
 Database username     :  root
 Database name         :  db_name
 PHP executable        :  /Applications/MAMP/bin/php/php5.5.10/bin/
                          php
 PHP configuration     :  /Applications/MAMP/bin/php/php5.5.10/conf
                          /php.ini
 PHP OS                :  Darwin
 Drush version         :  7.0-dev
 Drush temp            :  /tmp
 directory
 Drush configuration   :
 Drush alias files     :
 Drupal root           :  /Applications/MAMP/htdocs/drupal
 Site path             :  sites/default

I'm running drush in the drupal folder.

I'm using 127.0.0.1 instead of localhost in my settings.php.

I have the following setup in my ~/.bash_profile:

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php5.5.10/bin:$PATH"
export PATH
export DRUSH_PHP="/Applications/MAMP/bin/php/php5.5.10/bin/php"
export PATH=/usr/local/bin:$PATH

I've also created a symbolic link to mysql as follows:

$ sudo mkdir /var/mysql
$ sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

If I run:

$ php -i | grep php.ini

I get:

Configuration File (php.ini) Path => /Applications/MAMP/bin/php/php5.5.10/conf
Loaded Configuration File => /Applications/MAMP/bin/php/php5.5.10/conf/php.ini

Which means I'm using the same PHP version either in my apache server than in drush.

Now, I have no clue whatsoever on why drush is not properly working. Maybe one of you have an answer for this and hopefully for all of us who might have encountered this problem.

Thanks in advance!

What url do you use to access this Drupal site? I notice that drush reports Site URI as http://default. This is not necessarily a problem (I have multiple working sites running on a MAMP server, and this is what they report too), but what do you get if you re-run the command with the --uri flag?

drush pmi --url=example.local

If that does make things work, you can create a drush alias file as shown below and use drush @example pmi to run commands:

$aliases['dev'] = array(
  'root' => '/path/to/example.local',
  'uri' => 'example.local',
);

For the record though, I've never needed to do this when using MAMP--but I do create virtual host records for all local development sites so that may be a factor.


Is it possible to make site_email an i18n variable? We have multilingual site pointing to 2 domain according to site language.

  www.example.com (Swedish)

  www.other.com (English)

Now when some user post content from Swedish domain we want to send notification of content submission to user from info@example.com and if from English domain then from info@other.com

Is that possible ?

I have attempted like below in custom module whose weight is 1000:

function custom_overrides_init() {

  global $language;

  if($language->language == "sv"){
    variable_set('site_mail', "info@example.com");
  }else if($language->language == "en"){
    variable_set('site_mail', "info@other.com");
  }
}

When I see in maillog it shows correct from email addresse but its not working and use same email address which is set on site configuration.

i18n_variable also does not provide site_email as variable.

Please suggest !

Your current solution is actually a very bad practice, as you will be rebuilding the variable cache on every page request, which is a big hit.

You can set the site_mail variable as translatable by installing the Variable module (http://dgo.to/variable), then implementing hook_variable_info() and declaring the site_mail variable.

function hook_variable()
{
  $variables['site_mail'] = array
  (
    'title' => t('Site Email'),
    'description' => t('The email addresses site mails are sent from'),
    'type' => 'string',
  );

  return $variables;
}

You then need to go to Admin -> Configuration -> Regional and Language -> Mutilingual settings -> Variables, and set site_mail as being translatable. You will then be able to visit the site information page and set a different value for the site mail in each language.


CKEditor doesn't work after updating I've updated a drupal website to the latest 7.x version, and CKEditor stopped working. I had it originally getting //cdn.ckeditor.com/4.5.4/full-all, I've updated to //cdn.ckeditor.com/4.13.0/full but no luck. I've tried to remove and reinstall the module, clear the website and browser caches, etc. I've also uploaded the version and used it from the local disk rather than the CDN (in case there were network issues with the CDN site, but I didn't see any errors).

I'm short of ideas. Has anyone experienced this and has some more ideas for me to try?

Should anyone be interested, updating to the latest core (7.69) seems to have restored the CKEditor functionality.


Image not showing in page footer. I need to display an image in the page footer using  tag. In my page.tpl.php I have  the following block.

<?php print t('Copyright'); ?> &copy; <?php echo date("Y"); ?>

I can`t use print $logo since I can use another image for the logo.

You need to call the current theme URL and concatenate it with your alternative logo

    <img src="<?php print drupal_get_path('theme', 'THEME_NAME'); ?>/images/logo.png">

<?php print t('Copyright'); ?> &copy; <?php echo date("Y"); ?>


Event subscription for EntityTypeEvents So I'm trying to get an event subscriber working for EntityTypeEvents and I can't figure out why it's not firing.

This is a general outline of the code:

namespace Drupal\subscriber_class_module;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Entity\EntityTypeEvents;
use Drupal\Core\Entity\EntityTypeEvent;

class SubscriberClassModuleSubscribesToEntityTypeEvents implements EventSubscriberInterface {

    public function onCreate(EntityTypeEvent $event)  {
          //Do things on creation
    }
    public function onUpdate(EntityTypeEvent $event)  {
          //Do things on update
    }
    public function onDelete(EntityTypeEvent $event)  {
          //Do things on delete
    }
    static function getSubscribedEvents() {
         $events = [];

         $events[EntityTypeEvents::CREATE][] = array('onCreate', 100);
         $events[EntityTypeEvents::UPDATE][] = array('onUpdate', 100);
         $events[EntityTypeEvents::DELETE][] = array('onDelete', 100);
         return $events;
    }
}

Added class declaration and namespacing.  I should note that the same class that I am using has no probablem firing on kernel events, I'm just wondering if there is something special about entity events.

i already have the same issue, you have to implement this class to EntityTypeListenerInterface and use the trait EntityTypeEventSubscriberTrait

class SubscriberClassModuleSubscribesToEntityTypeEvents implements EntityTypeListenerInterface, EventSubscriberInterface{

use EntityTypeEventSubscriberTrait;

public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
}

public function onCreate(EntityTypeEvent $event)  {
      //Do things on creation
}
public function onUpdate(EntityTypeEvent $event)  {
      //Do things on update
}
public function onDelete(EntityTypeEvent $event)  {
      //Do things on delete
}

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
    return static::getEntityTypeEvents();
}

}

and you get to load entity manager in your module.service.yml declaration
    arguments: ['@entity.manager']


How can I format a cell to not wrap in a themed table with the Antonelli/Bartik theme? I want to limit the text in a cell so it truncates whatever would be wrap to the next line. However, I want there to be a minimum width, so if a user is viewing the table on a phone oriented vertically it won't just show 1 or 2 characters because of the narrow width.

one way would be setting the min-width in the css to some value.
this would ensure no matter what device it is being viewed it will set this minimum width.
google up for sum css trick.


How can I embed an Editor just like those in StackExchange Q&A in Drupal 7? I am new to Drupal.

I want to embed an editor in my content, body nodes so that I can do different editing when I add a new content. (i.e., bold , hyperlink, list) etc.

Is it possible to do that? Any module is available?

Yes, there are quite a few.  One of the most popular editor modules is WYSIWYG which allows you to choose which JavaScript library you want to use, or there are more specific modules such as the CKEditor module


How can i render webform on custom url with custom html in drupal 8 Basically I am using sample code which shown in below.

public function test(){

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('contact_us');
$webform = $webform->getSubmissionForm();
$dd= drupal_render($webform);

return array(
'#type'=> 'markup',
'#markup' => $dd.'

test

'

);

}

I'm using return type markup then form is not rendering properly.So any help available. Thank you all in advance.

This should work if you return $webform; without rendering. Or use the webform render element, then you don't need to load the form:

return [
  'test1' => ['#markup' => '

test1

'],
  'form' => [
    '#type' => 'webform',
    '#webform' => 'webform_id',
  ],
  'test2' => ['#markup' => '

test2

'],
];


Enable ck editor for textarea I have a custom form and a textarea in it as follows :

$form['fieldset']['email_template'] = array('#type' => 'textarea',
    '#title' => t('E-mail template content'),
    '#default_value' => '',
    '#description' => t('A valid template for email trigger.<b> Please type ":" for variable suggestions</b>'),
    '#required' => TRUE,
    '#cols' => 60,
    '#resizable' => TRUE,
    '#rows' => 5,
    //'#type' => 'text_format',
    //'#base_type' => 'textarea',
  );

When i installed the ckeditor module and enabled it , the following text appears under textarea ,

Then i gave sky:notification/addTemplate.edit-email-template in the visibility settings Fields to exclude/include: after enabling the include option in Use inclusion or exclusion mode:

Try adding '#wysiwyg' => TRUE,

Also i think you need to keep '#type' => 'text_format', instead of textarea.


Custom Entity Administration Pages I am trying to create a custom entity with user manageable bundles with very little luck.

I have been using a couple of other modules that do this very successfully like field collection and the latest version of the invite module.

Very simply, there is an event entity which has multiple types. The user should be able to create and manage these multiple types - similar to how users can create and manage multiple field collections.

My entity info is as follows:

function enf_entity_info() {
  $return = array(
    'enf_event' => array(
      'label' => t('ENF Event'),
      'entity class' => 'ENFEvent',  // defined - simple
      'controller class' => 'ENFEventController', // defined - simple
      'base table' => 'enf_event', // defined
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'event_id',
        'bundle' => 'event_type',
      ),
      'bundle keys' => array(
        'bundle' => 'event_type',
      ),
      'view modes' => array(      // I don't expect to need these
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'bundles' => array(),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'enf',
      'access callback' => 'enf_event_access',  // simply returns TRUE
      'metadata controller class' => 'EntityDefaultMetadataController',
    ),
  );

  $return['enf_event_type'] = array(
    'label' => t('ENF Event Type'),
    'entity class' => 'ENFEventType', // defined - simple
    'controller class' => 'ENFEventTypeController', // defined - simple
    'base table' => 'enf_event_type', // defined
    'fieldable' => FALSE,
    'bundle of' => 'enf_event',
    'exportable' => TRUE,
    'entity keys' => array(
      'id' => 'type_id',
      'name' => 'event_type',
      'label' => 'label',
    ),
    'module' => 'enf',
    // Enable the entity API's admin UI.
    'admin ui' => array(
      'path' => 'admin/structure/enf-event-types',
      'file' => 'includes/enf.admin.inc', // includes the form functions
      //'controller class' => 'ENFEventTypeUIController',
    ),
    'access callback' => 'enf_event_type_access',
  );
  return $return;
}

the bundles are then added in in the alter

/**
 * Implements hook_entity_info_alter().
 */
function enf_entity_info_alter(&$entity_info) {
  foreach (enf_get_types() as $type => $info) {
    $entity_info['enf_event']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/enf-event-types/manage/%event_type',
        'real path' => 'admin/structure/enf-event-types/manage/' . $type,
        'bundle argument' => 5,
      ),
    );
  }
}

The admin page seems to work - however, there are manage fields and manage display menu options on the page itself. These go to a

/admin/structure/enf-event-types/manage/%25event_type/fields

and
    /admin/structure/enf-event-types/manage/%25event_type/display

and there are notifications displayed and saving and such errors out.

It is possible to add types - the form is displayed and creates a new type on submit.

However, when clicking through the fields or display links, a 404 comes back

/admin/structure/enf-event-types/manage/test/fields
/admin/structure/enf-event-types/manage/test/display

It seems like it should really be very simple to do this but something is missing.

Any assistance greatly appreciated...

A little bit late, however, hope this will be of use.

When defining an admin path for each bundle, path provides the path that should be used in hook_menu for the Field UI´s pages. For resolving the '%event_type' placeholder in admin paths, you need to provide a loader function that, in your case, should be 'event_type_load' and it must return a single type object.

/**
 * Event type loader function.
 *
 * param $type string
 *  The name of the event type as it appears in the admin Path placeholder
 *  of a bundle. By convention, all Drupal paths use dashes instead of underscores.
 *
 * return $type stdClass object
 *
 */
function event_type_load($type) {
        $types = enf_get_types();
        // We need to replace dashes that may appear in $type with underscores.
        // By convention, bundle names needs to use underscores, not dashes.
        $type = str_replace('-', '_', $type);
        return isset($types[$type]) ? $types[$type] : FALSE;
}

You may need to modify as well the line that reads,

'real path' => 'admin/structure/enf-event-types/manage/' . $type,

and replace it with the following one:

'real path' => 'admin/structure/enf-event-types/manage/' . str_replace('_', '-', $type),

NOTE: to be consistent with the name of the module that defines your custom entity, you may want to rename the admin path placeholder '%event_type' to be '%enf_event_type', and thus the loader function would be 'enf_event_type_load'.


WHERE MySQL clause not working in Drupal 6 I am writing a Drupal Module and I have encountered a problem. This is my code:

$query3 = db_query("SELECT nid FROM {node} WHERE uid=19");
var_dump(db_result($query3));

It currently returns: bool(false)

Now when I run this query in phpmyadmin it returns the desired nid (47) - no problem.

What am I doing wrong?

Try

$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", 19);

this is the proper way to handle variables in the db_query, as it prevents sql injection.

//grab the current user
global $user;
$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", $user->uid);


How can I print a variable in the node template? How can I print a variable in the node template?

For example, if it's a variable of content, we can print it with the following code.

{{ content.field_name }}

If I have a {{ counter }} variable, how do I display it with Twig?

If it's a variable that came from a hook_preprocess_node, you can just print it in your twig template as you wrote it in your example:

{{ variable_name }}


Views Bulk Operations Checkboxes check on click I do search for a specific option in bulk operations. For now, when I click somewhere in my row, the checkbox for the bulk operation gets selected, but I want a user to directly click on the checkbox. If he clicks somewhere in the row, it shouldn't select the row for bulk-operations. Any chance to do that without hacking the core?

In short: only a direct click on the checkbox should select the row for bulk operations.

This is due to the JQuery in views_bulk_operation.js :

    // Set up the ability to click anywhere on the row to select it.
$('.views-table tbody tr', form).click(function(event) {
  if (event.target.tagName.toLowerCase() != 'input' && event.target.tagName.toLowerCase() != 'a') {
    $('input[id^="edit-views-bulk-operations"]:not(:disabled)', this).each(function() {
      var checked = this.checked;
      // trigger() toggles the checkmark *after* the event is set,
      // whereas manually clicking the checkbox toggles it *beforehand*.
      // that's why we manually set the checkmark first, then trigger the
      // event (so that listeners get notified), then re-set the checkmark
      // which the trigger will have toggled. yuck!
      this.checked = !checked;
      $(this).trigger('click');
      this.checked = !checked;
    });
  }
});

Commenting them will solve it but instead of hacking the core. In your custom js file add something like:

$('.views-table tbody tr').off();

This will disable all event handlers!!


How to use Drupal Captcha in Custom form? Creating nodes can take a long time. That is why for one specific part of my site, I have created my own custom form. The problem is, I want to use the captcha plugin so I don't have to get another separate module for that.

How can I use the Captcha module PROGRAMATICALLY so that I don't need a separate libary?

From looking at the code in the Captcha module, it looks like Captcha defines a new form element.

So an example would look like:

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

Where captcha/Math is the module that provides a type of captcha, followed by the type of captcha to use.


How to set one path alias as the canonical alias? I use the Tags taxonomy on several of my content types. In order to assist with a site-wide filtering mechanism, I'd like to be able to create additional path aliases for each piece of content.

For example, if my tags include baseball, football, soccer, and I post a news Article, I would like to have a primary path alias to that node using:

/news/my-article-1

but I'd also like to create a path alias to it for:

/baseball/news/my-article-1

/football/news/my-article-1

/soccer/news/my-article-1

However, when I create these programmatically, drupal seems to choose one of them, arbitrarily, to be the canonical alias. Is there any way I can control which alias is the canonical one?

Metatg seems to be your answer:

Currently supported meta tags:

Abstract

Author

Canonical URL

Copyright

Description

Dublin Core (sub-module)

Generator

Image source

Keywords

News Keywords

Open Graph Protocol (sub-module)

Original Source

Publisher URL

Robots

Shortlink URL

Title (e.g. Page titles)

Twitter Cards (sub-module)


Migrate sub_process plugin is not working There are a couple of questions that are closely related to this on this forum that I have reviewed several times.  None of them seem to address the issue specifically.

I have a target field (with subfields) that is set to unlimited.

The Source that I'm "migrating" from is JSON. The Target, in this case, is an address field on a node.

To simplify and debug the migration. I created a constant as a source for the values that I want to assign to field_locations/country_code.

The code in the migration configuration YAML is

source:
  constants:
    title_suffix: ' (Imported from remote file)'
    country: 'GB'
    countries:
      -
        country: US
      -
        country: CA
....

process:
  field_locations:
      plugin: sub_process
      source:
        - constants/countries
      process:
        country_code: country

If I replace the implementation of the sub_process plugin and use get, I update the target field (subfield actually) with:

field_locations/country_code: constants/country

The destination row is updated perfectly - though of course I can only et

For reference: This is what the entity should look like with repeating values set. How do I get that to work with this migration? I'm guessing there is something pretty simple I'm missing

OK - I spent far more time than I care admit debugging this one. (doesn't help that PHPStorm is very unfriendly when it comes to stepping through a migration (e.g. I have not found a way to do it). Hope this saves someone from the frustration I had.

Problem one: Source was not formatted correctly. It MUST follow the following structure:

$source = [
  'countries' => [
    0 => [
      'country' => 'US',
    ],
    1 => [
      'country' => 'CA',
    ],
  ],
];

The YAML for that is:

  constants:
    countries:
      - country: 'US'
      - country: 'CA'

Problem two: The implementation of sub_process was a little off. And a little off is like being on the wrong planet. It should like this

  field_locations:
    plugin: sub_process
    source: constants/countries
    process:
      country_code: country

One thing that is not obvious (and would never be if you were actually "migrating" from D7 to D8 for example, is the source.

Here, I am not actually migrating. It is an import from JSON. And, as it turns out, importing JSON can be a little unpredictable.
The final "gotcha" was that the key "country" had to relate to the source (which it usually does).  I had tried to slap in a different constant. (bad idea - though it could be done if that is really what is wanted.


Execute PHP on every page? I'm writing a custom module for Drupal 6, and I need to execute some PHP no matter which page the user accesses.

I see that hook_init is not run on cached pages, so that's a no-go. hook_boot doesn't work, either, because it happens too early in the page request to let me use some functions I need.

So I was thinking about specifying a block using hook_block, but that hook just makes me pull my hair out:

function test_block($op='list', $delta=0, $edit=array()) {
  switch ($op) {
  case 'list':
    $block['test_block']['info'] = t('Test block');
    return $block;
  case 'view':
    $block = array();
    switch ($delta) {
    case 'test_block':
      $block_content = '<?php echo \'WTF?\'; ?>';
      $block['subject'] = NULL;
      $block['content'] = $block_content;
      break;
    }
    return $block;
  }
}

This renders as:

Obviously, that's not what I'm looking for, either. Why does the PHP in that block not render correctly? Even if I end up using something other than a block to solve my problem, this issue really sparks my curiosity.

If I can't use hook_block, how do I get some PHP to run on every page? I need access to the $user global and to the drupal_goto() function.

What is wrong with your code is that the code that outputs the content of the block needs to be executed, such as:

$block['content'] = test_get_block_content();

This code makes sense if the code needs to output something in the page; if the code that needs to be executed doesn't need to output anything in the page, then hook_exit() is always executed, even on cached pages. The documentation for that hook reports the following text:

  Only use this hook if your code must run even for cached page views. If you have code which must run once on all non cached pages, use hook_init() instead.

As for redirecting a user, you can look at what the Redirect module does to redirect a user. The purpose of the module is to redirect a user basing on the currently visited page, and on settings decided from an administrator user. The code that redirects the user is contained in this function, which is the implementation of hook_init():

/**
 * Implements hook_init().
 */
function redirect_init() {
  if (!redirect_can_redirect()) {
    return;
  }

  $current_path = current_path();
  $current_langcode = $GLOBALS['language']->language;
  $current_query = drupal_get_query_parameters();
  if ($redirect = redirect_load_by_source($current_path, $current_langcode, $current_query)) {
    redirect_redirect($redirect);
  }
  // …
}

The redirect_redirect() function is a wrapper for redirect_page_cache_clear().

function redirect_page_cache_clear($redirect = NULL) {
  if (!variable_get('redirect_page_cache', 0)) {
    return;
  }

  if (isset($redirect)) {
    $path = url($redirect->source, array('absolute' => TRUE));
    // Use a wildcard to catch paths with query strings.
    cache_clear_all($path, 'cache_page', TRUE);
  }
  else {
    // Clear the entire page cache.
    cache_clear_all('*', 'cache_page', TRUE);
  }
}

If you would implement a way to redirect a user through drupal_goto(), you should consider implementing hook_init() in a similar way.


Using confirm_form to lead into a batch process How can you use confirm_form from hook_menu and present the user with a Confirm action page, when clicked, goes and sets a Batch process?

I always do this with a simple submit handler on the form...works a treat:

function my_confirm_form($form, &$form_state) {
  return confirm_form($form, 'Are you sure you want to run this batch?');
}

function my_confirm_form_submit($form, &$form_state) {
  $batch = my_batch_function();
  batch_set($batch);
}


Composer shows "nothing to update" but there is a new version of the module I am managing a Drupal 8 site in Composer.  Commerce 2.0 was just released; I currently have 2.0-rc2 installed on my site.
This is my composer.json
"drupal/commerce": "^2.0@RC",

"minimum-stability": "dev",
"prefer-stable": true,

To update, I ran composer update drupal/commerce --with-dependencies, which gave me this result:
Gathering patches for root package.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files
Warning: Ambiguous class resolution, "Drupal\Component\Utility\Random" was found in both "$baseDir . '/web/core/lib/Drupal/Component/Utility/Random.php" and "/mnt/c/Users/x/d/mysite/vendor/drupal/drupal-driver/src/Drupal/Component/Utility/Random.php", the first will be used.
Removing packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
Creating packages services cache file:
/mnt/c/Users/x/d/mysite/vendor/drupal/console/extend.console.uninstall.services.yml
> DrupalProject\composer\ScriptHandler::createRequiredFiles

So Commerce does not get updated to 2.0 (I already updated all the dependencies to their latest versions.)
I thought it might be a caching issue so I ran composer clearcache and then attempted to update commerce again, but I got the same result (nothing to update).
I thought it might be an issue with the composer module list being out of date, but Commerce 2.0 was released more than 48 hours ago.  So what can I do to get composer working in this case?
EDIT
My repo is based on the Drops 8 Composer repo from Pantheon, which is in turn based on drupal-composer/drupal-project.
Deleting the /vendor directory and running composer update gives me this error:
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Changing composer.json to "drupal/core": "^8.4@RC" "symfony/css-selector": "~3.2" also results in the same error.
But, running composer install or running composer update drupal/modulename allows me to install the site and update individual modules (except Commerce) without any problem.

Thanks to @Neograph734 for pointing me in the right direction.

I needed to require Drupal 8.4-rc2 and drush 9, and then Commerce 2 arrived automatically.

Drush 9 appears to be a requirement for the 8.4 core update.


Adding static images to theme In page.tpl.php, I add some static images by using :

$bolo = path_to_theme() . '/images/bolo.gif';
....
<img src="<?php print $bolo ?>" alt="bolo" width="71" height="125">

How I can do the same by using a preprocess function (like theme_image() for example) in template.php and calling the (image)variable in page.tpl.php ?
It seems easy, but I can't perform it.
Thanks

Bolo

You can to use hook_prorocess_page for this.

In the theme's template.php file, add the following function (make sure it doesn't exist. if so, append the function content to the existing file)

function THEMENAME_preprocess_page(&$vars) {
  $image = ... // Generate your image's img tag here, optionally wrap with some DIVs.
  $vars['my_image'] = $image;
}

Now, you can access this variable as $my_image.


How to overwrite Paragraphs Item on subpages? I am using a couple of Drupal Paragraphs Items in full-size edge-to-edge view with Bootrap’s container class. It’s working great.

I’ve applied a container class to paragraphs-item--service.tpl.php

However how can I overwrite the paragraph item on a subpage that uses a 2 column layout?

Instead of putting it into the template, a better solution would be to use the hook_entity_view_alter to add the classes based on some conditions.


Why doesn't the pager appear in page--taxonomy.tpl.php? $query = db_select('node', 'n');
$query = $query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(1);

$result = $query->execute();
while ($record = $result->fetchObject()) {
  echo $record ->title."<br/>";
}

echo theme('pager');

If I put the code in page--node--3.tpl.php  there is a pager under the title. When I put the same code in page--taxonomy.tpl.php the title is output, but there is no pager. Why?

If there is a term ID, the pager will disappear.

template.php

function mythemename_preprocess_page(&$vars)  {
 if (isset($vars['node']->type)) {
$nodetype = $vars['node']->type;
$vars['theme_hook_suggestions'][] ='page__' . $nodetype;
}

}

I tried with the Bartik theme, and it works.

The steps I followed as the following ones:

I copied the page.tpl.php file the Bartik theme has in its templates directory in the page--taxonomy.tpl.php file
Right before <?php print render($page['content']); ?>, I copied the following code.

<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "
";
  }

  echo theme('pager');
?>

I selected another theme instead of the Bartik theme, disabled the Bartik theme, and then selected the Bartik theme as default one. (This step is probably not necessary, but I did it to be sure Drupal would notice I added a new template file.)
I visited http://tero.local/dr72/taxonomy/term/2.

If it doesn't work for you, I suggest trying with another theme, possibly one that comes with Drupal, for example the Bartik theme. Be sure you are adding the template file to the theme Drupal is using. If the theme selected for the current user is another one, the template file is not being used, and that would explain why you are not getting any output.

This is what I suspect, as the code doesn't depend from arg(2). You just need to visit a page whose path starts with taxonomy, for example http://example.com/taxonomy/term/2, or http://example.com/taxonomy/term. (Replace example.com with the domain you should use for your site.)

Update

It works, but using the following code.

<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->element(10)
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "
";
  }

  echo theme('pager', array('element' => 10));
?>

Apparently, there is a conflict between the pager added from Drupal, and the pager added from my code. This is the reason why such code should not be added to a template file. Rather than using this method, it is better to override the taxonomy term page with other methods, such as the Views module, or implementing hook_menu_alter() in a custom module.

Using the Bartik module this is the output I get:

When there aren't nodes using that taxonomy term

When there are nodes using that taxonomy term

Any different result could be caused from the code used for the specific theme used on the site. Understanding what exactly causes the different behavior seems a little outside the purpose of this site, as it is too localized to be helpful for future readers, considering that similar code should not written in a template file.


Differences between Location and Location CCK? Location has three modules: Location, Node Locations and Locations CCK

What are the primary differences between them? Are there any advantages to using Node Locations over the Locations CCK?

Thanks!

Location: provides the Location API; handles address storage and geocoding. Essentially the base of the location module to which the other modules rely upon.

Location CCK: provide a Location behavior as a CCK field. This module uses the field API properly rather than its legacy node location module which implemented its own fields and storage.

If you are evaluating which one to use, I would recommend the cck one. The others are being deprecated soon.

Via the project page:

  Location 7.x-4.x is planned to be a stripped out version of location
  7.x-3.x, which has no node location, user location, location taxonomy (at least in its curren form), location add another sub-modules. It
  will only have location field, which will essentially be the current
  location cck module.


How to know all the available BASE_FORM_ID? I know just a few BASE_FORM_ID to use with the hook_form_BASE_FORM_ID_alter() hook, there is an old article named Using hook_form_BASE_FORM_ID_alter() talking about this.

In the article there is a method to know if a form have en BASE_FORM_ID

But, how to know all the available BASE_FORM_ID in Drupal 7 and Drupal 8?

In D8 only entity forms implement the interface BaseFormIdInterface. The code to generate the base form id is in EntityForm::getBaseFormId:

  public function getBaseFormId() {
    // Assign ENTITYTYPE_form as base form ID to invoke corresponding
    // hook_form_alter(), #validate, #submit, and #theme callbacks, but only if
    // it is different from the actual form ID, since callbacks would be invoked
    // twice otherwise.
    $base_form_id = $this->entity->getEntityTypeId() . '_form';
    if ($base_form_id == $this->getFormId()) {
      $base_form_id = NULL;
    }
    return $base_form_id;
  }

So for each config and content entity type there is a base form id available: [ENTITY_TYPE]_form

In some cases special entity forms override this method, for example the confirm form class ContentEntityConfirmFormBase defines [ENTITY_TYPE]_confirm_form.

To get all available base form ids the best approach is probably to iterate over all routes that have entity forms or build the form object with the information you find in the entity types. The most work here is to get an entity for the form object, because getBaseFormID() depends on this:

use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\ContentEntityType;

$entityTypeManager = \Drupal::EntityTypeManager();
$base_form_ids = [];
foreach ($entityTypeManager->getDefinitions() as $id => $entity_type) {
  $handler_classes = $entity_type->getHandlerClasses();
  // check if the entity type has form operations
  if (isset($handler_classes['form'])) {
    $entity = NULL;
    // for config load the first entity
    if ($entity_type instanceof ConfigEntityType) {
      $entity = reset($entityTypeManager->getStorage($id)->loadMultiple());
    }
    // for content create a new instance, because we don't know if content exists
    elseif ($entity_type instanceof ContentEntityType) {
      $values = [];
      // if the entity type has bundles we have to provide one when we create the entity
      if ($bundle_key = $entity_type->getKey('bundle')) {
        if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
          if ($bundle = reset($entityTypeManager->getStorage($bundle_entity_type_id)->loadMultiple())) {
            $values[$bundle_key] = $bundle->id();
          }
        }
      }
      $entity = $entityTypeManager->getStorage($id)->create($values);
    }
    // if we have an entity, get the base form id for each form operation
    if ($entity) {
      foreach ($handler_classes['form'] as $operation => $form_class) {
        $form_object = $entityTypeManager->getFormObject($id, $operation);
        $form_object->setEntity($entity);
        if ($base_form_id = $form_object->getBaseFormId()) {
          $base_form_ids[$base_form_id] = $base_form_id;
        }
      }
    }
  }
}


How to create front page for every language? My goal is to have three front page versions per language. Browser language detection is enabled. Front page is correctly rendered with a language according to Accept-Language, but there is no language indicator in URL, example: host.com/it.

Have I missed something in configuration or I have to do this feature (redirect) programmatically (or Rules) ?

You have to use the language detection method "URL" for this. When using other detection methods the language prefix is not used.

Even then a URL without a language prefix still works and uses the default "Selected Language" at the end of the detection methods list or another method you have enabled between those two.

If you want that the homepage is redirected to the language prefixed URL instead, use the module Redirect and set this option:

  GLOBAL REDIRECTS

  [x] Enforce clean and canonical URLs.

  Enabling this will automatically redirect to the canonical URL of any
  page. That includes redirecting to an alias if existing, removing
  trainling slashes, ensure the language prefix is set and similar
  clean-up.


Saving node with a text format another user doesn't have permission for renders it inaccessible I have an editor role which has access to an editor Text format.
I have an admin role which uses the Full HTML format.

When the admin edits a node and saves the body (or any other full text field) with their default text format, Full HTML, then the editor gets:

"This field has been disabled because you do not have sufficient permissions to edit it."

How can I allow the editors to simply have permission to edit this locked field with their own editor text format?

You can't I'm afraid.

Think about it like this: When rendering the text to screen, Drupal has to decide which text format to use to filter it. This means that per field, there must only be one text format, regardless of which users have edited it.

If this wasn't the case, Drupal would have no idea which format to use to render the text. It would have to guess, which is something you don't want a computer doing!

If you want users to be able to edit textarea fields, your admins will simply have to save them in a format that those users have permissions to use. Otherwise the whole point of having different filters available for different roles is kind of lost.

But the main point is that conceptually, if different users edit the same field, with different text formats, then Drupal has no idea which one to use when outputting the field value. This is why you cannot do it.


Why would !order-summary token be available/unavailable depending on payment method? I'm trying to use a payment gateway module (Icepay for Drupal Commerce), but I noticed that the payment method I choose in checkout influences the availability of order tokens.

I have Commerce Message configured with an email using the !order-summary token (like Commerce Kickstart does). When I choose commerce_payment_example's payment on checkout, the email contains the expected line items and total price provided by !order-summary. When I choose Icepay, this part remains empty in the email.

Could the payment method influence the availability of tokens? Is there something the payment module needs to implement for that, or should I be looking at other causes?

Of course I find the issue after posting the bounty :s

This Commerce Message issue explains that the problem is that some payment methods need to do a postback, which is executed as anonymous user. This apparently means that the view which returns the order summary (commerce_cart_summary) is also executed as anonymous and returns no results, so the token remains empty. The commerce_payment_example method does not have this problem because it doesn't rely on any external feedback.

The workaround to disable SQL rewriting in the commerce_cart_summary view works (I haven't tested the patch yet).


How can we theme menu blocks in drupal 6 I decide to theme menu blocks in my drupal 6.x.

I have copied block.tpl.php into my theme folder and I have renamed it to block-menu.tpl.php

but it seems it doesn't work !!

How can I modify the theme for menu blocks?

You can user the theme developer module to check whether your template is called at all. It will show you what nameing conventions to use.

And just in case: You have to flush your caches to make sure new templates and theming methods are taken into account.


Schedule cron jobs using Ultimate Cron In one of my modules I would like to create two different cron jobs to handle two different procedures. What I did was to use the Ultimate Cron module, and by implementing the cron api, to schedule one of my cron jobs.

My problem is that in /admin/config/system/cron/jobs only the default from the hook_cron appears and not from the hook_cronapi. This is what I wrote.

/**
 * Implements hook_cron().
 */
function MODULENAME_cron() {
  //code
}

/**
 * Implements hook_cronapi().
 */
function MODULENAME_cronapi() {
  $items = array();

  $items['generate_excel_files'] = array(
    'title' => 'Table Excel Generate',
    'callback' => 'generate_excel_files_callback',
    'scheduler' => array(
      'name' => 'crontab',
      'crontab' => array(
        'rules' => array('0 3 * * *'),
      ),
    ),
  );

  return $items;
}

function generate_excel_files_callback(){
  //code
}

Apparently cron api dosn't work with Drupal 8 at this time. What I did to fix my issue was to create one new module to handle only the cron job that I wanted. Then from the UI of Ultimate Cron I would add the rule to schedule my cron job.

use Drupal\MODULENAME\Controller\ClassName;

/**
 * Implements hook_cron().
 */
function NEW_MODULENAME_cron() {
 generate_excel_files_callback();
}

function generate_excel_files_callback(){
 $obj = new ClassName();
 $obj->generateXLSX();
}


How to set new AUTO_INCREMENT value? I have the following statement in my module code:

db_query("ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :number", array(':number' => $start_value));

During SimpleTest I get the following error message:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near ''20000'' at
line 1: ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = :value; Array (
[:value] => 20000 ) in _tripletex_add_invoice_log() (line 1769 of
/var/www/d7/sites/all/modules/tripletex/tripletex.module).

Why?

Parameter replacement only works for WHERE clauses, it won't work for the kind of query you're trying to run.

You need to insert $start_value directly into the query string. If that value comes from an un-trustworthy source then obviously you need to sanitise it and make sure it falls within the correct bounds yourself:

$start_value = (int)$start_value; // Make sure it's an integer

// Do any other checks you need to here (bounds checking, etc.)

// Build the query string and run it
$sql = "ALTER TABLE {tripletex_invoice} AUTO_INCREMENT = $start_value";
db_query($sql);


Adding titles to sorted nodes in a View So I'm struggling again with my sorted links: there are many many links (node type) which also contain the field "link_category".

I collect them all in a view and sort them by "link_category".

It works like a charm and looks like this:

link 1 | Category 1
link 2 | Category 1
link 3 | Category 1
link 1 | Category 2
link 2 | Category 2
link 3 | Category 2
link 4 | Category 2
link 1 | Category 3
link 2 | Category 3
link 3 | Category 3

but now I want to hide the link_category on each item and instead, show one title above them like:

*Category 1:

link 1
link 2
link 3

*Category 2:

link 1
link 2
link 3
link 4

*Category 3:

link 1
link 2
link 3

Is it somehow possible with Views or do I need some extra modules?

You can use the group by field option.

The process would go as follows.

In Fromt section next to the Format you have settings click on that.

You will find Grouping field Nr.1 Select the category Field from the list.

This would group the fields with the Category. But Now you would see both category as well as Link. Now you can go to the Category field settings and select exclude from Display so that only the links would be shown.


Inconsistent "UND" value in node fields I'm manually printing my node fields on its template (node--TYPE.tpl.php). Something like:

<?php print $year; ?>

And my hook_preprocess_node() looks something like:

function MY_MODULE_preprocess_node(&$vars) {
    switch ($vars['type']) {
        case "my_type":
           if (isset($vars["field_year"]["und"][0])) {
              $vars["year"] = $vars["field_year"]["und"][0]["value"];
          }
        break;
    }
}

The output is fine to all fields; however, when I view the node as administrator, no output is printed. I listed all the variables from the hook to see what was happening with the following code.

function MY_MODULE_preprocess_node(&$vars) {
    var_dump($vars);
    ....
}

I'm getting all fields without the "UND" value, $vars["field_year"][0]["value"] instead of $vars["field_year"]["und"][0]["value"].

Do you have any clue why this happens?

I was having the same problem with D7.  The solution for me was to use field_get_items(...) for reading the node data.

$year_items = field_get_items('node', $variables['node'], 'field_year');
$year = $year_items[0]['value'] + 1;

I found the post on Rendering Drupal 7 fields (the right way) very helpful.  It does seem strange that we shouldn't use the $variables provided to the preprocessor and template to read and modify the template variables.  I must be missing something.


How do I update core with Composer? Ok, admittedly I'm a composer novice. So, in my previous site, I used composer manager to update Drupal's core. That was pretty straight forward to use (just run "composer drupal-update"). However, composer manager now says it's deprecated.

  The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

So today I got a warning that I need to apply security updates to core, but I can't find any documentation on how you would update Drupal core with composer.

Is this done through Drupal Console, Drush or is it an actual composer command I need to run? I'm not very clear on what the preferred process is outside of "download the latest version of Drupal from drupal.org and replace all the files manually".

To update Drupal using Composer, you just need to move the "drupal/core": "~8.1" line from the replace section to the require section. At the end the content of the composer.json file is like the following one.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
}

I was used to run drush upc to update Drupal, but that overriden my composer.json file, and the vendor directory. As consequence of this, I should run composer update all the times to update the content of the vendor directory.

Now, using Composer to update Drupal, I can also use it to download/update the modules I am using.

The composer.json file I am using is the following one.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1",
        "drupal/imagick": "8.1.*@dev",
        "drupal/mollom": "^8.1",
        "drupal/honeypot": "^8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packagist.drupal-composer.org"
        }
    }
}

Apart from moving that line as I said, I also executed the following commands.

composer config repositories.drupal composer https://packagist.drupal-composer.org
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 8.1.*@dev

The first allows me to require Drupal modules and update them.

The last time I tried, the Drupal official repository was still in alpha stage, and it gave me problems with modules that declared themselves as Composer packages, but not setting the package type (i.e. drupal-module). I hope they fixed the problem, now. For the Drupal Packager repository, the commands to use are the following.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 1.*@dev

If you were already using https://packagist.drupal-composer.org, and you want to replace with the official Packagist site, you need to replace the first command with composer config repositories.0 composer https://packages.drupal.org/8, which works if you don't have other repositories, basing on Using packages.drupal.org.

Notice also that packagist.drupal-composer.org is scheduled to be deprecated in January 2017 (or when the official Package Repository from Drupal.org is ready).


Suggestions for a content type recipe? Currently I am building two content types, and I would like to consolidate them into one. Here is the scenario. I have two content types - Restaurants and Shops. These two have exactly identical fields except for 'Category' which is a taxonomy list. For restaurants, the taxonomy list contains restaurant food categories (asian, italian, etc) and 'shop type' for shops (fashion, electronics, etc).  The only reason I have two content types is so that I can enforce the category field which is required.

However, in my mind it seems like it would be better to just have one content type.  What I would like to do is create a 'Business' content type where you then select what type of business. In this case, Shop or Restaurant, for example. When the appropriate Business type is selected, the corresponding taxonomy to describe that particular selection will become apparent, and be able to be enforced. So, if I choose 'restaurants' then the restaurant types list will become visible where as selecting shops will display the shop type list.

Any thoughts on the best way to handle this architecture?

You can use a Taxonomy vocabulary with 2 level heirachy. Something like this:

Restaurants

Restaurant type 01
Restaurant type 02
...

Shops

Shop type 01
Shop type 02
...


How do I change the text of the "View" and "Edit" links on the user account page? I'm looking for a way to change the text being displayed in the links on the user account page.

More specifically, I'm trying to change the text "View" and "Edit" to "View Profile" and "Edit Profile". Ideally, I would prefer a solution that allows me to do this in my .theme file via a preprocessor or a hook function.

As I know you can't do it in your theme, but it is possible to do in your module.

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Change title for user profile's tabs.
  foreach ($data['tabs'] as &$tabs) {
    foreach ($tabs as &$tab) {
      $route_name = $tab['#link']['url']->getRouteName();
      if ($route_name == 'entity.user.canonical') {
        $tab['#link']['title'] = t('View profile');
      }
      elseif ($route_name == 'entity.user.edit_form') {
        $tab['#link']['title'] = t('Edit profile');
      }
    }
  }
}


Unable to update head_title string in template_preprocess_html I wanted to add some data to the page head title and created a template_preprocess_html function in my module.

I added a couple entries to the head_title_array and imploded the array back into head_title.

At first it looked like it wasnt working at all, but then I checked and in html.tpl.php the $head_title_array was updated.

My temp solution is to implode the array there before printing it but that's a little hackish for me.

Thoughts on where the title is being set or re-set to prevent it from being changed in template_preprocess_html?

Module code is aproximately:

function MODULE_preprocess_html(&$variables) {
  $head_title = $variables['head_title_array'];
  array_unshift($head_title, 'TEST');

  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);
}

and in html.tpl.php:

<title><?php print implode(' | ', $head_title_array); ?></title>

I just noticed that the metadata module is storing variables in an array called metatag_set_preprocess_variable.  That might be the cause, I'll investigate further.

If you find that $head_title is different from implode(' | ', $head_title_array), it means there is a module running after yours that implements hook_preprocess_html() which runs after your implementation, or hook_process_html().

The code executed from Drupal is the following:

template_preprocess_html() (It runs before hook_preprocess_html().)

// Construct page title.
if (drupal_get_title()) {
  $head_title = array(
    'title' => strip_tags(drupal_get_title()),
    'name' => check_plain(variable_get('site_name', 'Drupal')),
  );
}
else {
  $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
  if (variable_get('site_slogan', '')) {
    $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
}
$variables['head_title_array'] = $head_title;
$variables['head_title'] = implode(' | ', $head_title);

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'html')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

template_process_html() (It runs after hook_preprocess_html(), but before hook_process_html().)

There is no code that alters $variables['head_title_array'], or $variables['head_title'].

The fact $head_title_array contains the value you expect makes me think there is really a module that implements hook_preprocess_html to alter $variables['head_title'].

To be sure your module is the last one running hook_preprocess_html(), you need to make your module weight higher.


I'm probably completely over thinking this I am working on a calendar for our agency and want to have public access to submit events using a webform created from the webform module, and of course this event would not be published without admin signing off on it.

It doesn't appear this is a normal feature in webform/views/calendar module.  What am I missing?

Have a look at Entity forms https://www.drupal.org/project/entityform rather than webform then the user can create an entity that can be converted to your event style content type. Some form of workflow will clearly be involved. Rules may help you avoid coding.


How to integrate an Android database in Drupal? How do I add an Android apps database contents to a Drupal site?

I have an Android app with a database having 3 tables. I also have a Drupal site with 3 content types as the 3 tables of apps databse.

What should I do so that the contents of apps database is imported to Drupal contents, so that each content type corresponds to the contents of the 3 tables in Android? Is there any module available for this?

Consider using the Feeds module for such kinds of imports. Here is an excerpt from its project page:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files

Especially the first bullet seems to be what you're looking for.
Consider refining your question to provide some more details of the database format of your Android app. E.g. is it a PDO-compliant DBMS? If so, and in case you'd want to consider it, it might be possible to use a co-existance setup also (= use Drupal to only 'display' your data residing in your Android app).


How to only display Second level of menus in Superfish? I am using Superfish to display the menus in the left sidebar. I am using the Main Menu navigation structure which only displays the top/first level. In the sidebar, I would like to display only the second level menus. But I cannot figure out how to do this.

At the moment, the complete menu is being displayed...

PS. the reason I am using superfish is because I need the sidebar menu to be able to slide out/drop down menu items.

I have extracted https://github.com/mehrpadin/Superfish-for-Drupal/archive/1.x.zip to sites/all/libraries/superfish I have extracted http://ftp.drupal.org/files/projects/superfish-7.x-1.9.zip to sites/all/modules/superfish I have extracted ftp.drupal.org/files/projects/libraries-7.x-2.1.zip to sites/all/modules/libraries

My superfish menu parent is set to Main menu, Menu depth is set to 2 and Path levels is set to 1.

However, the superfish menu in the sidebar is always the same, regardles of what level of the menu I am in :(

Hit 'configure block' on your superfish menu block. Under 'Menu depth' make your desired changes. This sets number of child levels starting with the parent selected above. -1 means all of them, 0 means none of them. (Default: -1)