Contextual links for custom blocks: Add "Edit block content" has somebody an idea, how to customize the contextual links in D8?

I have created a custom block type and it would be wonderful to have a link in the contextual links menu: "Edit block content".

The missing "edit" link was a bug in early Drupal 8 betas, and has been fixed as of beta5:
https://www.drupal.org/node/2284917


drupal variables custom module and views I'm trying to figure out how Drupal works. I created a simple module named "myModule".

In its myModule.module file I have:

<?php

function myModule_node_view($node, $view_mode, $langcode){
drupal_add_js(array('myModule' => array('nid' => $node->nid)), 'setting');
           }
?>

on myModule.js file I have:

    (function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      jQuery("#test").bind('click', function(e) {
        alert(Drupal.settings.myModule.nid);
      });
    }
  };
}(jQuery));

On my view which has nodes (articles), I created a custom field which has

<a id="test" href="#"Testing!!!

So basically what I want is when I click on the Testing!!! link to show an alert which shows the node id (nid) that belongs to the article in the view's row.

Right now it's showing the nid of the current node I am in, not the view's row.

in your drupal_add_js, you are setting 1 variable many times. (Drupal.settings.myModule.nid). So the last one will be what this is set to.
You could add these nids to an array in Drupal.settings.myModule but then you would still need a reference from anchor in the views row that maps to the appropriate array index in your Drupal.settings.myModule array.

I think the best / easiest way to get what you want would be to set a data attribute in your views anchor using a token of the current rows nid.
Also, set it up as a class instead of an id, so you don't have the same id multiple times.
eg.

<a class="nid-button" data-nid="[node:nid]" href="#"Testing!!!

Then in your javascript you would just need to use this data attribute.

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      jQuery(".nid-button", context).bind('click', function(e) {
        alert($(this).data('nid'));
      });
    }
  };
}(jQuery));

Doing it this way you don't even need to set any settings variables, instead it is saved on the anchor itself.


Hide a block depending on the value of a field? I have put a block in the taxonomy pages.
I have added a new field to the vocabulary with two states: shown, hidden.
I want that when in taxonomy term I select hidden, the block to be hidden.

So I can display or not a block depending on the categories.

I've tried with this code in the block visibility options,  but it does not works:

global $field_show_block;
return ($field_show_block == "show");

Any ideas?
Can it be done with Views?

Thank You

As Letharion points out you can use Panels to do this, but panels does indeed have a bit of a steep learning curve. It might be quicker to learn something like the Context Module with Context Entity Field.

To do this with context, create a new context with whatever name you like. Then in the Conditions area add the "Entity field" as a condition and select entity type as taxonomy term. Then select the field you created in your vocabulary e.g. "field_show_block" and uncheck the "empty field" checkbox and put in "show" into the field value. Then in Reactions select which blocks you want to show, and assign them to the relevant regions.

If you don't want to do things using a Drupal contributed module though, the following visibility code (with the core PHP filter module on) may work with a bit of tweaking to match your exact field name:

<?php
// assumes the user is visiting taxonomy/term/<tid>
if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
  $term = taxonomy_term_load(arg(2));
  if (isset($term->field_show_block[LANGUAGE_NONE][0]['value'])) {
    return $term->field_show_block[LANGUAGE_NONE][0]['value'] == "show";
  }
}
return FALSE;
?>

The reason why using the PHP filter for block visibility is bad practice is because, when the PHP code is written incorrectly, it's a little awkward to fix it (e.g. clearing database columns). It's also a potential security risk, allowing database stored PHP code to be executed unchecked.


Set views contextual filter as request_path() There are fields in content type called URL and Image.

Suppose, A node has "service" value of "URL" field and I'm trying to show views block where current path (service) and "URL" field path (service) are same. The "URL" value can also be "content/services".

I tried with

adding "Alias" field as contextual filter in views.
adding URL field

Updated:

I also tried with URL field with PHP Code in contextual filter:

if(drupal_is_front_page()) {
    return '<front>';
}else{
    return request_path();
}

It works for only one path argument, like if current requested path is  services/one and views contextual filter only takes first path component as you can see in attached image

However, I need to set contextual filter with whole path no matter how many components are requested.

Theme

I have a content type with image and URL fields, I need to show image on the path where URL field is matched with requested path using views.

How would I do that?

If you want to filter nodes in a Views list that have the same expression in their "Alias" field as the path where the Views Block is shown then you can do it by adding the "Alias" field as a contextual filter and configured like this:

When the filter value is NOT available
Provide default value
Raw value from URL
Path component 1

Adjust the path component to the place where your service appears in the path.

You can also adjust the validation and other options that are relevant to you, but that first bit is what is the most important to match the path to your field.

The field value content/services might  match only on pages where the path starts with content/services. I haven't tested this, I expect the field expression will be treated as a one string, but the path will only take the first part before the / so in the end it won't match.

If you find that it doesn't work, then you might make it work with the help of Views Argument Substitutions and Views Contextual Filters OR.

You could also do it with the Context module and Context entity field but it's a fairly complex to configure.


How to display a node field value in a template file? I added a custom field in the ‘article‘ content type.
I am using bootstrap as a theme.
I want to print that field value as a css class in the h1 element of every node of type : article

So I duplicated the page.tpl.php in my subtheme template folder and changed the h1 code from :

<?php print $title; ?>

to

<h1 class="page-header <?php print $node->field_custom_field['und'][0]['value']; ?>"><?php print $title; ?>

The problem is that sometimes sometimes I get this error message

    Notice: Undefined property: stdClass::$field_custom_field in include()
(line 157 of /home/frost/sites/all/themes/subtheme/templates/page.tpl.php).

I have basic php knowledge, so my guess is I need to add a condition saying that the custom field is only printed if the template file is called when an article content type node is being viewed.

How can I add this condition in the template file ?

Thank you

Duplicate node.tpl.php and rename it node--article.tpl.php and then it's just:

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

If you really want to stay on the page level you better use page--node--article.php and then you need to get hold of the $node object first somehow. Maybe take a look at Clive's answer here: https://drupal.stackexchange.com/a/32310/15055


Migration of Drupal 6 to Drupal 7 I have a Drupal 6 site with different content types, and node references. I also have a custom theme. I want to migrate to Drupal 7.
I use the Node export, and Node import modules, but they are not working perfectly, as I am not able to import node references.

Is there any easy way to do this?

Read the UPGRADE.txt
Have a look at the CCK Module for D7. It comes with a migration submodule.
The them has to be adapted to D7 manually. Have a look at this for reference.


fonts not applied to high ASCII characters After installing the @fontyourface module and adding some Korean fonts locally, the fonts are not being applied to high ASCII characters (which makes no sense as the font is specifically for those characters). The fonts ARE applying to the regular ASCII characters, though.

As I suspected, the issue was NOT off-topic. It turns out that the downloaded fonts were not set for Unicode. Most likely, they were using the euc-kr character set. Since the site uses utf-8, the ranges for the characters in utf-8 are different from euc-kr, so the default font was being used to display.

I downloaded a different version that specifically listed the font as Unicode and now the characters display correctly for that font.


Translatable rich text configuration I have a problem with translating my configuration form in Drupal 8, particularly with rich text fields.

This is my configuration file.

langcode: en
more_info_text: 'More info'
first_link_list:
second_link_list:
third_link_list:

Here is my schema file:

customization.config:
  type: config_object
  label: 'Website config'
  mapping:
    more_info_text:
      type: text
      label: 'More info text'
      translatable: true
    first_link_list:
      type: text_format
      label: 'First link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'
    second_link_list:
      type: text_format
      label: 'Second link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'
    third_link_list:
      type: text_format
      label: 'Third link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'

The form itself works fine, but I cannot get the text format working for translations of the fields; it's always missing.
Any ideas?

I was playing with configs and finally found a solution. The configs should be:

langcode: en
more_info_text: 'More info'
first_link_list:
  format: 'full_html'
  value: ''
second_link_list:
  format: 'full_html'
  value: ''
third_link_list:
  format: 'full_html'
  value: ''

And the scheme file should not contain the following line

class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'

Another thing I noticed is that you should translate the whole custom form, otherwise it will give an error at config inspector, so in my case I had to split my form into general and language specific.

Hope this helps somebody


Horizontal scrolling in Safari on one content type only when logged out? So I have spent numerous hours trying to solve the following issue and without success I bring it to Drupal Answers. For some reason, on my site for content type 'level_1' when browsing in Safari it creates long horizontal scrolling. The strange thing is that when you are logged in, the issue is not there. Furthermore the issue doesn't exist when I coded the HTML/CSS pre-Drupal installation.

It's not an issue of caching as I've made changes and checked they followed through when not logged in.

Anyone have any ideas?

If someone has the opportunity to try and debug this issue it would be greatly appreciated.

The error occurs here in the Safari browser:
http://beta.innovista.org/about-us

Thanks for your time.

Looking though the markup, the problem is on the H2 for your search form.

Search form

Can't say exactly what's up, but if you take off the width from .level1 h2, .related h2, .tabTog h2 then it seems to be fine.


Adjusting module weight: what are the risks and things to look out for? Today I changed the weight of a custom module of mine in order to change the execution method of hooks (hook_form_alter). I've changed the weight to 1 value heavier than the other module's weight. This seemed the safest thing to do instead of giving it a "random" weight of 100. The original module is a core module (translation) so I hope I didn't break anything.

When adjusting the weight of a module in order to change the execution order of hooks, what are the things to look out for and what are the risks involved?

What I can think of: unwanted behaviour as result of high coupling.

Well there isn't a general answer to this, it really depends on the modules. Some of the things I would take into consideration (In Drupal 6) :

hook_boot is called as modules are loaded ; so only modules that are lighter than you have been included. If you rely on code from another module that is heavier than you, make sure you include them manually.
If a module has by default a weight other than 0, then it means that this module specifically set this weight. Check that module's .install file, as this is most likely where the weight is set - and with a bit of luck there will be a comment explaining why ! (this may be true even if the weight is zero)
Modules that set either a very low or very high weight usually have a good reason for it (must run before/after everything else). Typically development modules do this, though others might as well. Keep these modules first/last unless you have a good reason for it.
Look at the module's dependencies (the ones the module depends on, and the ones that depend on this module). Ideally keep these modules in the same order. If you must change the order, the only way to understand the consequnces is to look at the code.
Use common sense. Information that is added by a module (say to a node on node load) will not be available to modules lighter than this one.


How to create and add a page to a book programmatically? I have studied create nodes programmatically and create a book page but still i did not find how to create and add a page to the existing book. How to set parent child relationship if applicable.
I am using Drupal 8. Can anybody help please?

You can use the saveBookLink(array $link, $new) method of the BookManager service (book.manager).  See Drupal\book\BookManagerInterface.php

After you create the node programmatically, create a new array $link with the following key/value components:

Each book entry consists of the following keys:
 - bid: The node ID of the main book.
 - nid: The node ID of the book entry itself.
 - pid: The parent node ID of the book.
 - has_children: A boolean to indicate whether the book has children.
 - weight: The weight of the book entry to order siblings.
 - depth: The depth in the menu hierarchy the entry is placed into.

(See Drupal/book/BookOutlineStorageInterface::loadMultiple()).

So, your code will look something like this:

protected $bookManager;

public function __construct(BookManager $bookManager) {
  $this->bookManager = $bookManager;
}

public static function create(ContainerInterface $container) {
  return new static(
    $container->get('book.manager')
  );
}

/** Method that creates your node here... **/
  $link = [
    'nid' => $nid,
    'bid' => $bid,
    'pid' => $pid,
    'weight' => $weight,
  ];

  $this->bookManager->saveBookLink($link, TRUE);


Dynamic query with left join I need to collect comments that belong to certain user and submitted on pages of certain content type nodes. Currently I'm making two queries:
      $nodes = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->execute()->fetchAll();
      unset($node_list);
      foreach ($nodes as $node) {
        $node_list[] = $node->nid;
      }

      $comments = db_select('comment', 'c')
      ->fields('c', array('cid', 'nid', 'created'))
      ->condition('c.nid', [$node_list], 'IN')
      ->execute()->fetchAll();
      foreach ($comments as $comment) {
        some actions
      }

and it's working fine. However, I believe I can make just one query for comment table by using some kind of database join to node table and check if a node belongs to $content_type. How can I do that?

Here is the documentation on joins which should put you on the right path to answering the question.
Untested, but something like this should work:
$query = db_select('node', 'n');
$query->join('comment', 'c', 'n.nid = c.nid');
$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'page')
  ->condition('n.status', '1')
  ->orderBy('n.created', 'DESC')
  ->addTag('node_access');


hook or similiar to automatically send any webform submissions to an email address, without manually adding a handler to each existing webform? We have a Drupal 8 site running Webform 8.x-5.2. We have a special role, "Webform Editor", who is not a developer, but they are trained to create the webforms that we need for our organization.

We've been dealing with some organizational issues about who is getting what webform submission emailed to them. To help us troubleshoot the issue, we the developers want to implement a feature where each webform submission gets automatically copied (cc'ed or sent separately) to an email address that we devs have access to.

I looked at the webform module's hooks, and I didn't see any that jumped out at me as a post-submission hook. Webform version 7.x had one, but version 8.x doesn't appear to.

I made a custom submission handler, but realized I would have to add it manually to all existing webforms (we have more than I want to click through).

I began to write a form_alter hook to add custom submit handler, but when I debugged the $form and $form_state, I didn't see any information (i.e. sid) about the submission record. I suppose that the submit hooks fire before the submission record is created.

In the webform cookbook, there's a recipe for "How can you automatically create a default email handler for a webform when it is created", but again, I want to automatically add this to existing webforms.

If I could do this with something like a hook, once and for all, that is what I'm looking for. If the answer is "No, you can't do what you want automatically; you'll have to make a handler and manually add it to all existing webforms", am I interested in hearing that answer, too. I don't want to chase down any more rabbit holes of approaches that won't work.

I am going to go ahead and say No, there isn't any hook or otherwise automated way to do this.

I looked at hook_entity_insert(), as leymaxx suggested. From looking at the Webform Submission entity at /src/Entity/WebformSubmission.php, it appeared to me that the Webform Submission entity is not what triggers the emails and handlers of the webform, but rather the Webform entity does.

Looking further at the Webform entity at /src/Entity/WebformSubmission.php, I found functions for invoking handlers, but these only appeared to loop through existing handlers already attached to the Webform entity. So, there is no way to call an arbitrary handler on a webform.

What I'm going to do is create a custom handler, attach it manually to existing webforms, and use this recipe that I referenced in my question to have it automatically attached to new webforms as they are created.

Edit We are using config_export on our site, which has yamls for all of our current webforms. Because of this, I was able to copy and paste the additional email handler into the yaml, and do a config import, to update existing webforms. This saved some time over manually editing them in the web interface.


How do I disable the Update manager module? Is it possible to disable The Update manager module without uninstalling it?

You cannot disable a module as you do with Drupal 7 or previous versions, and this is valid also for the Update manager module. You could eventually avoid the module checks for new module versions, but the module itself doesn't have a setting for that in admin/reports/updates/settings.

What you could do is, using a custom module, avoiding Drupal invokes update_cron() which is the hook that periodically checks for updates.

function mymodule_implements_alter(&$implementations, $hook) {
  if ($hook == 'cron') {
    unset($implementations['update']);
  }
}

You could still manually check for updates from admin/reports/updates, but Drupal would not check for updates during cron tasks.

If then you also need to disable the route set by the Update manager module, you could also do it as shown in How do I alter the route defined by another module?
This is, I think, the closer you could get to disable the Update manager module.


Non-standard port with aliases I'm running Drush 9.5.2.

I set up a site alias. Drush recognizes it, but it will not connect via SSH. I get the following error:

ssh: connect to host mysite.com port 22: Operation timed out

The server doesn't use port 22. It uses port 2234.

My SSH config is set to use port 2234. I can SSH in if Drush isn't involved. There's nothing in the docs that addresses this. What am I missing?

Create an alias that looks something like one of the examples below:

Drush 9 Example: ~/.drush/sites/my-site.yml

live:
  uri: example.com
  host: isp.net
  user: www-admin
  paths:
    drush-script: /path/to/drush
  ssh:
    options: '-p 2222 -o "AddressFamily inet"'
    tty: false

Drush 8 Example ~/.drush/aliases.drushrc.php

$aliases["my-site.live"] = array (
  'uri' => 'example.com',
  'remote-host' => 'isp.net',
  'remote-user' => 'www-admin',
  'ssh-options' => '-p 2234 -o "AddressFamily inet"',
  'path-aliases' =>
    array (
      '%drush-script' => '/path/to/drush',
    ),
);

Adjust 'ssh-options' as necessary for your configuration.

You may omit 'path-aliases' entirely if Drush is in your $PATH on the remote machine. Defining the Drush path is safer, though; the rules Bash follows for sourcing resource files for login shells vs. non-login shells et. al. is somewhat confusing.


Manage 2 separate page cache for the same URI We have a multilingual website build with Drupal 7.

We have a IP detection for detect Chinese users. Chinese laws do not allow the use of certain JS librairies. In our case, for one page, we use Google Map for all the users in the world, and we replace the library with Baidu Map for Chinese IP.

The problem is that if the first user is Chinese, then Drupal will cache the page with BaiduMap. Anonymous users from all the world will then have the page with Baidu Map even if there aren't Chinese (since it is the same URI).

We can detect if the IP is Chinese or not. So, how can we handle 2 separate page cache according to the user IP and then call the right cached page ?

This assumes that the theme is changing.

Settings.php file:

// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so hook_init code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

hook_init():

  // If no cookie is set set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    $temp = empty($custom_theme) ? variable_get('theme_default') : $custom_theme;
    setcookie('custom_theme', $temp, time() + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }


Referencing/relating content between content types I'm completely noob on Drupal, actualy I'm trying to find a way to build a website idea using it.

I want to let users/visitors to create travel tips, so at this site I'll have contents like: Countries, States, Cities, Places and tips.

A tip must be related with a Place, that is related to a City and a State Country. Also a tip must contain any number of images related to it.

The thing is, I' just can't find a way to do it with a fresh install on Drupal, neither find somewhere I can see an code example of it, if I need to really code it.

I thought in creating a Entity type, but didn't found how to do it without coding, and I also need a way to let users upload any number of images they want, and them show everything on a page (I believe this is the easiest part, after I get the other ones).

Anyone can help me with a quick way to figure this out? Maybe a few blog post links, a ebook, videocast, anything.

Thanks!

Take a look at the Entity Reference Module:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a
  configurable view mode

  Integration with Views (for both forward and
  backward references)
  Integration with Entity Metadata (and as a
  consequence with Search API and the like)
  Integration with Devel generate
  Integration with Feeds and Migrate (>= 2.3) for painless data import

That should get you started.


Post to anonymous user's Facebook Wall with rules I wonder what is the best way to implement post to User's wall for anonymous users. All solutions I came across seem to require creation of a Drupal User Account (using FB Connect) first.

I need a rules action that automatically asks for permission to post and then posts immediately, without creating a Drupal User Account, fetching any additional information and especially without requiring the user to connect manually in advance.

Thank you for suggestions!

You didn't say what have you tried, so how can we know if we're suggesting some new solution? Anyway you could try Facebook Autopost https://www.drupal.org/project/fb_autopost if it isn't on you personal "All solutions I came across" list


Alternate solution to avoid handling a huge number of menu items I am on Drupal 7 and I am facing a dilemma with a project I am building. It will be a content-rich website, which means lots, lots, tons of articles. When user enters an article page, I want him to see the website area (menu item) it is associated with selected on top of the page. Drupal will handle it if the content is associated with the correct menu during node creation.

My concern is that I will have a huge menu page. When I have 1,000 articles or so, the menu admin page will be a terribly long list of articles associated with the top menus. I would rather have only the top two levels in my menu structure but I still need the subpages (articles) to be shown as associated with a menu item.

The question is: is it possible to associate a content type with a menu item so that it isn't actually in the menu, but it can interfere with the menu rendering so as to add ACTIVE or ACTIVE-TRAIL classes to the desired menu items? Do I have to play with template.php in order to achieve that?

Also, if you think that associating these many articles with a regular menu item is the correct approach and that there is no problem to end up with a monstrous menu list, please, tell me.

I am sorry if the question isn't enough clear, I will try to clarify further if necessary.

Context will handle it, but needs some template.php additions.

and it looks like Menu Position will too.


new created zen subtheme - content offpositioned I just created a new zen subtheme using drush. Everything went smooth but I think there is some kind of problem with css - #content container is completely off positioned from page. I did not make any changes to files. Is it some kind of bug or this needs some tweaking?
I have sass and compass installed. I use zen 7.x-5.5 version.
Please see screenshot.
Thank you.

Ahhh.  I had this same problem yesterday and it turned out that I was using the wrong version of compass.  I installed version 0.12.6 and the content returned to where it was supposed to be.
You can either unistall compass and then reinstall
https://stackoverflow.com/questions/3088454/how-do-i-downgrade-to-an-old-version-of-compass-using-gem-instal

or just add the old version and explicitly invoke the older version like so:
compass 0.12.6 watch


Drupal local configuration clone. Only home page is accessible I have cloned an existing drupal installation, the problem is, I can see only the home page, other url's are not working.My apache rewrite module is configured. I can not log in as any kind of user.

I did face with a similar problem when moving my site from local machine to dev server. but here is what i did

Install Backup and Migrate to download the existing database and Backup and Migrate Files to your local drupal installation.
Go to http://local-site/admin/config/system/backup_migrate and then backup the default database and local files to download

Install fresh copy of drupal with new database at the server(or to the location where you are cloning.
Copy from http://local-site/sites/all/modules and http://local-site/sites/all/themes to their respective directories at the server(or your cloning destination)
Enable both the modules in step 1, from http://local-site/admin/modules
Go to http://cloned-site/admin/config/system/backup_migrate/restore and restore the database and local files by browsing for the exported data at step 2

and don't forget to enable the theme which you used on the local-site before using backup and migrate.


How to get node Bundle in hook_form_alter on field config form? Can you wonderful people help me out please? I am altering the field config form (content types > plan > manage fields > edit field) and cannot seem to get the proper bundle out. Every time I call the bundle() function it returns the string "field_config". However the bundle is supposed to be "plan". Perhaps it's different because I am on the field config form, and not a node form?

Below is my code, the things I've tried and the field object showing the proper bundle. Does anyone know of another solution for me to get "plan" out?

<?php

use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\ContentEntityForm;

/**
 * Implements hook_form_alter().
 */
function rent_plan_custom_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
// print $form_id;

  switch ($form_id) {

    case 'field_config_edit_form':

        print $form['#title'];

        $field = $form_state->getFormObject()->getEntity();
        $field_name = $field->getName();  //returns correct field_plan_purpose

        //first try
        print $field->bundle(); //<---THIS RETURNS "field_config"

        //second try
        $bundle = FALSE;
        if ($form_object = $form_state->getFormObject()) {
            if ($form_object instanceof Drupal\Core\Entity\ContentEntityForm) {
                $bundle = $form_object->getEntity()->bundle();
            } elseif ($form_object instanceof Drupal\field_ui\Form\FieldConfigEditForm) {
                $bundle = $form_object->getEntity()->bundle();
            }
            print $bundle; //<---THIS RETURNS "field_config"
        }

        //Field Object Results Below
        print '<pre>';
        print_r($field);
        print '</pre>';

    break;
  }
}

Results from print_r($field)

Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =>
    [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] => node.field_plan_purpose
            [field_name:protected] => field_plan_purpose
            [entity_type:protected] => node
            [type:protected] => text_long
            [module:protected] => text
            [settings:protected] => Array

            ... lots of more stuff
        )

    [id:protected] => node.plan.field_plan_purpose
    [field_name:protected] => field_plan_purpose
    [field_type:protected] => text_long
    [entity_type:protected] => node
    [bundle:protected] => plan
    [label:protected] => Purpose
    [description:protected] =>
    [settings:protected] => Array
        (
        )

    ...lots more stuff
)

You're looking for FieldDefinitionInterface::getTargetBundle

  Gets the bundle the field is attached to.

  This method should not be confused with EntityInterface::bundle() (configurable fields are config entities, and thus implement both interfaces):

  FieldDefinitionInterface::getTargetBundle() answers "as a field, which bundle are you attached to?".
  EntityInterface::bundle() answers "as a (config) entity, what is your own bundle?" (not relevant in our case, the config entity types used to store the definitions of configurable fields do not have bundles).

e.g.

$target_bundle = $field->getTargetBundle();


How to create a view grid that changes content type per row Goal: Create a Grid that shows mixed content types and have control how those types are added to grid (ie. by row)

I have 3 content types and would like control over how they are added to a view.

Case 1: inject a row of Content Type B or C into a view of Type A based on row number.

Case 2: intersperse view with (possibly random) Content type C (think adding images to liven it up.)

Some approaches I've explored:

Display Suite View Display
Views Context Display
Panels with Context
Views embeded in views
NodeQueue

For case 1 I could just create seperate blocks but then I need to keep the view order consistent (perahps using nodequeue?) across blocks.  Do I need to pass the current node queue position as an argument to each block?

For case 2 how do I insert Content Type C images every few rows?  (I could even use css but need the grid to wrap around it.)

Important note: I'm a system builder, not a developer so prefer something that can be maintained without managing custom code but a basic views template would be fine.

Case 1

Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type B
Content Type B
Content Type B
Content Type B
Content Type B
Content Type B
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type C
Content Type C
Content Type C
Content Type C
Content Type A

Case 2

Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A
Content Type C
Content Type A
Content Type B
Content Type B
Content Type B
Content Type C
Content Type B
Content Type B
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type A
Content Type C
Content Type A
Content Type A

sounds doable with Views Field View, I have done something a bit similar using Views Field View with Contextual filters. if it did't work the way you want, so you need to code it checkout this answer


Add All link on view pager Is there a way to add a  Show All Link on my view pager.

I have a Block View.

I would like to be able to add an All Link button when the number of Items reach 5. I do not need the pager "Next, last 1,2,3" only the All Link button.

Thanks a lot

Yes see the Pager Options for your Block or Views Page:

EDIT:

Allow me to clarify. This gets the - All - text option into the configuration of the View. If you want custom business logic that says if there is 5 or more results I want to show/hide the Next and Previous and include the All options I recommend you look at hook_views_pre_view() or other Views hooks to implement hiding/removing options as needed. For ease I recommend hiding/showing the options using CSS or Javascript.

Again, this option builds the option into the page -- but doesn't really enforce your business logic.

EDIT 2:

The module Pagerer might get you a little further, but probably not all of your custom logic is possible out of the box with that module. It has an API to fine-grain it's custom pager views.


Comments not displaying This is very strange.

Comments are only displaying for a content type called "Issue" for roles that have the Comment permission "Administer comments and comment settings". I set the "View comments" permission for all roles. All the other content types display the comments properly to all roles. Somehow this content type is corrupted. Has anyone seen behavior like this? Any suggestions on how to fix it?

First verify that the Issue type isn't set to hide comments. If comments exist but are hidden, only admins will see them. A path something like this: /admin/structure/types/manage/issue, and go to the 'Comment settings' tab at the bottom.

Also, you might go to /admin/reports/status/rebuild and rebuild the permissions cache.


Drupal Commerce, Search API DB and Views | How to display the product variation accordingly to the attribute being applied as filter? SCENARIO:

A Size attribute field has been added to a Product Type at /admin/commerce/products/types/PRODUCT-TYPE/fields and "Enable this field to function as an attribute field on Add to Cart forms." option has been checked.
Two products have been created at admin/commerce/products/add/PRODUCT-TYPE. Size attribute Large at a price of $20 and Small at a price of $10 respectively.
One Content Type display node has been created at node/add/CONTENT-TYPE. The two sized product variants were attached to the Product Reference field.
A Search API Index for the product nodes has been created at admin/config/search/search_api/index/PRODUCT-INDEX.
A Search API - Product Index View has been created at admin/structure/views/add.
The Size Attribute has been added as an Exposed Filter Criteria to the view. One could also use the Size Facet.

ISSUE:

The filtering works just fine. The issue lies on the product field values displayed, like price for instance, that do not align with the filtering criteria.

Regardless of which size has been applied as filter, the price displayed on the view represents the first product attached to Product Field reference on the product display node.

In our case scenario, the Large size product is first on the list of products attached to the Product Field Reference. If size Small is applied as filter, it displays the price of $20 on the view display. This is troubling because $10 should be displayed instead.

Is there a way to fix it? That is, the price + other product fields will display the variant values accordingly to size attribute being applied as filter?

UPDATE:

This question here addresses the same issue wrapped into a different context.

Feature request here

This is not the ideal solution but will do for now. There are 2 steps to it:

At Views UI:

Add all the fields you need into your view and Exclude them from display.
At last add a Global Custom Text field for building your row display. This is my example:

[field_image]

[title]

[field_old_price][commerce_price]

[add_to_cart_form]

In your template.php file:

.

/**
 * Implements THEME_views_view_field__VIEWID__DISPLAY__FIELD().
 */
function mytheme_views_view_field__myview__page__nothing($vars) {
  $nid = $vars['row']->entity;
  $size_attibute_tid = myvalue;
  $row_product_id = $vars['row']->_entity_properties['field_product_reference:entity object']->product_id;

  $query = db_select('commerce_product', 'p');
  $query->join('field_data_field_size_attribute', 't', 't.entity_id = p.product_id');
  $query->join('field_data_field_product_reference', 'pr', 'pr.field_product_reference_product_id = p.product_id');

  $query
    ->fields('p', array('product_id'))
    ->condition('field_size_attribute', $size_attibute_tid)
    ->condition('pr.entity_type', 'node')
    ->condition('pr.entity_id', $nid);
  $query = $query->execute()->fetchAssoc();

  $query_product_id = $query['product_id'];
  if (isset($query_product_id) &&
      $query_product_id != $row_product_id) {

    $node_title = $vars['row']->_entity_properties['entity object']->title;
    $node_url = $vars['row']->_entity_properties['url'];
    $product = commerce_product_load($query_product_id);

    $line_item = commerce_product_line_item_new($product, 1, 0, array(), $product->type);
    $line_item->data = array(
      'context' => array(
        'product_ids' => array($query_product_id),
      ),
    );
    $add_to_cart_form = drupal_get_form("commerce_cart_add_to_cart_form_$query_product_id", $line_item);
    $add_to_cart_form = drupal_render($add_to_cart_form);

    $price = commerce_currency_format($product->commerce_price['und'][0]['amount'], $product->commerce_price['und'][0]['currency_code']);
    $old_price = commerce_currency_format($product->field_old_price['und'][0]['amount'], $product->field_old_price['und'][0]['currency_code']);

    $image_variables = $product->field_image['und'][0]['image_dimensions'] += array(
      'style_name' => 'my-image-style',
      'path' => $product->field_image['und'][0]['uri'],
    );
    $image = theme_image_style($image_variables);
    // You should install https://www.drupal.org/project/commerce_product_urls module
    $image = "$image";

    $vars['output'] = "
$image

$node_title

        $old_price$price

$add_to_cart_form
";
  }

  return $vars['output'];
}


Adding Data to a Variable in a Contributed Module I'd like to add some data to a variable in a contributed module but I'm not sure how to do that with a custom module.

The Question:

The module I need to 'hack' is the Drupal Commerce PayPal WPP Module. I talked with PayPal and they said specifically I'd need to hack this file: 'commerce_paypal_wpp.module'. They said on line 365 if I added more data to the 'CUSTOM' variable (see below) it would pass that on to PayPal. Sweet! But how can I do that?

My Proposed Solution

I'm thinking I will create my variables to add to CUSTOM, like so (this is how I'd normally do it in PHP of course:

$fname = 'examplename';
$lname = 'examplelastname';
$arr = array($fname, $lname);
$allthedata = implode('+', $arr);
CUSTOM = $allthedata

It's that last line I don't know how to add properly! This, because 'CUSTOM' is already defined in the contributed module (see below).

The Function I Need to Edit:

The function in question in the contributed module is:

function commerce_paypal_wpp_submit_form_submit($payment_method,
$pane_form, $pane_values, $order, $charge) {

And the relevant code with 'CUSTOM' > the variable I want to change:

// Add additional transaction invormation to the request array.
  $nvp += array(
    // Order Information; we append the timestamp to the order number to
allow
    // for multiple transactions against the same order.
    'INVNUM' => substr($order->order_number, 0, 127) . '-' . REQUEST_TIME,
    'CUSTOM' => substr(t('Order @number', array('@number' => $order-
>order_number)), 0, 256),
    'DESC' => substr(implode(', ', $description), 0, 127),

    // Customer Information
    'EMAIL' => substr($order->mail, 0, 127),
    'IPADDRESS' => substr($ip_address, 0, 15),
    'FIRSTNAME' => substr($billing_address['first_name'], 0, 25),
    'LASTNAME' => substr($billing_address['last_name'], 0, 25),
    'STREET' => substr($billing_address['thoroughfare'], 0, 100),
    'STREET2' => substr($billing_address['premise'], 0, 100),
    'CITY' => substr($billing_address['locality'], 0, 40),
    'STATE' => substr($billing_address['administrative_area'], 0, 40),
    'COUNTRYCODE' => $billing_address['country'],
    'ZIP' => substr($billing_address['postal_code'], 0, 20),
  );
}

You will not need to 'hack' this module, you can use a legitimate hook to modify the $nvp array, hook_commerce_paypal_api_request_alter

At line 382 of the commerce_paypal_wpp.module, right after the part you mention, the whole array is passed to the commerce_paypal_api_request where the mentioned hook is called early on, to allow modifications from other modules.

Following your example code, your hook implementation would look like this:

function yourmodule_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) {
  ...
  $fname = 'examplename';
  $lname = 'examplelastname';
  $arr = array($fname, $lname);
  $allthedata = implode('+', $arr);
  $nvp['CUSTOM'] = $allthedata;
  ...
}

Hope this helps!


Problems connecting to database in drupal 6 Whew, ok I am new to Drupal, and I am dealing with a outdated drupal site. Ive been told not to upgrade yet, so for now I am dealing with Drupal 6. I am trying to stage it on our test server, but it won't seem to connect to the database. (It returns a page that says "Site off-line" and "Deprecated: Function ereg() is deprecated in E:\development\ump_2010\includes\file.inc on line 926") Below that, it states that I could not connect to the database:

The mysql error was: Access denied for user 'root'@'localhost' (using password: YES).

I went into the settings.php file and changed $db_url to the correct one, and $db_prefix remains empty. Where is drupal getting 'localhost' and the password from as well?

Thanks,
Austin Slominski

All of those values are set in $db_url, in the sites/default/settings.php file.

$db_url = 'mysqli://username:password@server_ip_or_host/databasename';


How do I group taxonomy by hierarchy, not node? I am using Drupal 7 and Views.

I'm trying to use the generic Taxonomy/Term view and get a grouping I don't want.
I want this:

Taxonomy 1:

Node A
Node B

Taxonomy 2:

Node B
Node C

(Notice Node B is in both taxonomies.)

What I'm getting is the following one:

Taxonomy 1:

Node A

Taxonomy 2:

Node C

Taxonomy 1, Taxonomy 2

Node B

How do I get the first example to display,  where Node B just appears under the different Taxonomies and doesn't create a new heading with multiple taxonomies?

I started a new view of taxonomy terms (sometimes the default taxonomy term view is overkill) which created a view of my taxonomy terms. I then created a relationship to Taxonomy term: Content with term and then added a field Content: Title using the relationship just created.

Finally I changed the Settings of view under Format to group by by term and hid the actual term field.

My output ended up like the following, Product One was tagged with Shirts and Ties, product Two just with ties as expected.

Shirts

Title: Product One
Title: Product Two

Ties

Title: Product One


Is there a way to add a Tour on all the pages/routes? I need to create a Tour guide for the generic elements in a page like Search bar, notification, sidebar. These elements appear on all the pages. I want to create a tour which is available on all the pages. The tour is being created using Tour UI module. Is there a way to create a Tour for all the routes available. Most of the pages are Landing page nodes and few view pages.

Since you're using the Tour UI module, add the routes to the list
All node pages have the same route, entity.node.canonical
For view pages, they are unique. You can use Devel's Webprofiler module to see the route names, ex:

They are basically structured as view.[view_name].[display_id]
Note: display_id is also known as the machine name value.

Is there a possibility to have wildcards in the routes? Chances are
thin

There isn't. You would have to tinker with the Tour UI module's code.

Also, is there a way to enable tour for a specific node?

There isn't. You'll prob have to use one of the hooks shown in tour_test.module to unset if the entity/node id is not the one you want.

Because of the routing limitation, seems to me like the core tour module was built towards showing how to edit or configure pages for administrators and not catered towards anonymous users. For your use case, you're better off using
D8: Bootstrap Tour module which is using the bootstrap tour library

No need to be familiar with Drupal routing names to be able to assign
a tip to a page, this modules works purely on jQuery selectors so you
may add the page body class plus some jQuery selectors to target a
specific page instead of routing name.


Can a database query be written inside a template.php file? I am writing a query inside the following function of template.php file

        function theme_name_process_views_view_field(&$vars) {
 if ($vars['view']->name == 'view_name') {
// query is written here
      foreach( $vars['view']->result as $key => $value ) {
          $nid = $value->nid;
          $query = db_select('abc_in', 'abc')
            ->fields('abc', array('study_abc'))
            ->condition('abc_nid', $nid , '=');
          $result =   $query->execute()->fetchField();
        $vars['view']->result[$key]->field_field_abc_in[0]['rendered']['#markup'] = "
" .  $result . "
" ;

    } }

Is it ok to write a db_query inside template.php file ?
I an taking a data from custom table and inserting value into field of a view ?

You can definitely do it, however you really shouldn't.

The theme layer is for presenting the data.
The actual functionality and the data itself should come from modules.

If you mention what you are trying to do I can give some more information on where it should go instead

Edit

Based on your code example, if you are dealing with a custom data table the best thing would be to use hook_views_data() to let views know about your database table and fields. Then you would just use your new fields via the UI.

If you didn't want to go to that much trouble though you could use basically the same solution as you are using now in a custom module in one of the views hooks, like hook_views_post_execute(), where you can loop through the results in a similar fashion as you are doing now.

You generally wouldn't be dealing with markup here though (like your abc_code div). You're really only changing data here and then changing markup in the theme. Although your field should already have classes that let you specifically style it so adding that class probably shouldn't be necessary.


Suggested theme hook doesn't get applied The custom theme hook (abacus-product.html.twig) I've appended via a hook function doesn't get applied. But it shows up in the suggestions.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * abacus-product.html.twig
   * page--taxonomy--term--5.html.twig
   x page--taxonomy--term--%.html.twig
   * page--taxonomy--term.html.twig
   * page--taxonomy.html.twig
   * page.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/abacus/templates/page--taxonomy--term--%.html.twig' -->

abacus-product.html.twig is in the same directory as page--taxonomy--term--%.html.twig

Edit
This is the hook function:

function abacus_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $path = \Drupal::service('path.current')->getPath();
    if (0 === strpos($path, '/taxonomy/term/')) {
        $weight = \Drupal::routeMatch()->getParameter('taxonomy_term')->getWeight();
        if ($weight == 0) {
            $suggestions[] = 'abacus-product';
        }
    }
}

EDIT, after further debugging (see comments):

Using $suggestions[] = 'page__abacus__product' and a template called page--abacus--product.html.twig works. Theme suggestions should contain double underscores.


Drupal 8: Build "visitor history" using Flag/Rules I need to build a history for visitors so they can see which pages they've visited (ideally filtered by type).  To do this, it seems that the correct combo is to use Flag module and then Rules.

I'd anticipate that I'd create a new rule config where I'd ensure the content was of a certain type, ensure a flag existed, then automatically mark the flag each time the content of that type was visited.  I'd also have to update the time if an 'already-flagged' content was visited again (ie. so it appears at the top of a 'history' list).

I've messed around with Rules in Drupal 8 and I didn't get far at all.  I could obviously add a rule for 'node is viewed', and then condition of it being the right type.  But then I got stuck.

I need to be able to do things like see if there's a flag available, see the current value of the flag for that user, automatically set/update the flag, etc.  I couldn't figure out how to do any of this.

Help? :)

Honestly I gave up pretty quickly since it seemed unnecessarily complicated.  I created a very basic module that handles the marking/unmarking via the Flag API.  It has a single hook that looks like this:

function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  //UPON VIEWING 'mytype' NODES
  if($entity->getType() == 'mytype'){

    //CREATE HISTORY FLAGS
    $uid = \Drupal::currentUser()->id(); //current user
    $flag_id = 'history'; //flag type is named history
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    if($flag->isFlagged($entity) == '1'){
        //unflag then reflag to update date
        $flag_service->unflag($flag, $entity);
        $flag_service->flag($flag, $entity);
    } else {
        //flag it for the first time
        $flag_service->flag($flag, $entity);
 }
 }
}


Drupal 7: how to redesign, move stuff around, for a content type page? If when creating a View, I create a list of a specific content type, let's say Staff. It lists everyone from the Staff content type. I have this setting too: Link to the original piece of content. Then I get a list of content type labels and content type data. How can I rearrange everything? How can I edit the HTML?

I don't want to create a view for a specific content type, I want to redesign (edit HTML) the content type page, example: domain.com/node/5

Not clear with your questions ,adding some pointers on some assumptions.

Custom Way

1 . If you want to override a node structure for a specific content type

-- You can copy the node.tpl.php to your theme and rename it to node--type.tpl.php. Inside node--type.tpl.php , you will be rearranging the elements.

2 . If you want to override every node,irrespective to any content type.

-- Copy node.tpl.php inside your theme and do the rearrangement of elements.

3 . If you want to override a particular node

-- Copy the node.tpl.php and rename it to node--nodeid.tpl.php and do the rearrangement of elements

Some Helpful Links:

https://drupal.org/node/1089656

http://www.youtube.com/watch?v=dfwU0WtCuPs

Remember to clear the caches after you are done with building of templates.

Using Contrib Module

You can use panels module to override node templates without creating them. panele module will do that for you.

Some Helpful Links:

http://www.youtube.com/watch?v=_VIkE2ZS5oU


Responsive Image Module is only selecting fallback image style I recently tried implementing drupal 8's Responsive Images Module.
I studied about it's basics and implemented according to the guides available online. But when i try to use it on any image on the site, its only selecting the Fallback Image Style. I have defined 5 breakpoints and 5 image styles for each breakpoint.

My breakpoint.yml is as follows:

investindia.big_screen:
  label: big screen
  mediaQuery: '(min-width: 1025px)'
  weight: 4
  multipliers:
    - 1x
investindia.tablet_landscape:
  label: tablet landscape
  mediaQuery: '(min-width: 769px)'
  weight: 3
  multipliers:
    - 1x
investindia.tablet:
  label: tablet portrait
  mediaQuery: '(min-width: 481px)'
  weight: 2
  multipliers:
    - 1x
investindia.smalltouch_landscape:
  label: smalltouch landscape
  mediaQuery: '(min-width: 321px)'
  weight: 1
  multipliers:
    - 1x
investindia.smalltouch:
  label: smalltouch portrait
  mediaQuery: '(min-width: 1px)'
  weight: 0
  multipliers:
    - 1x

Edit : Adding my responsive image style configuration for further clarification on the issue.

The posted responsive image configuration seems correct. Remember that you also need to change the image field formatter to "Responsive image". If you are using image fields on node entities, you can do this at

/admin/structure/types/manage/MY_NODE_TYPE/display/MY_VIEW_MODE

(If you are using image media entities instead of image fields, use the "Rendered entity" field formatter on the node, and switch to the "Responsive image" field formatter on the media entity at /admin/structure/media/manage/MY_MEDIA_TYPE/display/MY_VIEW_MODE )


How do I overwrite the particular webform submit event in template.php? I want to control a particular webform submission event, and I am trying to use the following function in my template.php file.

function bartik_form_webform_client_form_7_submit(&$form, &$form_state) {}

The function is not working. How can I achieve this?

Try hook_form_alter() or hook_form_FORM_ID_alter(). This will help you to alter the array of the submission handlers and add a new submission handler.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your-Webform-ID') {
    $form['#submit'][] = 'custom_settings_form_submit';
  }
}

function custom_settings_form_submit($form, &$form_state) {
  // Your code here.
}


Filtering a table using views I am  new to drupal and I already created a table using view. I also applied exposed content filtering and I got the following screen

Now I want to show all the category and author are listed in a drop down and i want to select one from that. Also how can I display all the content of table before filter?

Thanks in advance.

You can change filter view settings. goto admin/structure/views and edit your views and follow the screenshots


Search form block only appear for administrarors I have a site with three different languages on it. for a while we had a search bottom on the English site. I wanted to be on all three languages. after playing around with it, it now appears in all languages, but only for administrators. how can I make it appear for users as well?

Most probably it's about the permissions. Give the users (anonymous user / authenticated user) the search permission (also), which you can do after navigating to admin/people/permissions.


Is it possible to disable a content type? I am currently creating a small Drupal 7 website, but I don't plan to use the delivered Article content type. Is it possible to disable it without deleting it? What I mean by that is making sure no user will create articles by accident.

I could not find an option for this. Thanks.

You can't disable a content type, but you can prevent (almost) everyone from creating/viewing/modifying etc. an Article it with setting the permissions accordingly.
If there's no Article content on the site, it's 100% safe to delete it. (It's interesting to check out how the default and minimal installation profile provide different sets of content types. Article is just a "stock" content type which is by no means necessary to have.)


Simple cycle that pick next free id What I'm trying to do is function working like this:

function my_function($id){
   while($id){
      if($id = not free){
          $id=$id+'1';
      } else {
          return $id;
      }
   }
}

I'm new to php and drupal generally and can't figure out how to handle this cycle.
For instance, 'if statement' should test if the id is already in database. If it is then +1 to id if not return this free id.

I'm using this to check whether the id is free or not:

$check_unique_station_id = 'SELECT field_station_id_value FROM {field_data_field_station_id} WHERE field_station_id_value = :input_id LIMIT 1';
if (db_query($check_unique_station_id, array(':input_id'=>$input_id))->fetchField()){

}

Any help would be appreciated.

//EDIT

I guess I didn't explain it well. I have custom module and few custom fields. One of them is 'station_id' which is field for storing number (type) of station. Let's say it is a name of the station expressed in number.
Here is an example of values I have in database in field_station_id:

22
45
89

Now what I want to do: when user input=22 then check if 22 already exists and if so check if exist 22+1. When input=45 then return 46 etc.
Now I see that I explained it really bad. Hope that now you know what I mean.

// EDIT 2
// MY SOLUTION

I came up with this piece of code. However I was just wondering if there is some query function to do it (propably faster). As mentioned by Felix downthere (pick as the right answer) it seems that the only query function founds the maximum number in db and return it. Which is not what I want.

Here is my code:

function free_value($occupied_value){

// loads all used values from db
$query_all_occupied_values = 'SELECT field_station_value FROM {field_data_field_station_value} WHERE field_station_value >= :occupied_value ORDER BY field_station_value';
$all_occupied_values = db_query($query_all_occupied_values, array(':occupied_value'=>$occupied_value))->fetchAll();

// count number of rows of used station_values
$number_of_values = count($all_occupied_values)-1;

// finds first closest value which is not occupied in db
for($i=0; $i<=$number_of_values; $i++) {
    if($occupied_value == $all_occupied_values[$i]->field_station_value) {
        $occupied_value = $occupied_value+1;
    } else {
        break;
    }
}

$free_value = $occupied_value;

return $free_value;

}

This will select the next free ID:

$next_free_id = db_query("SELECT MAX(field_name) + 1 FROM table_name")->fetchField();


MMenu Module Per Page Configuration Ok drupalers,

A good one.  I am using the MMenu module to implement right hand side overlay panels.  The site that I am building has two different types of users "Group A" and "Group B".  They each need to see different content displayed inside of the right hand overlay created by the MMenu module.

Problem: MMenu module displays the same content on ALL the pages for "Group A" and "Group B".

The site is a demo site for anonymous users to review, so there are no user login url's to distinguish a user in Group A from a user Group B.

basically, I need a way to dynamically change the content block based on what page loads.

Anybody got any good ideas?

Ok for a non-programmer (my last course was literally 2 decades ago) I feel pretty good at about this one, but invite folks to provide better solutions. :-)

To solve the problem described above, I utilized a little jquery javascript via js injector (into the head section) and added the following:

!function( $ ){
$(function () {

$("div#page_key_features").appendTo("div#right_panel_overlay_content");

});
}( window.jQuery )

From there, within the block that I will add to the Mobile Menu right overlay panel, I added the following HTML:

&nbsp;

Then via CKEditor (source) within the body of the page I added the following HTML:

This content is invisible in the body content of the page, but becomes   visible within the mobile menu block called "right_overlay_panel_content". This means I can edit content using ckeditor, then add the "display:none" style to the outter div to hide in the body of the page, but display it when the user triggers the right overlay panel.  I can change the content on every page if I choose.

NOTE: I had to use nested divs. This allows me to hide the content of the right overlay panel within the body of the page, then display it when the user clicks the trigger showing the panel.

Now I can add custom, per page content to the Mobile Menu right overlay panel.

Here's the JS Fiddle for anyone who wants to use/tweak my little solution.


How to Include an ATTACHMENT to a Drupal's Entityform Submission Email? I am using the Entityform module and the Rules module for its notification .
I noticed that the email sent out when the form is submitted does not attach the PDF file as part of the email's body.

I have one field in the form that allows a user to attach a PDF file.
The email body is fine with the exception that any file attachment is not part of the email.

I also added the Mime Mail module with no success.

Does anyone know how to include an attached file as part of the email notification?

Here is some more detailed guidance on how to solve this:

As mixerowsky states you will need to download and set up Mime Mail.

The latest version of Entity Form (7.x-2.0-rc1) comes with it's own preconfigured rules. You'll need the Entity Rules module for these. You can clone or edit these.

Alternatively you can set up your own fresh rules in the 'normal' way by using the 'After saving a new entityform submission' event.

Whichever method you go for you will need to add the 'Send HTML e-mail' element to the Actions stage of the rule (you can remove the existing actions if you cloned the packaged entity rules).

Edit the action and within the attachments section you can add a file path token, e.g.

[ENTITY_NAME:FILE_FIELD_NAME:file:path]

Check the Replacement Patterns for the correct ENTITY_NAME and FILE_FIELD_NAME and make sure you append ':file:path' as above and you will get an attachment on the HTML email.

Other file tokens include:

[ENTITY_NAME:FILE_FIELD_NAME:file]
[ENTITY_NAME:FILE_FIELD_NAME:file:url]
[ENTITY_NAME:FILE_FIELD_NAME:file:size]

You may wish to use these in the email body for example.

Here is a list of file tokens. There are other useful tokens listed on there too.

Trouble Shooting & Testing

Make sure you are using the correct token. Check the replacement patterns for the correct entity name and file field, e.g.

[ENTITY_NAME:FILE_FIELD_NAME:file:path]

Then try adding the file tokens to the email BODY to make sure that it is working correctly, e.g. Add this to the body:

Filename: [ENTITY_NAME:FILE_FIELD_NAME:file]
Filepath: [ENTITY_NAME:FILE_FIELD_NAME:file:path]
FileURL:  [ENTITY_NAME:FILE_FIELD_NAME:file:url]
Filesize: [ENTITY_NAME:FILE_FIELD_NAME:file:size]

This should output something like this in the BODY of the email:-

Filename: filename.pdf
Filepath: public://filename.pdf
FileURL:  http://website.local/system/files/filename.pdf
Filesize: 16.59 KB

If the 'filepath' is not present then there will be no attachment.

Make sure that the Drupal file system is set up correctly and files are getting saved when the entity form is submitted.

Double check your System Stream Wrappers and Token installs.

Make sure you have set up Mimemail correctly and you are receiving emails OK. Maybe set up a test using a different system (e.g. Webform) to check that file attachments are working in the first place.

If you use the correct token then it will work - however if there is an problem with the set up of the email sending or other modules then you may not get an attachment. The chain from 'entity form' to 'email with attachment' is quite long and complex so make you test every step of the journey.


setting user edit permissions In each user's profile there's a user reference field called "other editors." For all the users selected in that field, they should be allowed to edit that user's profile.

My first thought was that there'd be some kind of user access hook which would let me allow/deny users based on some criteria, but the only thing I can find is hook_node_access(), which doesn't get called when viewing a user profile. Is there a hook I'm missing, or do I need to look elsewhere?

As far as I can see, there isn't a module that allows to the users listed in a user reference field to edit the user account where the field is contained.
You should write your own module.

The easier step is to alter the access callback for the user edit form, and use a function that checks the value of that field, comparing it with the value of the user currently logged in.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
      $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($account) {
  // The argument is the user object for the user profile being edited.
}

The default access callback is user_edit_access() which should be always called to verify that the currently logged in user has still the permission to edit the user profile, even if the user is not listed in the user reference field; users with the permission to administer users should always be allowed to edit a user account.


Drupal Database Encryption I am seriously looking for a solution to encrypt at least some of the tables in my Drupal 7 database.

I'm totally suspicious about my hosting providers, I really don't want my user's data and also my business information to be visible at all.

Are there any solutions for database encryption?  I don't want to buy a VPS.

In short, unless you are the only person with physical access to the server, you are not safe, there is no way you can do this with reasonable effort, a VPS makes no difference.

If you could deploy something like full disc encryption which was only unlocked when you logged in to the system, your provider could still have virtualized the entire server, and not encrypt it anyway, only tell you they have.

Even if you somehow managed to safely encrypt the database, it needs to become readable at the server side at some point, or your server couldn't possibly serve the data.

Either this means that your webserver actually holds the decryption key, making it at most moderately complicated to copy it. You could require the key to be entered every time your http-deamon starts and store it only in RAM, but again, if your host is in a virtual machine you are immediately screwed, and a determined attacker could steal the key from RAM even from physical ram.

I could go on, but the gist is, you can't do what you want without a lot of resources, mainly physical servers in a locked serverrack.


"Cannot read property 'icons' of null" With Drupal 8.0.0-rc2, no matter what, I get this error in the JS console:

  Uncaught TypeError: Cannot read property 'icons' of null

I think I have defined everything correctly, so I don't know what causes this error or what I missed.

Plugin definition:

/**

* @file
 * Contains \Drupal\codesnippet\Plugin\CKEditorPlugin\CodeSnippet.
 */

namespace Drupal\codesnippet\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\ckeditor\CKEditorPluginConfigurableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;
use Drupal\Core\Url;

/**
 * Defines the "codesnippet" plugin.
 *
 * @CKEditorPlugin(
 *   id = "codesnippet",
 *   label = @Translation("CodeSnippet"),
 * )
 */
class CodeSnippet extends CKEditorPluginBase implements CKEditorPluginConfigurableInterface {
  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return array(
      'codeSnippet_dialogTitleAdd' => t('Insert Code'),
      'codeSnippet_dialogTitleEdit' => t('Edit Code'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return array(
      'CodeSnippet' => array(
        'label' => t('CodeSnippet'),
        'image' => drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/codesnippet.png',
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state, Editor $editor) {
    $form_state->loadInclude('editor', 'admin.inc');

    $styles = $this->getStyles();

    $form['highlight_style'] = array(
      '#type' => 'select',
      '#title' => 'Highlightjs Style',
      '#description' => t('Select a style to apply to all highlighted code snippets. You can preview the styles at !link.', array('!link' => \Drupal::l('https://highlightjs.org/static/demo', Url::fromUri('https://highlightjs.org/static/demo/')))),
      '#options' => $styles,
      '#default_value' => !empty($form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style']) ? $form_state->storage['editor']->settings['plugins']['codesnippet']['highlight_style'] : 'arta.css',
    );

    return $form;
  }

  /**
   * Returns available stylesheets to use for code syntax highlighting.
   */
  private function getStyles() {
    $styles = preg_grep('/\.css/', scandir(drupal_get_path('module', 'codesnippet') . '/js/plugins/codesnippet/lib/highlight/styles'));
    $style_options = array();

    foreach ($styles as $stylesheet) {
      $style_options[$stylesheet] = $stylesheet;
    }

    return $style_options;
  }
}

The icon on the toolbar when editing the text format appears just fine, I can drag it in and out of the active toolbar, and my settings form shows. But due to the JS error generated, it does not work.

The plugin used is available on ckeditor.com, I dropped it into the plugins/codesnippet/js folder untouched.

I can't find any other examples of custom plugins using anything called 'icons'.

@Kevin are you sure the fix was due to CKEditor being upgraded in that Drupal version? I'm getting the same kind of issue trying to add the Link plugin, on Drupal 8.1.1, which is using CKEditor version 4.5.8.
Trying to find more insight on this issue.
edit: upon manually upgrading CKEditor to version 4.5.9 I'm getting much more illuminating error messages:

Uncaught Error: [CKEDITOR.resourceManager.add] The resource name "link" is
already registered.
Uncaught TypeError: Cannot set property 'getLinkAttributesParser' of undefined
Uncaught TypeError: Cannot read property 'icons' of null

So looks like this is colliding with the Link plugin that comes with Drupal (which is lacking some features). So I'll find a way to sidestep this name space collision and will update here.
edit: renaming the plugin proved unfruitful. Still getting:

Uncaught TypeError: Cannot read property 'icons' of null


How to select from a specific choice of images on content forms? Is there a way to have a specific set of images on an add new content form.

So for example the "article" content type, when setting the fields on the form the only option for image is an upload function so the user can upload an image, I would like for there to be a selectable list of predefined images they can choose from.

Not a single default image, but an option of say 5 images.

Thanks.

(Drupal 7)

You can use

function template_preprocess_node

then loop in the variable you want.
For each value you have selected, you could add an  to your imagetype variables.
Then just display the variable in you node template.


Apply page template suggestion to a specific view by a hook? I have a website running Drupal 8.x with different views. I would like to use a page--template.html.twig template basing to the view ID. Is this possible?

I was thinking of using code similar to the following.

function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
 if ($hook === 'views_view') {
   if ($variables['view']->id() === 'movies') {
     $suggestions[] = 'page__movies';
   }
 }
}

First of all, the code is never run, because you have the hook page in the function name and check for the hook views_view. Secondly the variables in a page hook don't contain variables from the view, so you have to get them from the route:

function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id === 'movies') {
    $suggestions[] = 'page__movies';
  }

}


How can I turn off the caching for a Paragraph type? I'm rendering an array whose URL is dependent on a $_GET variable.
Where the variable is present and valid, I want to serve an iframe with the _GET variable as part of the URL. At the moment the cache is capturing the variable and preventing different value being passed to the page.
In my module I have this:
function MY_MODULE_preprocess_paragraph__iframe(&$variables) {
    $query = @$_GET['e'];
    /*...*/
}

But the value $query is staying the same until the caches are cleared.
Is there a better way of capturing the $_GET variable, or a way of preventing the value from being cached?

Declare the dependency on the GET parameter with a cache context:
/mymodule/mymodule.module
function mymodule_preprocess_paragraph(&$variables) {

  $foo = \Drupal::request()->query->get('foo');
  $variables['content']['foo'] = [
    '#markup' => "foo = $foo",
    '#cache' => ['contexts' => ['url.query_args:foo']],
  ];
}

More info https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts
However, if you have more than a few possible values of foo this is a problem with cache performance, especially for nested entities like paragraphs. Each value creates a new cache entry for the paragraph and its parent entities.
To avoid this put a placeholder in the paragaph:
/mymodule/mymodule.module
function mymodule_preprocess_paragraph(&$variables) {

  $variables['content']['foo_placeholdered'] = [
    '#lazy_builder' => ['\Drupal\mymodule\MymoduleLazyBuilders::getFoo', []],
    '#create_placeholder' => TRUE,
  ];
}

and build the content which depends on the GET parameter in a lazy builder:
/mymodule/src/MymoduleLazyBuilders.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class MymoduleLazyBuilders implements RenderCallbackInterface {

  public static function getFoo() {
    $foo = \Drupal::request()->query->get('foo');
    return  [
      '#markup' => "foo = $foo",
      '#cache' => ['contexts' => ['url.query_args:foo']],
    ];
  }

}

For time consuming calculations such placeholders can be delivered through BigPipe. So if you enable this module you can also improve page speed.


How to trigger an action when a site receives an email? In Drupal 7, is it possible for users to send an email to a website, which will trigger an action?

For example, the user sends an email to offers@mydrupalsite.com. The Drupal site receives this and then sends the user an email with a PDF attachment.

I've searched extensively; however, the nature of the query means that it usually turns up relevant results.

Here is how you might get it to work:

Use Mailhandler to create nodes by eMail. The content of the node could be the actual content of the request as contained in the eMail.
Use Rules to react to the event "after saving content" and combine it with the Message module to send the eMail back to the user.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation.


404 to sites/default/files/css/, I have a site that has a 404 being reported as "sites/default/files/css/," - yes, a css file with the name comma ","

I have no idea what is causing this 404.  The watchdog shows the referring URL can be almost any page on the site but going there and viewing the page source does not turn anything up.  It is intermittant and not created on every page request.

Has anyone seen this before? Anyone know what causes it?

I am using Drupal 7.14

Kind regards,

John

Assuming everything is using proper Drupal methods for attaching stylesheets (.info, drupal_add_css, $foo["#attached"]["css"], etc), I think it is impossible for core to create a bad link to a file.  Still, it would be worth it to search the code for "drupal_add_css" and "#attached" to see if there are any problems.

I think there are two possibilities here.

One could be a JS library dynamically attaching a stylesheet to the page.  Unless you are doing this yourself, I don't think this is a likely culprit.  Most of the libraries that do this (eg, jQUery UI) are rather well tested and I doubt would do this.  Stranger things have happened, though.

The other possibility is a bad url() reference in your CSS for a font or background image.  Search though all of your CSS for "url" and see if you have any problems.  Validating the CSS couldn't hurt, either.


Generate unique form ID based on context When you try to build the same form twice on a page, the submit handler of the first form gets executed.

In order to overcome this issue you need to generate a unique form ID.
How do you generate a unique ID based on some pass context.

As with Drupal 7, forms need to have a unique form ID. What's different is that in Drupal 8, the connection between the form (code) and the form ID is reversed.

In Drupal 7, as pointed out by @Ivan Jaros in the comment, you start with the form_id, so we had hook_forms() that allowed to map form ID's to a function that then built the form.

In Drupal 8, you first need to create a form object so that its getFormId() method can return a unique ID. The challenge there is that getFormId() is called very early, specifically before buildForm(), so the usual way of passing arguments to forms does not work.

What you need to do is create the form object yourself instead of just passing the class name to the form builder, then you can set any data on it that you want before passing it the form builder.

To get the form class, you can either instantiate it yourself, but then you can't use the ::create() method to inject dependencies, for that, you need to use the class resolver, from FormBuilder::getFormId(), this is what it does by default if you pass in a class name:

if (is_string($form_arg) && class_exists($form_arg)) {
  $form_arg = $this->classResolver->getInstanceFromDefinition($form_arg);
}

You could even use the current object or any other existing object as a form, as long as it implements \Drupal\Core\Form\FormInterface. One example in core that does that is the DraggableListBuilder and BlockListBuilder, see its render() method:

public function render() {
  if (!empty($this->weightKey)) {
    return $this->formBuilder()->getForm($this);
  }
  return parent::render();
}

That has the advantage that you do not need another class, you could make a block plugin that displays a form do it in the same class, for example. On the other side, that prevents you from re-using that form elsewhere and could also result in conflicts if the same method names are used for something else.


How do you automate text file upload daily to a Drupal Page? Im trying to create a plugin, possibly through IFTTT, where i can forward an e-mail with a text attachement that will replace a current file on a Drupal page.  Has anyone had any success in automating this process?  Bascially we're getting a text file sent to us daily that we would otherwise have to manually upload to the page.

it's much more simple, use Mailhandler

https://www.drupal.org/project/mailhandler

Mailhandler can connect your inbox and with feed you fetch the messages, so basically you need to run the feed using cron job.
you will find all of that in the configuration of the feed and mailhandler.

Also you can map the attachment with the field where you keep your text file, I don't think there is need to create any plugins, everything you need in mailhandler & feed.


Problems with file type field of node I have created some custom page on frontend for particular type of node modyfications. Here's my page callback:

function vintranet_talk_edit_entry_page_callback($sNid) {
    module_load_include('inc', 'node', 'node.pages');

    $oNode = node_load($sNid);

    return drupal_get_form('page_node_form', $oNode);
}

My node has one field with file attachments.

Config:

'vintranet_talk_attachments' => array(
    'field_name'     => 'vintranet_talk_attachments',
    'label'          => t('Attachments'),
    'type'           => 'file',
    'cardinality'    => -1,
),

Instance:

'vintranet_talk_attachments' => array(
    'field_name'     => 'vintranet_talk_attachments',
    'label'          => t('Attachments'),
    'entity_type'    => 'node',
    'bundle'         => 'intranet_talk_page',
    'widget'         => array(
        'type' => 'file_mfw',
    ),
    'settings'       => array(
        'max_filesize'       => 10,
        'file_directory'     => 'intranet/talk',
        'file_extensions'    => 'jpg, png, gif, pdf, zip, doc, rtf, xdoc, rar',
        'description_field'  => 1,
    ),
    'display'        => array(
        'default' => array(
            'type' => 'file_table',
        ),
    ),
),

My first problem is, when I want to upload JPG file after module installation, system sends me this message:

So ok... I'm going to check that particular field settings in Structure and I see this:

Why the hell it is saved like this?!

Okaaaaay.... so I'm changing this form field value on jpg, png, gif, pdf, zip, doc, rtf, xdoc, rar, saving and trying to upload the image one more time...

....clickin "Upload" button.... aaaaandd....

....yup.... that's my 2nd problem :/. Have no idea why it's not working. On the backend, in other hand, the "Upload" button works perfectly. Am I missing something?

(working on Drupal 7.31 version)

Answer for my problems:

function hook_menu_alter(&$aItems) {
    $sNodePath = drupal_get_path('module', 'node');

    $aItems['file/ajax']['file path']    = $sNodePath;
    $aItems['file/ajax']['file']         = 'node.pages.inc';
    $aItems['system/ajax']['file path']  = $sNodePath;
    $aItems['system/ajax']['file']       = 'node.pages.inc';
}


What is the correct way to attach an arbitrary field from a different content type to an existing form? I have a content type with a title and item id fields. The item ID field is a simple decimal and has unlimited entries. It acts as a reference to another field on a different content type.

In hook_form_alter(), I attach an AJAX callback to each existing item ID element. When the AJAX callback is called, I add the values that already exist from the other content type (image, a couple taxonomy terms), and two input elements to the results div. The two inputs are fields that exist on the other content type.

The way I do this is by loading the node whose item ID value correlates and adding it to the form (using a custom view type that only displays the fields I want). As for the inputs, I use drupal_get_form() to get the other content type's node form and copy the input element arrays into the form that I'm modifying. (This is the part that feels like cheating.)

On the page, everything displays fine. The problem is the form submission. When the new input elements try to validate, it fails. I've dug into the source code and discovered that the field does not exist in the $form_state array. That is to say, the corresponding $form_state['field'][$field_name] is missing.

My suspicion is that, upon splicing the form elements into the new form, the '#parent' and '#array_parent' arrays are not being updated correctly, despite being sure to add $form_state['rebuild'] = TRUE to hook_form_alter().

Is there a more correct way to add an arbitrary field from a different bundle to my form?

I considered using field_attach_form(), but I can't wrap my head around what the $entity argument should contain.

PS. I plan to handle the additional fields in a hook_node_prepare(), as I doubt shoving them into this content type would work!

I considered using field_attach_form(), but I can't wrap my head around what the $entity argument should contain.

It's the entity for which you want to show the form elements to edit its fields. For example, if you want have a reference to a node in $node, and you want to add the form elements to edit its fields, you add the following line to the code.

field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));

The validation handler for the form should then call either one of these functions.

entity_form_field_validate()
field_attach_form_validate()

The first function builds the entity object from its $form_state parameter; the second function requires the entity object as second parameter.

Keep in mind that, despite the fact the UI allows you to add fields to a content type (e.g. add a Portrait image field to a Biography content type, but not to a Blog content type), for Drupal the entity to which the fields are attached is a node, which means you need a node object. passing as entity a string containing the machine name of the content type doesn't produce the expected result.


How can I set a separator for a taxonomy field? Within my nodes I'm want to display my taxonomy field references with a separator, like this:

term1 - term2 - term3

what I get as a standard is:

term1
term2
term3

with display suite I can get:

term1 term2 term3

I know that I can do this with CSS styling, but is there another solution to add a separator?

You can do this in Twig.

Place this file in the templates folder of your theme (field-tags is the field name):

field--field-tags.html.twig

 <div{{ attributes }}>
    {% for item in items %}
      {% if not loop.last %}
        <span{{ item.attributes }}>{{ item.content }} - </span>
      {% else %}
        <span{{ item.attributes }}>{{ item.content }}</span>
      {% endif %}
    {% endfor %}
  </div>

To add classes use {{ attributes.addClass() }} or {{ item.attributes.addClass() }}, see https://drupal.stackexchange.com/a/212307/47547


How to add a property to a field type having data I have a custom field type. Now I need to add an additional property to it.

I added the new property to propertyDefinitions() and schema() methods.

What should I do in the update hook? The field type is already in use, and fields have values stored in the database.

I ended up using the following code.

function my_module_update_8001() {
  $field_type = 'my_field_type';
  $new_property = 'my_new_property';

  $manager = \Drupal::entityDefinitionUpdateManager();
  $field_map = \Drupal::entityManager()->getFieldMapByFieldType($field_type);
  foreach ($field_map as $entity_type_id => $fields) {
    foreach (array_keys($fields) as $field_name) {
      $field_storage_definition = $manager->getFieldStorageDefinition($field_name, $entity_type_id);
      $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
      if ($storage instanceof \Drupal\Core\Entity\Sql\SqlContentEntityStorage) {
        $table_mapping = $storage->getTableMapping([
          // We pass only one storage definition to make
          // \Drupal\Core\Entity\Sql\DefaultTableMapping::getDedicatedTableNames()
          // return only tables we need.
          $field_name => $field_storage_definition,
        ]);
        $table_names = $table_mapping->getDedicatedTableNames();
        $columns = $table_mapping->getColumnNames($field_name);
        foreach ($table_names as $table_name) {
          $field_schema = $field_storage_definition->getSchema();
          \Drupal::database()
            ->schema()
            ->addField($table_name, $columns[$new_property], $field_schema['columns'][$new_property]);
        }
      }
      $manager->updateFieldStorageDefinition($field_storage_definition);
    }
  }
}


custom module: drupal_add_js and drupal_add_css do not work after form validation? I have created a custom module that changes the layout & adds extra functionality to one of my content type creation and edit forms.

It works beautifully and as expected apart from when I submit the form with, for example, a blank node title or any other required fields.

The page is reloaded as expected with the error message, the form modifications are loaded from the module (field #prefix, #suffix etc..) but the css and the js are not loaded.

Here is the code I have:

/**
* Implementation of HOOK_form_alter()
*/
function mymodule_entry_form_modify_form_alter(&$form, $form_state, $form_id) {

  // 1.ENTRY FORM
  if ($form_id == 'entry_node_form') {

  // here were some form field modifications i removed

/* 1.3 LAYOUT - ADD JAVASCRIPT FILES
 * Add .js files
 */
// add jquery script before calling it
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/jquery.fixheight.js');
// call the script
drupal_add_js(drupal_get_path('module', 'mymodule') . '/includes/js/mymodule_entry_form_modify.js');

/* 1.4 LAYOUT - ADD CSS FILES
 * Add .css files
 */
drupal_add_css(drupal_get_path('module', 'mymodule') . '/includes/css/mymodule_entry_form_modify.css');

 }
}

Can anyone explain why this happens?

I don't use D7, but I believe you should be using #attached and it should fix your issue.


Info on Drupal.settings and #attached I'm trying to use Drupal.settings for the first time to pass variables from PHP to JavaScript. The documentation on the topic is sparse and I have a few issues.

Is it possible to use #attached to pass through the settings rather than drupal_add_js(array('myModule' => $settings), 'setting');? The reason I am asking is that I've been told that #attached is the "correct" way to add settings. ( I know it is also the correct way to add files also, but not sure if it works with settings variables.)

I'm using the following code, but I can't get it to load under the DOM objects and I am stuck.

(function ($) {
   Drupal.behaviors.myModule = {
     attach: function(context, settings) {}
   };
});(jQuery);

Any advice would be greatly appreciated. Please bear in mind that this is the first time I've set out to use Drupal.settings, so every detail is welcome and appreciated.

#attached can be used as follows.

$form['#attached']['js'][] = array(
  'data' => array(
    'xx_system' => array(
        'xx_code' => variable_get('xx_code', 'xx'),
        'xx_key' => variable_get('xx_key', 'xx'),
      ),
    ),
  'type' => 'setting',
);

With drupal_add_js(), you can use the following code.

 drupal_add_js(array('orgs' => $orgs), array('type' => 'setting'));
 drupal_add_js(drupal_get_path('module', 'module_name') . '/module_name.js');

In a JavaScript file, you can get the value of the variables as follows.

  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
      var cities = Drupal.settings.orgs.cities;// you will get the cities value here
    }
  };


How to get Drupal cache key? If you have caching enabled in Drupal, instead of getting URLs like so:

image.png

You get:

image.png?itok=RANDOMNESS

What function would I need to call to get back the value = "RANDOMNESS"? I ask, because I want to cache other things using the same method Drupal does internally.

Any ideas?

The itok is defined in ImageStyle@getPathToken entity when building the URL (ImageStyle@buildUrl):

  /**
   * {@inheritdoc}
   */
  public function getPathToken($uri) {
    // Return the first 8 characters.
    return substr(Crypt::hmacBase64($this->id() . ':' . $this->addExtension($uri), $this->getPrivateKey() . $this->getHashSalt()), 0, 8);
  }


How can I display the time passed since a comment was created instead of the creation date? how to personalize my comments ?

I want to display since when the comment was created instead of the date.
I want to display the comment ID with the link "permalink".

Can you help me ? Thank you

comment--field-article-commentaire.html.twig :

          {{ drupal_entity('user', comment.uid.target_id, 'comment') }}

            {{ permalink }}

            {{ author }}

            le {{ created }}

      {{ content.field_article_commentaire }}

        {{ content.flag_report_comment }}

        {{ content.links }}

Here is the current view of my comments :

https://ibb.co/QF051yV

I would like to display the date like this :

https://ibb.co/QCQbmG2

Twig's date extension does exactly what you ask:

{{ created | time_diff }}

However, this extension isn't in Drupal by default, assuming you're using Composer you need to add this extension to your project by running:

composer require twig/extensions


Display content by taxonomy term, including sub-terms I'm looking at Drupal for the first time in a long time, with a view to using it in a project we're starting. This seems like a very simple question, but I'm struggling to find the answer.

If we have a taxonomy of website sections and associated sub-sections, like this:

News
    - Europe
    - America
    - etc
Products
    - Widgets
    - Doodahs
    - etc

If we have a menu linking to News it's easy to display content associated explicitly with that term, I'm not seeing how to include content associated with its sub-terms though. Is the conventional way of achieving this through...views?

Thanks,

Toby

Update: It looks like in previous versions of Drupal you could perhaps specify a term depth in your URLs. I guess this is what I'm after, but in Drupal 7

link- https://drupal.org/project/taxonomy_menu_block

Taxonomy Menu Block allows you to make blocks
containing unordered lists that represent the structure of
your vocabularies, creating a menu out of your
taxonomies (without using Drupal's menu system).
TMB combines the idea of Taxonomy menu with the
workings of Menu block :
Make multiple menus per vocabulary.
"Split" the taxonomy into different menus.
This allows, for example, the creation of one menu with
only the top items (parents) of a vocabulary and
another menu with only the sub-items (children).
Make a menu out of a specific branch of your
vocabulary only.
Follow the active trail, also for nodes coupled to a term
with a term reference field.


Do not show picture when video available Got a content type with some text, and a video field and an image field (and some other stuff, like entity references between nodes, but not relevant for this question).

When displaying nodes for this content type, I don't want to display the image, if there is a video available.
So the image displays if the video field is empty.
If a video was added to the node, the image should not display.

Can only be done by modifying the node template I assume?
So I would need to copy the node.tpl.php  and rename it to node--contenttype.tpl.php   (with contenttype being the name of the content type)

But the PHP code in there just prints then entire $content  so I cannot interfere with the displaying of the image separately.

Is there another customisation (the one producing the html for the node probably?) where I can wrap some "if" statement around the image field that check for presence of content in the video field?

You can use conditional fields module for this.
https://www.drupal.org/project/conditional_fields
and set the  dependency for your field. See the screenshot it will help you.