Combine multiple sources into a field I have multiple sources which roughly looks like:

Wines - Contents: "1,2,3,4"
Sodas - Contents: "1,2,3,4,5"

I'd like to combine those into one taxonomy vocabulary, get them to be auto-created and referenced in the destination field. So I'd like to do something like the following. But, if I read the static_map documentation correctly, mapping multiple sources like this is not the way it works. Also, I'm not yet exploding the string in the example, which I think is mandatory to be able to map the values.

  field_drinks:
    -
      plugin: static_map
      source:
        - wines
        - sodas
      map:
        wines:
          '1': 'Sauvignon Blanc'
          '2': 'Chiraz'
          '3': 'Pinot Noir'
          '4': 'Malbec'
        sodas:
          '1': 'Coca-Cola'
          '2': 'Spa'
          '3': 'Sprite'
          '4': 'Tonic'
          '5': 'Bitter lemon'
    -
      plugin: skip_on_empty
      method: process
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: drinks
      value_key: name

How do I convert this to suit my needs?

Found it out after a lot of trial and error. Basically it comes down to breaking everything up into individual "pseudo fields" and prepare the data before processing it into the actual field:

process:
  # First convert legacy wine id's to regular string names in a pseudo field
  _prepare_wines:
    -
      plugin: explode
      limit: 100
      delimiter: ","
      source: wines
    -
      plugin: static_map
      map:
        '1': 'Sauvignon Blanc'
        '2': 'Chiraz'
        '3': 'Pinot Noir'
        '4': 'Malbec'

  # Secondly convert legacy soda id's to regular string names in a pseudo field
  _prepare_sodas:
    -
      plugin: explode
      limit: 100
      delimiter: ","
      source: sodas
    -
      plugin: static_map
      map:
        '1': 'Coca-Cola'
        '2': 'Spa'
        '3': 'Sprite'
        '4': 'Tonic'
        '5': 'Bitter lemon'

  # Third, get all the pseudo field output together in a new pseudo field and flatten them into a single array
  _prepare_field_drinks:
    -
      plugin: get
      source:
        - '@_prepare_wines'
        - '@_prepare_sodas'
    -
      plugin: flatten

  # Lastly, the data is now all in a nice single level array with only names for the new taxonomy terms so we can use those as source.
  field_drinks:
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: drinks
      value_key: name
      source: '@_prepare_field_drinks'

Disclaimer: I'm not sure if this is the way it should be handled, but it seemed to do the trick without any custom plugins. Also, please be aware that if any of the source fields can be empty, you should prepend a skip_on_empty plugin to make sure your rows will not be ignored.


how to make a page with record displayed from database I am using a cutom module to display records from database.code below fetches all the record from database table but does not know how to display it on a page in my Drupal site (version 7):

function formModule_menu() {
  $items = array();

  $items['form/formModule'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Form', //page title
    'description' => 'A form with a text field and Submit button.',
    'page callback' => 'formModule_intro', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form

    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['form/formModule/form1'] = array(
    'title' => 'Form One',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

  $items['form/formModule/reviewOrder'] = array(
    'title' => 'Review Order',
    'page callback' => 'formModule_page',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 2,
  );

  return $items;
}

function formModule_page() {
return array('#markup' => '
' . t('Review Order: The table below shows the TOTAL STOCK and TOTAL QUANTITY of product purchased.') . '
');

  $query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the
  $query->fields('t');
  $result = $query->execute()->fetchAll();

 $rows[] = array('data' => (array) $row);

  foreach ($result as $key => $row) {
  $rows[$key] = array();

  foreach($row as $col) {
   $rows[$key][] = array('data' => $col);

   }
  }
drupal_set_message("
" . print_r($rows, true) . "
");

}

iam using the following code to dispaly it on a page but no results:

$header = array(
    // The header gives the table the information it needs in order to make
    // the query calls for ordering. TableSort uses the field information
    // to know what database column to sort by.
    array('data' => t('S.No.'), 'field' => 't.S.No.'),
    array('data' => t('Product Name'), 'field' => 't.Product Name'),
    array('data' => t('Total Stock'), 'field' => 't.Total Stock'),
    array('data' => t('Total Purchasing'), 'field' => 't.Total Purchasing'),

  );
 drupal_set_message("
" . print_r($header, true) . "
");**/
  $query = db_select('formmodule_order', 't'); // Using the TableSort Extender is what tells the

            // the query object that we are sorting.
  $query->fields('t');

//drupal_set_message("
" . print_r($query, true) . "
");

 $result = $query->execute()->fetchAll();

// drupal_set_message("
" . print_r($result, true) . "
");

  foreach ($result as $key => $row) {
  $rows[$key] = array();
   foreach($row as $col) {
   $rows[$key][] = array('data' => $col);
   }
  }
drupal_set_message("
" . print_r($rows, true) . "
");
  // build the table for the nice output.
  $build['formmodule_order'] = array(
    //'#theme' => 'table',
    //'#header' => $header,
    '#rows' => $rows,
  );

 drupal_set_message("
" . print_r($build, true) . "
");
  return $build;

what is wrong in the code?

Probably because before anything has a chance to print you are already returning #markup from formModule_page().
You might also want to use the Devel module's dpm() function for more cleaner and convenient debug messages and variable inspection.


How to put the widget to rate nodes in a view next to title? I have a view with the list of nodes, how can I put the widget to rate the nodes next to title?

Note: I'm already using the Rate module. But it returns me only the results.

Since you're using the Rate module, you should configure Views as shown in this image:

So what you need to do, is to configure the field "Votes:Value". As you can see in my image above, within the Appearance Dropdown I selected Rate Widget (compact). if you only have "Rate Widget option or Default" (as in your comment, it's probably because you have not yet added the required Relationships to your view.

Relationships is a way to join tables from another module. To get you going with this also, have a look at the next image:

Some more details about the 3 (numbered) annotations I added in this image:

That's where you add the Relationship, in this case you need to select Content:Votes.
After you added that relationship, within Fields you can now add a new field Votes:Value (that is: because of the relationship that was added, you'll be able to select this specific field from the list of available fields when you try to add an extra field).
After you completed the previous step, automagically in the preview area you'll see a preview of the views results you'll get (don't bother too much about the theming of that preview at this time, what counts is that the result is correct).


roles for non-authenticated users? I'm looking at making a site that provides a different 'experience' (to use the marketing term) depending on who the visitor says they are, without authentication. The functionality I'm thinking of using is to programmatically change the role from anonymous to something else.

So the from the launch page, client wants the site to look different depending on whether the visitor clicks "I'm a floor manager", "I'm a purchaser", "I'm a decision maker" and a perhaps few other choices. They are going to see different promotional material and copy depending on which link they choose, and the client wants it to appear that the whole site is geared towards them -- in other words, menus, pages, and promotional material not 'for' that user will be absent when they make that choice. It should look like several different sites, after they click out of the initial page.

So I thought that a way to do this would be to make all the content, menus, images, pdfs,  and then assign access by role. That way, if you're looking at the site as that role, you only see the things relevant to you. But we don't want the users logging in -- they just click on a button to declare what role they are, and if they are tricking us, we really don't care.

Will I be able to do this in the way I am imagining?

Roles can be added to users who are authenticated users, which means they logged in. Anonymous users are only anonymous users; no other role can be added to them.

If you are just trying to show a page differently basing on the what selected from the anonymous users, then you can use a cookie to store a value that is used to alter the user interface. In Drupal 7 there are two helper functions that can be used to delete and save a cookie containing values for an anonymous user: user_cookie_delete(), and user_cookie_save().


Overwrite field theme function from within form alter I'd like to modify the html of a form field from hook_form_alter(). Any hook for this one?

Your question itself the answer, inside
 hook_form_alter use the following

$form['field_job']['und'][0]['#prefix'] = 'yours html'

and $form['field_job']['und'][0]['#suffix']='yours close tags of html' this html will wrap field.


How to enable an authenticated user to vote? I am new to the field . I made a drupal 7 site using theme Danland, I am able to vote for the poll as an administrator but when I login as an authenticated user I can see the completed poll and I can not vote. What do I need to do.

Authenticated users probably do not have permissions to vote.

Go to administration > People > Permissions and then grant authenticated users the "vote" permissions.


how to display view block in node page I have a block in view that is displaying the user details, i want to display that block in a nodes created by the respective users.

i am successfully using this block in user page now i want it on node page.

please help me.

For another block which is also coming from view is worked fine with this code
Show block on specific pages:

<?php

//Read URL
$path=$_GET['q'];

//If URL is node page

if ( strpos($path,'node')===0){
//Parse URL to get nid
$links=explode("/",$_GET['q']);
$nid=$links[1];

//Load node

$node=node_load($nid);

//Display block only if node is of certain content type
if($node->type=='user_art'){
return TRUE;
}
}

return FALSE;
?>

Thanks

It is better to check the arguments from arg() function, this way:

<?php
// PHP VISIBILITY CODE:
// If URL is node page

if (arg(0) == 'node' && is_numeric(arg(1))){
  $nid = arg(1);

  // Load node:
  $node=node_load($nid);

  // Display block only if node is of certain content type
  if ($node->type=='user_art') {
    return TRUE;
  }
}

return FALSE;
?>

Maybe the problem is with the views argument to get $node->uid. Try this:

More info: https://groups.drupal.org/node/129979#comment-751473

1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
Provide default value
In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
Specify validation criteria
Validator select box: Content
Content Types: choose the content types you want the view to work with.
Filter Value Format: Node ID
Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.


How to remove the value Search from the site search form? I would like to style the Submit button and use an icon instead of the standard button. I would also like to remove the text/value Search.

How would I go about doing this?

Sorry: you can use an image as a submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

alternatively you can also place an image an trigger a function that will call

form.submit()

by using the img tag's onclick handler


Using Drupal console, can I gitignore console folder? I'm working on a Drupal 8 project, and installed Drupal console globally on my system.

The command drupal init created a console folder at the root of Drupal.

It seems to be used as a cache directory. Well it's a guess from what I see inside it.

Can I safely add this directory to my .gitignore file? Or should I commit it?

Yes, you can add the console directory to your .gitignore like so:

/console

However, similar to drush, you may want to carry around project-specific configurations in your repository. This allows changing the behavior of Drupal Console on a per-repository basis.

If you do want to have per-repository Drupal Console configurations then do not gitignore the console directory and instead commit it to the project.

See https://hechoendrupal.gitbooks.io/drupal-console/en/commands/init.html for details on how to initialize configurations.


Selecting more then one column when groupBy is present (db_select) - Drupal 8 added 'ONLY_FULL_GROUP_BY' In my custom Drupal 8 plug-in I perform such query:

$select = db_select('my_table', 'e');
$select->addField('e', 'field1');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

And it works fine. It returns me all records grouped by field1 that meets the condition, orderered. But it returns only field1 column.

I wanted to get more columns, so I have added another $select->addField('e', 'field2'); just after first one:

$select = db_select('my_table', 'e');
$select->addField('e', 'field1');
$select->addField('e', 'field2');

$select->condition('field3', 'NULL', '!=');
$select->condition('field4', array(11, 12, 31, 32, 33), 'IN');

$select->groupBy("e.field1");
$select->orderBy("e.field1");
$select->orderBy("e.field5");
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);

This time I get error:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1055 Użyto 'my_database.e.field2' bez umieszczenia w group by:

Which means "my_database.e.field2 has been used without putting in into group by". But I don't want to group by every column I select.

Unfortunatelly Drupal 8 added ONLY_FULL_GROUP_BY :(
Then, how can I use groupBy and select more then one column at the same time?

This is pretty annoying, but it is to provide cross database compatibility for Drupal.  You can get around it by adding the following to your database connection array if you only ever intend to live in MySQL compatible land:

'init_commands' => [
  'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
],

But I haven't yet figured out how to disable in my Kernel tests.  Still getting something like "PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 'local.nfd.title' isn't in GROUP BY"


Using Static Variables in a Custom Module I'm trying to define a static variable for use in my custom module. I want it to let me pass a number from function to function. I'm using drupal_static() but I can't get it to work. How do I do this?

This is the code I'm using to define my static variable.

$var = &drupal_static(__FUNCTION__);
if (!isset($var)) {
  // generate contents of static variable
  $var = '8';
}
return $var;

I've tried putting it in a custom module.

 function viewusercontact_locateuser($value, $key, &$counter) {
   global $user;

   /**********In here***********/

   if ($value['uid'] == $user->uid) {
      ........
   }
}

I can't seem to get it to work. What am I doing wrong?

(I got my code from the following guides)

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_static/7
http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
http://erikwebb.net/blog/drupal-design-patterns/static

drupal_static() stores variables based on the name of the function they're related to (hence the use of __FUNCTION__ when you initialise it in the relevant function).

You can pick it up again in any other function by querying drupal_static() again, with the name of the originating function. So in your case:

function viewusercontact_foo() {
  $static_var = drupal_static('viewusercontact_locateuser');
  ...
}


How add menu to my node programmatically? This is how i create my node :

    $value= array(
                'type' => 'page',
                'title'=>"First node",
                'body' => array(
                    'value' => "test",
                    'format' => 'full_html',
                ),
);

$nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->create($value);

        $nodeEntity->save();

This work fine.

But i try to give a menu parent to this node.

i try that :

$value= array(
            'type' => 'page',
            'title'=>"First node",
            'body' => array(
                'value' => "test",
                'format' => 'full_html',
            ),
            'menu'=>array(
             'title'=>"First node",
             'menu_parent'=>6,
             'description' => '',
             'enabled'=>1

        ),

);

i set the field menu because it's the name of the field in the node edit form.
But for the nodeEntity, this field doesn't exist.

How can i give a parent menu id to my node ?

UPDATE

if i set menu_link instead of menu, i got no error i still can't see the menu on the node.

After look into the database and some test, this is how i add a menu to my node on the creation or on node update :

For this example, i load a node :

  $nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->load(312);

  After you create the link :

$menu_link = MenuLinkContent::create([
    'title' => 'name of your menu',
    'link' => ['uri' => 'internal:/node/' . $nodeEntity->id()],
    'menu_name' => 'main',
    'expanded' => TRUE,
]);

$menu_link->save();

If you want add a parent to your menu just add this in $menu_link :

  $menu parent is the uuid of the parent menu

'parent' => 'menu_link_content:' . $menuParent,

  Then you need to update menu_link_content_data

  $this->database->update('menu_link_content_data')
            ->fields([
                'link__uri' => 'entity:node/'.$nodeEntity->id(),
            ])
            ->condition('id', $menu_link->id())
            ->execute();

The link between the menu and the node is the link__uri, you need to tell him to reference the entity node.

After that, you ll see your menu link on your node.

I haven't find better solution with Drupal API for now.


How to show a menu item for anonymous users only? I want to show a "Join Now" tab on the main menu for anonymous users only.

In the past I used Menu per Role module which does exactly that.

Since it's only one tab I would rather use 5 or 10 lines of code. Which hook should I use and what are the functions to check the current user role and add a menu item (or hide it for logged in users)?

I think the simplest way would be to override the access callback for the path that your menu link will be pointing to. You can do this in a custom module with hook_menu_alter(), and use user_is_anonymous() as the callback function:

function MYMODULE_menu_alter(&$items) {
  $items['path/to/page']['access callback'] = 'user_is_anonymous';
}

If you add a menu link for this path, Drupal's menu system will respect the access callback, and the link won't be shown to anyone who's logged in.

Using this method will also make sure that logged in users can't access the page directly, which is probably a good thing.


Custom Content types nodes with Nodeblocks module I have been unsuccessful in accomplishing the following:

I am using the Nodeblocks module and trying to follow its documentation for using it with a custom content type.  My custom content type machine name is content_block. I want a client to be able to create a new content_block and then be able to place it wherever he wants using the Admin > Blocks page.

The content_block content type has these fields (machine names - purpose):

title - Title of the block (nodeblock) that will be seen on the Blocks administration page. Will be hidden from output.
field_headline_level - stores a value like, "h2", "h3", "h4", etc. To be used to customize the HTML Headline tag. Will be hidden from output.
field_headline - The actual words for the headline
field_content - Content to be displayed below the headline

I've been trying to follow the Nodeblocks documentation (linked above) as well as the Drupal 7 Template Suggestions but I can not get it to work.  I keep running into nested template problems, such as the default block template wrapping around the node type template and getting double headlines.  I also can't figure out the correct syntax to display the various content_block fields.

Can anyone out there help me out or point me to a "Node Templates for Dummies" article?  I've done lots of searches on Google, but can't find anything very helpful.

Figured it out by getting my head around what Drupal calls "Template Suggestions".  The Theme Developer Module helped.

For my particular use case I had to create a template file called block--nodeblock.tpl.php to override the default block output. I basically stripped everything out of the default except the actual content so that this was all that was left: <?php print $content ?>.

Then I made a node--content_block.tpl.php template to override this particular content type's display the way I wanted it.  I had to add some trim() methods to strip out some leading spaces that Drupal insisted on inserting.

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php if($content['field_headline']): ?>
        <?php print render($title_prefix); ?>
        <<?php print trim(render($content['field_headline_level'])) . ' ' . $title_attributes; ?>><?php print trim(render($content['field_headline'])); ?></<?php print trim(render($content['field_headline_level']));?>>
        <?php print render($title_suffix); ?>
    <?php endif ?>

    <div class="content"<?php print $content_attributes; ?>>
        <?php print trim(render($content['field_content'])); ?>

The last thing I had to do was create a template to strip out all the extra tags that the Drupal default field comes with.  I did so with this file, named field--content_block.tpl.php:

<?php foreach ($items as $delta => $item) : ?>
      <?php print render($item); ?>
<?php endforeach; ?>


XML feed in Drupal 7 I'm using drupal 7 with feeds module.

I've followed this tutorial to try to create nodes with the feed but it didn't work.

Here is the feed : https://cb1-demo-fr-staffing.luceosolutions.com/openrest/requisitions/active
Does anyone know why ?

You do not have xpath parser inside your mapping, which is required for the XML feed you are using, as it is in XML format.

The Xpathparser is a little confusing at first, but basically in your mapping, map all the XPath parser values to your values within your Content type you're importing too.
Then on /import it should be where you assign your XML field values from the feed to said Xpathparser values, AKA your CT fields.

Flush all caches then go back to your parser settings and click XPath XML parser.

Inside your mapping your source should be xpathparser:0 and then you can map it to what field it should go to from your associated CT(set in Node processor settings). Do this for ever field from your CT which you want a value coming into.

Then when you go to /import there should be a dropdown called XPATH PARSER SETTINGS click on that. there will be a context field, give the context field the value of //requisition. (Optionally you can set this up on the Feeds settings under the Xpath XML parser Settings IF you have already set up your mapping)

The context is  where you want the feeds importer to start importing tag data from. You want the context to be //requisition so you can grab the tag values from within it. (example job_id). Then map the XML field in the XML file to said field.

Example: title = job_id, and Body = rendered_job_posting.


Randomize the result of a database query I'm executing a query for which I want to randomize the results.

I tried with $res=db_query("SELECT DISTINCT nid FROM content_type_event ORDER BY RANDOM()"),          but this doesn't work.

For MySQL you can do

ORDER BY RAND()

To order by random, for PgSQL RANDOM() instead should yield the desired result.


Programmatically creating a custom block I followed the steps from https://www.webwash.net/programmatically-create-block-drupal-8/.
I have a view already created and I want to render this view in this block.
I can't find a good documentation for build() function.

The reason is that I want to hide the view for a role implicitly included by authenticated role.

How can I display the existing view inside the custom block I've created?

I didn't find a way to display the view and restrict for certain roles.

But I've managed to solve the problem in another way.

I created a script in Admin > Structure > Block > My_Block > Configure > Visibility PHP:

<?php
$match = TRUE;
$heh = \Drupal::currentUser()->getAccount()->getRoles(TRUE);
$hide_from_roles = array('administrator', 'sefii', 'membership');
 if (count(array_intersect($heh, $hide_from_roles)) > 0) {
    $match = FALSE;
}
return $match;
?>


Views for specific user profiles I have  view that displays a users nodes. When you view "my account" it displays all the nodes you created in a view.  However when viewing another user's profile, you don't see the node's that they added, instead you still see your nodes.  Is this something I would need to set up with views and rules?

tl;dr How can I create a view that displays user specific content on their own profiles.

X user's content on X user's profile
Y user's content on Y user's profle

EDIT
Answer:
Drupal 7 views, filter by owner

To list content owned by a user you can:

Create a View that lists content
Create a Page Display within that view
Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".


What is the difference between DRUPAL_ROOT and file_directory_path() in drupal 6? I want an alternative for file_directory_path() deprecated in Drupal 7. I got an alternative with file_default_schema().

What is the difference between DRUPAL_ROOT and file_directory_path() or
DRUPAL_ROOT and file_default_schema()?

DRUPAL_ROOT is a root folder of Drupal's installation. file_directory_path() returns a path to directory meant for uploaded files, default DRUPAL_ROOT/sites/example.com/files (replace example.com with your site or default). If you will replace it with hardcoded path, your modules will break on sites configured to store files in other directory. So this is not the way.

If you need it for forms, use new managed_file form element. It takes care. No need to provide path.

For reading file, if you know it's ID it's easy again. Load it and access it's properties, like that:

file_load($fid)->uri; // get URI to display it

If you don't want to use managed files (you should, but no one can force you), use:

$dir = file_default_scheme() . '://' . $any_subdirectory_you_want;

This will create directory string Drupal functions understand. For example, you can use it as $destination in  file_save_upload($source, $validators, $destination, $replace) - again, no need for hard-coding actual path or using DRUPAL_ROOT on your own.


Custom Javascript doesnt work unless JQuery is set to Default jQuery Version I spent the entire day trying to figure out why my custom JavaScript was not working.

Eventually I stumbled into the JQuery Update configuration and set it so that the JQuery that I use for my site was the "default (provided by Drupal)" setting and then it worked. Before it was set to 1.7 jQuery version. Looks like someone set it to 1.7 perhaps for magnific.js because that is now spitting out errors in my console "TypeError: a.off is not a function." Not sure what we use that js file for, but I find it strange that I never found anything on line about this being a potential issue when I was trying to troubleshoot my custom javascript.

Does anyone know anything about this? or am I just in left field? I know it wasn't the same issue the gentleman had in this post.

My custom code was not complex and it never worked. So I reduced it all down to just console out a simple message. But that proved to not work either. My simple console out code for my pulsing.js is:  (function ($) {
  Drupal.behaviors.notWorking = {
    attach: function () {
      console.log("finally is working");
    }
  };
}(jQuery));

Ill just show the screen shots. The first one is the image where my custom code doesnt work because of jQuery update settings as I said above.

The second one is what makes my custom code actually work - but like I said magnify.js then breaks - which maybe i'll hack at it or look for a newer version or something.

magnific.js clearly needs the .off() function which was added in jQuery 1.7. If you need magnific.js, you will need jQuery 1.7 and it is your job to upgraded your custom JavaScript accordingly.

Upgrade to 1.6
Upgrade to 1.7

You may find the changes you need are minimal.


How do I dynamically change cookie_lifetime? I'm trying to change cookie_lifetime dynamically in my D8 project, to set cookie_lifetime to 0 or to some value(for example 24 hours). I know that this can be partially acomplished by changing cookie_lifetime variable in sites/default/services.yml, but this is not my case.

I've tried to use this answer but looks like it works only when I use start() method of the session manager.

So how do I change dynamically cookie_lifetime for existing session?
Any answers appreciated, thanks in advance!

You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:

/mymodule/src/MySessionConfiguration.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;

/**
 * Sets session cookie lifetime dynamically.
 */
class MySessionConfiguration extends SessionConfiguration {

  /**
   * {@inheritdoc}
   */
  public function getOptions(Request $request) {
    $options = parent::getOptions($request);

    // Set the cookie lifetime dynamically depending on the request.
    $options['cookie_lifetime'] = 30;

    return $options;
  }

}

Swap the service class in the container:

/mymodule/src/MymoduleServiceProvider.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('session_configuration');
    $definition->setClass('Drupal\mymodule\MySessionConfiguration');
  }

}

See Altering existing services, providing dynamic services.


Adding comment count to view I want to be able to add a comment comment to a view , through comment.tpl.php as I have tried to add the comment counter through the admin area and it doesn't work

Can you elaborate on the error?

I just did a quick test and was able to add comment count to a view:

Go to the views admin page , click fields, add

  Content: Comment count The number of comments a node has.


Run query after page load I have a table of reservations which is built using Views module.

I want to highlight new reservations only 1 time. So I want to run a database update query (function db_update) after a page load. I tried to run it in hook_page_alter() or in hook_process(), but I didn't succeed, because query runs before showing a table. What hook should I use in my case?

hope this will help

/**
 * Post process any rendered data.
 *
 * This can be valuable to be able to cache a view and still have some level of
 * dynamic output. In an ideal world, the actual output will include HTML
 * comment based tokens, and then the post process can replace those tokens.
 *
 * Example usage. If it is known that the view is a node view and that the
 * primary field will be a nid, you can do something like this:
 *
 * <!--post-FIELD-NID-->
 *
 * And then in the post render, create an array with the text that should
 * go there:
 *
 * strtr($output, array('<!--post-FIELD-1-->' => 'output for FIELD of nid 1');
 *
 * All of the cached result data will be available in $view->result, as well,
 * so all ids used in the query should be discoverable.
 *
 * This hook can be utilized by themes.
 * @param $view
 *   The view object about to be processed.
 * @param $output
 *   A flat string with the rendered output of the view.
 * @param $cache
 *   The cache settings.
 */
hook_views_post_render(&$view, &$output, &$cache)
    {
if ($view->name == 'your_view_name')
    {
   //do your logic
   }}


Can we load core css files from custom theme with yml lib? Is there a way to provide f.e normalize.css within my custom template using a *.libraries.yml config file? Tried the following, didnt work out.
I was just wondering if this would be possbile, for it seems to be nice, while the file comes with drupal8 installation.

global-styling:
  css:
    theme:
      css/style.css: {}
    core:
      normalize-css/normalize.css: {}
  js:
    dependencies:
      - core/modernizr

The first attempt to load the single file normalize.css is not correct. If you want to do it this way, you have to use the full path to this file.

But this is not the preferred way to do this. You don't know if in future the position of this file will change. Better use the library already defined in core, as you have done in the second attempt to load modernizr. This will work, if you put the key dependencies on the first level of the array, for example see the core library date:

drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

If you look for normalize.css, this is defined in core:

normalize:
  remote: https://github.com/necolas/normalize.css
  version: "3.0.3"
  license:
    name: MIT
    url: https://github.com/necolas/normalize.css/blob/master/LICENSE.md
    gpl-compatible: true
  css:
    base:
      assets/vendor/normalize-css/normalize.css: { weight: -20 }

And you can use it as dependency in *.libraries.yml:

  dependencies:
    - core/normalize

Or as library in the theme.info.yml file:

libraries:
  - core/normalize

If you use a core library, you don't have to put it in your own library, you can choose the direct way to use it.


How to make a blog tab in every user profile I have enabled the Blog module in order to have a blog for every user. Now I want to create a tab in each user profile that it links to that user's blog.

Is it possible? How can I do this?

Using a custom module, you can implement hook_menu() in the following way:

function mymodule_menu() {
  $items['user/%user/blog'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file path' => drupal_get_path('module', 'blog'),
    'file' => 'blog.pages.inc',
  );

  return $items;
}

The "file path" property is used because the module that defines the menu is not the one containing the "blog.pages.inc" file.

If you have few experience on how to create a Drupal module, you should start looking at:

Creating Our First Module using Drupal 6 (Part1)
Creating a Simple Drupal Module
Creating Drupal 6.x modules
Creating Drupal 7.x modules


how to write views for our own custom module? I am new to drupal. I have created one form submission module like this

 <?php
function form_test_permission()
{
return array(
'submit_form_test' =>array(
'title' =>('submit_form_test'),
'description' =>('submit the form_test form'),
),
);
}
function form_test_menu() {
$items=array();
$items['application']=array(
'title' =>'Application Form',
'type' =>MENU_NORMAL_ITEM,
'access arguments' => array('submit_form_test'),
'page callback' =>'drupal_get_form',
'page arguments' => array('form_test_form'),
);
return $items;
}

function form_test_form($form,&$form_state){
$form['firstname'] =array(
'#title' =>t('Firstname'),
'#type' => 'textfield',
);
$form['lastname'] =array(
'#title' =>t('Lastname'),
'#type' => 'textfield',
);
$form['addr']=array(
'#title' =>t('Address'),
'#type' => 'textfield',
);
$form['age']=array(
'#title' =>t('Age'),
'#type' => 'textfield',
);
$form['submit']=array(
'#value' => 'submit',
'#type'=> 'submit',
);
return $form;
}
function form_test_form_submit($form,&$form_state) {
$ft_id=db_insert('form_test')
->fields(array(
'firstname' => $form_state['values']['firstname'],
'lastname' =>$form_state['values']['lastname'],
'addr'=>$form_state['values']['addr'],
'age'=>$form_state['values']['age']
))
->execute();
drupal_set_message(t('Saved.'));
}

if I go like localhost/drupal-example/application.. this module works.. But I want to display this module in front page.I referred a lot. But it doesn't works. Can anyone guide me how to write a view function in this module?

In order to be able to use a custom module's table with Views, you need to use hook_views_data().

Even better, I would recommend that you invest some time to learn about entities. Entities are much better for most and thay can be almost immediately used in views.

To define a custom view into your module, put it in file module.views_default.inc (replacing with your module name), in a function module_views_default_views().


When 'cron_safe_threshold' is set to 0 in settings.php, should the dropdown value on admin/config/system/cron be "Never"? or is it irrelevant? I've installed Drupal 8.1.6. As Ultimate_Cron won't work on this site consistently or reliably, I've decided to just use Drupal's core cron, triggered externally (via /etc/crontab) rather than using Poormanscron.

The documentation on https://www.drupal.org/cron says:

  Disabling "automated cron"

  Another way to disable cron is to add the following line to your
  settings.php: $conf['cron_safe_threshold'] = 0; Note that this fixes
  the setting at admin/config/system/cron to "Never", and administrative
  users cannot override it.

I set $conf['cron_safe_threshold'] = 0; in the settings.php file, but when I go to admin/config/system/cron, I still see the following:

  Cron settings
    Run cron every 3 Hours

What does fixes the setting at admin/config/system/cron to "Never"  actually mean?

The value I see is set to "Never", and can't be changed
The value is overwritten in the {variables} table to a fixed value equal to 0, and that the displayed drop-down value on admin/config/system/cron is irrelevant

p.s.

There's gotta be an easier way to find out available $conf settings than this

1) realize that cron in Drupal8 is actually controlled by a core module

cd web/core/modules/automated_cron

2) look for any drupal::config() assignments

grep -i "drupal::config(" *.module
    $automated_cron_settings = \Drupal::config('automated_cron.settings');

3) for each one found, get set-able vars

grep -i "automated_cron_settings" *.module | grep "=>"
    '#default_value' => $automated_cron_settings->get('interval'),

NOTE: in default.settings.php

 * Example:
 * @code
 *   $conf1) realize that cron in Drupal8 is actually controlled by a core module

     cd web/core/modules/automated_cron

     2) look for any drupal::config() assignments

         grep -i "drupal::config(" *.module
                 $automated_cron_settings = \Drupal::config('automated_cron.settings');

                 3) for each one found, get set-able vars
                     grep -i "automated_cron_settings" *.module | grep "=>"
                             '#default_value' => $automated_cron_settings->get('interval'),
                             ig_directories = array(
 *     CONFIG_SYNC_DIRECTORY => '/directory/outside/webroot',
 *   );
 * @endcode
 */

Re: automated cron, no less

and, a 'simpler' method:

drush cli | grep -i cron
    automated_cron.settings
    system.cron

drush cget automated_cron.settings
    interval: 10800
    ...

drush cget system.cron
    threshold:
      requirements_warning: 172800
      requirements_error: 1209600
    ...

This setting is for Drupal 7. In Drupal 8, the equivalent is in the config management system as automated_cron.settings.interval. To override it, like in Drupal 7, you can add:

$config['automated_cron.settings']['interval'] = 0;

to your settings.php.

To address the other question, the relevance of automated_cron.settings.interval & cron_safe_threshold is the minimum amount of time (in seconds) since the last cron run that Drupal is allowed to run again. This value is checked (D7 & D8) for a 0 threshold which it will interpret as FALSE and thus never run cron.


How to log all outgoing links generated in a view? What is the most lightweight method of tracking all outgoing links generated in a view. By lightweight I mean that I don't want to have to load a module such as statistics that will potentially slow down my site due to it going above and beyond my needs.

Basically I would need to record the data into a database using the following structure:

product_id | uid | timestamp

The product id is associated with each link and is a separate field. The purpose would be to create sets of clicked links for each user, product, etc. This could in turn be used as a dataset for subsequent user/item analysis. I would imagine I would need to use some sort of callback function.

Can anyone provide an example or any hints?

You could use jQuery to attach a click event to each link that triggers an ajax request to record the click.

The problem with this is that the page may redirect before the ajax request has had a chance to fire so you will have to prevent the default action of the click, and then perform an ajax request with async=false, and then provide a call back function to redirect to the links destination.

Not exactly lightweight...

Another option is to define an outbound link function in PHP that will accept the final destination as a argument. So the link would look like /outbound?dest=http%3A%2F%2Fwww.google.com.

Then in that function you can record the click, and then redirect them on to the destination passed in...


How to add text under menu items In my menu, I want to add some text under the menu item.  For example, I have 'About Us', and right under that, I want some subtext 'About our company'.

Do I add this in region.tpl.php?

Use superfish module for building your menu, and then whatever you type in your description depend on configuration will be print out too.

Under Advanced HTML Settings > Hyperlinks enable the "Include hyperlinks description (title) in hyperlinks text."

then simply add a display: block; style to the ul li a span to make it look the way you want.

you can see a demo HERE


How can I redirect users on login based on their chosen language? I'm looking to redirect users after they login.

The site is multilingual, using English and French.

I've tried using the Login Destination module and using Rules, but it has no options for accessing the language the user has chosen.

On the user edit page, the user can select 'English' or 'French' as their language.

I'm looking, ideally, for a simple rule condition to add, or some PHP.

None of the answers I've found so far have mentioned multilingual sites.

Thanks.

May be this can help you.

function custom_module_user_login(&$edit, $account){
  $base_url;
  if($account->language) {
          $redirection = $base_url.'/'.$account->language;
  } else{
      $redirection = $base_url;
  }

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.

  if (!is_null($redirection) && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
    $GLOBALS['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }


Photo gallery with taxonomy filter It's not easy to explain so I made simple example below. I'm making a gallery in Drupal 8.
First I made articles with taxonomy term: animals, forest or people. Some of articles have two or three taxonomy terms. Each article contains 1-5 photos. The main page (gallery) displays a main photo from each article (picture 1). As you can see when you click FOREST gallery shows all articles contain 'forest' taxonomy (picture 2). When someone click on a thumbnail from the forest gallery then a page (picture 3) appears and we can see our tree with 2 more photos (for example colorbox) plus some comments and thumbnails of articles with forest taxonomy above. Picture 4 is easy to understand.  Additionaly when you click on a thumbnail from NEWEST(ALL) gallery the next and previous articles has to include all taxonomy terms or just all photo articles.

I've made a few projects but none of them can do this all same time. Is there a way to make this photo gallery? It looks like a basic gallery but I couldn't find solution or module.

EDIT 2019-11-27: From the beginning: I have articles (with photos) that have taxonomy term.I have views for each taxonomy term. For example, for the "People" category, I have a view that displays the title and thumbnail photo from each article that has "People" taxonomy. If the article has two taxonomy terms, its thumbnail is displayed, for example, in the "People" view and the "Forest" view. And that's ok. I also have a pager for every taxonomy, made by the Entity pager module, which is a block. I would like this pager to be displayed in the article. But now, if I have an article that has two taxonomy term, it displays two pagers. I would like only one to be displayed. If I click on the article shortcut in the "People" view
(and this article has the taxonomy term "People" and "Forest") I would like this article to display the "People" pager only. If I click the same article thumbnail, but in the "Forest" view, I would like only the "Forest" pager to be displayed in this article. Is it even possible to do this?

This is quite a bit more complicated than your previous question.

My best advice would be that in order to get each content node to have a gallery with multiple images, each Article node should use an image field with multiple values.

These "child sideshows" will be completely separate from the "parent slideshow" which is the one using Views with the taxonomy filters (e.g., "Previous / Next Forest").

You should still be able to make the "child slideshow" into a scrollable gallery as you show in your thumbnails (e.g., "Previous / Next image in Article") by using a library like SlickSlider.

This Drupal.org issue queue talks about setting up Slick without Views as a "multi-imagefield single-node slick on D8" so it can definitely be done. (The Slick Extras module may help, but I haven't tried it so I'm not sure.)

It will be a bit more work this way, and not all the advice you find online will be completely applicable to your situation. If you get stuck, I recommend following the Javascript code in the Slick demos rather than any Drupal-specific walkthroughs.

Good luck!

EDIT 2019-11-27: Thanks, the comment below helps me to understand what you're trying to do.

The real problem is that your data model is a mess: you want to apply the taxonomy terms to the Article (child slideshows) content type, and also to the individual photos within the Articles. You apparently don't want to display all the photos in each Article, but only the individual photos that match the selected taxonomy term in the parent. That wasn't very clear from your earlier description.

To accomplish that, I think you'll need to implement the term filters (Animals, Forest, People) as an exposed filter on the child slideshow. You can't filter by the taxonomy terms on the child node because you want to jumble terms together at both levels.

This is made more complex by the fact that you want the same buttons to act as exposed filters on two different Views. No wonder you are having trouble.

Maybe you can use a contextual filter on the child slideshow that refers to the value of the exposed filter on the parent.


How do I reload the theme .info file on Drupal 7 How do I reload the theme .info file on Drupal 7?  I added the following line of code in order to add my own Javascript file to the pages:

scripts[] = myJavaScriptFile.js

Now I need to refresh the .info file somehow. It doesn't seem to be doing this on its own. How do I do this?


Views conditional fileds: multiple values I have a content type with the following field:

List (float) - blue - green - yellow

In the view, I want a condition that says that if the value is "blue" display this: div class="blue"

If it is green display class="green"

If it is empty display class ="empty"

And so on...

I tried Views Conditional Module but it can't handle multiple values...

What is the best way to do this?

I solved this with a simple solution:

Added custom text field in views and something like:
div class="[field_value]"

The result of the field (blue,green,empty) is the class of the div so I can manipulate the css.

Thank you


Extending an existing Plugin class results in Class not Found PHP Fatal Error I am trying to create my own Plugin that extends an existing Plugin class.
I can extend the base class and everything is fine.
However, if I extend a existing Plugin class, I get a Class not Found error.

e.g.

<?php

namespace Drupal\my_module\Plugin;

use Drupal\contrib_module\Plugin\ClassA;

class MyClass extends ClassA {
  public function implement() {}
}

The error I am getting would be
Class 'Drupal\contrib_module\Plugin\ClassA' not found in /var/www/project/web/modules/custom/my_module/src/Plugin/MyClass.php on line 7

Any Thoughts guys?

There is no D8 commerce_usps module yet. I found a development version on github, I pressume you're using this one.

The use statement uses the following structure use [namespace]\[classname]

So your use statement needs to be

use Drupal\commerce_usps\Plugin\Commerce\ShippingMethod\USPS

class ForExample extends USPS { ...


Updating modules with drush without breaking SVN? Right, this has been breaking me for two days. I can't get an answer anywhere!

I have drush 4.4 on my server. I am using SVN via Unfuddle.com. I have a site, I want to update a lot of modules. I want to update just the code, then check it's working (DB updates are not a concern at this point) then commit the relevant code.

It used to be that drush dl  would simply download the module code over the top of the old module, without removing it. That is no longer the case. Now, AFAICT, drush removes the module directory and replaces it with the newer version. That's all well and good, because it solves the problem of old files that are no longer in the updated module being left behind.

However, using the drush dl or upc commands, I am stuck, because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php" problems everywhere for files that aren't there any more.

I have been advised that "drush upc/dl modulename --version-control=svn" should work, but it doesn't. The SVN data is still destroyed.

This leaves me with the potential nightmare of having to:
svn del module,
svn commit -m"Removed module",
drush dl module,
(test the module),
svn add module,
svn commit -m"Added module" -
for every single module, which is a total horror.

I do not want to set up drush to auto-commit my changes, I just want to download them and commit them all manually at the end when I'm happy with the changes. This can't be that hard, but I simply cannot get it to work.

I have also been advised that moving to git (yes, I'm aware unfuddle supports git!) is also a solution, but it's not an immediate one, and is not satisfactory at this point in time.

Can anyone please shed some light on this?!

because running these commands does indeed get the newer version, but it destroys the SVN data folder in the process, leaving me with "! module/file.php"

I'm running Drush 4.4 and this does not appear to be the case for me. Running drush upc or drush up keeps your .svn directories intact. You can svn status to review the changes to the modules. New files are indicated by ? and removed files are indicated by !.

Test your site's functionality. Once you are satisfied that the modules are still working correctly, you can then svn add/remove with a snippet such as the following:

add:

svn status | grep '^\?' | cut -c8- | while read f; do svn add "$f"; done

remove:

svn status | grep '^\!' | cut -c8- | while read f; do svn rm "$f"; done


Content type not responding to AJAX callback I am using a ctools content type plugins to render a custom form that will have only one submit button.
The submitbutton will switch an eck entity field (boolean) from 0 to 1 and back (if pressed again, of course).
I have defined my ctools content type plugin, form (with ajax callback) and a submit handler
When i tested it with a hook_menu path, all was fine and it worked.
Since i have put it in a ctools content type, no luck.
Any help would be very much appreciated!
Ps: What would be the best place to put my database logic? The submit handler?
Thanks a million!
$plugin = array(
  'single' => TRUE,
  'title' => t('Project isClient'),
  'description' => t('Project isClient AJAX plugin'),
  'category' => t('Project'),
  'render callback' => 'project_isclient_ajax',
  'defaults' => array(),
);

function project_isclient_ajax() {
  $pane = new stdClass();
  $pane->title = t('Project isClient');
  $pane->content = drupal_get_form('project_isclient_form');
  return $pane;
}

function project_isclient_form($form, &$form_state) {
  return array(
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Subscribe'),
      '#ajax' => array(
        'callback' => 'project_isclient_ajax_submit',
        'wrapper' => 'project-isclient-form',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    ),
  );
}

/**
 * Ajax callback function.
 */
function project_isclient_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  return 'works!';
}

A little after posting this, i found AJAX calls in CTools Content Type Plugin? which states that ctools handles ajax forms differently. I checked using blocks, and this appears to be correct.
In a block my callback works.

yes it seems like panles content type plugin handles the ajax calls differently. You could use the ajax commands listed in the ajax.inc file in core. There are functions for ajax_command_remove, ajax_command_append and more...

Here is my ajax callback that i call from my ajax form submit button
example:

function my_form_ajax_callback($form, &$form_state) {
  $output = '
Clicked!
'
  $commands = array();
  $commands[] = ajax_command_remove('#id_to_remove');
  $commands[] = ajax_command_append('#id_of_wrapper_to_insert_in', $output, $settings = NULL);

return array('#type' => 'ajax', '#commands' => $commands);
}


hook_form_alter to limit user select list to those referenced in a node I have a content type called Project. I am linking users to this content type through several user reference fields.

I am also creating related Events (another content type) related to the Project content type pages through the Node Reference URL Widget.

So far so good, but...

In the Event content type I would like to add Attendees, through another user reference field, and limit the list of users to only those referenced in the original Project page. First I tried using a view, but I couldn't find the proper arguments / filters / relationships. Now I am trying through a custom module with hook_form_alter.

Could I get some advice on an efficient way to do this? Any ideas would be greatly appreciated.

EDIT:
I have been working on this, and it seems I am almost there, but not quite. Bare with me as this is my first custom module and my php skills are quite basic. My structure (content type > fields) is as follows:

Project:

field_users (entity reference)

Event

field_project (entity reference, prepopulated from Project on event
creation)
field_attendees (entity reference)

Then, in a custom module, I added the following code to modify the Event content type form:

<?php
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_event_node_form') {
    $id_project=var_export( $form['field_project']['und']['#default_value'][0], TRUE );
    $project = node_load($id_project);
    $user_ref = array();
    foreach($project->field_users as $u){
      $user_ref[] = $u;
    }
    $form['field_attendees']['#options'] = $user_ref;
  }
}

But I still see all users, not just those referenced in the Project. Strangely enough, if I do:
dpm($user_ref);
I get this array, which contains the ids of the users I want to be able to choose from:

array (
  0 =>
  array (
    0 =>
    array (
      'target_id' => '7',
    ),
    1 =>
    array (
      'target_id' => '8',
    ),
    2 =>
    array (
      'target_id' => '9',
    ),
    3 =>
    array (
      'target_id' => '10',
    ),
  ),
)

But somehow I fail to pass that as the options for field_attendees. Any ideas?

I finally managed to get it working:

<?php

function my_module_form_alter(&$form, $form_state, $form_id) {
 if ($form_id == 'project_event_node_form') {
  $node = $form_state['node'];
   if (!isset($node->nid) || isset($node->is_new)) {
    /** This is a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
   }
   else {
    /** This is not a new node */
    $id_project=var_export($form['field_project']['und']['#default_value'][0], TRUE);
    /** horrible hack, but I can't get the nid to behave as an integer no matter what */
    $id_project = substr($id_project, 1, -1);
    /** no need to change the referenced project, hiding the field  */
    $form['field_projet'] = array('#type' => 'hidden');
   }
   /** common code */
   $project = node_load($id_project);
   $user_ref = array();
   foreach(field_get_items('node', $project, 'field_users') as $u){
   $usr_obj=user_load($u['target_id']);
   /** this makes the checkbox form render in a useable way */
   $user_ref[$usr_obj->uid]=$usr_obj->name;
   }
  $form['field_attendees']['und']['#options'] = $user_ref;
 }
}

Any suggestions or improvements are welcome, particularly with the dirty hack whith the nid behaving as a string in the node edit.

Although this is a rather simple module it is my first one, so I'd like to thank the patience and support of all those who helped with this, particularly Peyman and Josh at robustLINKS, bnjmnm and Michael.


Views - field template vs php field What should be considered the optimal way of creating a custom field in views?

For example:

if($content_type == 'article'){
  print 'something';
}
else{
  print 'something else';
}

I either create a Custom Text field and write my php code in its template, or, lately, I've started using views_php field.

The disadvantage with the templates is that if your site is kinda big, you end up with tons of template files that are sometimes hard to manage, and also (obviously) cannot be managed from someone without server access. Furthermore it cannot support sorting/filtering of some kind.
Apart from that, it's "fail safe", it's robust, it doesn't add to complexity via an extra module.

The (possible) disadvantage of the php field is that it's an extra layer of complexity to the site and thus an extra bug possibility.
Apart from that, it's easily manageable and it can even be used for filtering/sorting!

So, what would you guys suggest? What do you usually do in such cases?

Here are some advantages of using templates instead of a custom PHP field.

Templates can be naturally version-controlled just like the rest of your code.  (You could version-control the custom php field with Features, but that is an additional layer of complexity.)
Since the code for templates is in files, you can use UNIX commands like grep, etc. to search them.  You can also batch edit them easily if necessary.
If you accidentally misconfigure your site permissions and give a role access to Views administration that shouldn't have it, they still won't be able to insert PHP into your site if you're using templates (eliminates a security risk).  Consider that one of the security enhancements in Drupal 7 over Drupal 6 was hiding the PHP filter and making it harder to enable.
The Views PHP module is still in dev and thus not subject to audit by the Drupal security team.  There may be (are) bugs in the module and since it is not in widespread use they may not be found for some time (avoids another security risk).

Yes, templates might be a little inconvenient, but from a security and maintainability standpoint I think they are clearly superior.


Switch theme by http status code We have a page that uses several themes, but the 404 pages should all look the same.

So, for all themes except one we need a rule that switches to another theme when the URL does not match any content.

There are ways to choose the theme by the current URL, like using the context module, or implementing a ThemeNegotiatorInterface, and we use them to assign our themes to certain parts of the website.

It seems that the ThemeNegotiatorInterface is not used when delivering a 404 error page.

So, how can we switch the theme according to the http status code?

I've done something similar by implementing the ThemeNegotiatorInterface. In the function that determines which theme should be used, the following code snippet checks for a 404 Page Not Found exception:

$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($status && $status->getStatusCode() == 404) {
  return 'name_of_the_theme_that_should_handle_404_responses';
}


Merge menus for mobile menu Hi I have 3 menus on my site and for display on mobile/tablet I would like to merge these menus to only 1 menu. Do you know how to do it. I tried to use menu_tree_all_data

and then merge them but I get Call to undefined function menu_tree_all_data. I'am confused that the function doesn't exist.

As I'm also looking for a solution to this issue I've come a bit further and maybe it will get you in the right direction.

To load a menu in Drupal 8 you can put this in a theme_preprocess_page in your .theme-file.

  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);
  $menu_html = \Drupal::service('renderer')->renderPlain($menu);

I have not yet worked out how to merge different menus into one big menu but I will let you know if I come up with a solution.
You can find out more about the code above at Drupal 8.2.x » menu.api.php which is where I found it.

Ok, I now have found the solution which I found in the module Responsive and off-canvas menu

  $menus = array("main-menu","footer-menu","utility-menu");

  $combined_tree = array();
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters(trim($menus[0]));
  $manipulators = array(
    // Show links to nodes that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  // Force the entire tree to be build by setting expandParents to an
  // empty array.
  $parameters->expandedParents = array();
  // Iterate over the menus and merge them together.
  foreach($menus as $menu_name) {
    $tree_items = $menu_tree->load(trim($menu_name), $parameters);
    $tree_manipulated = $menu_tree->transform($tree_items, $manipulators);
    $combined_tree = array_merge($combined_tree, $tree_manipulated);
  }

  $menu = $menu_tree->build($combined_tree);

  $vars['mobile_menu'] = array(
    '#prefix' => '

',
    '#suffix' => '

',
    '#markup' => \Drupal::service("renderer")->renderRoot($menu),
  );

If you put this in your theme_preprocess_page in your .theme-file you could then in your page.html.twig print the twig variable {{ mobile_menu }}.


Redirect to Continue Multi Step Form I am building a form that can either begin on the home page or at the '/apply' url. I used this tutorial to build the multi-step form. The form works great if I start from '/apply' and begin at the very beginning of the form process. The form does not work if I start from the home page and get redirected to the second step of the form, then try to submit that second step. This is the error message I receive when I try to submit that second page of the form when I started on the home page:

PHP Fatal error:  Cannot create references to/from string offsets nor overloaded objects in /Applications/MAMP/htdocs/drupal/includes/common.inc on line 6548
PHP Stack trace:
PHP   1. {main}() /Applications/MAMP/htdocs/drupal/index.php:0
PHP   2. menu_execute_active_handler() /Applications/MAMP/htdocs/drupal/index.php:21
PHP   3. call_user_func_array() /Applications/MAMP/htdocs/drupal/includes/menu.inc:517
PHP   4. drupal_get_form() /Applications/MAMP/htdocs/drupal/includes/menu.inc:517
PHP   5. drupal_build_form() /Applications/MAMP/htdocs/drupal/includes/form.inc:131
PHP   6. drupal_process_form() /Applications/MAMP/htdocs/drupal/includes/form.inc:374
PHP   7. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:842
PHP   8. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP   9. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP  10. form_builder() /Applications/MAMP/htdocs/drupal/includes/form.inc:1857
PHP  11. _form_builder_handle_input_element() /Applications/MAMP/htdocs/drupal/includes/form.inc:1795
PHP  12. drupal_array_set_nested_value() /Applications/MAMP/htdocs/drupal/includes/form.inc:2003

I am attempting to continue the multi-step form from the home page to the '/apply' page by saving the $form_state['storage'] array in the session, then reading it out of the session in the custom_module_primary_form function.

//Save form 'storage' in $_SESSION
function custom_module_first_form_submit($form, &$form_state) {
  ...
  if(request_path() == '') {
    $form_state['redirect'] = array('apply');
    $_SESSION['storage'] = $form_state['storage'];
    $form_state['rebuild'] = FALSE;
  }
}

This is the modified custom_module_primary_form function from the tutorial.

//Read form 'storage' out of $_SESSION
function custom_module_primary_form($form, &$form_state) {
  // Check to see if anything has been stored.
  if ($form_state['rebuild']) {
    $form_state['input'] = array();
  }

  if (empty($form_state['storage'])) {
    if(isset($_SESSION['storage'])) {
      $form_state['submitted'] = TRUE;
      $form_state['rebuild'] = TRUE;
      $form_state['storage'] = $_SESSION['storage'];

      unset($_SESSION['storage']);
    } else {
      // No step has been set so start with the first.
      $form_state['storage'] = array(
        'step' => 'custom_module_first_form',
      );
    }
  }

  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state);
  return $form;
}

I would recommend reviewing the Drupal Contrib examples project:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

It has an example in the form's submodule that provides you some working stub / skeleton code that you can learn, modify or apply to your own project.


Cannot find out what is rendering a view block? I am working on an existing Drupal 7 website. I have a view that has a block display. The block is being displayed on some pages in the "second_sidebar" region. The mystery is that I cannot figure out how this block is being rendered/displayed in that region of those pages! In other words, the block is being added to the $page['sidebar_second'] variable, but cannot find how it is being included in that variable.

Please take into consideration the following facts:

The block is not being assigned to any region in
"admin/structure/block
In the page.tpl.php, there is no inclusion of that block in the page['sidebar_second'] variable
None of the theme templates are directly rendering that block

I have just found out that the Context module is installed which was rendering the block on those pages.

The "Themer Info" should have indicated that somehow.


Do path parameters need to be sanitized before using in the controller action method? I was surprised to not see anything in the documentation as far as whether or not wildcard routing parameters need to be sanitized before using them in the controller action method.

In Using parameters in routes, there doesn't seem to be any mention about whether or not the Symfony routing takes care of the sensitization or not unless I'm missing something.

This is my test.routing.yml file.

test.test_controller_doTest:
  path: '/test/hello/{name}'
  defaults:
    _controller: '\Drupal\test\Controller\TestController::doTest'
    _title: 'This is the page title - nothing more Yo'
    name: "Rumplestiltskin"
  requirements:
    _permission: 'access content'

It seems that others are having a question about this as well:

  Obviously anything in the path could be altered by a user so you’ll
  want to test for valid values and otherwise ensure that these values
  are safe to use. I can’t tell if the system does any sanitization of
  these values or if this is a straight pass-through of whatever is in
  the url, so I’d probably assume that I need to type hint and sanitize
  these values as necessary for my code to work.

Based on some additional research it looks like they are not sanitized by default. See https://stackoverflow.com/questions/24880067/are-symfony-2-0-route-wildcards-sanitized.
This seems like it's ripe for a code injection attack via something like the following.

$res = eval('return 1 + '. $_GET['crazy']+ ';'); with ?crazy=0;exec("rm+-rf+/")

Can anyone confirm that we do need to sanitize and if so a recommendation for sanitizing string input in a standard way?

How to sanitize something depends on what you want to use it for.

It's entirely different if you want to protect against SQL injection in a database query or XSS when printing something.

PHP tried to do magic things on input but those features were removed a long time ago, see http://php.net/manual/en/security.magicquotes.whynot.php for example.

Protecting against SQL injecting is easy with the provided tools, Drupal 8 also autoescapes all output unless its told that something is safe. And simply don't use eval(), ever.


Custom template fields Drupal 7 In Drupal 6, I was able to use a Row Style Fields template and create variables to arrange and print later i.e.:

foreach ($fields as $id => $field) {
  if ($field->label == "Phone") {
    $f_phone = $field->content;
  }
}
print "
${f_phone}
\n";

Then I was able to use the variable $f_phone in other places in the template.  This does not work in Drupal 7.  I am instead getting variable not found errors.

How would I do this in D7?

I figured I would reply to this question since I figured out an answer.  Don't know if this is the best way, but it works.

If you use the views-view-fields.tpl templates, you can skip the loop and directly list and style your fields ie:

print $fields['title']->content;
print $fields['field_location']->content;

**the code above is inside your php tags


Is there an easy way to check for http resources when I am switching to https? The company I work for is going to be switching to serving everything over https. This means that all referenced images/scripts/etc. need to also be server over https. Is there a way to see what links/references and such I will need to manually fix?

Saint Mary's College in Notre Dame, IN has developed a script to look through the node_revisions table and help you visualize the references. You will likely have to adapt what they have written to fit your situation, but you can check it out on github.


Views Filter 2 Content types but with condition on one of them I looked up this one before posting: Views filter criteria multiple content types (Drupal 7)

And even though the problem is the same, the solutions provided do not seem to work.

I have Content Types A and B. B has a boolean field.

I need to filter and display all As and Bs if boolean is true.

My filter setup looks like this:

Content : Published AND
Content Type : A

OR

Content : Published AND
Content Type : B AND
Boolean Field : True

The Query that gets produced is the following:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM `node`
INNER JOIN `field_data_field_boolean` ON node.nid = field_data_field_boolean.entity_id
  AND (field_data_field_boolean.entity_type = 'node'
  AND field_data_field_boolean.deleted = '0')
WHERE (( (node.status = '1')
  AND (node.type IN  ('poll')) )OR( (node.status = '1') AND (node.type IN  ('webform'))
  AND (field_data_field_boolean.field_boolean_value = '1') ))
ORDER BY node_created DESC

The problem is that Inner Join that gets produced instead of a Left Join for instance.

Which setup would allow me to perform the required filtering?

EDIT: Seems it's a know bug. Related links:
http://drupal.org/node/1766338
Changing an inner join to a left join in views 3.3?

Although this post is quite old, it appears it's still an issue going up to Views 7.x-3.7. Referring to the post already mentioned here and specifically comment 36 on that page, I found my working solution.

I had two content types that I wanted to show the title from: an Event and a Blog, however I only wanted the blog posts which had a Boolean field returning as true.  Below is a screenshot of what my grouping filters look like but the trick is, on the Boolean filter, make sure you select the 'Reduce duplicates' check-box. Once I did that, I got the results I was expecting.

Hope that helps.


Replace rewrite output URL aliases Is it possible to rewrite parts of taxonomy terms URL custom aliases before output, for example with something similar to the the following code?

  function replace_term_url ($term_alias) {
    // Url alias "article/first"
    $term_alias = str_replace("article", "article-sub", $term_alias);
  }

In Drupal 7 there isn't a specific hook to alter the URL associated with a taxonomy term, but you can use the generic hooks for altering URLs, which are hook_url_inbound_alter(), and hook_url_outbound_alter().

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^taxonomy/term/([0-9]*)|', $path, $matches)) {
    // Alter $path; $matches[1] contains the term ID.
  }
}

function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Revert the change done in mymodule_url_outbound_alter().
}

hook_url_outbound_alter() is invoked for URLs output from Drupal, hook_url_inbound_alter() is invoked for URLs Drupal is receiving.

In Drupal 6, it is possible to implement hook_term_path(), but that is invoked only for the module associated with the taxonomy term. The code invoking that hook is in taxonomy_term_path().

  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }

If you want to use a third-party module, then there is the Pathauto module, which allows to automatically set the alias for users, nodes, and taxonomy terms.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


How do I change position of a "fixed" element/header to go below Admin toolbar when in Admin view? New to JS / CSS

How do I change / control the position of a sticky navigation bar to go below Admin toolbar when in Admin mode?

Site uses:

Subtheme of Omega / Commerce Kickstart
Through subtheming, I have two sticky "zones": (1) user (contains login/checkout); (2) menu-super (main menu)
User zone is sticky and came as part of the Commerce Kickstart theme and works in both regular user and admin mode.
My new "Menu-Super" works in regular user mode, but disappears behind the admin toolbar when viewing as an admin. (less than ideal.)

In the js file, I found the following:

// Handle user toolbar when user is admin and have admin toolbar enabled.
  Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
        });
      }
    }
  }

I tried repurposing this code to handle my new zone, but no dice. When I clear cache, I can see the zone built and then pop up under the admin bar. What am I missing here?

Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          var zoneuserHeight = $('div#toolbar').height()+ $('div#zone-user').height();
          $('.zone-menu-super-wrapper').css('top', zoneuserHeight + 'px');
        });
      }
    }
  }

where the css file specifies

User Zone (Working)

.zone-user-wrapper {
  background-color: #666666;
  height: 32px;
  width: 100%; }

Super Menu Zone (Not working)

.zone-menu-super-wrapper {
  background-color: #9E4934; /*Monkey brown*/
  height: 36px;
  width: 100%;
  position: fixed;
  top: 32px;
  z-index: 99;}

In drupal you need to use jquery like this

(function ($) {
 $( document ).ready(function() {

      // custom code here

     });
  });
}(jQuery));

So try:

(function ($) {
  $( document ).ready(function() {
      Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
        attach: function(context, settings) {
          if ($('body').hasClass('toolbar')) {
            $(window, context).resize(function() {
              var toolbarHeight = $('div#toolbar').height();
              $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
            });
          }
        }
      }
    });
  });
}(jQuery));

If that doesn't work, all you have to do is check if the toolbar div class or id exists.

if ($('#toolbar').length > 0) {
    // dostuff
}

So if there is a wrapper that wraps everything on your site except the admin toolbar. that would be more ideal to use. So all you do is move everything down by 10 or so pixels

Using CSS with jQuery

(function ($) {
 $( document ).ready(function() {
          if ($('#toolbar').length > 0) {
           $('.zone-user-wrapper').css({"position": "relative", "top": "10px"})
           }
     });
  });
}(jQuery));


Comments -> link to node i have a content type which display some text image and comments count, in my View module i need to rewrite this comment count to link on this node. How to do it?
I though i should create field with nid but i dont know how to do it.

Add the "Node ID (nid)" field
Add the "Comment count" field -> Configure field -> Rewrite results -> Output this field as link -> in the "Link path" enter: node/[nid]

You can hide the nid field as you probably don't need it.

Make sure the comment count is coming after the nid. You can just reorder them.


Page Not Found for anonymous (clear cache fixes it) I'm getting reports from users that clicking a link gives them Page Not Found.

These are anonymous users.
Page caching is turned on (but not aggressive)
I log in, the page works.  I log out, the page does not work.
Three reports of unrelated pages in the past week (but all were different node types)
Clearing All Caches fixes it.
I could be wrong about this (because I didn't think to check until after I cleared caches), but I think it's returning error 406 in Recent Log Entries.

How can I begin to troubleshoot this?

Ask your sysadmin about the health and size of cache tables. Being logged in bypasses page cache. Clearing cache truncates them. Last time I've encountered similar effects, they were caused by a bad sector on server's HDD - when cache table grew enough to start using it, caches got all messed up. It was most visible with page cache.


Overwrite taxonomy/term page with custom view isn't working I'm trying to style my taxonomy/term page and as it turns out, a lot of people are trying to do this. Internet is filled with tutorials and how-to-guides, but for some reason, it seems I'm doomed and not able to do so.

I've installed the Taxonomy Display module and I think my settings are all good:

And my view is configured with the taxonomy arguments:

But still, the products/tents (aka taxonomy/3) doesn't take the View style I've configured... What am I overlooking here?

When I take a look at my live preview of my view, it seems everything is right. Only something looks overwritten on my website because there it doesn't take over the Views layout.

Keep in mind

The taxonomy path is normally taxonomy/term/% ( not taxonomy/% )
Views ships with a default taxonomy/term/% override ( just needs enabling )

Perhaps that will help.


Can I completely exclude a pane title? I'd like to apply several panes without title to a panel (in Drupal 7).

I can select Override title and leave the input field blank, but this still leaves the wrapping HTML.

Can I completely exclude a title?

I learnt adding <none> to the title field does this.


How to check if a library is present during installation? How can I check if the library, which is required by my module, is present while the module is getting installed?

I have used hook_requirements with the libraries_detect function with REQUIREMENT_ERROR severity. This restricts the module from getting installed irrespective of the library is present of not.

Here is my code:

function hook_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'install') {
    if (function_exists("libraries_detect") && !libraries_detect('external-lib-api')) {
      $requirements['library_api'] = array(
        'severity' => REQUIREMENT_ERROR,
        'description' => $t(
          'The required Libarary is not installed.'
        )
      );
    }
  }

  return $requirements;
}

Am I doing something wrong in this? Is there any other way of doing it?

this is one of the working example from my module. I hope this helps you

function sfs_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'install' && function_exists('libraries_get_path')) {
     $plupload_path = libraries_get_path('plupload');
     $chosen_path = libraries_get_path('chosen');
     if (!$plupload_path) {
       $requirements['plupload'] = array(
         'severity' => REQUIREMENT_ERROR,
         'description' => $t('Secure File Share module requires !plupload, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.',  array('!plupload' => l($t('Plupload Library'), 'https://github.com/moxiecode/plupload/archive/v1.5.8.zip'), '%path' => 'sites/all/libraries/plupload')),
       );
     }
     if (!$chosen_path) {
        $requirements['chosen_js'] = array(
          'severity' => REQUIREMENT_ERROR,
          'description' => $t('Secure File Share module requires !chosen, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.', array('!chosen' => l($t('Chosen Library'), 'https://github.com/harvesthq/chosen/releases/download/v1.3.0/chosen_v1.3.0.zip'), '%path' => 'sites/all/libraries/chosen')),
        );
      }
  }
  return $requirements;
}

Karthik


Views AJAX error when too many results returned per page? I have a View that returns a complete list of all my site's users and their data. That being said, I have 1000 users. If my view returns 500/page, I'm able to view it successfully. However, if I want all of my user data displayed on one page (ie. no pager), Views throws me an AJAX error that reads:

  An AJAX error occurred. HTTP result code 500. Status Text: Internal
  Server Error.

Why is this happening? How can I make it so that all data can be displayed on one View page without this error occurring?

Found the fix (finally - at least in my case). Generating the View was exceeding the memory limit. I simply increased the allowed memory limit in my settings.php file by adding the following line to it:

ini_set('memory_limit', '512M');


LEFT JOIN with db_select() I'm trying to do a left join but it isn't working.

I have 2 tables:

TABLE profile
- uid
- pid

TABLE field_data_field_naam
- entity_id
- field_naam_value

I want to select the field_naam_value where uid is equal to .. and pid equal to entity_id. My normal query looks like this:

SELECT fdfm.field_naam_value, pf.uid
FROM field_data_field_naam fdfm
LEFT JOIN profile pf
ON fdfm.entity_id=pf.pid
WHERE pf.uid = 4

When I execute this on my database it works. Then I have this:

$naam = db_select('field_data_field_naam', 'fdfm')
     ->fields('fdfm', array('field_naam_value'));
$naam->leftJoin('profile', 'pf', 'fdfm.entity_id = pf.pid');
$naam->condition('uid', 4)
     ->execute();

And when I do the following:

foreach ($naam as $record) {
    die;
}

nothing happens... (he doesn't kill the app). Also tried to add ->fetchAll() but no success.

Use the below code for fetching values. It will give you field_naam_value field data.

$naam = db_select('profile', 'pf');
$naam->join('field_data_field_naam', 'fd', 'pf.pid = fd.entity_id');
$all_names = $naam->fields('fd', ['field_naam_value'])
  ->condition('pf.uid', 4, '=')
  ->execute()
  ->fetchAll();
foreach ($all_names as $record) {
  die;
}


TB Mega Menus: Image block doesn't show anything I'm building my first page with Drupal, creating a subthem of Omega 4, and for the menus I chose to use TB Mega Menu. The problem is that I want one of the columns of the drop down to contain an image. For that, I create a block and add that image to it, having it this HTML code:

But when I add that block to a column, it shows nothing. If I check the option to show the block title, it shows the block title, but no image.

Any help on that? I have searched for any issues like mine, but no luck.

Thanks in advance.

I would suppose that you need to choose "FULL HTML" format for your block content.


Enable new content types to use as newsletter I am using the simplenews module in order to create newsletters and enable users to subscribe to those. By following the instructions in the readme file it says:

Enable new content types to use as newsletter:
Structure > edit content type > Publishing options

What I did, I created a new content type and in the Publishing options I enabled the "Use as a simplenews newsletter" option.

Is this correct? Or should I have gone into one of the existing content types and selected this checkbox instead?

Also,
ENABLE SIMPLENEWS BLOCK

With the Simplenews block users can subscribe to a newsletter.

Enable a Simplenews block per Newsletter category:
Structure > Newsletters > edit newsletter category

In my block structure I have the following available to me:
Newsletter: Multi Subscription
Newsletter: Newsletter

Enabling Newsletter: Newsletter displays nothing. SHould it?
Enablinb Newsletter: Multi Subscription displays an option of subscribing to available newsletters. But I only have one newsletter so it's a bit misleading.

What settings have I stuffed up in order for the Newsletter: newsletter block to not display anything, but to instead have a multi subscription block?

The main options are the defaults.  So when you edit a content type all the options you turn on/off are the defaults for newly created content.  Any content that has already been created will need to be edited and re-saved with that option selected.  If you have a lot, I suggest using VBO.


Translate product pages automatically I have a website with a product catalog of more than 500 products.
I'm using Drupal Commerce and have created a product display content type to group several SKUs under a single product page.

I'm using the i18n module because I need a multilingual website.

Once the data entry is done (for the English section), the catalog must be totally translated into all the other languages, and that means a huge amount of work. Can this step (translation of product display contents) be automated in any way?

Please note: I just need all the products to be visible in all the active languages, at present there are no "string" product fields to translate.

Edit

By "automated" I mean that I start from creating product display pages in one language, and then I need product display pages in each of the defined languages; I'm looking for an automated way to create product display nodes in other languages instead of having to manually translate each page.

I've accepted the answer below because it does provide a solution to the problem and it's not a workaround, anyway it's not the way I took.

How I made it work

I set product display pages as language neutral.
I translated all the product page fields' labels, and then all the select lists' values.
At that point, I was faced with an hybrid page, with translated labels and untranslated values. I wondered why, until I found this page, mentioned in this post. That is, I...
went to Administration > Structure > Content types.
Click on Product page > Manage display.
Set format to Default translated, Link (localized) or Plain text (localized) depending on the field type.

To translate products, you will have to look into Entity translation. Make sure to check the Title module as well which allows to use a field for the product title so that can be translated as well.

For the automation/mass management part, have a look at the the Translation Management Tool* project. The new alpha2 release now integrates into the default Translate tab added by Entity translation and there is also a generic overview for all translatable entity types that allows to mass-translate (by sending a job to translation agencies, machine translation services, export as XLIFF and translate in a desktop tool, ..) entities, which includes products.

Note that the project is in alpha which in this case means that it hasn't been tested on many real sites yet, especially not the new entity translation integration. It has an extensive automated test suite though and is well documented (there is even a introduction video now!).

You can also translate product displays (nodes) using the same tool chain.

*Disclaimer: I am the maintainer of that project.


menu block with nice menu I am using the Menu Block module and the Nice Menus module. In my theme's left sidebar I have a block with that menu block (2nd level). How to use a Nice Menu in that region? If I put that Nice Menu, I get 1st level menu, but I need 2nd level menu from Menu Block module who create me 2nd level +

In the block configuration, you should be able to choose which menu it uses.


Create one-off page with specific fields and template I'm new to Drupal and trying to add a single new page to an existing Drupal website. It has its own design (with its own css) and its own content requirements separate from the rest of the site.

I'd like to be able to define a set of custom fields for the page, and then use a specific twig template to render those fields.

Is this possible? I'm struggling to find a way to do this.

I get most of the way there with a custom content type. I can create all the fields I need for the page. But, I don't want it to function as a repeatable content type, but rather as a one-off page that has a specific, single path.

When I try using Page Manager to create a page, I get presented with what looks like a WYSIWYG kind of editor for laying out blocks/panels on the page. I'm hoping to rather simply be able to define a set of fields and use the template to arrange everything on the page.

Use the Empty Page module and create an empty page.

Just like node content types, you can create a custom block type in /admin/structure/block/block-content/types

Add fields to your block type, and then in /admin/structure/block/block-content create a block of your block type.

Place block in content region and for Visibility > Pages put the URL for your empty page, so the block is only visible at this page.


How to override Page Title of View using Contextual Filter I have a view that uses a contextual filter for part of the URL. For example: www.example.com/categories/%/all

I have successfully replaced the % with the name of the taxonomy term from a specific category (for example, www.example.com/categories/shirts/all), but I cannot get the Title Override options to work.

Here's how I have things set up...

Contextual Filter - Indexed Content: Clothing Categories
When the filter value is NOT in the URL -  Display empty text
Override title - %1
Specify validation criteria: Validator: Taxonomy Term
Filter value type - Term Name Converted to Term ID
Transform dashes in URL to spaces in term name filter values  (checked)

When I preview the View result by typing the contextual filter "shirts", it does display the shirts and it does display the title "Shirts". However, on the live page, the View's title is displayed instead ("Category View"). I have tried deleting the View's title, but that just causes the front-end page to display no title.

Any idea on how I can get this to work, or any other methods to make it work?

Thanks!

In Drupal 8, if you are using a contextual filter to pass a taxonomy term to a View and want to change the page title to match with the term title, you can:

/**
 * Implements hook_preprocess_views_view().
 */
function HOOK_preprocess_views_view(&$variables) {

  $id = $variables['id'];

  if( $id == 'YOUR_VIEW_NAME' && $variables['view']->args[0]) {

    // Get tid from contextual argument of the view
    $tid = $variables['view']->args[0];

    // Load the Term Entity
    $term = Term::load($tid);

    // Term Title
    $new_title = $term->getName();

    // Set the new Page Title
    $request = \Drupal::request();
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      $route->setDefault('_title', $new_title);
    }
  }
}


How to get comment cid in hook_comment_insert? I've read the answers to How to get the node id the comment is attached to in hook_comment_insert? and found how to extract the nid of the node the comment is associated with.
However, I also need to get the cid of the comment itself from inside hook_comment_insert(). How do I do that?

All entities have an id() method:
$cid = $entity->id();