What is the replacement pattern in rewrite ouput for current user id? I have a custom content entity listed with Views.
I want to conditionally display some information depending on the fact that the row is related to the current user.
I tried {{ user:uid }} with no success.
Any idea?

With help from @4k4, I could use 'Custom text' to add on each row of my Views output two 'buttons' (Edit, Delete) depending on the current user:

{% if user_id_1=="[current-user:uid]"  %}

{% endif %}

As you can see, there is also a button in the header (Add).
I'd like to have this button displayed only if the user is not anonymous.
I tried (in either Text area or Unfiltered text):

{% if "0"=="[current-user:uid]"  %}
Ajouter
{% endif %}

but it doesn't work:

Any idea why?

The twig variables in {{ }} are replacement patterns for fields. Globally available tokens are accessed by their usual square brackets syntax:

[current-user:uid]

Custom text field

This token works in a global text area, but not a custom text field, because this plugin Drupal\views\Plugin\views\field\Custom doesn't have global token replacement. You need to extend it and override renderAltered():

/src/Plugin/views/field/CustomToken.php

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\field\Custom;

/**
 * A handler to provide a field extending custom by global token replacement.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("custom")
 */
class CustomToken extends Custom {

  /**
   * {@inheritdoc}
   */
protected function renderAltered($alter, $tokens) {
    return $this->viewsTokenReplace($this->globalTokenReplace($alter['text']), $tokens);
  }
}

and tell the plugin manager about the new class:

mymodule.module:

function mymodule_views_plugins_field_alter(array &$plugins) {
  $plugins['custom']['class'] = 'Drupal\mymodule\Plugin\views\field\CustomToken';
}

This applies the function globalTokenReplace() before the twig patterns are replaced.

Then you can use

{% if anotherfield_id == '[current-user:uid]' %} YES {% else %} NO {% endif %}

You have to enclose the token in single quotes so that you get a valid twig syntax after the global tokens are replaced.

Global text area

A global text area in header/footer is exactly the opposite, it supports global tokens but not Twig.

You could do the same as before and add Twig support in a custom plugin. But there is an easier solution. Install the module Twig input filter and go to "Text formats and editors" in Configuration and enable the Twig filter for the text format you use in the text area.


How to prevent programmatically created blocks from caching I've been working with Drupal 7 for a couple of years but am new to Drupal 8, and am just getting into building custom modules.

What I have built is a module that alters Drupal Commerce in order to make it work smoother for sponsoring children (so that it doesn't feel like you are buying children).

It does a couple of things:
1. If you add a second product to the cart, it deletes your old cart.
2. After clicking add to cart, it redirects you to an information page.
3. That page contains a module-generated block with a "continue" button that takes the customer to checkout.

The issue I am hitting is that the code which generates the checkout button block is getting cached, and is pulling an old, no longer existing order ID number.

Is there a way to prevent the block from getting cached, or a better way to programmatically set up a custom block?

Here is my code:

\src\Plugin\Block\ContinueCheckoutBlock.php

<?php
/**
 * @file
 * Contains \Drupal\commerce_custom\Plugin\Block\ContinueCheckoutBlock.
 */
namespace Drupal\commerce_custom\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Symfony\Component\HttpFoundation;

/**
 * Provides a 'Continue Checkout' block.
 *
 * @Block(
 *   id = "continue_checkout",
 *   admin_label = @Translation("Continue Checkout"),
 *   category = @Translation("Continue Checkout Custom Block")
 * )
 */
class ContinueCheckoutBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */

   public function build() {

      $user = \Drupal::currentUser()->id();
        $connection = \Drupal::database();
    $user_ip = \Drupal::request()->getClientIp();
        $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft' and commerce_order.ip_address = :user_ip order by commerce_order.changed asc limit 1", [':user' => $user, ':user_ip' => $user_ip]);
        $result = $query->fetchAll();
        $order_id = $result[0]->order_id;
    drupal_set_message($order_id);

        return array(
            '#type' =>'markup',
            '#markup' => 'Continue',
            '#cache' => array('max_age'=> 0),
        );
   }
}

commerce_custom.module

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_order\Entity\Order;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function commerce_custom_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $form['actions']['submit']['#value']='Sponsor';
   $form['#validate'][] = 'commerce_custom_form_validate';
   $form['actions']['submit']['#submit'][] = 'commerce_custom_cart_alter_redirect';
}

function commerce_custom_form_validate(array &$form, FormStateInterface $form_state) {

    $user = \Drupal::currentUser()->id();
    $connection = \Drupal::database();
    $user_ip = \Drupal::request()->getClientIp();
    $query = $connection->query("select * from commerce_order_item join commerce_order on commerce_order_item.order_id = commerce_order.order_id where uid = :user and state = 'draft' and commerce_order.ip_address = :user_ip order by commerce_order.changed desc limit 1", [':user' => $user, ':user_ip' => $user_ip]);
    $result = $query->fetchAll();

    $cart_count = $result[0]->quantity;
    $order_id = $result[0]->order_id;

    if ($cart_count > 0 && $order_id) {
        $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($order_id);
        $items = $order->getItems();
        $order->delete();
    }
}

function commerce_custom_cart_alter_redirect(&$form, FormStateInterface $form_state) {
  $responce =  new RedirectResponse('/how-it-works');
  $responce->send();
}

The bug is in your code. max_age should actually be max-age.

See the documentation page for more information: https://www.drupal.org/docs/8/api/cache-api/cache-max-age

You could also set the max age in Jdrupal's answer.


User menu page visible to the author user (uid) The view module has a great function when set a menu tab with contextual filter user:uid, so the user that is author of that node will be able to see the content. Lets say for an example the flag module has a view bookmarks, so when a user choose some node to follow/flag it will be available in his user/%/bookmarks.

How can I do this with custom code?
I have my code here as a test:

<?php
function mymodule_menu() {

    $items = array();

    $items['user/%/add-news'] = array(
        'title' => 'Hello World',
        'page callback' => 'mymodule_user_news',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
    );

    return $items;
}

function mymodule_user_news() {
        return 'Hello world';
}

This "Hello World" everybody can see it. Of course, because I'm using
'access arguments' => array('access content'),

How can I set this page to be visible only for user author?

I'm planning to add here a form, so the user can fill the form and send it to the administrator of the website.

Oh, by the way when I set a link only visible to the author user I use this
 echo l(t("Profile edit"), 'user/' . $GLOBALS['user']->uid . '/edit');

How can I use the $GLOBALS['user']->uid in a module?

Access arguments

  Understanding access arguments in Drupal's menu system can be a little
  confusing, but they are really quite simple. Let's take this example
  and work through the arguments.

<?php
  $items['foo/bar/user'] = array(
    'title' => 'Foobar',
    'description' => 'List, add, and edit Foobars.',
    'page callback' => 'foo_bar_function',
    'access callback' => 'user_access',
    'access arguments' => array('administer users'),
  );
?>

  Permissions Arguments, array('this_permission') Here access arguments
  is the key for an array that contains one item administer users. This
  means that the current user must have permission to administer users
  in order to access the page. Which page? Notice the first line gives
  the path to $item. The path is 'foo/bar/user'.

  In this example, 'administer users' is the string that drupal uses to
  reference permissions. If you go to the permissions page (Administer

      User Management >> Permissions), you can see a list of strings you might use for access arguments. Each permission can be used by your
      module.


Getting $content of content type in template.php I am trying to get form that is used in content type template in template.php.
I am creating node collections with EntityFieldQuery, and I am pulling field values of content type without problem.

But i need to access form, and add it to html stream that i create in template.php

In content type i can do

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

To get form out.

But now in template.php i need that form for specific nodes (im pulling them with EntityFieldQuery) as html, so i can include it to rest of the stream and send the  data in variable, and simply output it where i need it (content type page.)

Thanks!

I'm not sure, if this is what you are looking. But if you want to embed a node-add form you could use the following code.

<?php
$node = new stdClass();
$node->type = 'machine_name_of_your_content_type';
module_load_include('inc', 'node', 'node.pages');
$output = drupal_get_form('machine_name_of_your_content_type_node_form', $node);
print $output;
?>


Why is it so abstract? Please forgive me for asking an open ended question.

Are there various resources that explain WHY different changes were made? I'm getting used to the idea of YAML and TWIG files. I'm just struggling to understand WHY they moved. I'm supportive of learning a new way.

To me, it seems like they took the old TPL files which were decently easy to understand and replaced them with the alternate syntax from TWIG.

What is the functional/practical benefit? is there something I can read or watch to get it?

From what I understand there are two primary reasons this was done. The first was because people were using templates incorrectly - they are supposed to be templates, not logic files. People were putting lots of logic into the tpl.php files, when any logic should be in a preprocess function. The other reason is that TWIG escapes data, preventing people from putting bad code into a template, making Drupal sites more secure overall.


need a special image slider with views Is there any module that works with views and slide images like the following image?

so far I've found about 13 image slider in Drupal but non of them does such thing.

you can achieve that by jCarousel module

This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.


How to add a menu tab to a node to link to an information page to be used by author? I just need some direction from module developers. I would like every node to have an 'information page' that the author can easily view. When they are logged in and viewing the node, I'd like it to appear as a link right along side that node menu bar (where it says "Edit, Revisions, Devel" etc.), called menu tabs.

I'm not very familiar with custom modules, but I'm simply looking for the basic framework, or an example module, that will add that menu link, and also allow me the place to begin adding my code.

I'm basically trying to display Google Analytics data for each node.

Check out the Examples for Developers module, particularly the menu_example sub-module. You are looking to create a MENU_LOCAL_TASK-type menu. This should get you started.


How do I create a "quick post" bookmarklet for use with Drupal 7? I'm trying to create a bookmarklet. This is not working:

javascript:window.location="http://domain.com/node/add/content_type?title="+encodeURIComponent(document.title)

The Prepopulate module is not ported for D7. Any recommendations?

Out of the box, Drupal 7 doesn't support form population from the URL. Just like Drupal 6. That's why the Prepopulate module exists. Prepopulate is about 100 LoC, porting it to Drupal 7 is probably the best option. The effort has been started, see issue #935990.


Paragraph of text in webform generated email is split into multiple lines rather than presurving single line of text I am using a webform to send an email. The webform contains a textarea field.

I have noticed that if I enter a paragraph of text in the textarea field, then that same text is split into multiple lines in the email I receive.

So rather than being a single line of text which is wrapped within the email, it looks like the paragraph is split into separate lines (as shown in following image):

This is puzzling since if I check the body of the email using hook_mail_alter() the paragraph appears as a single line of text:

I can't work out why this is occurring. I am not sure if this is something that webform is doing or if it is something being done by the mail server itself (could it be something to do with plain text email protocal perhaps?). Was hoping someone would be able to enlighten me on the likely cause of this issue and how to solve it?

The issue seems to be with the plain text format of the mail.If you want to send mail content with designed structure then you must use  Mime mail module.Once you enable the module you can use a HTML formatter for the textarea that is used to structure the mail. Let me know if you face any issues.


How to convert currency dynamically on Product Page? I am using drupal 7 and commerce modules. I want a dynamic currency converter on product display page or cart page (priority is product display page). Suppose Product A is displayed with price 1 USD and user is from India or some other country then I want to give the user an option to change the currency before adding product to cart. If the user selects INR then the 1 USD will be converted to INR which makes it 67 and payment will be made in INR. How can I achieve this kind of functionality in Drupal ?

Suggestions are welcomed.

Thanks

You can use  Commerce Multicurrency module for INR price field in the products content types.


Create navigation through taxonomy We have an taxonomy with "news" and "articles" parent terms and structure with different child terms.

What we need, is simple navigation through this taxonomy without menus, but with pages: so at the "Article" page are presented child terms of "Article", once an term is selected user is redirected to the page with child terms of this term and list of items in current term + path to this term (like Articles > Child term 1 > Child term 2 etc for easier navigation).

Such navigation system is typical for many CMSs, but I couldn't find nothing like this in Drupal 7.

Is there a module or guide to implement such navigation?

Taxonomy menu module suits your need.

  Transforms your taxonomy vocabularies into menus with ease!


contextual menus on drupal I have some questions about Drupal menus. I am interested to have a Contextual Menu in sense that its links change depending where the user is.

I have a Taxonomy Menu and I would like to show in the menu only the term links to the level where the user was. For instance,

Product

cat1
cat2

cat2.1
cat2.2

cat3

If I have the taxonomy shown above, if I click on product the menu should list only cat1, cat2 and cat3 but if I click cat2 menu should list only cat2.1 and cat2.2

How can do this on Drupal?

Thanks in advance!

If you mean literally only show that level, you can do this with Menu Block module using the Make the starting level follow the active menu item option.

If you mean that only that level should be expanded, you can do it like this: go to edit your Taxonomy Menu vocabulary. Under Taxonomy menu -> Structure options, uncheck Auto expand menu items.

But I'm not sure if Taxonomy Menu can be used with Menu Block like this.


How do I move a site to another server? I'm having troubles migrating a Drupal 5 site. I don't have direct access to the original site, but I've been given the Drupal source files and a dump of the database.

When I upload the database to my local server and alter the settings file to connect to the database I can access the first page, but nothing else (eg: nothing within the admin area). When I click on any other link I get a generic HTML file with just one string of text in it. I can't even tell how the file is being generated, it's the oddest thing.

I'm really thrown off because I move Drupal 6 sites all the time, and although I do run into all sorts of problems related to file paths, a few search/replace queries in the database seem to fix most of those problems

So I'm wondering if there is something specific to Drupal 5 that I should be doing (but that I'm not aware of). Perhaps the database is corrupt?

I'm at a loss here!

Just thought I'd give an update: this problem actually had to do with Clean URLs, once I migrated the site, I had to disable Clean URLs directly in the database since I couldn't access any of the sub-pages of the website so I couldn't get to the admin area, then I replaced the custom htaccess I got from the remote server with an htaccess from a fresh Drupal 5 installation, and that basically solved it! Wow, what a relief, thought I was going to go crazy trying to figure this one out!


No 'Div Container' button in CKEditor I've got CKEditor 4.5.0 working on a Drupal 7.42 install. I'm now trying to find a way to wrap more than one HTML element inside a DIV (I want an image and caption to be wrapped in a single DIV).

On the CKEditor Profile I got 'Div container' selected under Buttons and Plugins. As I understand it this should give me a 'Div container' button in the Wysiwyg, which then opens a dialogue. But it ain't there.

All the buttons I've selected are in the toolbar. It's just that selecting 'Div container' doesn't appear to be doing anything.

I've tried manually installing the Div Container Manager but this also doesn't seem to have any effect. (And it shouldn't, because the plugin comes with the 'standard' CKEditor package).

Please tell me I'm missing something very obvious.

Weirdly, I solved this by replacing the standard library with the full library. Seems odd as Div container is part of the standard library but it works.

When replacing the library, make sure to clear both Drupal's and your browser's cache.


Importing Group Audience data I have a site using OG7 and created groups to let users to access to some content as per the user membership and concent-type membership as well.

Each user has to belong to a group and I can select that group(s) for him/her in the corresponding Group-Audience list box when adding or editing user information.  I have also created content-types which should be attached to a group via Group-Visibility and Group-Audience Fields.  When creating content, let's say an Event, I just select in the group-audience list the group I want that event to stick to and also I choose private as the group visibility choice.

Now, the problem is that I need to import a huge number or nodes of different content types, say Events, and each one has to be associated to a group.  Currently I just import the content-type data using feeds modules (feeds-import) using a CSV file and once in Drupal I do the group associations by hand. I cannot find a way to import the content-type along with group association while importing the data, also I don't know how to do it directly in the database, I tried but it didnt work.  Anyone of you know how to import group-audiences? anyone knows which tables are affected when associating a group to a content-type?  Thanks in advance for your time in assisting me.

If you want to import a lot of different content types

you might want to check the Migrate Module out

It supports Organic Groups.

Migrate Documentation

// Maybe this can help you some of the way

Migrate Classes: Location CCK to Address Field

Migrate Extras

This might also give you a clue on how to do it. I know its

Migrate OG


List of users who signed-up last month, or last year I want to get the number of users who signed-up the last month, or the last year.

Is there any module for achieving this? How can I do it using the Views module?

I believe you can create a View of Users. Group by signup date.


How can I make my site only accessible to logged-in users? I want to make my site accessible to logged-in users. How can I achieve this?

There is a permission in the permissions list called "View published content". The permissions are set under /admin/people/permissions. You can remove this permission from the Anonymous user.

If you want to show some pages but not all of them, more granular access controls can be set up with Content Access.

Custom 404 and 403 pages can be set to use any content on your site, using settings at /admin/config/system/site-information (in Drupal 7). Sidebars are automatically hidden on 404 and 403 pages but if there are any other blocks (such as menus) you want to hide, you can control which roles see those on their block config pages.

The content of these nodes will also be unaccessible to anonymous users unless you install Content Access and make at least th 403 page allowed for anonymous users. I suggest allowing the 404 page too. Otherwise, you can still get info through if you put it in a node-specific template for your custom 404 page.

The login block can also be invoked programmatically in a tpl.php file with the code from this d.o comment or it can be shown to anonymous users via the block settings.


How to retrieve files from url when they have whitespace into filename? I need to import a lot of images/pdf from urls, and then save them to a file/image field into nodes.

To achieve that, I am using this script (example with images):

if($image!='\N'){

    $image_url = 'http://www.example.com/images/news/'.$image;
    $managed = TRUE; // Whether or not to create a Drupal file record
    $path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);
    $fid = $path->fid;
    $node->field_image['und'][0]['fid'] =$fid;

}

This is working so well in almost every case. Only files containing whitespaces in filename are not retrived as expected. Example:

2009 juin texte TVA vote final.pdf
Geoffrey Schinder Award.jpg

/**** EDIT ****/

Regarding Molot comment I changed my code including urlencode(), this way:

if($image!='\N'){
    $image_url = urlencode('www.example.com/images/news/'.$image);
    $managed = TRUE; // Whether or not to create a Drupal file record
    $path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);
    $fid = $path->fid;
    $node->field_image['und'][0]['fid'] =$fid;
}

But it's even worse, I can not retrieve any file this way. Here is my filename after urlencode():

http%3A%2F%2Fwww.example.com%2Fimages%2Fnews%2F2009+juin+texte+TVA+vote+final.pdf
http%3A%2F%2Fwww.example.com%2Fimages%2Fnews%2FGeoffrey+Schinder+Award.jpg

And before:

http://www.example.com/images/news/2009 juin texte TVA vote final.pdf
http://www.example.com/images/news/Geoffrey Schinder Award.jpg

/**** EDIT 2 ****/

Here is the kind of errors I am getting when file has white spaces:

HTTP error 404 occurred when trying to fetch http://www.example.com/images/photos/Geoffrey Schinder Award.jpg

This is so strange because I can reach all these images from browser, for example typing http://www.example.com/images/photos/Geoffrey Schinder Award.jpg in url bar will display the image correctly. But system_retrieve_file() isnt' able to reach it.

$path = system_retrieve_file($image_url, 'public://news/', $managed, $replace = FILE_EXISTS_REPLACE);

I managed to solve the issue by adding this command:

$image= str_replace(' ', '%20', $image);

I juste replaced all whitespaces with html whitespace characters..


Views: Display only first value from content field in a staff directory I'm creating a staff directory for my library in Views. In one of the display field, Departments, staff often are assigned more than one departmental affiliation when I create their Content Profile. In this tabular view I'm creating, how can I make it so only the first value of the field representing departmental affiliation is displayed? It really clutters things up to display two or more departments in this table. I'd be happy to export the view & post it if that will help solve my problem.

Thanks,

Jason

I am assuming you are using Drupal 7 and Views 3. If that is true, then you could use the below -

Quoting from the comment here - http://drupal.org/node/1024158#comment-5064416

  Under fields, when you add your image field, one of the configuration options is "Multiple Field Settings". Under that make sure you check the box for "Display all values in the same row". The last line under this will ask how many items you want to display. Type "1". You can also specify which number to start with if you like. Hope this helps.


My theme is automatically disabled! My Drupal website has a sub-domain. there is a  theme that is in the sub-domain folder. the settings.php in the sub-domain folder is same as the one that is in the /default folder so they both display the same web page. the problem is after a few hours this theme is automatically disabled and I have to enable it again.

why such thing happens?

Do you mean you have 2 URL (www.ex.com and sub.ex.com) with the dir/ and files:

/sites

   all/

      themes/

      modules/

   www.ex.com/

      themes/

        your_theme/

   sub.ex.com/

and no "/sites/sites.php" in here? (read for ex "example.sites.php")

And selected in www.ex.com/admin/appearance for ex bartik as default
and for sub.ex.com/admin/appearance "the your_theme" as default (and clear cache)?

and each time, you need to go in sub.ex.com/admin/appearance in order to set "the your_theme" as default, with no error in logs?


How can I set up an existing site from Pantheon on my computer? I am a real newbie to all this so I appreciate all the help.

I am helping a company develop a Drupal website which already exists and is hosted on Pantheon. I have login access to the drupal site. How do I get the current codebase for the existing drupal site?

From what I understand, Pantheon automatically commits codechanges to the development section. However pantheon seems to use git so I downloaded git and then created an ssh key and pasted it into my account on pantheon. So I think I have created the connection between my laptop and pantheon.

So really all I think I'm missing is how to extract the codebase.

Thank you and let me know if I'm missing a whole bunch of other steps.

By the way do I have to use git? Or can I use github?

Uploading your key is the first step towards cloning your repository because this gives you access. The next step is to grab the git repository address from your site's dashboard. This is located in the "Connection Info" dropdown menu on the upper righthand side, or in the "Connection Mode" bar above your commit log. The info button provides the git commands you'll need to get started. Please note that you'll need to be in the Git mode in order to push your local commits to the Pantheon repository.


What would be on your checklist when trying to debug a non-reverting feature? I've lost far, far too many weeks and weekends fighting with Drupal and the Features module in the last year, and I still can't find consistently reliable approach to debugging failed feature reverts.

Now I'm sure I can't be the only person having this problem, because I've watched enough other developers on projects I work on tearing their hair out too, so I'm asking this question, in the hope of saving pain in future.

What steps should you take when troubleshooting a non-reverting feature with Drupal 6?

It's safe to assume knowledge of drush, to run diffs of features, and watchdog, and the --debug and --verbose when answering.

Do you have any modules implementing hook_strongarm_alter()?

If you're blindly overriding Drupal system variables using hook_strongarm_alter() as follows:

function mysite_strongarm_alter(&$items) {
  $items['upload_extensions_default']->value .= ' qtz';
}

...some Features may incorrectly appear as Overridden.

Instead check to see whether the item is defined first:

function mysite_strongarm_alter(&$items) {
  if($items['upload_extensions_default']) {
    $items['upload_extensions_default']->value .= ' qtz';
  }
}

...and the Strongarm aspect of the Feature will no longer incorrectly appear as Overridden.


How to print name of Payment Method in Commerce 2 order receipt email? The commerce-order-receipt.html.twig contains a variable called {{ payment_method }}, which returns no data. Likewise, when I add Payment Method field to my orders table view, it shows no data. Payment Gateway does contain the name of the payment method used in the order. I'd like to print that value in my order receipt email, but cannot seem to find the correct syntax. So far I have tried the following:

{{ payment_gateway }}
{{ order_entity.field_payment_gateway }}
{{ order_entity.field_payment_gateway.value }}
{{ field_payment_gateway }}
{{ field_payment_gateway.value }}

All of those turn up blank in the email.

How can I show the payment gateway title in the order receipt email twig?

This patch (https://www.drupal.org/files/issues/2019-02-26/order_receipt_payment_gateway_and_instructions.patch) from this thread (https://www.drupal.org/project/commerce/issues/2884497#comment-12988057) fixed my issue. It required patching commerce_order.module and commerce_payment.module, as well as adding the display code to the order email receipt twig.


How do I integrate the Color module in my theme? I have installed drupal 8.4.2 and created a subtheme with base theme
   bootstrap. I want to customize settings adding the color module, but
   really I do not know what steps I am missing.

I have enabled color module (it's in core)
I have copied (from bartik) the color directory and files
I have edited color.inc to have  my custom color schemes
I  have edited THEME.theme adding this:

function MYTHEME_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
}
function MYTHEME_preprocess_page(&$variables, $hook) {
    // Hook into color.module
    if (module_exists('color')) {
        _color_page_alter($variables);
    }
}

As a result I have white page with no rendering. (It's not cache issue) and I guess my problem is with .theme file
I'd like to know where to find the instructions (drupal.org has not much). Thanks

There's actually a video on YouTube about how to do this in Bootstrap.  There's also a more general video for other themes by the same person.

You'll need to use a LESS or SASS subtheme; the most basic subtheme that just uses regular CSS will not work because the Color module will change the values of the variables.

You will also need a way to compile the LESS/SASS on the server that you use the Color module on, so if you plan to make adjustments on your production server, you will need something like the LESS module, which does not yet have an official release for Drupal 8 (might still work, needs testing).

You can also find a feature request on drupal.org for putting this directly into Bootstrap, but it hasn't made any progress in the past couple years.


How to add conflicts in D8 info.yml? I want to know how to add conflicts in D8 info.yml.

I tried like this in D8 .info.yml:

name: Example
type: module
description: some example.
core: 8.x
package: Other
dependencies:
  - menu_ui
conflicts:
  - module1
  - module2

and in .install file

<?php
/**
 * Implements hook_requirements().
 */
function example_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    if (\Drupal::moduleHandler()->moduleExists('module1')) {
        $requirements[] = [
          'title' => t('Module 1'),
          'value' => t('Module 1'),
          'description' => t('Module 1 conflicts with example.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

But in D7 it is working:

name = Example
description = some example.
core = 7.x
dependencies[] = menu
package = Other
conflicts[] = module1
conflicts[] = module2

While enabling my example module it is not showing any conflict error in D8.

  Installation Order:

  1) Fresh Drupal installation.

  2) Module 1

  3) Module 2

  4) Example module(here i need to show module1 and 2 are present while
  installing)

It seems that this is not implemented yet. Related issue is here.

An alternative would be to use hook_requirements() in your module's .install file. You can check here if the conflicting module is present during the installation process and prevent the system from installing the module.

Here's example code that would go in your module's .install file:

/**
 * Implements hook_requirements().
 */
function YOUR_MODULE_requirements($phase) {
  $requirements = [];

  switch ($phase) {
    // Called while the module is installed.
    case 'install':
    // Called during regular use of the website.
    case 'runtime':
    // Called while the update.php is being executed.
    case 'update':
      // Do not allow administrators to install the module if conflicting module
      // is already installed.
      //
      // You can move this code to any other phase as well.
      if (\Drupal::moduleHandler()->moduleExists('ARCH_ENEMY_OF_YOUR_MODULE')) {
        $requirements[] = [
          'title' => t('Name of your module'),
          'value' => t('Arch enemy module'),
          'description' => t('Explain that administrators need to uninstall the module before proceeding.'),
          'severity' => REQUIREMENT_ERROR,
        ];
      }
      break;
  }

  return $requirements;
}

You can see a working example of hook_requirements() in my Drupal 8 boilerplate repo on Github.

Hope this helps.


How can I hide one commerce specific shipping option without deleting? I am trying to hide a couple of Commerce shipping options we no longer use.

I can't figure out the proper syntax for addressing the individual form radio options.

Here is what I have so far:

function MYMODULE_form_commerce_checkout_form_shipping_alter(&$form, &$form_state, $form_id) {
    $form['commerce_shipping']['shipping_service']['#options']['express_shipping']['#access'] = FALSE;
}

...this throws an error ' Illegal string offset #access'. Am I addressing the wrong member of the array? I've used this code before successfully for text and select fields, but never a radio.

Thanks so much!

You could try to remove the value from the form by using unset($form['commerce_shipping']['shipping_service']['#options']['express_shipping']);.

Also note that most of commerce's actions are handled by rules, there might be something there as well.


How to change client session variables during a functional browser test? I have a session variable, that once set changes block output of the system branding block. Normally this variable is intercepted from the query string by an inbound path processor, however that is a different test. In this test I just want to make sure the output is as expected.

So I set up my test as follows:

class ConfigOverrideCacheTest extends MyLabelTestBase {

  protected function setUp() {
    parent::setUp();

    $this->tokenOwner= $this->drupalCreateUser(['my permission']);
    $this->drupalLogin($this->tokenOwner);
  }

  public function testNotoken() {
    $this->drupalGet('<front>');
    // Check site name is Drupal.
    $this->assertSession()->elementTextContains('css', '.block-system-branding-block', 'Drupal');
  }

  public function testToken() {
    // Set session variable.
    \Drupal::service('session')->set('my_session_key', 'value');

    $this->drupalGet('<front>');
    // Check site name is NOT Drupal.
    $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
  }

}

This second test keeps failing, and the output is the same as in the first test. Which I suspect to be because it is set in the testrunner session, rather than the actual testing session.

How so set (or synchronize) session variables from the testrunner to the site that gets tested?

I am not sure if the storage you use to save the my_session_key attribute is shared between the testrunner and the site that gets tested, and that could explain why the test fails.

Why not test exactly the case of the inbound path processing, e.g.:

public function testToken() {
  $options = [
    'query' => [
      'param' => 'value',
    ]
  ];
  $this->drupalGet('<front>', $options);
  // Check site name is NOT Drupal.
  $this->assertSession()->elementTextNotContains('css', '.block-system-branding-block', 'Drupal');
}

Good luck in any case!


Connecting to a database from another application What is the proper way to do a remote connection to my Drupal database from a remote application? I am trying to integrate IPB with Drupal so I would like to modify my Drupal database from IPB.

Since you asked, the "correct" way would be to implement a simple web-service in Drupal in order to perform these tasks remotely from your application.  You could build a simple RESTful API to handle all your CRUD needs, for example.

The Services module is an excellent starting-point.

The reasoning for this is that you should really avoid modifying your Drupal database directly (unless you really know what youy are doing) and even if you must, connecting to it directly from another application is not only bad practice but a security risk too!

Please reconsider and use a webservice-approach, think of the kittens! :)


Combine two views on one page I have 2 custom views(block types) 'view_A' and 'view_B', one shows content the other shows orders. I need to cobmine them in a single page displaying in 2 different tables. Really dosen't make sense to bundle events and orders in one table.

I tried creating a page, but I can't select 'block' for the context type. I can only select nodes. What's the best way using the UI in Drupal 7 to do this?

A simpler way can be:

Current Setup:

View A (show content)
View B (show orders)

Steps:

Create a new "page display" of the View A and set the path and menu if you have to.

2 a. Then on the view header or footer (depending if you want the View B before or after View A) add a global view area that will show the View B when viewing View A page.

2 b. Select from your existing views the View B

2 c. Apply the change to the current display and you are done.


How to get into a Drupal 7 site using only Drush without touching code or anything else? I'm working on a acquia site and right now the dev environment is replicated from the prod. I want to be able to get in as admin on the dev site, but every time i hit the /user path it redirects me back to the prod site. I tried doing a drush uli admin but that doesnt work neither as I still get redirected back to prod. However, I am logged in as admin on the prod by doing a drush uli admin.

Without touching any of the code/files to get me logged into the dev site and only using Drush. How can one get in logged as admin?

Keep in mind there's no way to get to the /user path on dev as it redirects you once you land on there. And I'm not sure which modules/files is doing this functionality.

I was thinking of copying the cookie session from the prod database and then copy it into the dev database to simulate myself as being logged in, but I'm not sure how to go about that or what else might be needed.

What I did was change the default theme to the basic seven theme:

drush @mydomain.dev vset theme_default seven

Then reset your admin password:

drush @mydomain.dev upwd admin --password="mypass"

Then go and find a page that loads the seven theme and by default the seven theme has the login block somewhere in the footer area. Login with admin and your new pass! =D

If you have a theme switching module, you'll have to turn that off too. Such as themekey or rules or securepages (this is what was causing my issue.)


What events, conditions and actions I should use for this case? I use "commerce" and "commerce stock" modules, I created a list with products and a few extra fields in Product types:
- Image
- Deposit 1 Stock
- Deposit 2 Stock
- Deposit 3 Stock

I created a view (table - http://ucreateawebsite.com/DRUPAL/dalexgrup/pt)  with this fields:
- Bulk Operations
- SKU
- Imagine
- Title
- Deposit 1 Stock
- Deposit 2 Stock
- Deposit 3 Stock

I have a problem in succeeding to create another stock field (the fourth - called TOTAL STOCK) and making it to automatically update when the other 3 fields are being changed. I want the fourth field to calculate and show me the sum of the other 3 fields.

Example 1 *
Deposit 1 Stock -> 15
Deposit 2 Stock -> 15
 Deposit 3 Stock -> 15

     TOTAL STOCK -> 45

Example 2 *
Deposit 1 Stock -> 10
Deposit 2 Stock -> 05
 Deposit 3 Stock -> 01

     TOTAL STOCK -> 16

This TOTAL STOCK field I should create in Product type like:
- Deposit 1 Stock
- Deposit 2 Stock
- Deposit 3 Stock ??????

Then I should create a rule? What events, conditions and actions I should use?

Thank you.

I found the answer:

For Event I used:

 1. After updating an existing commerce product

For Conditions I used:

1. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock1

2. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock2

3. Entity has field - Parameter: Entity: [commerce-product], Field: field_stock3

4. Entity has field - Parameter: Entity: [commerce-product], Field: field_totalstock

For Actions I used:

1. Calculate a value - Parameter: Input value 1: [commerce-product:field-stock1], Input value 2: [commerce-product:field-stock2]; Provides variables: Calculation result for Stock1  and Stock2 (stock1_plus_stock2_result)

2. Calculate a value - Parameter: Input value 1: [stock1-plus-stock2-result], Input value 2: [commerce-product:field-stock3]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1_plus_stock2_result_plus_stock3)

3. Set a data value - Parameter: Data: [commerce-product:field-totalstock], Value: [stock1_plus_stock2_result_plus_stock3]

You can see what I wrote here -> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt


Performance Implications when Views JOIN added twice? I have a view with a flag (relationship, only show flagged nodes). I have modified it a few times and now I see in the query output that views has the join added twice:

INNER JOIN {flag_content} flag_content_node ON node.nid = flag_content_node.content_id AND flag_content_node.fid = '9'
LEFT JOIN {flag_content} flag_content ON node.nid = flag_content.content_id AND flag_content.fid = '9'

Is there a performance hit for the extra LEFT JOIN?

Astonish Design did a good write up on this topic: Writing Efficient Queries in Drupal.

You should measure your specific queries though, it always depends on the amount of data you are working with, proper indices, mysql configuration and so on. Joining too many tables will almost always increase your query execution time, keep that in mind.


Hide default "all" parameters from Views Querysting By default Drupal Exposed Filters query string includes all filters even if they aren't selected
i.e. www.example.com/?optiona=valuea&optionb=all&optionc=all

How do I adjust it not include default/all values in the query string?

For example, if the user does not touch "option b" just option a they would get

i.e. www.example.com/?optiona=valuea

The goal is to create a "cleaner" query string by not including the default values.

This is a known issue that hopefully will be solved in Drupal 8.

I accomplished it with JS:

jQuery(document).ajaxComplete(function(e, xhr, settings) {

let src = window.location.href;
let url = new URL(src);
let title= document.title;
let re = /all/;
let props = [...new URLSearchParams(url.search)]
            .filter(([key, prop]) => !re.test(prop));
url = url.origin + url.pathname;
let params = new URLSearchParams();
props.forEach(([key, prop]) => params.set(key, prop));
url += "?" + params.toString();

history.pushState(null, null, ("/page?"+params.toString()))

});


How do I get a LEFT OUTER JOIN in Views that displays all rows with no match in the LEFT JOIN-ed table? Views 7.x-3.x

Staff

sid name
1   Adam
2   Barbara
3   Carol
4   David

Staff Roles

sid rid
1   1
2   1
2   2
3   2
3   3

Let's say that I want a list of all staff, excluding staff who have a particular role, and that role id (rid) will be provided in the URL.

Let's say that the rid we want to exclude is 2. So we want our view to display Adam, David.

My approach has been to list all the staff in a view, then add the relationship to Staff Roles, put the rid into a contextual filter, and then say it is to be excluded.

Unfortunately, what this produces is a LEFT JOIN of all the rids except 2. So we get Adam, Barbara, Carol.

So you might think: let's not exclude the contextual filter for rid. Let's include it on a non-excluding LEFT JOIN. Then we can maybe filter for rows with a rid of NULL. Unfortunately, views puts the contextual filter into the WHERE clause of the query, so we end up with just Barbara and Carol.

So my question is:

How would you build a view to list all staff, excluding staff who have a particular role, where that role id (rid) will be provided in the URL?

Alternatively:

How can I get conditions from a contextual filter into the ON part of a view query, instead of the WHERE part?

In your RID contextual filter, if you expand the "More" fieldset at bottom of the options modal, you should see an "Exclude" option which will flip the filter operator to negate.


Is extending Bartik a recommended move? I'm starting a new Drupal 8 project. As first steps I need to choose a theme. So far, I have only experience with Bario, chosen initially for using Bootstrap 4. I'm now looking for a theme that's not using Bootstrap.

I'm considering extending Bartik. Is this correct, or should I extend a different theme?

Please have a look at the Drupal core themes no longer extend Classy change record.

  Bartik, Claro, Seven, and Umami are part of the product rather than
  the API and therefore it is not officially supported to extend them.
  These themes can change as part of a minor release and cause
  regressions to any themes extending them.

Means: No it's not recommended to extend Bartik. Extend Classy or Stable instead.


How to add and remove tabs from/to My Account page I have created a role Customers. I added UserA to the role. When I logged in as UserA, I see My Account link in the Header region. After I click My Account, I see three tabs : Views, Edit, Checklists. How to remove Edit and Checklists tabs from the My Account page?

I created a page view. The path for the page view is xxx.com/payments. How can I add a new tab (Payment) next to Views tab on the My Account page? When UserA clicks the Payment tab, the page view xxx.com/payments displays right under all the tabs.

For your first question answer remove the  from page.tpl.php or you can alter it by hook_menu_alter. Use type MENU_NORMAL_ITEM.

For you view you need to create one hook_menu_alter and add type as MENU_LOCAL_TASK.


Hiding a View if empty when contextual filter is already used On my content type "page", I give my client the option to upload a sidebar image while editing the page fields. In the manage display of the content type, the image is hidden.

I have a view in the sidebar that shows the side bar images. I placed a contextual filter of Nid, and set it to provide a default value using the Content ID from URL, meaning that only the sidebar image for that page will be displayed.

This works sweet, but on pages where a sidebar image isnt uploaded, the sidebar is empty, but the views headers are there, and forcing the main content to be pushed to the left as if the sidebar region has content.

Reading other solutions, people have used a contextual filter of Global: Null, and set the view to hide if empty. But this isnt working for me, probably as I am already using a contextual filter to determine the content from the URL.

Other advice of setting the "no results behaviour" of the field doesnt do anything, the empty block still renders because it has nothing to do with fields, it is only printing the view headers.

I'm a bit stumped! Any ideas?

I found a very simple answer to this question.

The problem I was having was two contextual filters, Content:NID from URL, and Global:Null Hide If empty, which stopped the view displaying even if full.

Instead, I simply added a Filter Criteria for one of the fields in my view, with :fid on the end. In my case, it was Content: Sidebar Images:fid (not empty)

Now the view shows if it has content, and hides completely, including block region if empty.


How can I programmatically create products via REST? I have a module of rest service api, that is used to receive users upload products. Here is my code...

function commerce_services_product_create($data, $flatten_fields) {
    $status =1;
    $commerce_price = array();

    $sku = $data['sku'];
    $title = $data['title'];
    $type = $data['type'];
    $commerce_price = $data['commerce_price'];
    $price = $commerce_price['amount'];

    $cp = commerce_product_new('product');
    $cp->uid = 1;
    $cp->sku = $sku;
    $cp->title = $title;
    $cp->language = LANGUAGE_NONE;

    $cp->commerce_price = array(
        LANGUAGE_NONE => array(
            0 => array(
                'amount' => $price ,
                'currency_code' => 'MMK',
     )));

    // for store
    $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);
    // for category
    $cp->field_category[LANGUAGE_NONE][0]['value'] = 137;

    try{
        commerce_product_save($cp);
        $result = "success!";
    }catch(Exception $ex){
        $result = "not success!, error -> ". $ex;
    }
}

When I pass the following json string to the function, this function create a product but not include cmp_store, mean cmp_store is null.

{
  "sku": "saa_prduct120",
  "title": "saa_prduct",
  "type": "product",
  "commerce_price": {
    "amount": "150000",
    "currency_code": "USD"
  },
 "cmp_store": 2
}

And when I check store drop down button with themer info module, it shows #name as like this, "field_product[und][form][cmp_store][und]".

Above my code I use this code for adding store, mean when users upload their product, they have to choose store. User choose store is passed by json.

 // for adding store
 $cp -> cmp_store = array(LANGUAGE_NONE => $data["cmp_store"]);

And I also try like this,

$new_product ->field_data_cmp_store[LANGUAGE_NONE]['cmp_store']['und'] = $data["cmp_store"];
$new_product -> field_product[cmp_store][und] = $data["cmp_store"];
$new_product -> cmp_store = $data["cmp_store"];
$form_state['values']['cmp_store']['und'] =   $data["cmp_store"];

not ok yet!

This might need to work around as below

['field_store']['und']['#options'] = Store_array


Dynamic RSS Feed in View Passing a context from the panel to the view.

Need the view to accept the context and then consume an RSS feed.

For example: visiting /stock/MSFT would pass in MSFT to the view. The view would then hit http://finance.yahoo.com/rss/industry?s=MSFT and consume that RSS content.

I know you can consume a static feed with the Aggregator or Feeds module but what about a dynamic one. Any ideas?

Thanks!!

For those of you interested -- the only way I could figure out how to solve this was with writing a custom cTools plugin (See: What are Ctools plugin (content type, access, etc), and how does one create them?).

In that plugin I created a block and placed it in the panel.

I used Magpie RSS for the parsing/fetching of the feed.


How to programmatically read the display name of a CCK field from the allowed list? For example if a CCK text field is configured to have the following allowed values:

US|United States
UK|United Kingdom

The node has the corresponding field:

node->country

and its value can be found by accessing:

node->country[0]['value']

which will return 'US' or 'UK'. What is best way to return the display name which was specified in the allowed list (i.e "United States" or "United Kingdom")?

You can use the following code.

$field = content_fields($field_name);
$function = $field['module'] . '_allowed_values';
$values = array_values(function_exists($function) ? $function($field) : (array) content_allowed_values($field));

This code is similar to the code used by optionwidgets_options(); the difference is that optionwidgets_options() returns also the value for the empty choice.

The output of content_allowed_values($field) is an array that in your case is the following one.

array(
  'US' => 'United States',
  'UK' => 'United Kingdom',
);

As you are only interested to the options visible in the user interface, I passed the result of content_allowed_values($field) to array_values().


switch project to dev mode I faced to problem trying drupal console:

1) In documentation written (https://www.drupal.org/docs/8/theming/twig/debugging-compiled-twig-templates):

drupal site:mode de

But I haven't that command in a list of other commands when I attempt drupal list in a project root

2) Then when I put in settings.php or settings.local.php this:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

I got Error...

The website encountered an unexpected error. Please try again later.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "cache.backend.null". Did you mean one of these: "cache.backend.apcu", "cache.backend.php", "cache.backend.memory"? in Drupal\Component\DependencyInjection\Container->get() (line 157 of core/lib/Drupal/Component/DependencyInjection/Container.php).
Drupal\Component\DependencyInjection\Container->get('cache.backend.null') (Line: 83)
Drupal\Core\Cache\CacheFactory->get('render')
call_user_func_array(Array, Array) (Line: 254)
Drupal\Component\DependencyInjection\Container->createService(Array, 'cache.render') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('cache.render', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.page_cache') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.page_cache', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.reverse_proxy') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.reverse_proxy', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_middleware.negotiation') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_middleware.negotiation', 1) (Line: 494)
Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array) (Line: 236)
Drupal\Component\DependencyInjection\Container->createService(Array, 'http_kernel') (Line: 177)
Drupal\Component\DependencyInjection\Container->get('http_kernel') (Line: 1320)
Drupal\Core\DrupalKernel->getHttpKernel() (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

If someone resolved it please share)

1 It appears that there is no site:mode command in the latest drupal console (1.0.0-rc16), but instead site:maintenance (sma) (on/off) is available. Maybe they ditched site:mode at some point because site:maintenance made more sense in Drupal context.

2 Make sure you have this code in development.services.yml:

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory


How can I show the receiver name in a rules email I use the rules module in Drupal 7. I use it to send an email to a few receivers with a certain role. How can I get their name or userID? Is there a Replacement Pattern to get the email Receiver details?

edit:

I'm sorry for being unclear. I have made a rule that emails all users with a certain role after new content of a certain type was created. In this email I would like to start with "Hi [Username_of_email_receiver]" but it seems I can only use the author username or the current logged in username

You cannot, the message is the same for all users of a certain role in this case. I think you have, first, to get the users of a certain role (php custom code) and then for each user fire an other rule or a custom hook_mail with the account as argument


Proper way to display custom line item fields on checkout form Is there any proper way to display custom line item fields on checkout form?

I know that I can add each custom field one by one into views but it's complicated when I have few line items with dozen conditional fields and you need always to remember about it.

I found out that I can add to checkout view "Rendered Commerce Line item", formatter: "render complete entity" and choose necessary fields by adding custom view mode by hook_entity_info_alter. That's great with one little problem. It's always rendering number before my fields (it's line item id?).

Is there any way to get rid of that number (maybe altering some hook?) or other way to list out all line item fields?

Solution to this problem is to create custom entity.tpl (Theme developer can suggest filename) and remove printing out entity title.


Why is the old version of the module being used? I am creating a module, and I tried to update its files. I disabled the module, uninstalled it, deleted its files and then I put the new files in the sites/all/modules/mymodule. Then, I enabled my module.

The problem is that Drupal somehow is using the old version of my module rather than the new files I added. I cleared all the caches, from Drupal and manual from MySQL, but nothing changed.

Anyone ever had the same issue? Any ideas?

When this has happened to me, it's because I have had the module in two locations and forgotten about it. Just search for the module's info file (using for example find - on Linux):

find /path/to/drupal_root -name mymodule.info


How to change the price ? (add_to_cart) Here is my code

function addToCart($product_id, $quantite){
    global $user;
    $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, $quantite);
  $line_item->data['context']['product_ids'] = array($product_id);
  $line_item->commerce_unit_price->amount  = '900';
  commerce_cart_product_add($user->uid, $line_item);
}

The above code add the product to the cart with the correct quantity but the price isn't changed ...
Any idea ?

Update (resolved thanks to scott's answer)

//Panier
function addToCartCallback()
{
    addToCart($_POST['product_id'], $_POST['quantite']);
}

function addToCart($product_id, $quantite){
  global $user;
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, $quantite);
  $line_item->data['context']['product_ids'] = array($product_id);
  commerce_cart_product_add($user->uid, $line_item);
  $order = commerce_cart_order_load($user->uid);
  commerce_cart_order_refresh($order);
}

function groupes_views_commerce_cart_line_item_refresh($line_item, $order_wrapper) {
  global $user;
  $idProduit = $line_item->commerce_product['und'][0]['product_id'];
  $prix = getPrixClient(getIdClient($user->uid), $idProduit) * 100;
  $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount'] = $prix;
  $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount'] = $prix;
}

I thought of another way to do it.

Start with code that just adds the product to the cart without modifying.

function addToCart($product_id, $quantite) {
    commerce_cart_product_add_by_id($product_id, $quantite);
}

Then you can use a hook to modify the line item amount

//alter the price in cart & order
function my_module_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

    $price = 100; //1 dollar
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['amount']=$price;
    //alter the base_price component
    $line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price;

}

If this doesn't work try forcing the cart refresh
e.g.

function addToCart($product_id, $quantite) {
    global $user;
    commerce_cart_product_add_by_id($product_id, $quantite);
    $order = commerce_cart_order_load($user->uid);
    commerce_cart_order_refresh($order);
}


Configuring the Popup Calendar Widget Currently I have a date contextual filter. When I click the date field the popup calendar displays. when I click on a date (for example today's date) it displays as 3/18/2014, but I would like it to display as March 18th, 2014. Would anyone know how I should go about this?

Any help would be much appreciated. Thanks!

Go to your content type and edit the field. You'll find "More settings and values" as a collapsed fieldset (which is how I always missed it at first.)

The first option will be to change the "Date entry options" and how this is displayed.

You can also modify the default start and end dates here, as well.


How to check user has permission special node I following topic https://atendesigngroup.com/blog/custom-permissions-node-access-grants-drupal-8-and-drupal-7 to create custom permissions for node. It's working ok. Example I can edited node 1 with url: example.com/node/1/edit/. I wan't check user have permission edit node by code eg:

node_access('view', $node);

and Drupal 8

$node = Node::load(1);
$account = User::load(1);
$check = $node->access('edit', $account);

But It don't working. So how can check permission of special node?

Just tested this and $node->access('update'); works for me. I let the optional $account parameter out so that it would check the currently logged in user.

The only difference was that I loaded my node with:

\Drupal\node\Entity\Node::load($nid);

To just use Node::load($nid); Make sure to include:

use Drupal\node\Entity\Node;

at the top of your file.


Taxonomy Term View with Expose filter Dropdown of Terms Name I Have a view of Taxonomy and "not Content".
In this View I want a Expose filter of Term Name. But when ever i add Term Name as expose taxonomy's filter it shows text box and not Dropdown.

Without using relationship with content is it possible to get Dropdown filter of term's name as expose filter in Drupal 8 ?

to get a dropdown filter you dont have to choose the taxonomy name rather the taxonomy term and select the vacabulary.

You follow this steps to get what you need :

1- https://monosnap.com/direct/Zw1q6Ww9If5vQZAAQsvysCt3TmL4L7

2- https://monosnap.com/direct/P4YbmYcXooNk7eLd1kev5y9sRyxekW

3- https://monosnap.com/direct/7gI69kySC5ciKtaBeBtbRRkCQS9Mf1)


How to disable image caption in views block? How to disable image caption in views block?

The image caption module is image field caption.

I apply it on my Drupal 7.

Enable module and add in caption.

In node, it looks good.

In View Block, it looks like this. How to remove the caption in Views block?

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

Add View configuration image

Below is Views setting:

Below is Configure field: Content: Image settings:

If you're not picky, a possible alternative quick fix is to just hide it with CSS. This way you don't have to worry about or spend time patching the module.

You can do it like this:

.image-field-caption { display: none; }

Note that the above will hide all captions, if you only want to hide the captions of a specific view:

.view-id-[name] .image-field-caption { display: none; }


Image field in field collection not working I have an image field inside a field collection (set to unlimited). After selecting the file to upload and clicking Upload the field reverts back to 'No file selected'.

There is nothing in the Drupal or Apache logs and there are no JS errors.

Even stranger, this works on my local dev environment but not on staging server. I have set PHP config to mirror local but again, still not working.

Image field appears to work okay when not in a field collection.

Absolutely no idea what this could be?! Only other difference I can see is PHP version on local is 5.6 and on staging is 5.5 but not sure why this would cause a problem.

EDIT: This is a field collection inside a field collection. An image field nested in a field collection does work.

1) Check if your web-server has read/write access to sites/default/files(typically uploaded files go here).

2) Other reason might be the file you're trying to upload is bigger than allowed. Increase max-allowed upload file-size in .htaccess file

php_value upload_max_filesize  "20M"


How can I count how many times a node appears in a view? I would like to keep a count of how many times a node is displayed in a view. For example, in my home page I have a view that displays a list of 20 products. I can count how many times users click on it. I can also count full node views.

But what I would like to do is to count how many times this product is displayed in this view. I use a random system to show users different products each time the home page is reloaded.

I have searched a lot, with different statistics modules, for example radioactivity, node view count, and entity view count but I'm just not able to find something that do what I want.

The answer should work with caching of the view enabled as well.

This can be done by tracking events with the help of Google Analytics
Drupal provides module for it
https://www.drupal.org/project/google_analytics

Events can be tracked by event tracking module
https://www.drupal.org/project/google_analytics_et

Will need to write custom js for making this event tracking, see documentation of google analytics event tracking module

I'm adding a code sample for tracking click on social media share icons:

    $('.facebook_popup', context).click(function (e) {
    // First register an event in Google Analytics
    if (typeof ga != "undefined") {
      if (jQuery(e.target).closest('.node-social-media').length) {
        ga('send', 'event', 'social-side-bar', 'fb-share', window.location.pathname);
      }
      else if (jQuery(e.target).closest('#block-menu-menu-share').length) {
        ga('send', 'event', 'social-shares-top', 'fb-share', window.location.pathname);
      }
    }

This might help you creating google analytics events


Drupal get form returns string "array" I have module, that should build form. However it is not showing form.

There is my code:

function weblabs_form() {
    $form = array();

$form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
);
$form['last_name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your Last name'),
    '#description'=>t('Your Last name goes here')
);

$form['email']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your email'),
    '#description'=>t('Your email goes here')
);

$form['country']=array(
    '#type'=>'select',

       '#title'=>t('Select your country'),
        '#options'=>array('USA','UK','France','Japan')
    );

    $form['submit']=array(
        '#type'=>'submit',
        '#value'=>t('Submit')
    );

    return $form;
}

function weblabs_form_submit($form, &$form_state){
    echo("
TEST
");
    drupal_set_message("TEST");
}

function weblabs_menu() {
    $items['calculator'] = array(
        'title' => 'Kalkulačka WebLabs',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('weblabs_form'),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
        );
    return $items;
}`

To print the HTML code corresponding to your form you need to render it:

$form = drupal_get_form('weblabs_form');
print drupal_render($form);


How to get nid of Views row? From a views field--body template, how do I access the nid of the node being displayed? So if I have 3 unique rows, I want 3 unique nids. Thanks.

$row->nid

I know this was asked a while ago, but for the benefit of people still searching, here is a solution.

<?php foreach ($rows as $id => $row): ?>

<?php
$node = node_load($view->result[$id]->nid);
// do something with your node
?>

<?php endforeach; ?>


how can i add billing information in invoice email I have been using commerce Invoice 7x-10-alfa3
commerce Email 7x-2x-dev
Variable email 7x-10-alpha -1x
Variable 7x-22,4-dev
HTML 7.x-2.65 modules

I want to sent an invoice email, which will include except of the order information
(included in the token [commerce-order:commerce-email-order-items] ) , also the billing information address (I need all the information as it is appearing in the order view).

However, even though i try two different tokens [commerce-invoice:order:commerce-customer-billing:commerce_customer_address] and
[commerce-order:commerce-customer-billing] none of the them renders any data but they just appear as simple strings!. Also other tokens i added in the body of the email, are just displayed as simple strings. I trying to modify the  "default" value of the email through the store->configuration->emails

From what i have seen there is an issue with commerce email ,which have not been yet resolved https://drupal.org/node/1818380 . I was wondering whether someone has found a workround solution i can use.

Failing that is there any other way i could achieve the same result ? (To be able to sent an invoice email with order details and complete billing information). Maybe a combination of tokens in rules with different  modules (or different versions of modules).

As i am pretty desperate any suggestions would be more than welcome.
Thanks in advance

I've implemented similar functionality for a Drupal Commerce site I built using Commerce Kickstart 2. It's actually a Rule created by the commerce_email module which I'll break down for you below:

Rule is called "Send an order notification e-mail (Customers)"
Event: Completing the checkout process
Action: Send mail with variable (contains all default commerce_email variable settings)

Then if you navigate to the Commerce Email admin section: (/admin/commerce/config/email)

The token I use to display the customer address is:

[commerce-order:commerce-customer-shipping:commerce_customer_address]

Using that token everything prints out in my email template correctly as expected.

Hope this helps!


How do I invalidate a page from cache? In Drupal 7 we could clear a cached URL with the following.

$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');

What's the equivalent in Drupal 8?

There is no equivalent in D8. What would be the closest to this is to assign a custom cache tag to the page and then invalidate it. See https://www.drupal.org/docs/8/api/cache-api/cache-tags.

But normally you don't need to invalidate cache tags in custom code. If you set the correct cache metadata this should happen automatically.


Remove labels in printer friendly version of books Is there any way to remove labels or apply a CSS file to the printer-friendly version of books?

Here is how I approached the problem:
Copied

/modules/book/book-node-export-html.tpl.php
/modules/book/book-export-html.tpl.php

to my theme directory and modified the $contents variable via str_replace.

This works fine as a temporary fix, but I guess performance-wise this is not the best solution, would would be still nice to find a way to apply CSS.


Tags not rendering in the correct location I have tags after body in article but its not rendering in the correct place.
Instead it displays at the end.

I have included the screenshot below.

I had the same issue before, try rearranging the fields then save. after that rearrange again to the original order of fields, save then clear all caches.


How to delete a Drupal sandbox project? This thread: http://drupal.org/node/1077884 indicates we can delete our own sandbox projects, but I'm a little confused as to how this is done.

I see nothing on the UI on drupal.org that would allow this. If this is done directly with git, I would appreciate some guidance.

Go to http://drupal.org/node/<yoursandboxnid>/edit and at the bottom of the edit page is a delete button.


Message not being sent in the body of the mail I am using the code below and the mail gets sent but without the body of the message, but the subject is correct am I sending the body in thee wrong parameter?

 function mailMessage($msg){
 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = "mymodule";
 $key = 'uploaded files';
 //$to = \Drupal::currentUser()->getEmail();
 $to="diana@me.com";
 $params['message'] = "THIS IS my body of the message";
 $params['node_title'] = "File Upload Report";
 $params['subject'] = "File Upload Report";
 $langcode ="en";
 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
 if ($result['result'] !== true) {
   drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
 }
 else {
   drupal_set_message(t('Your message has been sent.'));
 }
}

You need to add a hook_mail code

As this line $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send); behind the scenes will invoke this hook_mail function.

something like this:

/**
* Implements hook_mail().
*/
function <module_name>_mail($key, &$message, $params) {

 $options = array(
   'langcode' => $message['langcode'],
 );

 switch ($key) {
   case 'uploaded files':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('@title', array('@title' => $params['node_title']), $options);
     $message['body'][] = $params['message'];
     break;
 }
}


Is there a way to get Drush to download all required dependancies for a specific module? For example if you perform the following commands:

drush dl views
drush en views views_ui views_export

You will get the the following error when trying to enable the views modules:

  Module views cannot be enabled because
  it depends on the following modules
  which could not be found: ctools

Is there a way to get drush to download required module dependancies?

Drush 5 and up:

Newer versions of Drush (version 5 and higher) will ask you if you want to download the required dependencies when you enable (drush en) a module. It will also ask if you want to download the module itself if you didn't download it yet. Combined with the "-y" option (e.g. drush en views -y), everything will be downloaded and enabled automatically without asking further questions.

Note that the automatic downloading of dependencies may fail if the required module's name is not the same as its project name on drupal.org. For more info, see the my original answer for Drush 4 below.

Original answer (Drush 4):

No, there is no way to do that. The problem is that there is a difference between a module and a project. Often (but not always) the name of the project is identical to the module (or one of the modules) contained in the project. A single project (eg. Views) can contain multiple modules (views, views_ui, views_export). While drush dl downloads a project, drush en enables a module.

When a module declares dependencies, it declares dependencies on modules, not projects. When performing a drush en, Drush can check if the required module is available. However if it's not available, Drush has no way of knowing which project to download. For Drush to be able to automatically download required projects, work needs to be done in the underlying projects/modules infrastructure, so Drush can retrieve a mapping of projects and modules. See also Smarter handling of missing dependencies.


hook_node_validate doesn't work I have a new type of content project.

I allowed an anonymous user to add project content in /node/add/project.

I want to add a test before saving node (like the hook_form_validate of webform)

I use hook_node_validate but it's not working

function projects_node_validate($node, $form)
{
  die 'in hook';
}

If this is the right hook, how can I use it?

Thank you

Should work fine as long as your module name is "projects"

Did you clear all the site caches after adding the code. Drupal won't detect and start using that hook until you have


Show only "Read more" link How can show only "read more" link in node's teaser, and remove or unset other links like "add new comments" or "2 Comments" at the end of a node teaser?

There are two ways to do this:

Through PHP. This is the correct way. The code below would go in your theme's .theme file.

function YOUR_THEME_preprocess_links(&$variables) {
  // Determine which links should be removed. These are CSS classes, because
  // they are used as keys in the $variables['links'] array.
  $links_to_remove = array(
    // X comments link.
    'comment-comments',
    // X new comments.
    'comment-new-comments',
    // Add new comment.
    'comment-add',
  );
  // Loop through the links and remove them.
  foreach ($variables['links'] as $css_class => $link) {
    if (in_array($css_class, $links_to_remove)) {
      unset($variables['links'][$css_class]);
    }
  }
}

Through CSS. This is not the best way, but is faster:

.your-node-selector .node__links li.comment-comments,
.your-node-selector .node__links li.comment-new-comments,
.your-node-selector .node__links li.comment-add {
  display: none;
}


What would be the most efficient way to select node for a content type? Right now i am using this query :

$query_info = db_query("SELECT nid FROM {node} WHERE type=:type  AND language = :language AND status=1",
                array (':language'=> $language->language, ":type" => 'info_pages' , ))->fetchCol();
$info_pages = node_load_multiple($query_info);

As this site is going to have lots and lots of content I am wondering if this is the right way ? If not what would be a better approach ?

<?php
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'status'))
  ->condition('type', 'info_page')
  ->addTag('node_access')
  ->execute();
while ($result = $query->fetch()) {
  print_r($result);
}

Query against node table must be a dynamic query with "node_access" tagging to prevent node access system by-passing.


List all tags associated from specific content type only? I'm trying to make a view which is listing all taxonomy tags associated from nodes of a specific content type only.

How can I make this?

I can make a view which is listing all taxonomy tags, but I can't figure out how to filter it with a specific content type only.

Any ideas?

\Thomas

Thomas - the answer is going to assume you are using Drupal 7, since you didn't specify.

Likely, the issue here is that you are using Taxonomy terms as the base of your view and therefore not able to select Content: Type as a filter.

To get that filter to show up, you need to add a Relationship (under the Advanced section of the view options) for Taxonomy term: Content with term.

After you do that, then Content: Type will show up in your filter list.


Solr index fields not showing a field I have a field within a field collection that I need indexed. It's not showing up in the /admin/config/search/search_api/index/solr_node_index/fields page. I tried using this to try to add it myself, but I don't really know how to reference it. I know that the field collection is just an array of id numbers that you can reference, but I need to reference the actual field. Any help is appreciated.

There is an apachesolr field collection module available, which makes me think that field collection support is probably not out of the box with the apachesolr stuff.

As a matter of fact, if you look at the issue queue for the apachesolr module you can find this ticket #1810228 : Process Field Collection Items. It confirms that field collections are not supported out of the box, and the comments point to the apachesolr field collection module, and indicate that the module may be buggy...

I'd say try it, but test your integration thouroughly. And do try both available versions (alpha and dev), and see how it goes.


Manually importing webforms and data with mysql... where is it now? I wanted to experiment and see if I could just import all the webforms, webform data, submissions, configurations, etc. from one Drupal 7 site to a new one. The import seems to have gone well but I can't see anything, even after clearing the caches. I even performed a MySQL query on the new site to see if the tables were actually populated.

    mysqldump -u root -p database_name webform webform_component
webform_conditional webform_conditional_actions webform_conditional_rules
webform_emails webform_last_download webform_report webform_roles
webform_submissions webform_submitted_data webform_validation_rule
webform_validation_rule_components content_type_webform> webforms.sql

Then I logged into mysql, chose the correct database and imported it:
source webforms.sql

Did I miss some other crucial table or something else? I have had a lot of success with migrating users and other info over this way even though I'm not sure it's wise and haven't found much in the way of doing data migration for Drupal without modules.

Webforms are nodes, so you'll also need to bring the node (and potentially field and other depending on your site's configuration) data across.

Make sure the node ids for the webforms are the same as they were in the original site, or you'll have to do some manual work to get the data linked back up again.

This is why it's arguably better to migrate content, rather than do a raw data export/import, as it gives you the opportunity to massage/prepare data as required for the new system.


Conflict between with a function in two different modules I have the same function in two different modules to change the page: node/add.

I need the second one(see below) to override the first one. I implemented hook_install to change their weight but is not working. My guess is that the hook_install function is executed after those modules.

How can get this done?

Codes below:

My hook_install function

/**
* Implements hook_install().
*/
function utilities_install(){

db_update('system')
    ->fields(array('weight' => 10000))
    ->condition('name', '[content_type_thumbnail]', '=')
    ->execute();

}

Function in commerce_backoffice_product module:

 /**
 * Implements hook_theme_registry_alter().
 */
function commerce_backoffice_product_theme_registry_alter(&$theme_registry) {
  $theme_registry['node_add_list']['function'] = 'theme_commerce_backoffice_product_node_add_list';
}

/**
 * Override node_add_list theme.
 */
function theme_commerce_backoffice_product_node_add_list($variables) {
  $item = menu_get_item();

   .... code ....

  return theme_node_add_list($variables);
}

Function in content_type_thumbnail module

/**
 * Implements hook_theme_registry_alter().
 */
function content_type_thumbnail_theme_registry_alter(&$theme_registry) {
  $theme_registry['node_add_list']['function'] = 'content_type_thumbnail_node_add_list';
}

/**
 * Override of theme_node_add_list().
 */
function content_type_thumbnail_node_add_list($variables) {

  .... code ....

  return $output;
}

Rather than module weighting, I would suggest using hook_module_implements_alter to ensure your hook gets run last. So, something like this:

function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'theme_registry_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}


How do I implement hook_finder_goto_alter()? I'm having a bit of trouble with troubleshooting a module I am working. I am trying to modify a module to redirect traffic but even though its enabled it doesn't seem to do anything.  I've had problems in the past with using hooks and i'm not sure what I'm doing wrong.

I am basically using the finder module and here's the code to redirect:

function test_finder_goto_alter(&$result, $finder) {
  /* Redirect to a different page in the current directory that was requested */
    drupal_goto("testpage");
}

I see the module in modules and enabled it but it still doesn't redirect the way I want it to.  Do you have any suggestion on what I'm doing wrong? I don't think its specific to this module I think I might be doing something wrong in general.

Hooks 101

hooks should be created in a module. The module which they are called from should be enabled.

So in the first instance you will need to create a .info and a .module file with the correct information in.

Then to implement a hook you must use the module name.

So the example code above would work if the php code is in a module called test which was enabled.

So hook_menu() in a module called test.module would be a function called test_menu()

Secondly hooks will only be called when invoked, some get invoked rarely when for example building the menu system, and others are invoked when specific actions happen. You will need to read up on the documentation for the hook in question to find out more.

The same goes for parameters and return values, each hook is different. So the documentation is important there.

So a general checklist for hooks.

Is the hook in a module?
Is the module enabled?
Is the hook named the same as the
module?
Is the action which is calling the
hook being called?
Have I cleared the cache?
Am I using the hook in the correct way?


Is there a way to get a default e-mail recipient by default when adding a new webform node? When I add a new Webform node type, this have no e-mail recipien by default. You can read this message:

  Currently not sending e-mails, add an e-mail recipient below.

Is there a way to get a e-mail recipient value by default when creating a webform node?

You can do this with a custom module and hook_node_presave(). After you have a custom module created, you can use code like this to create a default e-mail configuration for any created Webforms.

Assuming your module were called myexample.module, the hook would look like this:

<?php
/**
 * Implements hook_node_presave().
 */
function myexample_node_presave($node) {
  // Add a default e-mail configuration for new nodes.
  if (empty($node->nid) && $node->type == 'webform') {
    $node->webform['emails'][] = array(
      'email' => 'example@example.com',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
      'html' => 0,
      'attachments' => 0,
    );
  }
}
?>


How do i use Webform API to submit my Custom Module form? OK kinda noob-ish question but im unfamiliar with the programing side of Drupal... Im currently building a Form from scratch in drupal 7 (custom module since im using Form_Panel to arrange my form fields) and i would like to implement the webform API into my code as the submit handler.(This way i can hopefully use webform UI to deal with submissions and viewing results at least) Currently i have all the form fields and a submit button but not much else...

function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('Subscription'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('Subscription'),
'type' => MENU_CALLBACK,
);
return $items;
//some random fields from form API after
///////////////////////////////////////////////////
////////////////// Submit button
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Submit',
 '#submit' => array('my_module_my_form_submit'),
);
return $form;
}
function my_module_my_form_submit($edit,$form, $form_state) {
drupal_set_message('Submission recieved.');
}

And thats it.It shows perfectly on site and submit refreshes the page.. What i need to know is which function and methods should i use to get webform or drupal period to save my values(create a db table first?) and display them at the necessary time through whatever links on the site.

You want to use hook_schema() in your module.install file to make a database table to store your values. A small stupid logging schema I wrote is as follows:

function idprocessing_schema() {
  $schema['idprocessing_log'] = array(
    'description' => 'webextract process logging',
    'fields' => array(
      'id' => array(
        'description' => 'id of entry',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'created' => array(
        'description' => 'The Unix timestamp when the entry was made.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'msg' => array(
        'description' => 'whats going on in the processing',
        'type' => 'text',
        'size' => 'medium',
        'not null' => FALSE,
      ),
      'num_students' => array(
        'description' => 'number of students from xpath query',
        'type' => 'int',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

You then insert into the table as needed with say db_insert() a Database API function of drupal.

  db_insert('idprocessing_log')
    ->fields(array(
      'msg' => $msg,
      'num_students' => $cnt,
      'created' => REQUEST_TIME,
    ))
    ->execute();

You would want to insert $form_state['values'] by the way in your my_module_my_form_submit function.


Just migrated to pressflow and now users can't log in.. any ideas? I just migrated to Pressflow (newly downloaded) from vanilla Drupal install, and all of a sudden users cannot log in.  The page simply reloads, but there is no authenticated user.

I am getting the following errors when I flush the cache (and I got them after running update.php):

  Warning: Attempt to assign property of non-object in
  drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). Warning: Attempt to
  assign property of non-object in drupal_write_record() (line 3488 of
  /home/traders/public_html/includes/common.inc). User warning:
  Duplicate entry '0' for key 'tmd' query: INSERT
  INTO blocks () VALUES () in _db_query() (line 147 of
  /home/traders/public_html/includes/database.mysqli.inc).

Any help would be so so greatly appreciated!  If I can't figure this out in next couple of minutes, I'll roll back to normal Drupal.

Thank you!

**Edit:  My admin account was already logged in after I ran update.php and is working fine.  It seems like a problem creating a new session.

MORE INFO:  When a user logs in, my log says "Session opened for XXXXX." but it's quite clear the account isn't logged in ($user->uid is not set)

Not sure if that's going to be of any help for you, but I had kind of similar problem - on staging site, after upgrade from Pressflow 6.16 to 6.26, users were not able to log in anymore - or actually, according to Watchdog, they were logged in, but still being redirected to log in form.

No warning like yours though, although I assume that in your case they we caused by your admin account already logged in.

At this time prod site was still running Pressflow 6.16.

What helped in my case was changing $cookie_domain value in settings.php file on the staging server, which "unlinked" staging and prod cookies.

Essentially, before both staging and prod sites were using the same $cookie_domain (let's say it was mydomain.org), and everything started to work fine after changing it to stage.mydomain.org on the staging server.

Perhaps the problem is with the different way of handling cookies, and once our Pressflow is updated on prod server too it will again work fine with the same $cookie_domain, but this is still to be tested and confirmed.


How do I migrate a view? After releasing Drupal8-beta-15 we decide to migrate some of sites to Drupal8.
I read this article about how to migrate to Drupal 8, But I have some problem with it, I know when I want use a views in another website ( in Drupal 7) I can export/import it  or also use Features but now I don't know how I can migrate my views from Drupal 7 to Drupal 8.

How can I migrate a view from Drupal 7 to Drupal 8?

You can do it using this module :
Views D8 Upgrade

Tentative upgrade instructions (these may change):
Before upgrading your site to Drupal 8, update to the latest 7.x-3.x
release of Views on your Drupal 7 site.
Back up your data and place your site in maintenance mode.
Install the 7.x-1.x release of this module.
Navigate to admin/build/views_d8_upgrade and click "Perform upgrade."
warning: This will copy your Views data and uninstall the
Drupal 7 Views module.
Follow the Drupal core instructions for
upgrading to Drupal 8, including updating this module to its D8
version. This will convert your old Views data (still saved in the
database) to Drupal 8 Views.


Getting a linkable table of children in hook_block_view from taxonomy_get_children (Drupal 7) I am trying to programmatically create a block that will display all of the children of the term being referenced by the current page in a linkable table (so that I can click on any of the taxonomy terms and then go to their page).  So far I have managed to create an ordered list of children names with the following code:

function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);
      $children = taxonomy_get_children($term->tid, $term->vid);
      $stack = array();

      foreach ($children as $child) {
        array_push($stack,$child->name);
      }

      $theme_args = array('items' => $stack, 'type' => 'ol');
      $content = theme('item_list' , $theme_args);

      $block = array(
        'subject' => t('Children'),
        'content' => $content
      );
    break;
  }
  return $block;
}

But what I really want is a table that might contain some other details about the taxonomies but more importantly I would like each taxonomy in the list to be a link that will take me to that taoxnomies term page.  I image the reason these terms are not linkable is because I am only passing the name into the array but when I tried to pass the actual term into the array I get an error from the theme module.  How would I make these linkable?  Also, I imagine that I could change the ordered list into a table by replacing the 'ol' in the call:

      $theme_args = array('items' => $stack, 'type' => 'ol');

with a table but I am not sure what I would pass instead of 'ol' and I could not find any documentation about this.  Could anyone link me to such documentation?

You can use the l() function to create the link to each term, and the theme_table() function to build your table:

function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();
      $header = array('Link', 'Vocab ID');

      $children = taxonomy_get_children($term->tid, $term->vid);

      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      $block['subject'] = t('Children');
      $block['content'] = theme('table', $table);

      break;
  }

  return $block;
}

I've put a second column in there (Vocab ID) just as an example of how to add extra columns to the table.


Show Parent Menu children in sidebar I want to explain this as simple as possible...

I have a main navigation placed into the main_navigation block in my site
and I want to add a sidebar menu if the CURRENT main_navigation page has
child menus...

For example:

My main navigation is: Home | About | Services | Blog | Contact
Us
I added Request Quote page/form as a child of Contact Us
so when I am in Contact Us page, I want to show Request Quote in the
sidebar but don't show it if I am in About or Services

I saw this question but can't duplicate it

Get menu link siblings

Any help is welcome!

Use the Menu Block module, create a new Menu Block using the Primary Navigation, starting at Level 2.

This will only show the children of the current parent menu item you are in.