How to show the author as entity reference of a file used in a node? I have a content type where images are uploaded / managed with media module. Images have a mandatory entity reference field for the author.  Now i want to show the author always next to the images. I can't get it to work. Last thing i tried was an entity view attachment, which works great if attached to the file itself, but not if attached to the node. I think the problem is the contextual filter. If i use the file-id the view takes the node id and shows the wrong author. If i try the node-id as contextual filter, it doesn't show anything (because the nodes have no author). How do i setup this configuration right?

Any help appreciated! Thanks!

Yes, ultimately a query needs the file ID. There are a few ways you can get the file ID considered. You should pick the mode most consistent with the rest of your site build:

If you are using the Panels suite you then have a ton of options both within the "Views content panes" module (that comes as a part of CTools) and within Panels itself for setting up the passing of arguments. My main recommendation under this approach would be to use the "context" concept within panels to go from the node object to the file object that can then be passed to a contextual filter.
You've tried Entity Views Attach. This works well if it is appropriate to show the author of the file within the View Mode of the file.
You've also tried the "Provide default value" option under contextual filter handing but there isn't a suboption for "value from field X on current node". These are "default argument handlers" and here is the code for the one you are using: http://cgit.drupalcode.org/views/tree/modules/node/views_handler_argument_node_nid.inc and the generic API page for them: https://api.drupal.org/api/views/plugins!views_plugin_argument_default.inc/group/views_argument_default_plugins/7 If you are comfortable with PHP you can write one custom to your use case.
Views Field View (https://www.drupal.org/project/views_field_view) is maybe the ugliest (but perhaps the easiest) option. It would allow you to construct a View that takes the argument of the NID (which you already have working) and using that to get the FID as field which would then be passed to another View. A View inside a View.


How do I list all nodes created by the same author on a (custom) profile page? In my setup each user has a profile page. The profile page is a custom content type (each user can only have one and they have to add it them selfs).

On this profile page I would like to list all nodes of a certain type created by the same user as the profile page.

How do I do this (in a views block preferably)?

I think this might be the solution

https://www.drupal.org/node/1919622


How to manage the display of a multiple value field in a individualy way? I have a content type with a field called "anotations" which is set to have 2 values.

Im using display suite,then in admin/structure/types/manage/mycontenttype/display I'd like to show the 1st value of the "anotation" field in the "header" region and the 2nd value of the "anotation" field in the footer.

Is there any way to do this?

Just in case someone wonders why do I need to do this: I'm just trying to avoid to create new fields as much as I can, since I noticed that having too much fields affect the general performance of the site.

I got this creating Dynamics Fields with the Display Suite module. Here is a quote about it (from the module's project page):

... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.


How to I style the Superfish accordion menu to have bars? I would like to show my super fish menu with bars as shown in the picture (when in mobile responsive mode), but at the moment i can only get the word "Menu". The menu functions perfectly, i just wanted to add the bars. Can anyone advise?

Seeing you are using responsive and that implies that you are size aware. You may find an icon set more elegant rather than a fixed sized background image.

I load the font-awesome set into the site css anyway for use elsewhere. Therefor the icon's css are available sitewide.

If you look at the accordian settings for that sf menu, you'll see that you can edit that menu button (trigger) text. I found that though a text field, it does accept some html.

For example
Open Menu<i class="fa fa-bars" aria-hidden="true"></i>

gives you those the bars and they re-size as the button text does.


Media Browser doesn't show I've got the media module installed, but I'm not seeing the Media browser at all when I go to upload images.

Do I need to do something special to enable the media browser?

try checking the "media library" in the settings of the field, as seen on the picture in the Quick Start Guide


Devel 'Display Query Log' not showing any queries I've enabled 'Display Query Log' in the Devel Settings but I don't see any logged at the bottom of my page when I load a page. I just get 'Queries exceeding 5 ms are highlighted.'.

I'm running Drupal on PHP 5.3.2 with a mySQL database.

The issue is present in both the Admin theme and my custom theme.

Other Devel outputs seem to display fine.

Any ideas why the queries aren't showing?

You need to check 'Collect query info' in the devel settings: /admin/settings/devel

Otherwise no logs can be shown.


How do I change priority of two different implementations of hook_node_access()? I am using the Node View Permissions module, which implements hook_node_access(). I am also using a custom module (mymodule.module) which is implementing the same hook. node_view_permissions_node_access() is always invoked after mymodule_node_access().

How can I change the hook invocation order? mymodule_node_access() should be executed after node_view_permissions_node_access().

Use hook_module_implements_alter():

  This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

Example:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_access') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

In the possible event that another module also implements hook_module_implements_alter to move its own implementation of hook_node_access to the end of the list, you can get cunning and make sure your implementation of the alter hook runs last too:

  if ($hook == 'node_access' || $hook == 'module_implements_alter') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }


What is the best way to verify controller arguments? For example, I have a path on my site.

Let it be www.mysite.com/year/{year}/month/{month}/day/{day}

Could you clarify me, what is the best way to avoid getting of wrong arguments, such as year/3000/month/15/day/32 ?

Should I verify them inside the function called with the controller? Or is there a separated function or method to verify them, which wouldn't let invoke the controller function in case of wrong arguments?

Here my working example:

.routing.yml

forcontu_pages.calculator:
  path: '/forcontu/pages/calculator/{num1}/{num2}'
  defaults:
    _controller: '\Drupal\forcontu_pages\Controller\ForcontuPagesController::calculator'
    num1: 20
    num2: 10
    _title: 'Calculator Page'
  requirements:
    _permission: 'access calculator'
    _custom_access:  '\Drupal\forcontu_pages\Controller\ForcontuPagesController::access'

ForcontuPagesController.php

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
...
  public function access(AccountInterface $account, $num1, $num2) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return AccessResult::allowedIf($num1 > $num2);
  }
...

I just verify that $num1 is greater than $num2, but you can add your other params and your validations.

See that you can add more params:

  The access method arguments are resolved similar to normal
  routing. The following arguments are optionally available; they will
  be populated if they are properly type hinted:

  The slugs, like with normal routing.
  \Symfony\Component\HttpFoundation\Request $request
  \Symfony\Component\Routing\Route $route
  \Drupal\Core\Routing\RouteMatch $route_match
  \Drupal\Core\Session\AccountProxy $account

Read: What is a slug?

Reference:
Access checking on routes


Best way to export Commerce orders, line items, and customer profiles from live to dev? I've got a massively diverged commerce development site, and I'd like to import all of the orders, line items, users, and customer profiles that have happened on the production site into my development site and then push the database back up to production.

I exported a bunch of tables and then ended up with a significantly borked dev site. Hmm.

I can continue to tweak my tables, but is there a better way to do this?

I ended up exporting the tables from Sequel Pro using the "DROP TABLE IF EXISTS" syntax and then importing them (see screenshot).

If you don't use the DROP TABLE syntax (I believe this is the option in phpmyadmin) then just delete the tables before importing.

Basically, I spent a half an hour browsing the field_data_fieldname tables and others to see what sort of content they had and if they were pertinent to orders, line items, or users. I erred on the side of more db tables rather than less.

One of my field_data_fieldname fields was shared with other entity types, in addition to commerce_order, and so rather than clobber the incoming values, I had to create INSERT queries. Using Sequel Pro cut and paste did that for me. Make sure to get the field_revisions_fieldname table as well.

Make sure you empty out your cart before you import, else the cart will point to a possibly non-existent order and throw an entity metadata wrapper exception.

Here's the full list of tables:

`commerce_customer_profile`;
`commerce_customer_profile_revision`;
`commerce_line_item`;
`commerce_order`;
`commerce_order_revision`;
`commerce_payment_transaction`;
`commerce_payment_transaction_revision`;
`field_data_commerce_customer_address`;
`field_data_commerce_customer_billing`;
`field_data_commerce_customer_shipping`;
`field_data_commerce_line_items`;
`field_data_commerce_order_total`;
`field_data_commerce_shipping_service`;
`field_data_commerce_total`;
`field_data_commerce_unit_price`;
`field_data_message_commerce_body`;
`field_data_message_commerce_line_item`;
`field_data_message_commerce_order`;
`field_data_message_commerce_payment`;
`field_data_message_order_display_name`;
`field_data_message_text`;
`field_revision_commerce_customer_address`;
`field_revision_commerce_customer_billing`;
`field_revision_commerce_customer_shipping`;
`field_revision_commerce_shipping_service`;
`field_revision_commerce_total`;
`field_revision_commerce_unit_price`;
`field_revision_field_phone_number`;
`og_role`;
`og_role_permission`;
`og_users_roles`;
`users`;
`users_roles`;


How to display fivestar average infos? I am building a view with fivestar infos under the voting widget which look like this with the views preview:

But it is rendered without the infos in the page:

In both cases I'm an admin user identified.
 I notice that a whole div with the description class available in the views and including the average/total votes infos is not rendered in the final display.

Is there some configuration to do ? Permission don't seem to be the problem.

EDIT: So the main issue comes from the theme which is hardcoded from scratch and nothing is displayed unless it is willingly preprocessed or regenerated in a view. I found my way out (see below)

Have you gone to Display Manager
/admin/structure/types/manage//display
and played with those settings by the gear?

I normally setup display types like "default", "teaser", "teaser- icon side", etc. Then when I create a view, instead of outputting "fields", I output one of these pre-setup display types. I use Display Suite to help get more control of them.

I'm using this votingapi widget in D8 in this way and had no issues.


Multiple language node import with Feeds I am using Feeds to import a very huge CSV file with products to my Drupal Commerce site. My site must be in two languages and it appears that Feeds hasn't support for this. How can I import nodes in multiple languages with Feeds?

There was a fantastic Solution not so long ago that addressed something similar.

I believe that the best thing to to would to be to split each node into two nodes (one in Language A, one in Language B) and import each one in a separate feeds import, and then use the SQL query in the above solution to link the translation. This way, each node can contain otherwise identical information about the same item, in its own language, and simply be displayed based upon which translation the user/viewer would prefer.

Let us know how you go with the SQL script and if you have any issues that you need help with!


Group search result of drupal 7 and show them in tabs I am using function like this. I have grouped the search output and displaying, but i need to make these grouping in tabs using any tabs feature available, how do i do it over here by using any other module function.

function arras_preprocess_search_results(&$variables) {
    $variables['search_results'] = '';
    // get a list of node types
    $nodeTypes = node_type_get_types();
    // loop through results, group by type
    $resultTypes = array();
    foreach ($variables['results'] as $result) {
        $resultTypes[$result['node']->type][] = $result;
    }

    // create fieldsets for each type
    foreach ($resultTypes as $resultType => $resultTypeResults) {
        $value = "";
        // loop through entries
        foreach ($resultTypeResults as $result) {
            $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
        }
        //$variables['search_results'] .= $value;
        // add fieldset

    /*    $variables['search_results'] .= theme('fieldset',
            array(
                'element' => array(
                    '#title' => $nodeTypes[$resultType]->name,
                    '#collapsible' => TRUE,
                    '#collapsed' => TRUE,
                    '#value' => $value
                )
            )
        );
      */

/* Problem here */

     $variables['search_results'] .=   quicktabs_build_quicktabs('test',array(),array('title' => $nodeTypes[$resultType]->name, 'contents' => 'test'));
    }
}

Thank you for sharing. I made some minor changes in your code because I was getting some floating search results. So I changed this part:

    $output .=  '
';
    $output .=  $value;
    $output .=  '
';

}
    $output .= '
';
    $output .= '
';

     $variables['search_results'] = $output;

To this:

$output_results .=  '
';
$output_results .=  $value;
$output_results .=  '
';

}
$output .= '
';
$output .= $output_results;
$output .= '
';

 $variables['search_results'] = $output;


How to solve my Field mapping problem during import of Registration codes? I'm using the RegCode Module and I need to have 64 different registration codes and I want each of them to be used an infinite number of times. So the only solution is to import them.
I created an Excel spreadsheet with two columns:

"code", which contains the 64 codes.
"maxuses", which contains "999999".

I exported it as a CSV file but when I try to import it, I get this message:

File successfully saved
Successfully inserted 0 rows out of 64
Warning: array_combine(): Both parameters should have an equal number of elements in regcode_ie_admin_import_submit() (line 167 of /sites/all/modules/regcode/regcode_ie/regcode_ie.module).

Am I doing something wrong ?

Preparing your cvs file
First remove all the column names from the first row, otherwise they will be added and will throw an error, as they won’t be in the correct format.
Drupal Regcode import tab
You can map to the following six fields:

begins: When code should be active from in date format
expires: When code should expire in date format
code: The registration code text format (for numbers and letters) and should be unique
is_active: Whether the code is active text format ‘Yes’ or ‘No’ Default is Yes
maxuses: Maximum times the code can be used number format default is 1
uses: Number of times the code has been used number format default is 0

If your cvs file codes are in the first i.e column one (A) then you would map it as code and if the next column is maximum times the code can be used then you would map as code, maxuses separated by a comma. Note: no colons.


How do you add a custom field to a menu link in Drupal 7? I am currently using the menu module (Drupal 7 Core) to manage my menus. A menu link consists on only a title and a description. I would like to add an image field as well as another text field. I have considered using taxonomy rather than menu links, but I still want the capability to add a basic page to a menu.

I have looked into a module called Menu Attributes http://drupal.org/project/menu_attributes, but it doesn't add an image field.

Menu icons should do what you're after.

This module allows you to upload an image in the menu-item's configuration form.
After uploading the image, the icon data will be added to the menu link's
options array.


Is the current form an entityform form? I am using entityform module on subscribing certain organic groups forms.
I only need to add some custom submit logic when unsubscribing the form if the subscribe form was created with entityform.

Depending on if the subscribing form was generated by entityform, when unsubscribing I need to do some custom logic to clean up the DB from entity data not covered by entityform.

I am using hook_formID_alter, and this is my $form array:

The thing is I need to do a database clean up if it was submited with entityform in the first place, even though I understand the unsubscribe form is not a entityform.

Therefore, this doesn't work: if (isset($form['#entity_type']) && $form['#entity_type'] === 'entityform')

Can you help me identify programmatically which kind of form is the form?

Assuming you are trying to implement a *_form_alter() function in a module (which is what I got out of your post), you can implement hook_form_BASE_FORM_ID_alter(), which in this case would be hook_form_node_form_alter(). If you implement this, it will only be executed if/when you are on a node form, and therefore you will know you are in a node form.


Drupal Commerce - How do i specify a user name for new account other than the email address on an anonymous order? Ok so here's the use case:

Our site also includes phpBB forums, which of course display the user name in posts... most people don't like their email address being displayed, for obvious reasons.

Orders placed by anonymous users automatically generates an account with the username the same as the email address. I want to keep the auto account creation, but have the user enter a UserID when they enter their billing info.

So i've created a field on the billing profile (field_account_name is the machine name). How do i reference that field in the entity creation rule? I looked at this topic:
http://www.drupalcommerce.org/questions/5370/how-do-i-base-new-account-u...
but that doesn't show me how to reference a field i've created, only ones that already exist in the commerce-order entity.

This might be a stupid question, but i'm still relatively new to drupal... any help would be HUGELY appreciated.

I also posted this on the Commerce site, but it doesn't look like that gets tons of answers.

On the create user Rule you need to bring field_account_name into scope by running condition "Entity has field."

First run EHF on Commerce Order to bring the billing profile reference into scope. Then you can EHF your account name field.

You then will have the ability to have access to that field's token and use it as the new account's username.

Note: this is more a Rules usage technicality, which Commerce uses heavily.


D8 HTML tags from field converted to special characters when printing variables I have WYSWYG editor enabled on my fields when there is html in these fields. When I print out the variables in my template, the html gets converted to special characters.

for example my print statement

{{ node.field_hours.value }}

My full HTML in the field becomes this.

Camping : &lt;p&gt;&lt;strong&gt;Equestrian, Group and Primitive Sites:&lt;/strong&gt;&lt;/p&gt;
46 miles of marked multiuse trails.

Florida law requires bicyclists under 16 to wear helmets.

Bird Watching :    Site 64 on western section of

&lt;ul&gt;

It is unsafe to print raw data from a field value.

Instead of using {{ node.field_hours.value }} put this in your node template:

{{ content.field_hours }}

This will print out the field as configured in the view mode. In the view mode you can select a text filter that matches the allowed tags of the ckeditor. In Drupal 8 all necessary text formats are predefined to be used together with ckeditor.


Are the data stored with the tempstore.private and tempstore.shared services expected to be removed when the user account is deleted? Both the tempstore.private and tempstore.shared services store data which have an associated owner; for logged-in users, that is the user ID.

When an account is deleted, are the data having that user ID as owner removed?

I looked at User::postDelete(), but there isn't code for that.

public static function postDelete(EntityStorageInterface $storage, array $entities) {
  parent::postDelete($storage, $entities);
  $uids = array_keys($entities);
  \Drupal::service('user.data')
    ->delete(NULL, $uids);
}

It could be I didn't look at the correct class, or the code to delete those data is still missing from Drupal core.

Should I expect the data stored with the tempstore.private and tempstore.shared services be immediately deleted after a user account is deleted?

The user's temp storage deletion isn't attached to the user deletion process.

If you look at the class, PrivateTempStoreFactory, instantiated for tempstore.private & tempstore.shared, you can see that the class has an expire property that determines the storage's TTL (in seconds).

These services are instantiated with an expire value of defined by parameters:tempstore.expire in core.services.yml, with a default of 604800 seconds (1 week), so the temp storage will expire 1 week after its creation.


How obtain the Distance/Proximity between 2 fields? I am working on a project (Omega subtheme) with Panels and Views. I'm trying to create a list of local secondary schools and their distance from a few locations.

Installed Location Module, enabled it, together with Location Search, Location Taxonomy, Node Locations and Location CCK. Also, imported list of zipcodes for my location (gb) into database.

Next I created Content Type ‘secodnary school’ with School Location field, containing Address ,Postal Code, City, Country, and Latitude and Longitude fields.

Then I created 3 pieces of content – namely 3 local schools (to start with) with their addresses and lat/long info.

Finally, I tried to create a view that will contain the above list of secondary schools, sorted by their proximity to the given location and to connect it to a different piece of content (page) that holds the location info (address, postcode, latitude/longitude) of different (X,Y,Z) locations.
X, Y, Z (…) are pieces of content (pages) of XYZ content type that among other things contain their individual location info.

So I need my new view (lets call it distance_sec_schools) to pick up location info from it’s host (XYZ) content  (hint: I tried to configure CONTEXTUAL FILTER – content NID to provide content ID from URL – but it didn’t do the trick) and then provide me with the distances to 3 local schools, which I will then sort by proximity criteria.

Take a look at the screenshots of my view and Location: Distance / Proximity - Field Settings (framed red) and Filter (framed blude), which I suspect might be where my problem lies.

At the moment, my view produces a table with the school names but without the distances.

As far as I know it is not built into the location module but can easily be done in php with Haversine Formula, have a look here.

To add it to your view you can use Views PHP or theme a field with views-view-field--your-field.tpl.php passing in the two coordinates.


Appending markup to privatemsg message body First, a little background info:

I'm running privatemsg 7.x-1.2 across several sites running on a single D7 codebase. I have all of the privatemsg tables in one database, which is accessed by all of the sites as to keep private messages synchronised between them.

To enhance that little setup, what I would like to do is manipulate the message body at the time of insertion/saving to append a "This message was sent via [site name]" line at the very end of each message. This is how I achieved it at first:

function global_privatemsg_message_presave_alter(&$message) {
    $message->body .= "
(". t("Sent via !site_link", array('!site_link' => get_site_link())) .")
";
}

That worked well except I overlooked the fact that hook_privatemsg_presave_alter takes place prior to the input filter being applied, so if the user sends their message as "Filtered HTML" or "Plain text", the 'sent-via'  gets thrown out.

So, what I'm looking for is a reliable way of appending markup to the message body, or even introducing a new template variable that I can populate accordingly, without it being mangled by input filters (the result of Drupal's check_markup, I suppose).

Preferably I want to do this entirely within the constraints of the Privatemsg module API, but I appreciate that might be asking for the impossible.

Doable?

(I haven't used privatemsg) ... but sure it's doable because of a new feature in D7:

  Instead of attachments, private messages are fieldable and any number
  and combination of fields can be added to them.

So what you do is code up a custom module that defines a custom "sent_by_sitename" field that is a text field_type. Then in your presave hook you would just do:

$message->sent_by_sitename = 'some_sitename_in_your_multisite_install';

Then you could alter your message display to show this new field with a custom formatter that adds the markup and leading "This message sent by " markup.

I dont have the code to do this offhand (its probably about 30 lines). Here is a similar request of adding custom fields to the default user object in drupal -- your request is different regarding privatemsg but you probably will still use some of the same functions: add-properties-to-an-entity-hook-schema-alter

So in short:

Define your custom field in your custom module, eg hook_field_info()
on module_enable() and module_disable() attach your field to the message entity, eg field_create_field() and field_create_instance()
alter your existing privatemsg API call to set this new field value instead of raw HTML.
alter your privatemsg message display to show your new field with its associated field_formatter to be at the bottom of the message display.


Migration bringing in duplicate taxonomy terms I have a very simple taxonomy term migration (migrate module, that lets in duplicate terms for no reason I can figure out.  I have tried explicitly setting allow_duplicates to False, even though that should be the default behavior, but nothing changes.  The base migration that this migration inherits from just sets up a db connection object, sets up team description variables, and sets some configuration variables.  It also sets up a few helper methods that are not used in this migration.

Here is the migration class:

class EnviroscopeKeywordMigration extends BaseEnviroscopeMigration
{
    public function __construct($arguments)
    {
        parent::__construct($arguments);

        $this->description = t('import Keyword data');
        $query = $this->getConnection()
            ->select('doc_keyword', 'k')
            ->fields('k', array('ID', 'NAME'));

        $this->dependencies = array("GeoArea");

        $this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

        $this->destination = new MigrateDestinationTerm('keywords');
        $this->map = new MigrateSQLMap($this->machineName,
            array(
                'ID' => array(
                    'type' => 'int',
                    'length' => 11,
                    'not null' => TRUE,
                    'description' => 'Keyword ID',
                ),
            ),
            MigrateDestinationTerm::getKeySchema()
        );

        $this->addFieldMapping('name', 'NAME');

        $this->addUnmigratedDestinations(array(
            'description',
            'parent',
            'parent_name',
            'format',
            'weight',
            'path',
            'pathauto',
        ));
    }

}

Can somebody, PLEASE help me debug why this might be bringing in duplicate terms like this:

I ended up biting the bullet and writing it myself.  I still don't know what was causing it to not work in the first place, but I replicated the desired behavior with this helper method in the migration class:

public function check_for_existing_term($taxonomy, $term) {
    $query = db_select('taxonomy_vocabulary', 'v')
        ->condition('machine_name', $taxonomy);
    $query->innerJoin('taxonomy_term_data', 'td', 'v.vid=td.vid');
    $new_tid = $query->fields('td', array('tid'))
        ->condition('td.name', $term)
        ->execute()
        ->fetchField();
    return ($new_tid) ? $new_tid : False;
}

In the constructor of the migration class I set $this->taxonomy = 'keywords'; and I used that in $this->destination = new MigrateDestinationTerm($this->taxonomy);, then I added the following prepareRow:

    public function prepareRow($row)
    {
        $new_tid = $this->check_for_existing_term($this->taxonomy, $row->NAME);
        if ($new_tid) {
            $this->map->saveIDMapping($row, array($new_tid),
                MigrateMap::STATUS_IGNORED, MigrateMap::ROLLBACK_DELETE);
            $this->rollbackAction = MigrateMap::ROLLBACK_DELETE;
            return FALSE;
        } else {
            return TRUE;
        }
    }

This tries to find a matching term in the database for each row.  If it finds it, it adds an entry in the map table and then returns FALSE so the migration won't do anything further for that row.  If it is a new term it returns True, and the migration continue happily, adding in the new term.


How to reverse a drupal patch on netbeans Is there a way to reverse a patch on Netbeans?

Does simply copying the target file and repasting it will work?

Or can the patch affect mutliple modules and code?

Use patch to reverse

patch -p1 -R < path/to/patchfile

Use git to reverse

git apply -R path/to/patchfile


How to add relationship in view for custom entity I have an entity that references node and user via nid and uid fields.

I have created an entity around my schema and would like to use it in views. I can create a view based on a new entity that shows fields from the entity.

Now I want to add relationships to node and user so I could pull fields from them. So I want to show fields from related user and node, not my entity bundles.

What's the right way to do this?

Entity API supports this out of the box, but you will have to let it know which entity your data represents. If Entity API encounters a field containing numeric data it will by default assign it the type 'integer'. Just change the type to the right entity type and you can define the relations in Views:

<?php
  /**
   * Implements hook_entity_property_info_alter().
   */
  function my_entity_entity_property_info_alter(&$info) {
    $info['my_entity']['properties']['nid']['type'] = 'node';
    $info['my_entity']['properties']['uid']['type'] = 'user';
    $info['my_entity']['properties']['tid']['type'] = 'taxonomy_term';
  }
?>


Preprocessor to use a different template for popup window I'd like to provide the ability to open some content in a new window without all of the headers and sidebars of the normal content window.  I tried to do this with a preprocessor, and got close, but still no cigar:

function THEME_preprocess_page(&$vars) {
  if (isset($_GET['popup']) && $_GET['popup'] == '1') {
    //error_log( var_export( $vars['theme_hook_suggestions'], true ) );
    // returns as last array item: page__node__3
    $vars['theme_hook_suggestions'][] = 'page__node__3__popup';
  }
}

I then have a template with the file name: page--node--3--popup.tpl.php which is just a straight copy of the region--content.tpl.php file, and it actually does hit that template!  The problem is that only the title shows up - and when I clear the cache I get a warning message that content is undefined in my popup template. I've also tried naming the file and setting the theme_hook_suggestions to 'region--content--popup'/'region_content_popup' with the same results.

Here is the content of region--content--popup.tpl.php

<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>

    <?php if ($title): ?>
    <?php if ($title_hidden): ?>
<?php endif; ?>
    <?php print render($title_prefix); ?>

<?php print $title; ?>

    <?php print render($title_suffix); ?>
    <?php if ($title_hidden): ?>
<?php endif; ?>
    <?php endif; ?>
    <?php if ($tabs): ?>
<?php print render($tabs); ?>
<?php endif; ?>
    <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
    <?php print $content; ?>
    <?php if ($feed_icons): ?>
<?php print $feed_icons; ?>
<?php endif; ?>

The H1 page title appears and nothing else.

You probably want:

print render($page['content']);

You can find the variables available to you in the template by printing get_defined_vars() using print_r(), core's debug() function, or one of the extremely handy devel module debugging functions such as kpr() or dpm().

I'd install devel and do this:

kpr(get_defined_vars());

Your modal method might not play nicely with page cache so I'd definitely test to make sure it fits your usecase.


Rules - Check if coupon has been added to an order I need to check in Rules if a coupon has been added to an order as a condition.

I have tried using the ENTITY HAS FIELD option in Rules and then a data selector of

Commerce-order

and to then look for the field commerce_coupon_code

But this fires a negative, I have also tried to look for commerce_coupon_fixed_amount

But this also fires a negative.

Add A Condition Also In Rules That Will Help You In These You Can Also Create Manual Option


Show user content using subdomain I have a social content publishing site maintained in Drupal 7.  I want to show content only specific to a user when everyone visits the site using the user's user name as the subdomain.

For example when the mail site is
www.example.com

And the user is john

When people visit the site using URL
john.example.com

I want to show only the content created by John, like that is his own site or book.

When people visit the site www.example.com they shall see all content including John's content also.  This may mean Drupal 7 content shall be as usual , only the subdomain shall show content created by John.

It is not clear whether this can be achieved by Domain Access module, hence asking here to get more targetted answer from any one who may have done something like this.

You're really just passing an argument ("john") to a view (or multiple views, view blocks, etc.) to control what content is being displayed. I'm sure there is a way to do this in domain access but you can bypass that overhead by adding the logic in the view itself as a contextual filter. In rough detail:

Create your view listing the content you would want to show
Add a contextual filter based on Content: Author uid, and select 'provide default value'
I would recommend using 'PHP Code' to provide your default value and having it return value from a custom function which you can place in a module for better maintainability, ex: return _my_custom_function();

Your custom function should be returning the UID of the user you are looking for and could look something like this:

function _my_custom_function() {

  $domain = $_SERVER['server_name']; //reserved php variable
  $host = explode('.', $domain);
  $subdomain = $host[0]; // probably a more elegant regex to use here..

  // your code here that takes the subdomain 'john', sanitizes it, runs security checks, then pulls the uid for this username from the user table or wherever

  return $uid;
}


How to set Form API date_select option values Creating a date_select field in a custom form, like this:

$date_format = "Y-m-d";
$form['birth_date'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => NULL,
    '#date_type' => DATE_FORMAT_UNIX,
    '#date_timezone' => date_default_timezone(),
    '#date_format' => $date_format,
    '#date_increment' => 1,
    '#date_year_range' => 'now:1910',
    '#date_label_position' => 'within',
    '#required' => TRUE,
);

The  element it generates for the year dropdown is like this

<select>
  <option value="0">-Year</option>
  <option value="1">2017</option>
  <option value="2">2016</option>
  <option value="3">2015</option>
   .
   .
   .
  <option value="108">1910</option>
</select>

The year value returned in $form_state['values'] is the value of the option, e.g. if 2017 is chosen the value returned is 1. Is it possible to somehow set the option values like this instead

<option value="2016">2016</option>

so that the actual year will be returned?

This is how I get when I copied your code without any change. Option values are correct, but somehow the order got reversed.

<select class="date-year form-select" id="edit-birth-date-year" name="birth_date[year]">
    <option value="" selected="selected">-Year</option>
    <option value="1910">1910</option>
    <option value="1911">1911</option>
    <option value="1912">1912</option>
    .
    .
    .
    <option value="2017">2017</option>
</select>

Check your Date / Date API module versions. I'm using 7.x-2.8


add code automatically for any article/post I built a Drupal website with a custom theme, but in the last stand I need to add a specific code after any post/article published on the site. For example:

article 1

code

article 2

the same code...

The pinpoint is that I don't know how to take a reference of a single post/article to include it in a buckle to add this code.

The easiest way is to create a block and add your code to it if it's html or javascript code. Then for Show block on specific pages select only on the listed pages and add articles/* This will affect all the pages that have articles in their url.

If it's php, you will need to create a custom page tpl file.

go to drupal/sites/all/themes/mythemename/templates and add page--articles.tpl.php This will affect all the pages that have articles in their url.


Is it possible to display a Mailchimp campaign (the newsletter, not a link) from my Drupal 7 website? I've tried using views, but when I choose the rendered entity display of the MailChimp campaign field, the result is empty even though I've created 3 campaigns from within my Drupal site.  I don't think views is the answer anyhow as creating a campaign from a Drupal site still requires logging in to MailChimp to send. So I need to be able to display newsletters created in MailChimp.

I've resorted to displaying the archive of the latest newsletter in an iframe.  Besides being unattractive, it requires my client perform extra steps which is counterproductive. Not to mention, it is not responsive.

Outside of linking or iframe embedding, there isn't a way of simply displaying the content as, say, a Drupal page. There is actually a reason for this.

First, the content of the email is already an entire webpage: it (should) have an <html> tag and it will likely have <head>, <style>, and <body> sections. So it actually makes plenty of sense to just include it as an iframe directly on a page since it will need it's own space to format the content properly.

But let's say you decide to use the /campaigns/content.format API call to grab the actual content of the campaign. You'd likely still need to strip away the CSS and other HTML from within the content to make it display within your page nicely.

And with regards to synchronization, it only syncs from Drupal to Mailchimp. You'd need some other way of grabbing those campaigns if you wanted to see them in Drupal. This is especially useful because Mailchimp is used by many who have a single account + multiple clients.


Rewrite labels on fields rendered via php So I'm designing a specific node page where I'm manually inserting every field (to ensure I can customize it as the client wants) and I'm having a bit of trouble with certain areas.

Essentially I'm curious if there's a way to rewrite the label of a field while I'm including/rendering it.. see the code below for what I'm currently using:

<?php print render($content['field_product_reference']); ?>

I should also mention that I'm using Drupal 7 & the DisplaySuite module.

UPDATE: Is it possible to make it display HTML in the title area?

The label is usually in the #title key in each content member of the array, so something like

$content['field_product_reference']['#title'] = t('Something new');
print render($content['field_product_reference']);

should update it.

If not, try installing the Devel module and running dpm($content['field_product_reference']); to see whereabouts in the array the label value is.


Can I use custom name for theme directory? I'm developing site using Drupal 7. I want to give a custom name for the themes directory. Is it possible with Drupal?

Renaming core directories is not possible without hacking Drupal's core. Hacking core is highly discouraged. Even if it will work, one module that will try to access directory directly may mess up your installation.


How can I upload bulk images as separate nodes in drupal 8? I have a folder of images I am trying to bulk upload. As they will be used in galleries that can be filtered by year and location I was hoping to make them individual nodes with year and location fields that the bulk upload would fill in with a preset on each upload batch.

I've played with the media entity module and managed to upload a group of images as a single media entity but I don't really want the files grouped.

Is there a way to do this in D8 yet?
I'm fairly new to D8 so am not too sure of how things work yet.

DropZoneJS can auto-create media entities for every uploaded image.

Remember that you need to set up an entity browser using the DropZoneJS-Widget for the bulk-upload feature.

Your image gallery is an entity reference field to media entities (unlimited cardinality).

If you are looking for a general tutorial on how to set up media entities, I found this tutorial quite helpful.


require doesn't work in a module's file I have this module's inc file, which hold page callback functions. Also I have a 'config.php' file that hold the parameters. I know this is not a good practice, but I would like to leave these config there for now.
Here is the question, I cannot get access to the parameters in the config.php file after I used require 'config.php' or require_once 'config.php'.
e.g. I have admin.inc which holds these:
<?php
    require 'config.php';

    function my_page_callback(){
        global $config;

        var_dump($config); //this prints NULL when I access this menu item.
    }

and config.php holds these an located in the same folder:
<?php

    $config = array();
    $config['key'] = 'value';
    $config['name'] = 'foobar';

The file is successfully included since there is no fatal error, but why can't I get these values?
update
var_dump($config); this would print the right content after I move the require statement to the body of my_page_callback, but I don't think this is how PHP works.
Explicitly set $config as global in the required file could give non-NULL result, but it is not needed in my test files.

You can use this approach to include a file in .module

function module_name_init(){
    module_load_include('inc', 'module_name', 'includes/common');
}

and place common.inc file in includes folder in your custom module.Now write your php code here.


How do I theme the core modal with twig? Drupal 8 comes with built in modals.

This works:

modal

How can I style that modal using twig, to add new classes to the box? The intention is to take over the bootstrap style language.

Modals in Drupal are built with jQuery UI. If you want to add just some class to the modal window, you can make use of the dialogClass option.

Click me

or

\Drupal\Core\Link::createFromRoute(t('Click me'), 'entity.node.canonical', [
  'node' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
    'data-dialog-options' => \Drupal\Component\Serialization\Json::encode([
      'dialogClass' => 'foobar',
    ]),
  ],
]);

but that won't make you a Bootstrap modal. For that you could either dynamically load the node and build the markup completely following the Bootstrap sample with a button targeting a
 with a certain ID (nah, probably not the best idea, performance-wise).

OR you could make use of view modes and the concept of the View Mode Page module.

  Create separate pages for different view modes for a given content type.

That is, you create a new view mode for your node type for example mymodal, where you display only the fields you need and where you have full control over the markup using a view-mode-specific template like for example node--article--mymodal.html.twig. Now you can build the markup exactly like Bootstrap needs it. And finally link to this node in that view mode: /node/11/mymodal

or

\Drupal\Core\Link::createFromRoute(t('Click me'), 'view_mode_page.display_entity', [
  'view_mode' => 'mymodal',
  'entity_type' => 'node',
  'entity_id' => 11,
], [
  'attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => ['modal'],
  ],
]);

The only thing that would be missing now is to hide the jQuery UI modal title bar, 'title': FALSE didn't do it. But just CSS would do.


Custom commerce order_id Where is the default commerce order_id set and how can i change it to my custom order number?

I am using the Commerce Order Counter module to set a custom order number.
drupal.org/project/commerce_order_counter

The problem i have is the order_id that is passed to paypal is the default commerce order_id and not my custom order number.

You cannot change order id as other functionalities are dependent on it.But you can change order number before saving order to shopping cart status by using  hook_commerce_order_presave($order).

function example_commerce_order_presave($order) {
   if ($order->status == 'cart') {
   $order->order_number = 'new order number;
   commerce_order_save($order);
   }
 }


How to suppress print in only in front page via twig {{ node.field_test1.entity.label }} prints the label of a taxonomy field in a node.html.twig.
Is there a possiblity to suppress that outside the frontpage via node.html.twig? Or enable that only for front_page?
That means: in a view, that is searching for this term exactly, I have the same information double on screen in the view result.

"is_front"condition is not defined in node.html.twig.
'EDIT:
What I meant is that:

{% if not page %}

        {{ node.field_kategorie.entity.label }}: {{ label }}

    {% endif %}

This'll be printed all over.
How to do: print this (in the URL above) only for front page, for example not not in a view (that just searched for this entity)?

You can have as many differen view modes as you want, both the frontpage and the term pages by default are views, so they are easy to customize.

So create a new one under Admin > Structure > Display modes, then enable it for that node type and configure the fields as you want. Then change one of the views to use that view mode.

Another option would be logic in process, but then you need to add the right cache context.

Or you just hide that field with CSS.


MODULE_preprocess_block() get rendered region in drupal 8 So I am trying to port a Drupal 7 module to Drupal 8, and am struggling with how to translate a "NAME_preprocess_block" method. In the D7 code, it filters by the region a block is getting rendered

if ($vars['elements']['#block']->region == "my_region") {
   // Do stuff.
}

However, the "['#block']->region" object doesn't exist in drupal 8, and I can't seem to find an alternative. Is it still possible to do this?

Thanks!

So, getting everything working here is the code I got to work.

use Drupal\block\Entity\Block;
/**
 * Implements hook_preprocess_block().
 */
function harfang_preprocess_block(&$variables) {
  $block = Block::load($variables['elements']['#id']);
  $region = $block->getRegion();

 // Add classes to all bocks in footer region.
  if($region == 'footer') {
 // Do something.
  }
}

added the use statement at the top and removed the non-joiners


In Drupal 7, how can I include a CSS file only when the front page is being viewed? I'd like to include a particular CSS file only when the front page is being viewed, since it only applies to the front page, and it's a relatively large file. I know that the solution will involve using drupal_add_css(), but I'm not sure where in my theme's template.php file this would go. Is there a particular hook within my theme that I should be implementing to use this? Thanks.

EDIT: I essentially have the code down, I'm just not sure what hook is available to my theme files to implement. The actual code will look something like...

if (!strlen(request_path())) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
}

Try this:

function mytheme_preprocess_page (&$variables)
{
  if (drupal_is_front_page()) {
    drupal_add_css(drupal_get_path('theme','mytheme'). '/css/front.css');
  }
}

See template_preprocess_page and drupal_is_front_page for more info.


Print something in a tlp file if a field isnt empty I need to print some html in a node tpl file if a certain field is not empty. The follwing is giving me a white screen:

<?php if (!empty($content['field_hotel_sat_nav'])) {
                        print '
The field is not empty
'
            }
?>

Try this code:

<?php
  if ($content['field_hotel_sat_nav'] != '') {

    //Do something

  }
?>


how to display labels of empty profile fields I have enabled profile2 module. There is profile type called personal information and it has related manage fields.I want to display the labels for empty profile fields on profile page. The fields are visible when it contains information but how to display the labels of empty profile fields to prompt the user to fill out empty fields. Does anyone have the solution? Please help.
Thank you.

Use the Empty Fields module. With this you can place custom text as filler until content has been entered. This will have the labels show up.


How can I alter (theme) the default content feed? How can I alter (theme) the default content feed on the front page (the list of node teasers) so that my 'thumbnail' image style is used instead of my 'medium' style for the images contained in the nodes.

All I can think of is to create my own page--front.tpl.php file or use is_front in node.tpl.php. Either way it means creating a custom listing for the front page.

Thanks.

The best way to do this if you're running stock D7 is in config: you'll want to change the default field dislpay settings by clicking "manage display" on the Article content type in admin/structure/type.

Click the gear icon to adjust the display type:


Collapsed and collapsible Field Sets in Admin I have created a fieldset (which groups a field collection). Because it has a few nested levels and many fields, I want it to be shown collapsed. I am trying this code but it does not work. The id is retrieved directly from the source code of the web browser. The fieldset is the top-level, and there are more fieldsets inside of it. The form is displayed in the Admin page, the node edit form. The field "field-seo-general" is a #container.

function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "my_form"){
        $form["field-seo-general"]['options']['attributes']["#collapsible"] = TRUE;
        $form["field-seo-general"]['options']['attributes']["#collapsed"] = TRUE;
      ...
} // function

I have solved it installing the module Field Collection Fieldset, and instead of Embedding the Field Collection, I have put it as a Fieldset, and then one of the options is to be shown Collapsed at rendering. All with a module.


Removing "node" path from "node/add/*" URLs How can I remove the "node" part from "node/add" URLs? I have clean URLs on, and I have successfully used Pathauto to remove "node" from other paths.

If you go to admin/config/search/path/add then you can easily alias node/add/type to whatever you want.  For example, if you're using a node type called contact-form for a contact page, then just add contact-form as an alias for node/add/contact-form.


Creating a Redirect from old url to root I'm trying to create a 301 redirect from a link from my old site format(because links are coming in from this URL).

The URL I'd like to redirect is like this:

http://www.example.com/Default.aspx?id=index

I'd like to simply have the above url redirect to the homepage:

http://example.com

I've tried several options, but nothing seems to be working.
Any help?

Assuming this question is about D7, you can use the Rules module for this, with a custom rule that looks like so:

{ "rules_redirect_some_path_to_the_frontpage" : {
    "LABEL" : "Redirect some path to the frontpage",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Default.aspx?id=index",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path is no longer in use, you will be redirected automatically to the homepage" } },
      { "redirect" : { "url" : "[site:url]" } }
    ]
  }
}

If you have the Rules UI module enabled, you should be able to just import the above rule, then "enable" it, and that's all you'd need to do.

What this rule actually does:

Check if the current path is Default.aspx?id=index
If that's indeed the path, then a redirect to your frontpage will be performed.

Note: feel free to adapt the first Rules Action (to display a message), or if you don't want such message at all, just remove that Rules Action.


How to set fields value in Views PHP module? How to define the fields value in Views PHP module?

First you need to load the node

$node = node_load($data->nid);

then you can either access

$value=$node->field_name['und'][0]['value'];

or assign

$node->field_time['und'][0]['value'] = $value

values to the node items. You may need to print out the content of the $node object to see the actual field_name

$node_r = print_r($node, true);
watchdog('NODE PRINT OUT', "$node_r");

then view it in the recent log mesages

admin/reports/dblog

Ensure the DBlog (Database logging) core module is enabled


Which are the file_save_upload() validators? In the file_save_upload() function, what keys can $validators take? I cannot find answers anywhere.

You can see the validators in core at the end of this listing:

http://api.drupal.org/api/drupal/includes%21file.inc/group/file/7

the ones starting with file_validate_

Also there's an example of the array structure here: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_validate_picture/7


Adding Search to Responsive Menu Module I'm trying to set up responsive menu module (https://drupal.org/project/responsive_menus) and add an advanced search inside of it. I've been unable to get the advanced search to show up in the responsive menu. I am using the codrops' Google Nexus* theme and Drupal 7.

If its not possible to add search inside Responsive Menu, or if there is an alternative module or solution I am open to that as well. Any help would be appreciated. Thank you!

Can you make a "feature request" over on drupal.org about this?
https://drupal.org/node/add/project-issue/responsive_menus

It doesn't have a way to do anything other than the left-side vertical menu currently.  I'd like the Google Nexus style to be able to use the top horizontal area as well.


Translating pages, only the last version remains I am setting up my first Drupal site, with Drupal 7, which is multilingual; I thought after surprisingly much work I had set it up correctly.
I can choose a language for each page, and translate pages, but when I translate a page, all translations of that page will have the same text: the last one I entered. So the text of the other language versions is overwritten by the last edited one. Did I do anything wrong? Is there a bug?

You may have a look here.

The login credentials, if you want to test it are: test, test.

The problem is the 'synchronize translations' submodule of i18n was enabled.
I took the privilege of disabling it on your test site.
I know multilanguage is a tricky part in D7 but you should start with the basics of multilanguage by enabling locale, content translation, Internationalization, block languages, multilingual content and string translation. Just to get a feeling of what you're doing.
Later on you can activate some other submodules of the i18n module but in my opinion it is never a good idea to activate all at once. Activating to many modules at once can result in losing control of your installation like you're having right now.


Why do I get the "Maximum function nesting level of 100 reached" error? On all Drupal 8 beta sites, I have this error:

  Maximum function nesting level of '100' reached

Is this a problem with Drupal 8 or my server? How can I fix this error?

It is probably caused by xdebug. Increase nesting level in php.ini

xdebug.max_nesting_level = 200


Migrating to the webserver - what do I have to take care for? What do I have to keep in mind? What do I have to take care for - especially if I have troubles with

file ownership
permissions

If I set up a drupal-commons version 6.25 locally on my machine at home - which is a openSuse 12.1 - everything runs nice. All goes smoothly.
especially if I want to upload files - no problem here.
But if I want to do the same - uploading pictures - on the version that I either installed directly on the webserver or ported over to the webserver I have terrible issues.
It is not possible to upload any file - I have troubles and get error messages....
regarding the temp-directory (which is complained to be missing)
regarding the permissions on site/default/files
Well some words regarding the server and the circumstances and conditions it runs with: my serveradmin works with the setgit bit
I run a linux sever that is administered by a friend of me. He prepares the chown and permissions - with the setgit-bit to on. See the issues with the server described more detailed here
on a sitenote:
Well the trouble is that i get lost the setgitbit every time when I touch the permissions with FileZilla.
That is the terrible issue! Note - at the moment I do not have a access to the server wit WinSCP - WinSCP can set the Setgit. FileZilla cannot do this at all!
The question is: what do I have to take care for if porting over Drupal. Both versions:
.a a Drupal commons version 6.25 and
.b a Drupal version 7.12
Do I have to set up a tmp directory again? Note: if I create the whole installation here on my local server then my assumption is, that all things have been done properly.
What experience do you have - what do I have to take care for?
I love to see a fruitful discussion.

I strongly recommend you look into using drush to synchronise sites.  Although it admittedly will not solve your permission woes, it will greatly ease the pain of doing this for every update you need to push.

As for permissions, there are many ways of configuring depending on your set-up and how safe you want to be. I usually just have all files belong to webserver and add my user to webservers group, but like I said many things can go wrong with permissions.

Coming back to drush rsync, I would most probably attack this by setting up 2 aliases, one for @dev and the other one for @live (or @stage). So, with those aliases you can rsync  via the simple command  drush rsync @dev @live your whole site will be transferred. Just set proper permissions the first time you do this on /files and other folders needing write access, and you should be set to go.

PS: Do look into drush sql-copy and other goodies hidden in drush.  I cannot imagine doing this manually anymore, I have used aliases for a few years now and would NOT go back the old way!

Hope that helps, good-luck!


how to get the value of list field type (check boxes) $node=node_load(18);
$logo_img = file_create_url($node->field_site_logo[$node->language][0]['uri']); //origional image path
$show_logo = $node->field_options_site_logo['value']; //original image path
if(isset($logo_img)) {
  $web_logo = theme('image_style', array('path' => $node->field_site_logo[$node->language][0]['uri'], 'style_name' => 'site_logo'));
  print $web_logo;
}

I created CMS option of uploading site logo. I also added an option of show/hide this logo (form in node 18). Using the above code, I am able to load the image but don't know how to hide it if this option is not selected. I just want to know how to get the value of this check box. I can write the condition to show or hide this. Please help. Also, please let me know how to include alt option to the above image.

Where do you put this PHP code? If it's in the page.tpl.php, then you can use the $logovariable to display the field or not.

Otherwise, this configuration is available in your theme. So you need to get your theme configuration, with theme_get_setting. You should have a variable 'toggle_logo' or something like this. The full code would be

$test = theme_get_setting("toggle_logo");
if($test) {
   //Put your code here
}

If you're using different theme, or you need to get this value for a specific theme, then you need to pass your theme name as second parameter of the function, for example:

$test = theme_get_setting("toggle_logo", "my_custom_theme");

[EDIT FULL ANSWER]

So you just need to check the value of the field field_options_site_logo before outputing the image:

$node=node_load(18);
if(isset($node->field_options_site_logo['und'][0]['value']) && $node->field_options_site_logo['und'][0]['value'] == 'yes') {
  $logo_img = file_create_url($node->field_site_logo[$node->language][0]['uri']); //origional image path
  $show_logo = $node->field_options_site_logo['value']; //original image path
  if(isset($logo_img)) {
    $web_logo = theme('image_style', array('path' => $node->field_site_logo[$node->language][0]['uri'], 'style_name' => 'site_logo'));
    print $web_logo;
  }
}


Make multiple templates for site (new one for many pages) So I have my page-front.tpl.php and page.tpl.php.  I'm making a music website for a client and literally only need like 5 or 6 pages.  How can I basically make a php page from scratch for each page?  Thank you.

P.S. I think I'd rather make it all from scratch than use panels

Drupal has flexible theme system. You can create different sections of your site and theme and select dedicated template according to path. This is what I am suggesting you.

e.g. your site has different pages(paths) targeting different sections.

example.com/music                   (page-music.tpl.php)
example.com/artist                  (page-artist.tpl.php)
example.com/artist/profile/%        (page-artist-profile.tpl.php)
example.com/store                   (page-store.tpl.php)


How to create a rule to notify administrators of new comments by non-administrators? I would like to use Rules to notify all administrator users of new comments that have been posted to the site.

I can get as far as getting the notifications working for all comments, but I would like to set it for notifications to just comments by non-administrators. Administrators will then not be notified for their own responses to comments.

Any hints?

Note: I want to do this so that I just have to specify the admin role only, as many new roles will be added that are non-admin roles. This way I do not have to update the rule every time a new role is added by site admins.

What you are trying to do is pretty straightforward. I suspect that you have a Rule that is active and has the following:

On event After publishing a comment

(no condition)

DO

Send an email to user (or whatever you want to be your notification method; it doesn't really matter)

What you need to do is add a condition by clicking on the respective option. In the "Condition to add" option, you need to select: "User has role(s)" and press Next.

In the next page, select "Published Comment Author" in the User option and select all the roles of your site except for the Admin role. Leave the rest unchanged.

Now your admins should be receiving notifications for comments from non-admins only.


Drupal 7 Views filter criteria Entity Reference At the moment i'm making a drupal environment.

I'm trying to reach the following:

"Use a views to show my content types, but only the content types that have lets say "ads" as a field_type (Entity Refrence)."

Setup:

Content Type: Packets

Title
Image
Entity Reference field_type to Content type: packets_types..

It gives me blank result.. the sort criteria is just working fine on thee Pakket_type

I've tried the Relationships, but this didn't changed anything for me.

If there is someone out there to help me, i would love that =)

Already thanks!

Correct me if Im wrong but I think the problem is that Type Reference filed is actually node id.

What worked for me is the following:

Add a relationship from the Type Reference field.
Add the field you are trying to use as filter and use relationship from (1). Set your operator and value.
Profit!

P.S. It seems that using Taxonomy terms would be a better solution though i have no idea what you are trying to achive.


Alternative to Field Collection Does anyone know an alternative to the module "field collection" ?

While the concept of field collection is very good, I'm having trouble with the collaboration of other modules, like e.g. features or search api. So I'm looking for alternatives.

See the Multifield module.

  This project seeks to provide a true compound field solution for
  Drupal 7. As much as I love Field collection, it still has to save
  actual entities, and can cause performance problems due to having to
  load all the referenced field collection entities on node, or parent
  entity load.

I am not sure of its compatibility with Features or Search API though.


How do I hide the end date part of a Date field but not the time? I have a content type that uses Date, it has a start date with time, and end date and can even repeat. But I need to hide the part of date that handles the end date and leave just the time, most events in this content type happen the same day, so that the user doesn't gets confused when making a new node of this particular content type. Any ideas?

To control the display of the date field, you need to do a few things:

Add a date format that will match your requirements, for example, display time only from the date. To do that, go to Configuration > Regional and language > Date and time > tab Formats (/admin/config/regional/date-time/formats). Add a new format, for example, for time only, add g:i a
Add a date type (admin/config/regional/date-time) - for example, call it "Time only" and use that new format from #1 that was added (on the list of formats you should now see the time only value)
In your content type, under Display tab, change the date field to use that new date display "Time only". Optionally, if you want to change how the date is displayed in a View generated page, select that new date display in the date field display options.


Adding classes to menu items Hi I am developing a custom module for menus and I want to add active class to menu items based on the current path. For this I have tried theme_menu_link() but this function only provides the mlid(menu link ID) of the original links and not all the menu items. But I need the mlid of all individual menu links.

Is there any alternate hook for this functionality, or any other way to do this?

have a look at l() function in includes/common.inc:

...
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
    (empty($options['language']) || $options['language']->language == $language_url->language)) {
  $options['attributes']['class'][] = 'active';
}
...


hide field based on its value or value of another hidden field I need to hide a radio button field of a content type (not a form) only on the edit view based either on its own value or based on the value of another field that is already hidden.

Dependencies does not work,  I think because the other field is already hidden and because it does not allow the dependent and dependee field to be the same field.

Any ideas?

You can give a try to this module: https://www.drupal.org/project/ffc


How to construct a db_query() with complex criteria? I'm getting into the database API and it's really interesting how it works. The function db_query() makes querying the database very easy. However, I don't quite understand placeholders and the relationship between placeholders and $args parameter.

Example #1, the first comment on the doc page, can be written as:

$result = db_query('SELECT n.field1, n.field2, ... FROM {table} n
            WHERE n.field0 = :field0', array(':field0' => $field0value));
foreach ($result as $record) {
  // Data are in $record->field1, $record->field2, ...

The db_query function has two parameters; the first is an SQL query and the second is an array definition. The two are related by ":field0", which is called a placeholder. The fields and table are also modified by something called "n"; I don't know what that is.

I found that the above code works. However, I also found that it works and yields the same results without the n's, without the placeholder, and without the array: (The function syntax says the default if the array is not provided is simply "array()".)

'SELECT field1, field2, ... FROM table WHERE field0 = ' . $field0value

I tried this because I need to use complex criteria in which it is not clear what to do with the placeholder and array:

SELECT * FROM table WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"

I ran this in phpMyAdmin and it works fine. It works by first looking at field1 and if there's something there, it uses that but if it's empty then it takes the value from field2. It then combines that with "value1" and selects records for which the result equals "value2".

So I put that in db_query like so:

db_query('SELECT * FROM {table} WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"');

which resulted in the message:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause': SELECT * FROM {table} WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"; Array ( ) in include_once() (line 87 of ....php).

Drupal does not seem to be complaining about the use of the concat and if functions, so it seems to be capable of handling them.
The symbol between the words "column" and "in" above is a pair of single quotes. So it looks like Drupal is looking for a column designation somewhere and not finding one. My guess is it's looking for something in the empty array. Do I need to use one or more placeholders and some form of array construct in order to get this to work?

Thanks for your help.

The answer provided in the comment above did get the code to work, but according to Jaypan in the Drupal forums, using that solution is a security risk. The error was caused by not using placeholders and the associated array argument, and the purpose of those devices is to prevent SQL injection attacks. The solution of reversing the quotation marks was able to stop the error messages, but at the cost of leaving open a security hole in the code. Jaypan gave me the code to implement the complex criteria with placeholders:

<?php
db_query('SELECT * FROM {table} WHERE concat(if(field1 = :empty, field2, field1), :value1) = :value2',
array(':empty' => '', ':value1' => 'value1', ':value2' => 'value2');
?>

I've implemented that and it works. The pattern seems clear enough to be able to adapt it to other complex criteria in the future, although it would be nice if we had some documentation of placeholders and their syntax.

===============

Edit: It turns out there is some documentation of placeholders, although it's not comprehensive and the discussion with Jaypan (linked above) helped to clarify things.


How do I hide Bartik Main Menu on front page from unauthenticated users? I have a private website in which content can only be viewed by authenticated users.  All I want is the login box for non authenticated users.  I am using NodeAccess and also Rules module to do this.  Seems to work fine with one exception.  The pages which should only be visible after login show their links to the anonymous user on the Bartik theme main menu right on the home page.  All menu items appear including those for pages specifically limited to administrator viewing.  True, clicking on them merely brings up the login dialog box so the individual can't see the page, however, I don't want the menu itself to appear at all until the person is authenticated. How do I make the entire menu disappear if unautenticated? Thanks in advance.

In case you are using D7, when you configure your menu block, you have a section called "visibility settings".There select the Roles tab and check the option "authenticated user" under "show block for specific roles". Then click save block.


In Drupal 7, where is the code for the "powered by Drupal" block? The "powered by Drupal" block used to be a module in Drupal 6.  I can not find this module in Drupal 7.  Where do I find this module/block? So I can duplicate it, or modify it.

The contents is provided by theme_system_powered_by(), which is turned into a block by system_block_info() and system_block_view().


How to set a default value for Simple hierarchical select? I tried to implement hook_form_alter in order to pass default value to Simple hierarhical select views exposed filter.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $tid = get_tid_from_termalias (arg(1)); // here I get tid
  $form_state['input']['field_sity1_tid'] = (!empty($tid)) ? $tid : 'All';
  $form_state['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#default_value'] = (!empty($tid)) ? $tid : 'All';
  $form['field_sity1_tid']['#value'] = (!empty($tid)) ? $tid : 'All';
}

I see that shs.js creates 2 selects, one hidden and one shown. My code changes only the value in the hidden select while second select always remains 'All'. How to change the visible select's default value?

Hmm, That's a challenge to set default with Simple hierarchical select using form alter.

As they are handling options to taxonomy in js.

But we have another way to set default value for the field. Passing in URL.
Like : http://localhost/drupal/demo-view?field_test_tid=1

Hope this will help.
Just trying other way.


Drupal Views page URL problem I've created page with Views, which is displaying gallery (image fields).

I've set the path to node/%/gallery.

Page is working when I access "http://example.com/node/9/gallery" but it doesn't work when I access it with alias "http://example.com/event/example-name/gallery"

Any ideas?

do not use node/%/.. as your path, this will disturb the default routing system.

  change the view's path to gallery/% or something.

if you want to keep this url, register a local task like here How to add a local task tab to node view?

and in this page callback you can display the view with views_embed_view,
 in this case you will remove the path of the view, or change it to a test-path.

but still, the alias with /gallery needs to be registered too !


Not able to make simple node path show up in "crumbs module" I have read all the documentation, and I have been clicking about wildly for hours, and I have used the "debug" tab for the Crumbs module, and I still cannot get the simplest path to show up:

Home > Content type > Node title

It always gives me: Home > Node title

This seems a simple task. Someone please give me the steps...

Many thanks.

What is the path you want to link to for "Content type" ? Do you have e.g. a view at this url?

You need to have something at this url, and Crumbs needs to be able to determine a title at this url. Otherwise it won't appear in the breadcrumb.

So, what you can do:

Create a view at path "events" or "news" or whatever.
Let the title of the view be "Events" or "News". There are two ways to do this:

In the Views admin, "Page settings", click "Menu", and set it to something where you can specify a title. OR
Choose your favourite menu, and create a link to the Views page.
It is NOT enough for the view to have a title by itself. It needs to have a title in the menu/routing system. (*)

In Crumbs "Entity parent" settings, set "events" or "news" as the parent path for the respective node type.

There are other ways to create a parent page like "news" or "events". For instance, I like to use a "page" content type with a "blockreference" field to embed a views block.

(*) Maybe I should create a plugin that uses the real page title of the View as the title of the breadcrumb link.


Is there a way to add infinite number of Add More on webforms in Drupal 6 Simple question for all of you here dealing with Drupal 6.x...

With Drupal's Add More module, is there a way to configure my webform so that there is no limit on how many of a specific fields I can add more of?

For instance, I have a web form where users can request titles. I would like to enable the user to add as many titles as they would like. Is this doable or does there have to be a theoretical limit?

I believe the answer is no. At least I've never found a way to do it. I've always had to add 10+ fields and use webform_conditional to hide them until they fill in one and then show the next, or provide a drop down so they can select how many fields to fill. Not ideal but I'm not sure any other way to do it.


How do I remap folder to different folder in URL? I have developed website in Drupal. There is folder(e.g., my-demo) which contains few PHP files which are developed in plain PHP. The my-demo directory is placed in the Drupal root directory.

Now I want to access this folder in a menu. If I put http://example.com/my-demo, it is accessible. I want the folder path to be like http://example.com/product-details/my-demo in the menu, without creating the product-details directory, because I have already mapped product-details to a path alias.

How can I achieve this?

Yes you can do this with remapping in .htaccess

Find this code:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

And add this line after it:

RewriteRule ^product-details/my-demo/(.*) my-demo/$1

So the complete version will be:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^product-details/my-demo/(.*) my-demo/$1

See documentation for more examples.


Validate URL with a specific pattern? Anyone know of a module that can check the base path of the URL to ensure the user is entering the correct URL?

I.e. the field is asking for the Facebook URL but they put in a Twitter one.

So should the user enter a different URL they won’t be able to continue unless the link contains www.facebook.com/.

Not a module, but you can add a custom validator that parses the string that the user put in for URL to see whether it contains the expected strings, e.g.

if (strpos($url, 'facebook.com') === 0) { ... }

Note the triple-equals is necessary with strpos because otherwise "found at position zero" (return value of 0) is falsey, and so is "not found" (no return value).


How to hide the grid lines from Yaxis and draw only one line from specific Yaxis points? I am creating a view using the Charts module. I am using the (interactive) Google Charts API as the charting engine.

Is it possible to hide other gridlines and only display one grid line from a specific y axis point?

Just like in this image:

Refer to HowTos about vertical axis, located within the Community documentation of the Charts module. Here is the relevant part of it:

Refer to #2356053-2: Automatically adjusted value range for vertical axis, which explains how to automatically adjust the minimum and maximum of the Y-axis to fit the available data. Specifying a "Max" and "Min" value is optional. Specifying a minimum of 0 is recommended in the event that numbers will always be positive, while for the maximum value the recommendation is (usually) to just leave it empty.
To experiment with this in your own site, use the column chart with the number of nodes for each content type (located in charts/examples/views ):

If you do not specify a maximum there, you get a close to perfect chart, no?
If however you only have a few nodes (like a dozen or so) but use a huge maximum (like 240 ...), the chart looks not so nice, right?


Create a layout 3 column with 2-1-2 teasers I would like to create a layout like in this image.

It's all the same content type, and I am displaying images.

The columns have all the same width, the first columns -left- contains 2 teasers ( one below the other), the second one -center- contains 1 teaser, the last column -right- contains 2 teasers ( one below the other).

The image teaser on the center column has the same width of the other but it has the double of height, so I will need another image style or another field.

I can't achieve this just with css otherwise the images will look stretched/cropped.

I don't know how to approach to this issue. How to say that each two nodes, I need to display one with a different image style or another field image, using views.

Any help, suggestion, idea would be appreciate!

This solution is not perfect, but will most likely be the fastest to achieve:

In hook_node_preprocess() render the image field twice, once with small and once with large image style.
Edit your node--YOUR-CTYPE.tpl.php file and display both images.
Use CSS to display the correct one. You can basically do this:

.views-row-1 .your-large-image-selector,
.views-row-2 .your-large-image-selector,
.views-row-4 .your-large-image-selector,
.views-row-5 .your-large-image-selector {
  /* Hide large image. */
}
.views-row-3 .your-small-image-selector {
  /* Hide small image. */
}

Other than that, you could try doing this in a custom module, unless you really need Views for something. I think doing this through a custom module makes more sense if you have to display a larger number of images on the page (e.g. 20-30), because with the approach above you will end up with twice as much images.

Here's what you would need to do in a custom module:

Add hook_theme() implementation and declare your own custom template. Here you would display the first two items on the left, third in the middle and the last two in the right column. The arguments for the template would be just an array called items for example.
Get all nodes you want to display, prepare the output and split them into groups of 5. Every third item would use the larger image style.
Loop through the groups and theme the output based on your custom theme.
Put everything together and display on the page.

This way you won't have 2 images for each node, but you will have to write custom code.

There are other ways to achieve this, but I believe developer sanity should not be overlooked. The ways I suggested above are more or less easy to do.

Hope this helps.


Importing products via Feeds csv import is generating error: "General error: 1366 Incorrect string value:" I'm trying to import products using the import via csv functionality within feeds and am getting the following errors:

SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'field_description_value' at row 1
Error message SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'message' at row 1

I also have the commerce-feeds module installed.

There is quite a lot of stuff on this on drupal.org, but it all seems to be contradictory and I am more than a little lost. I am a non-coder and a relatively inexperienced configurator at best.

My csv is definitely encoded UTF-8. I have opened it in Notepad++ and converted it to UTF-8.

I found this post on stack overflow utf-8 database problem The line "It seems your connection is not set to UTF8 but some other 8 bit encoding like ISO Latin" seems to indicate to me that there may be a bug in the Feeds or Commerce Feeds modules in that the database connection cannot cope with csv input files encoded UTF-8. Could that be correct?

I'd really appreciate some sage advice on this. I am completely stuck.

Maybe the csv is encoded in UTF8, but everything else needs to be UTF8: UTF8 all the way through

I don't know exactly in what step is failing, did you check the databases and tables collation?
Drupal has by default the "SET NAMES="utf8", http://drupal.org/node/310447

Hopefully the Feeds maintainers have a look to your case here. http://drupal.org/node/1140194 , it seems you are not alone.


How to make payments on recurring product automatically(RESOLVED) I have drupal 7 and commerce modules. I'm using Stripe payment system with module commerce_stripe. Customer's card details are stored in file (commerce card in file).
Site sells recurring products.

My question is:
can I make payments on recurring products automatically without user agreement?
And if I can how should I do it?

Thanks in advance.

UPDATE

Found how recurring entities and card on file work. After user bought subscription first time his card data saves into file to use it in later payments. When user should pay for subscription again cron commerce_recurring_cron should run. This cron checks recurring entities and if it's time to pay creates an order with status pending.

When this cron runs once again it charges payments and necessary amount of money debited from users account.

So everything I need is processed and my customer is happy.

If you're using the Card on File module, that means you're storing tokens that point to card data stored securely by the payment gateway itself. What you then need is to combine that with Commerce Recurring or the Commerce License suite to create the schedule for recurring charges and Commerce Dunning to react to payment failures.


Is complex field validation possible with WebForm? WebForm is a very nicely done module, but (at least at first glance) it seems to lack some things that I expect to need.

Specifically, I'd like a way to specify more complex field requirements than just a boolean.  For instance, what if I have a form with an e-mail address field and a telephone field, and I want the user to be required to enter at least one of the two.  In other words, if they enter an e-mail address, they don't need to enter a phone number; and if they enter a phone number, they don't need to enter an e-mail address.

Is this possible with WebForm?

Try using the WebForm Validation module.

  The following validation rules are currently included:

  Numeric values (optionally specify min and / or max value)
  Minimum length
  Maximum length
  Minimum number of words
  Maximum number of words
  Equal values on multiple fields
  Unique values on multiple fields
  Specific value
  Require at least one of two fields
  Require at least one of several fields
  Minimum number of selections required
  Maximum number of selections allowed
  Exact number of selections required
  Plain text (disallow tags)
  Regular expression
  Must be empty (Anti-Spam: Hide with CSS)
  Words blacklist
  Must match a username


Display a view block with a list of content excluding the one currently displayed on the page I sometimes use contextual filters to display fields matching the content ID from url

In that case , i would like to display a list of content as a view block , except the one that is displayed

It would require to :

negate the condition " Content ID from URL contextual filters "

or

being able to choose the 'content id from url' as value of a view filter

I don't know how to do the first option.
That token conditions module would do for the second option but is not stable
https://www.drupal.org/project/token_conditions

How can i possibly do that then except JS?

Considering the first option, it is simple :

add a contextual filter of type "ID: Content" with the following configuration :

WHEN THE FILTER VALUE IS NOT AVAILABLE > provide a default value > content id from url
Go all the way down in the "more" section, expand it and check "exclude".
Then click apply
And save the views

That's it !


How to test an exception have been logged instead of thrown? I have the following code that throws catch an exption:

  public function deliverPrintable(array $entities, PrintEngineInterface $print_engine, $force_download = FALSE, $use_default_css = TRUE) {
    try {
      $renderer = $this->prepareRenderer($entities, $print_engine, $use_default_css);
    } catch (\InvalidArgumentException $e) {
      watchdog_exception('entity_print', $e);
      return FALSE;
    }
  }

The test below will fail because it's expecting an exception to be thrown:

  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   * @expectedException \InvalidArgumentException
   * @expectedExceptionMessage You must pass at least 1 entity
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
  }

I took out the exception part of the method and left and just tested the returned value. But I would like to test that an exception have been logged is this possible?

  /**
   * Test that you must pass at least 1 entity.
   *
   * @covers ::deliverPrintable
   */
  public function testNoEntities() {
    $print_engine = $this->container->get('plugin.manager.entity_print.print_engine')->createInstance('testprintengine');
    $return = $this->container->get('entity_print.print_builder')->deliverPrintable([], $print_engine, TRUE);
    $this->assertFalse($return);
    // @TODO test that an exception have been logged?
  }

There is no standard test feature to assert a logged message.

The simplest approach is to just install dblog in your test and then inspect the watchdog table for the expected record.

Alternatively, You could write your own log backend that stores it in memory and then access it from there if you don't want to install the necessary database tables in the test.

Or, don't use watchdog_exception() but an injected logger service that you can mock and then configure that to expect the call.


Overwrite the default taxonomy view I want to overwrite the default taxonomy view. I am cloning the original one, but the view I get does not provide any item.

How can I achieve this?
Also could I have two views, default and cloned enabled and visible through a panel?

It seems to be [a critical issue on an upgrade of the Views module1.

Can't really comment on the no results problem.

However, the Taxonomy View renders as a page, so no you can't have both the original view and the cloned view enabled at the same time and expect them both to override taxonomy pages.

The only way to have both enabled is to set a different path for each view, which means one or both views would not override taxonomy pages at all.

If what you want to achieve is overriding taxonomy pages for terms of specific vocabularies, what I did was use the Disable Taxonomy Term Listing module to completely hide results of the normal taxonomy page, then replaced that content with taxonomy block views.  If this isn't what you are looking for then feel free to disregard this all ;-)


Change Product type's referenced Variation type Once a Product type is created, I cannot change Variation type in Product type. Is this a feature, or is there a way to change it?

Is it safe if I change it in the database?

This is useful because I want to use entity_clone and create multiple similar Product types and change the variation type after the clone.

It's safe as long as you don't have any products. We need to change the logic in Commerce so that it checks for existence of product entities, instead of just checking whether the product type is new. Continued in your issue: https://www.drupal.org/project/commerce/issues/3014686


Need to add SKU to order confirmation email - Commerce 2 I have been able to customize the order confirmation email twig file for a client to some degree, however when it comes to adding the SKU for each item ordered I cannot find a way to have it populate. I have tried to insert the commerce checkout order summary block that displays each product variation's sku, it did not populate in the email. I have also looked at the order item table which does include the SKU for the items ordered so I cannot pull from there.

Any advice on how to pull the SKU's into the order confirmation email twig file?

I found this article that helped:

https://www.drupal.org/forum/support/module-development-and-code-questions/2018-08-23/drupal-8-commerce-2-get-item-from

This is my commerce-order-receipt twig that displays the quantity, title, price and in a row below the sku.

Hope it helps.

      {{ 'Order Confirmation'|t }}

        {{ 'Order #@number details:'|t({'@number': order_entity.getOrderNumber}) }}

        {% block order_items %}

          {% for order_item in order_entity.getItems %}
           {% set product = order_item.getPurchasedEntity %}

              {{ order_item.getQuantity|number_format }} x

              {{ order_item.label }}
              {{ order_item.getTotalPrice|commerce_price_format }}

              SKU:

              {{ product.getSku }}

          {% endfor %}

        {% endblock %}

        {% if (billing_information or shipping_information) %}

            {% if shipping_information %}
              {{ 'Shipping Information'|t }}
            {% endif %}
            {% if billing_information %}
              {{ 'Billing Information'|t }}
            {% endif %}

            {% if shipping_information %}

                {% block shipping_information %}
                  {{ shipping_information }}
                {% endblock %}

            {% endif %}
            {% if billing_information %}

                {% block billing_information %}
                  {{ billing_information }}
                {% endblock %}

            {% endif %}

          {% if payment_method %}

              {{ 'Payment Method'|t }}

                {% block payment_method %}

{{ payment_method }}

                {% endblock %}

          {% endif %}

        {% endif %}

        {{ 'Subtotal: @subtotal'|t({'@subtotal': totals.subtotal|commerce_price_format}) }}

    {% for adjustment in totals.adjustments %}

        {{ adjustment.label }}: {{ adjustment.total|commerce_price_format }}

    {% endfor %}

        {{ 'Order Total: @total'|t({'@total': order_entity.getTotalPrice|commerce_price_format}) }}

        {% block additional_information %}
          {{ 'Thank you for your order!'|t }}
        {% endblock %}


How to choose multisite instance inside script running from main Drupal directory? As in question. I know that I can use drush command, but I have small script and I don't want to create module from it. Now I calling that script inside main Drupal folder (no multisites).

Inside that script I just bootstraping Drupal (I need Access to Drupal API):

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
#db integration

(The same PHP header I use for e.g unit tests class)

It is possible to run such script in multisite enviromnent too?

My problem is that every sites config settings.php has db name called 'default'. So I don't know how to use db_set_active properly.

I have script that creating data  (txt file) for Menu Import module. I need access to Drupal and Joomla db, because I need to migrate menu from Joomla.

Anyway here is a script

Since you know the database name, you can dynamically set a database name which you will call with db_set_active().

This is copy/pasted from the link below.

  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

More about this can be found here.