Give non-administrator users acces to node-class I have installed "node-class" on my drupal webiste. As an administrator, i can assign a class now to a node, but other verified users can't...?

Here is a framework for a module to add that permission:

In your contrib module folder, add the folder node_class_perms and add these files within that folder:

node_class_perms.info
node_class_perms.module

in node_class_perms.info add this:

name = Node Class Perms
description = Alters permissions for Node Class.
core = 7.x
dependencies[] = node_class

in node_class_perms.module add this:

<?php

function node_class_perms_permission(){
  return array(
    'administer node classes' => array(
      'title' => t('Administer Node Classes'),
      'description' => t('Allows node classes to be added to nodes.'),
    ),
  );
}

function node_class_perms_form_alter(&$form, &$form_state, $form_id) {
  // Check form type && if user_access is ok
  if (isset($form['#node']) && ($form_id == $form['#node']->type . '_node_form') &&
    user_access('administer node classes')) {
    // Add form elements in vertical tab to node settings.
    if (!isset($form['node_class'])) {
      $form['node_class'] = array(
        '#type' => 'fieldset',
        '#title' => t('Node Class settings'),
        '#description' => t('Assign CSS classes to the node.'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#access' => user_access('administer node classes'),
        '#weight' => 80,
        '#tree' => TRUE,
        '#group' => 'additional_settings',
        '#tree' => TRUE,
        '#attributes' => array('class' => array('node-class-form'))
      );
    }

    // Get css attribute information
    $attributes = node_class_attributes($form['#node']);

    // Check CSS exists in DB to prepare SQL update
    if ($attributes) {
      $form['node_class']['existing_css'] = array(
        '#type' => 'hidden',
        '#value' => '1');
    }

    $form['node_class']['css_class'] = array(
      '#type' => 'textfield',
      '#title' => t('CSS class(es)'),
      '#default_value' => $attributes,
      '#description' => t('Separate classes with a space.'));
  }
}

Now install the module, then add the permission 'Administer Node Classes' to the role you want.

You can tighten the permissions if you want, but as the node edit form has already gone through a basic node-edit permission it really is not necessary.


How to Include custom tokens in the user register welcome mail Is it possible to use custom tokens in the default user regitration welcome mail? I need to pass variables from a custom module. Is the solution to create a token in the custom module and include it into the mail?

The user mail templates can be found at example.com/admin/config/people/accounts. The welcome mail for instance looks like this:

  [user:display-name],

  A site administrator at [site:name] has created an account for you.
  You may now log in by clicking this link or copying and pasting it
  into your browser:

  [user:one-time-login-url]

  This link can only be used once to log in and will lead you to a page
  where you can set your password.

  After setting your password, you will be able to log in at
  [site:login-url] in the future using:

  username: [user:name] password: Your password

  --  [site:name] team

As you can see there are already many tokens used.

Furthermore, Drupal does not distinguish between core tokens and those of modules. So if a textfield allows you to use core tokens (like this one), you can also use any other token. If you create a custom token, you will be able to use it in the mail. BUT, you must keep in mind that this mail template only has access to a select set of tokens (click the Browse tokens link below the textarea):

Current date    current-date    Tokens related to the current date and time.
Current page    current-page    Tokens related to the current page request.
Current user    current-user    Tokens related to the currently logged in user.
Random  random  Tokens related to random data.
Site information    site    Tokens for site-wide settings and other global information.
Users   user    Tokens related to individual user accounts.

When working with tokens, each module can define which tokens it handles (The $data array passed to Token::replace()). In this specific case, it only gets the user entity of the created user. Apart from that, several global tokens are always available, these are Current date, Current page, Current user, Random and Site.

So your custom token must be provided within the user or site type.


How to export / feature the "picture guidelines" field I have some legal mentions to put under the file upload form of user account.

I would like to put them a feature some elements about user configuration, but I'm not able to find which variable (i.e. Strongarm or anything else) is mapped to field "Picture guidelines"
(available in Home » Administration » Configuration » People).

Could someone give me a hint, or is it even possible ?

Use Strongarm to export the variable called user_picture_guidelines.


Feeds tamper find and replace Is it possible with Feeds Tamper to find something in a string and replace all the string with something ?

Ex : I've got a .csv file and column 23 can contain something like:
"XL SSR FR RB" or "XL TL RB"

I need to find if this column contains SSR, and rewrite everyting to 1 or 0

Ex : "XL SSR FR RB"  => "1"
     "XL TL RB"      => "0"

Is this something the tamper module can do ?

If it's possible to convert it to boolean it's even better.

Thanks.

So you'll need two tampers for that field. From the manual:

Find replace REGEX
Find and replace a user-specified string using REGEX with an option to limit the number of replacements. See the PHP Manual on PCRE Pattern Syntax for a complete reference, or RegexPal for a quick tester.
Convert to boolean
Convert a user-specified string to boolean, with the option of specifying what to do in the case of no match.

Here is a regular expression that will find SSR and replace the entire string with it.

https://regex101.com/r/aO0uG3/2

/\b(SSR)\b/\1/

Then match SSR in the Convert to boolean tamper. (Note: The regex in the screen shot is now out of date. Use /\b/(SSR)\b/ instead)


removing page title in drupal page I have a Drupal 7 site, where I created a new page which became my front page.

Drupal requires that the page have a title and I've found no way of removing the title from showing on the page. At the moment, I have the title as "Welcome".
I'd like to remove it completely from the page or make it invisible.
I'm looking for the easiest method to accomplish this.

1 - you can create file page--front.tpl.php in theme dir and you can
  hide the title .

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

 <?php endif; ?>
  <?php print render($title_suffix); ?>

  2 - you can use css Rule to hide this title

  3- you can use hook_page_alter or hook_preprocess_page
     add this code

if (drupal_is_front_page()) { drupal_set_title('');}


Best practice for node expiration with email notification I have a page where users can create meetings which have a specific start date and time, other users can join this meetings until up to an hour before it starts.

One hour before the meeting starts i would like to send an e-mail to the participants to tell them that the meeting will take place, or that it is canceled because not enough participants have been found. So i need to filter all the existing and not yet closed/started meetings and see if any of them are less than one hour away from starting.

Question:

Whats the best practice to do this kind of data evaluation in Drupal. Is there a recommended way of doing this?

My idea:

Just create an external PHP file including all the drupal shebang, call it every x minutes with a cron job and access the DB from inside this script.

Drupal has a custom module available called Rules with a submodule Rules Scheduler that will allow you to set up custom scenarios for when you want a certain action to take place.

In your specific scenario you would use Rules and Rules Scheduler to set up custom emails to be sent out at your specified time based off of your time field.

Node one has several tutorial videos available to watch with a specific video available about how to use content fields and rules scheduler to set up time specific actions.


how to show a message after a node form is submitted How do I show a message (notice or alert) after the node form is submitted and saved?

I'm writing a module that synchronizes the node content with a remote endpoint. All working good. But, if for any reason the sync fails, I want to show a message on the page the user is redirected to.

My problem is that I don't find the hook or function which is invoked after the form is saved to databases but before the redirect happens, where I hopefully can set the message I want.

You can create an additional submission callback.  Not sure if it will run late enough for you.  May be worth a shot.

Create a form alter hook using hook_form_alter();
Within there add an additional submit function to the #submit array

Example:

hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

You could try going 1 step further and adding the submit hook to #submit in the #after_build.  This will ensure it is the very last submit callback (unless other higher weighted modules also use the afterbuild)

Example:

hook_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'custom_afterbuild_function';
}

function custom_afterbuild_function($form, &$form_state) {
  $form['#submit'][] = 'custom_submit_function';
}

function custom_submit_function($form, &$form_state) {
  drupal_set_message('your message');
}

I hope this helps

[update] added drupal_set_messages to code examples.


Use another language than "default" as standard We're currently building a rather large website that will be release in swedish initially, but other languages later on. For this reason we've built everything in english and then translated everything to swedish. For the release, only swedish should be accessible. This is where the problem begins.

-We don't want / can't use language URL prefixes for different reasons (PURL clashes, uglyness, won't need once the site is available in more than one language)

-We can't use Swedish as default language because that will break all of the translations (string translations will then consider swedish as the original language). Since everything from fields, labels, content types, help text etc. are in english originally this is not an option.

-We can use browser detection, but that isn't really fool-proof and doesn't cover all cases. A lot of users in sweden use english as browser language.

-We could use IP location, as an addition to the above, but it's not fool proof either.

What we would really need is to use Swedish as the default language but somehow use english as the language of origin. Is this possible somehow?

Drupal 7?

The language negotiation is extendable, you just need to implement hook_language_negotiation_info(). In there, you can do whatever you want, like always default to swedish for now. It also looks like you can limit to what languages you can switch to, I am not sure how that exactly works, though.

Not sure what to do once you add more languages, but you could for example call other negotiation callbacks in yours and fallback to swedish if it not one of the languages you want displayed.


Required Checkbox Field Has No Effect I used hook_form_alter to add a required 'confirmation' checkbox to the node deletion form and the #required status is not honored.

The fields/fieldset are property displayed 'node-delete-confirmation' form.

Here is the hook_form_alter content:

$form['warning'] = array(
    '#type' => 'fieldset',
    '#title' => t('Warning! - You Must Check The Box Below To Continue'),
    '#weight' => -30,
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
);
$form['confirm_delete'] = array(
    '#title' => t('I fully understand that this action cannot be undone and that statistics linked to this item will be permanently removed.'),
    '#type' => 'checkbox',
    '#required' => TRUE,
    '#default_value' => 0,
);

How can I enforce the 'required' status so that nodes cannot be deleted until the confirmation is acknowledged.

If I change the code, to completely remove the added fieldset everything works as it should.

Works:

$form['warning']['confirm_delete'] = array(
'#title' => t('I fully understand that this action cannot be undone and that statistics linked to this item will be permanently removed.'),
'#type' => 'checkbox',
'#required' => TRUE,
'#default_value' => 0,

);

You can add your form validation handler (hook_form_alter):

$form['#validate'] = array('delete_validation_handler') + $form['#validate'];

Your validation handler:

function delete_validation_handler($form, $form_state){
    if(!$form_state['values']['confirm_delete'])
        form_set_error('confirm_delete', t('Message about to confirm it first'))
}


Tokens for taxonomy term parents in Pathauto I am trying to find the correct tokens to use for a Pathauto pattern in Drupal 8.

In Drupal 7, I have a Pathauto module pattern that creates a URL alias with a node's term and parent term.

So if the node had a Term reference of Health -> Diet. The URL would be health/diet/node-title.

The pattern to generate this is [node:field-topic:0:parents:join-path]/[node:field-topic:0]/[node:title]

Note the :0 is because the Term reference field allows multiple values.

I just tested the tokens that I suggested in the comments with field_tags on articles and it works perfectly, no idea what your problem is, make sure you use the latest versions of pathauto and token.

Token: /articles/[node:field_tags:0:entity:parents:join-path]/[node:field_tags:0:entity]/[node:title]

Tag hierachy: A > B > C

Alias for an article tagged with C: /articles/a/b/c/pathauto-test


Commerce Product using Display Suite Im using Commerce for Drupal 8. When using Display Suite to create a two column display for Products, the Price and Attributes disappear. Is it possible to use Display Suite for Commerce Products to achieve a two column display?

No. Display Suite is not compatible with Commerce Products.

Commerce issue: https://www.drupal.org/node/2723689
Display suite issue: https://www.drupal.org/node/2725077


Paging data from a web service I'm working on a module that uses soap to fetch data from a webservices.
Data are ok, and I'll use theme functions to display them as a list.
I should also to split results in pages, like views.
Is there a way to add a pager?

Use something like
 foreach ($result as $node)
{
    $rows[] = array('data' => array("".  $node  ."..."));
    $html = theme('table',array('header' => $header,'rows'=>$rows,'caption' => '','sticky' => FALSE,'empty' => 'No details found...','attributes'=>array('class'=>'table-class'),));
    $html.= theme('pager',array('tags' => array(),'quantity'=> 10));
}


How do I filter an entityreference field based on other fields? So I'm trying to create a node that has an entityreference to another node. THing is I need that field to filter the data from an entityreference view based on three use cases.

New content. Should only show referenced nodes created by the same user.
Editing created content. Should only show referenced nodes created by the person who created the edited node
New Content as Admin - An administrator/editor should be able to add content under another users name, and it should filter and show nodes created by that user.

I've got 2 out of three but I'm not sure how to get the last one done.

Your question reminds me of this similar question you may or may not find it relevant.

Alternatively, you could use Masquarde

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.

Video Tutorial


How can I filter child terms in an exposed filter by parent term from contextual filter? I have a vocabulary of Districts with nested taxonomy terms like below.

I have a view of taxonomy terms in Drupal 8 which has an exposed filter of all terms with parent and child. What I want is that when I add a contextual filter of term parent the exposed filter should only show child terms matching the parent term in the contextual filter.

For example, if the URL contains Deoghar, then the exposed filter (like below filter) should only show the term Karon as option.

I've done this recently in a project of mine using MYMODULE_form_views_exposed_form_alter. The code assumes you've a view with the term ID on first position as contextual filter, e.g. domain.com/myview/123

<?php
function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $view = $form_state->getStorage('view');
  $display_id = $view['view']->current_display;

  if ($form_id == 'views_exposed_form' && $view['view']->id() == 'MY_VIEW' && $display_id == 'MY_VIEWDISPLAY') {
    if (!empty($view['view']->args) && $view['view']->args[0]) {
      //get the term ID from the contextual filter
      $contextTermId = $view['view']->args[0];
      $entriesToRemove = [];

      $currentFilterValue = $form_state->getUserInput()['FIELD_FILTER_TAXONOMY'];
      foreach ($form['FIELD_FILTER_TAXONOMY']['#options'] as $idx => $entry) {
        if ($idx === 'All') {
          //remove the old root '- Any -' option
          $entriesToRemove[] = $idx;
        }
        //the next line is a bit shaky might need rework:
        //sometimes filter entries are a stdClass,
        //but I've also seen entries as array in other exposed forms (grouped filters?)
        elseif ($entry instanceof stdClass && is_array($entry->option)) {
          $termId = key($entry->option);
          $termName = current($entry->option);
          //the context filter term is our new root, so we change its label to '- Any -'
          if ($termId == $contextTermId) {
            $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => t('- Any -')];
            if (empty($currentFilterValue) || $currentFilterValue == 'All') {
              //we've removed the default empty/All entry, reset it to our newly created, faked '- Any -' category
              $form_state->setUserInput(['FIELD_FILTER_TAXONOMY' => $contextTermId]);
            }
          }
          else {
            //this is the core part: for each filter option load the term
            //and check if it is a child of the contextual filter term
            $parents = \Drupal::entityTypeManager()
              ->getStorage('taxonomy_term')
              ->loadParents($termId);
            if (!in_array($contextTermId, array_keys($parents))) {
              $entriesToRemove[] = $idx;
            }
            else {
              //optional: we are in a sub-filter now,so we no longer need the leading '-' to indicate hierarchy
              $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => trim(preg_replace('/^-/', '', $termName))];
            }
          }
        }
      }
      foreach ($entriesToRemove as $idx) {
        unset($form['FIELD_FILTER_TAXONOMY']['#options'][$idx]);
      }
      //optional: if there is only 1 entry left, hide the filter
      if (count($form['FIELD_FILTER_TAXONOMY']['#options']) == 1) {
        $form['FIELD_FILTER_TAXONOMY'] = [
          '#type' => 'hidden',
          'value' => $contextTermId
        ];
      }
    }
  }
}

A word of caution: Don't to this on huge taxonomies, my code loads every taxonomy term to decide if it needs to be removed.


How programmatically filter text? I need to display a text and apply the chosen filter to it. The text is saved using the text_format field type.

So I know the original text, I know the chosen format type but I don't know how to actually filter the text.

How can I programmatically filter text? Thanks

This post on stackoverflow describes how to do this programmatically.

Just call check_markup and pass in your text and the filter id.

check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE)

  Run all the enabled filters on a piece of text.


HTML being removed when rewriting field in Views I have completely stripped all my views/blocks down so they only produce exactly what I put into them..but I created a view and rewrote the fields and this part of my code will not print exactly as it is here:

Instead, when the block is rendered I get:

So it strips away come of my code. Does anyone know how I can get round this problem?

Adding a class and then the style to your stylesheet is the normal practise.  Quick fix

.slides-full-screen-image {
Background-image:  url....

}

If you have more calls to that class where you don't want the image then you should add an additional class name.


How to resolve the MySQL error Duplicate entry 'comment_publish_action' for key 'PRIMARY'? I'm a beginner in Drupal. I want to import my database to my webserver and get this error when trying to do so:

  "#1062 - Duplicate entry 'comment_publish_action' for key 'PRIMARY'"

I don't know how to fix this error.

Here are more details about it:

  INSERT INTO actions (aid, type, callback, parameters,
  label) VALUES ('comment_publish_action', 'comment',
  'comment_publish_action', '', 'Publish comment'),
  ('comment_save_action', 'comment', 'comment_save_action', '', 'Save
  comment'), ('comment_unpublish_action', 'comment',
  'comment_unpublish_action', '', 'Unpublish comment'),
  ('node_make_sticky_action', 'node', 'node_make_sticky_action', '',
  'Make content sticky'), ('node_make_unsticky_action', 'node',
  'node_make_unsticky_action', '', 'Make content unsticky'),
  ('node_promote_action', 'node', 'node_promote_action', '', 'Promote
  content to front page'), ('node_publish_action', 'node',
  'node_publish_action', '', 'Publish content'), ('node_save_action',
  'node', 'node_save_action', '', 'Save content'),
  ('node_unpromote_action', 'node', 'node_unpromote_action', '', 'Remove
  content from front page'), ('node_unpublish_action', 'node',
  'node_unpublish_action', '', 'Unpub[...]

From the information provided in the question so far, it is hard to tell what is causing your problem (consider refining your question by editing it).

However, as an alternative, you may want to consider using the Backup and Migrate module like so:

install that module on both Drupal sites (where you want to export from, and where you want to import to).
use this module to create a backup in the originating Drupal site (and save it somewhere to a local file), of the relevant tables in the MySQL database.
use this module to restore that "local file" (= backup) to import it in your target site (which is where you're currently encountering the problem.

Does this help somehow?


Should I share the same image style as much as possible or create different styles for each size? I have an image field displayed in slightly different sizes.

Let's say :

100px X 100px as a view field format
120px X 120px as another view field format
150px X 150px as a node view format

My question is :

Which is the best practice ?

1.
Creating three different image styles for each size.

2.
Creating just one image style and share it (Fixing the size accordingly by CSS)
For example, create just the image style of 150px and then make it smaller for 100px and 120px by CSS

Why I wonder is :

1 obviously creates more files but 2 uses unnecessary bigger files for 120px and 150px

I would zoom out the thinking and try to get two things into perspective:

user interaction "paths" and which images they "touch"
graphics design decision for the image sizes

What is the likeliest user scenario for downloading each image size?

What is the path your users take through the site that would trigger downloading those image sizes? Will the user see many of the 100px images in a list, then click through to only one that would display the 120px one, and then clicking on that one so 150px is displayed in a lightbox?

Aim to reduce downloaded data bandwidth

Diagram some likely user paths (if you have some analytics on your site you probably already know this, better to get data instead of making assumptions) and calculate how many Kb/Mb of image data users would most often download under those paths.

Compare if the data load is larger with 1, 2 or 3 sizes for those "user paths".

If you have a lot of mobile visitors the data size is super important. Your goal should be to provide meaningful content and experience while keeping the data exchange to a minimum.

If users click through a lot and you end up serving the largest 150px size very often, it may not be useful to have the smaller sizes, better use 150px and size down with CSS.

If your images are such that with the change in pixel size the file sizes also vary greatly (if the 100px image is disproportionately smaller in file size than the 150px one) then it may be useful to have a smaller size, especially if users mostly view "list pages" with smaller images and don't click through, so they rarely see the larger image.

Don't forget server resources and requests

The downloaded data size isn't the only criteria, reusing the same size pulls it out of cache, so saved bandwidth again, fewer server requests.

If you upload a lot of images and have a lot of image styles, server processing power is being used for that and can get congested in extreme cases. You also end up with a lot of data on the disk so storage is also important, as mentioned in comments.

Graphics design refinement

Having so many close-but-not-identical style elements might be a sign you could improve your graphics design by making different design elements more consistent. How justified is it to display some image type in that many different sizes, is there a need for it?

Taking a blind guess I don't expect a lot of difference between 100px, 120px and 150px so I would try and see whether I'd need 100px and 120px at all, maybe 120px and 150px would be enough? 3 sizes do seem excessive here, 3 sizes are usually used when there is a much larger difference between them (100px, 500px, hero).

I have a real-world example where I disabled image sizes completely because the uploaded originals were so well optimized that the smaller versions made by Image styles were bigger in file size than the large pixel original, even after using custom imagemagick rules!


Theming a slider view using templates I am creating theming view using row style theme named as

  views-view-fields--slider-block.tpl.php

and here is code for it:

<?php
$string='

';

foreach($fields['field_slider_image_fid']->handler->view->style_plugin->rendered_fields as $row) : ?>
<?php $i=1; ?>
<?php $i=$i+1;?>

<?php

if($row['field_image_position_value'] == 'left') {
    $string.="

".$row['field_slider_image_fid']."".$row['field_image_text_value']."
";
}
else {
    $string.="
".$row['field_image_text_value']."".$row['field_slider_image_fid']."
";

}
?>
<?php endforeach;  ?>

<?php
$string.="

";

echo $string;
?>

Now it is working fine when there is exactly one node in the view. But a problem occurs when the view contains more than one node, e.g. if the view contains 5 nodes, this template renders 5 times causing duplication.

Anyone have ideas on how to resolve this?

Apart from your template needed some serious code cleanup (to follow the coding standards for PHP Template), I would say your issue lies with the fact that you have overridden the wrong views template.

It seems like your views template is doing the iterations around the nodes itself (from the foreach), and I bet your view is also doing the same (hence the double up).

My suggestions:

Read https://drupal.org/coding-standards - thoroughly
Also look at the default implementations in the views templates, these will give your excellent examples on how your code should look

As for your problem, either:

override a higher level views template (i.e. one that only gets rendered once per view)
or alternatively, use the same template, and leave out the foreach loop (as the view is essentially doing this. I would say this is the 'cleaner' option. All the fields you have pulled out in your view will be available to be used without having to access the global $view object.

Consider installing the devel module to help with outputting variables, so you know what is available to be themed (using the dsm() function)


After upgrade admin menu not coming After upgrading from Drupal 6 to Drupal 7 successfully, the admin menu links are disappeared.

I have carefully followed the steps to upgrade it successfully. But after upgrade, I changed the administration theme to Seven and everything was working but the administration menu. What could be the problem?

Update: Management Menu snapshot

I tried to see if the problem is with Menu, so I installed Admin menu but after that admin menu appearing. Only problem is with Drupal7 default toolbar. What am I missing?

Can't tell you why, but can tell you how I fixed it last time when it happened to me:

Disable Admin Menu
Uninstall it if possible
Delete it's files and directory
Download and unpack fresh copy
Clear all caches (Drupal and browser)
Enable Admin menu

Worked for me, when menu disappeared during 6.x -> 6.x upgrade, when everything else failed to bring it back.

If the problem is only with core toolbar module, and not Admin Menu module, you have 2 options, really:

Try steps above, just for Toolbar. You can download core archive and then just extract toolbar's directory. Admin menu and toolbar are build in similar fashion, and purging all module's data is a pretty solid method anyway, so it still can work.
Give up on toolbar, and use 3rd party module instead.


Why drush needs a stage server I have seen a lot drush setups in the past and every setup had a stage server configuration Is there a reason why thay have

a development server
a stage server and
a productive server

What are the advantages if you have a sage server and must there be such a server osr is this optional?

There are a number of scenarios where having dev, stage and live are useful.

Example:  minor updates.

Run drush pm-update on dev, test and make sure everything is okay.
Push your code to stage / test, run drush updatedb, and make sure everything is still okay.
Push your code to live, run drush updatedb, and confirm everything is still okay.

The point here is that the operation of 1. and 2. are slightly different; by testing your deployment on the stage server before bringing it live, you can confirm that the deploy will go okay (i.e. there are no uncommitted components on the dev machine, or all state needed for a successful deploy is part of the deployment process.)  If you did not test this, then you'd break the live site if you forgot to commit an important file, or otherwise did not faithfully update the components used in deployment.


How to display a view link in another view? I’m listing in a view a list of article filtered with taxonomy terms.

The result is like this :

taxonomy term 1
- article A
- article B
- article C

taxonomy term 2
- article D
- article E
- article F

taxonomy term 3
- article G
- article H
- article I

Here is the view configuration :

I’ve also created a view which contains 3 articles and which have the same taxonomy relationship than articles.

I can see this view as a page like this : http://my-site.com/my-view

Here is my view configuration :

I would like to display this view link in the listing :

taxonomy term 1
- article A
- article B
- article C
- link to view A (associated with term 1)

taxonomy term 2
- article D
- article E
- article F
- link to view B (associated with term 2)

taxonomy term 3
- article G
- article H
- article I
- link to view C (associated with term 3)

How can I do that? I can't find a field in view configuration to display this view.

You can use either of these modules:

Views Field View

  There are a lot of cases in views where you want to embed a list
  inside each row. One example could be, you have a list of groups, and
  for each groups you want to list the first and last name of all of
  their members.

Viewfield

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.


How do I prevent a user from re-using the same password within a certain period of time? How do I prevent a user from re-using the same password within a certain period of time?

I have configured a number of password restriction modules {Password policy, Generate Password and Flood control} which I have configured to do things like "Password must not match any of the user's previous 10 passwords" but I can't configure them to prevent the same password from being reused within a certain period of time like a year.

I am using Drupal 7.

You are looking to alter Password policy module:

A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.
Current constraints include:

History constraint (checks hashed password against a collection of users previous hashed passwords looking for recent duplicates)

Now, all you need is to take this constrain and make a copy based on time, not number. Should be pretty easy, real difference is in one WHERE condition.
If module provides hooks, make it in your custom module. If it does not, provide a patch with your constrain.


Create fieldable bundle types for an entity with Drupal Console I am trying to recreate the functionality of a NodeType/Node entity at a basic level.

I want to define entity types (FooType) which can be fielded individually, just like NodeType can be.

I used the Drupal Console to generate a config entity and content entity. Out of the box, it creates types and content entities of those types. However you can't field those types, I don't see a way to add that.

When I try to mimic the annotation in NodeType to allow fields, I get the following error when I try to save a field to a FooType:

Missing bundle entity, entity type foo_type, entity id foo.

Where am I going wrong? Is this something the Drupal Console can already do and I missed it?

Update:

So I think I am past the original issue... now when I want to add a field on a type, I get:

Attempt to create a field 'field_testfield' without a bundle.

The URLs don't seem to be correct, as it keeps dropping me back on Foo entity settings instead of stay within FooType, where I am trying to add fields to.

I eventually got it by comparing how NodeType/Node is defined:

http://cgit.drupalcode.org/user_alert/tree/src/Entity?h=8.x-1.x

Now I can have unlimited entity types and add fields to them for different content configurations of the entity.

I started out by generating a config and content entity with the Console, but found that in order to get a more intuitive user interface, I had to modify the routing.yml and some of the paths as well.

Just a note for those looking for the same functionality.


Cron queue not working I'm trying to set up a cron queue, but for some reason, I don't manage to get this done.
Here is what I have so far:
function mymodule_cron() {
    // Setup the queue
    $queue = DrupalQueue::get('import_jobs');
    // Create cache
    drupal_flush_all_caches();
}

function mymodule_cron_queue_info() {
    $queues['import_jobs'] = array(
    'worker callback' => '_import_all_jobs',
    'time' => 15,
    );
    return $queues;
}

The _import_all_jobs function does it's work excellent, so nothing wrong with that. I use the Ultimate Cron module and my cron job is listed over there:

But for some reason, nothing happens... So I'm wondering what I do wrong...

You need to add items to your queue. You have created a queue, but haven't added anything to it, so nothing is being done.

$queue->createItem($item);

$item will get passed to the queue callback function (_import_all_jobs).

I would suggest modifying _import_all_jobs to import an individual job (_import_job). Then $item would be a job added to the queue and you let DrupalQueue do its thing.

This article may be helpful: Cron Queues: Processing large amounts of data in cron

And here is some relevant Drupal documentation: Queue operations


terms of use at login The user has to agree to a terms of use at EACH login, not just at registration.
What is the easiest way to do this?

Right now, I have a login page with only a login block on it (asking for username and password); once logged in the users are sent to the homepage. I need a pop up with terms of usage to appear after the login. The user accepts the 'terms of use' and are then directed to homepage, or are logged out.

There are several good modules that do what I want but only at registration, not for EACH login.

I'd check out Login Toboggan.  There's an example on the project homepage that nearly matches your use case.


how to export custom installed module(s) configurations? Possible Duplicate:
  Deployment for staging and production

how can i export the change in configuration of a custom install module, configuration module is exporting configurations of these, components Content type,Field,Image style,Variable,Permission, Vocabulary.

These are my finding. Drush provides the sync, using mysql dump and restore as complete, not the changes made after some interval.
Many things can be tracked with

Configuration Module
Features
Extra Features

Please see the presentation for futher.
https://docs.google.com/file/d/0B6Sp-HBmxgGMMnhhQXVrR1hDUVU/edit?usp=sharing


Jump to a heading in a view from outside the view on the same page I have a page with an introductory area and then a view that contains a large number of items grouped by a series of known headings. Kind of like this:

_________________________________
Welcome Message and list of headings:
  - Heading 1
  - Heading 2
  - Heading 3
_________________________________
View:
Heading 1:
   - item 1
   - item 2
   ...
Heading 2:
   - item 3
Heading 3:
   - item 4
   - item 5
   - ....

and etc.

The page is put together using Panels; there is a custom content pane with the welcome message and list of links and the lower content is a view inside a pane.

I want the user to be able to click on a link in the top panel and be taken to a particular heading in the view below. I can't seem to think of a sensible way to do this without reworking how I do the entire view/page.

Any suggestions?

You should be able to do this using standard HTML anchors, just rewrite the output of the Headings to include a simple anchor tag and in your top panel (aka table of contents) make the links go to their corresponding anchor tags.


To Connect to MYSQL - How to access database array in setting.php I need to connect to my database in php file in drupal 7. Each time I move from local server to development server, I have to change my db and host. I have seen setting.php file which have array of database.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'my_db',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

How do I aceess this database array in drupal 7 to use it connecting to database

$con = mysqli_connect('localhost','root','','my_db');

Thanks for Help

If you want to access the Drupal database from a standalone script.

Firstly, consider if you can put the PHP code in a Drupal module instead.
Secondly, consider bootstrapping Drupal in your PHP script

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', '/var/www/drupal');

// Bootstrap to database level for db api
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

You can then use the Drupal database API to query content from the Drupal database.

Thirdly, if connecting to a different database is required, consider defining the other database in settings.php and switching to a target database using db_set_active

// Settings.php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal7',
  'username' => 'drupal_user',
  'password' => 'drupal_password',
  'host' => 'localhost',
  'prefix' => '',
);

$databases['other_database']['default'] = array(
  'driver' => 'mysql',
  'database' => 'other_database',
  'username' => 'other_database_user',
  'password' => 'other_database_password',
  'host' => 'localhost',
  'prefix' => '',
);

Then you can switch between databases with db_set_active

// Query other database
db_set_active('other_database');
// $query = db_select('my_table'); // e.g
// Return to default database
db_set_active();


How to create a page category of products in Commerce 2? Usually in commerce 1 did:
Display-products (node), in which field "Catalog" of taxonomy-term.
Create a displays. Go to the term page and see all products! Great!

In commerce 2 tried to do but failed, probably because product is not a node, and the view for taxonomy, only works on him and no teaser.

Tell me, how do organized easy catalog on commerce2?

Preferably without the panels and search_api. Thank you.

Unfortunately, this is an issue with Drupal core itself and the Views module.

As you mentioned right now the taxonomy term views in core has Content: has taxonomy term ID which only work with nodes.

It should be Entity: has taxonomy term ID so it can handle other entities such as Drupal Commerce products

There's an issue in Drupal core/views here that you can read about it, for the time being there's a module that will help you out with this situation.

Commerce: Product taxonomy filter

  The Module extends Taxonomy module from Drupal core and provides a new
  contextual filter "Product has taxonomy term ID (with depth)".

Note that the contexual filter has to know your entity reference machine name


How to link an image with a PDF? Actually, I have a content type with 2 fields, image field (multiple) which will contain some pictures and an attachment field (accept only one file) which is file of type PDF.

I have a view where I put my gallery and each picture opens in a colorbox. The PDF file (actually global pdf for all images) is only a button.

There was a change and the new requierement is: "For every image that goes up, must have its own PDF. Every image should have its own associated file."

Another requirement is, if the image is opened on a colorbox also appears a button (in the colorbox) which displays the PDF associated with the corresponding image.

Any idea???
Sorry for my bad english.

You can create and use https://www.drupal.org/project/field_collection to have a new field containing an image field and a file field for your pdf.
You set the field in unlimited.
Problem is that you might have to reupload every picture manually or write an update script that does the conversion for you.

Then for the colorbox popup with your button, have a look at https://www.drupal.org/project/entity_popup


Lost setting of the custom field when editing a page I created a content type with my own custom field as described in Why do I get this error when I save my custom field?

The insertion of an item with this content type works, but when I want to modify the article I verified that I lose my custom field setting (it's a select box).

What is the method to keep the setting?

According to the code in the mentioned question, you need to define #default_value property and assign the $value variable to it like this:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $client   = \Drupal::httpClient();
    $request = $client->get('http://localhost:8083/regionilist');
    $response = json_decode($request->getBody());

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select element'),
      '#options' => $response,
      '#suffix' => '

',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
          'custom_field/my_js_custom_field',
        ],
      ],
      '#default_value` => $value,
    ];

    return ['value' => $element];
  }


Negate a block visibility condition Found it useful and did not find any contributed module to fulfil this so, adding it for knowledge purpose.
Stuck in a situation where we need to hide a block for certain role.
Drupal 8 has functionality to hide for certain URLS.
But, for Roles, only show condition is there not Hide.
I have already answered my question and I would love to accept another solutions.
Please suggest a solution.

There are visibility settings where, we can select which pages the block can be visible.
The same form has an underlying functionality to hide the block for the selected list or URLs.
Unfortunately, the same is not the case of Roles.
You can select which roles you want to display the block, but, you cannot select which Roles you want to hide the block.
Following code adds a Negate condition to Roles Visibility:
/* Negate the condition to decide visibility of which user roles to show/hide. */
function YOUR_MODULE_form_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['visibility']['user_role']['negate'] = [
        '#type' => 'radios',
        '#title' => '',
        '#default_value' => 0,
        '#options' => [
            t('Show for selected Roles'),
            t('Hide for selected Roles'),
        ],
    ];
}

This adds two radio buttons under the form: Roles.
Following is the screen shot for the same:

Reference:


How to wrap content around a display suite region? I'm using the nifty Display Suite module to create a custom layout for an event page. I'm using the stacked fluid 2 column layout with the Body field on the left and the image and event fields in the left column.

I would like the body (left region) to wrap around the image and date fields (right region). I''ve been unable to figure out to to accomplish this.

http://ctu.robohobo.net/node/17

How  would I make that happen?

Drupal: 7.19
Display Suite: 7.x-2.0

To solve this issue you need to reorder your html by flipping columns in your custom layout

If you inspect your html you'll see that group-left renders first then group-right

content

image and location

So you need to have the following structure:

image and location

content

Then add the following style to your css file

.ds-2col-stacked > .group-left {
  float: right;
  width: auto;
}

.ds-2col-stacked > .group-right {
  float: none;
  width: auto;
}


"Unable to send email" error shown to anonymous users in Workflow action Using the Workflow module, I've got a content type that can be created by anonymous and authenticated users alike, then it goes into a review process. Upon creation, I want to email the user with a confirmation email. You may be asking, "do you want to email anonymous users too?", and that'd be a good question; the answer is "ideally, yes", but the important thing right now is authenticated users.

Ideally, we'd use the email field (field_email) as an address, but when I try to use [node:field_email] or [node:field-email] (the field itself is of type "Email", from the "email" module.), I get the error "Enter a valid email address, or use a token email address such as [node:author:mail]"

So, we decided to just use [node:author:mail], but, of course, anonymous users don't have an email and it follows that when they save the new node, they get the "Unable to send e-mail. Contact the site administrator if the site persists."

NOTE: This action is being created on the /admin/config/system/actions page, and added as a trigger; not on the "/admin/config/workflow/rules" page. For some reason, it seems like using the actual Rules module itself with workflow breaks; none of the rules we try to set up actually fire.

I'm assuming you're using a Rules Event "Before saving content (optionally limited to selected content types)", or some variation of a node related Rules Event.

Try to add a Rules Condition like "Entity has field" (related to that node:field-email field). After you do, that field will be available as a token you can use in any subsequent Rules Condition and/or Rules Action (where a field of that data type can be used). Your 2nd paragraph appears to me like a confirmation you don't have such Rules Condition yet (so Rules has no clue you're interested in using that eMail field).

With that, you should be able to just get it to work with the Rules module, due to which your "note" probably doesn't apply/matter anymore.


Webform Thumbnail Image Not Created I've created a form using D7 Webform 7.x-3.20. This form works in the following manner:

Fill out form and attach image.
Email is sent to admin to approve where you click through to admin approval pages.
Approve information and upload image (no issue).
Page generation page where you select the image to thumbnail.
Save and publish page which is added automatically to a gallery.

One issue; on step 4 the thumbnail will occasionally break and not generate in the specified folder I've defined after so large a size. I've tested to confirm it's not a file type since all JPG, GIF and PNG work just fine. It is only after about 10MB of size the issue presents itself. I've also checked my form to confirm it allows for larger file uploads than that. Additionally my php.ini file is currently allowing for up to 150 MB file size during this time of testing.

Hopefully we can brainstorm this issue together and come up with a solution.

Thanks in advance!

Issue resolved. This was a combination of issues with file compression, max width dimensions and ram allocated to it.


Validate a group of fields so that form can only be submitted if 0 or 2+ fields have been completed In Drupal 7 I need to validate several cck fields so that the node can only be saved if 0 or two or more fields have been completed. So if only one of the fields is completed validation would fail with an error message like 'Please submit two or more years worth of data, or no data at all'.

I know that I can useField Group and Field Group Multiple To set up groups of fields. I can see that Field Validation provides basic validation options, including checking that a minimum of 1 of several fields have been completed. But as far as I can see it does not have the capacity to achieve what I need it to do.

Could you please suggest how to go about forcing a user to either complete 2+ fields or none at all?

Thanks

First I assume this must be for Drupal 6 since you are describing CCK fields? I would suggest creating a small custom module, and implementing hook_validate.

You can then check how many fields have been entered by your user to see if it passes your requirements described above.

If the validation fails you can then display the error to the logged in user with form_set_error

EDIT:

Since you're using Drupal 7, you can use hook_node_validate within a custom module.


Unit test for custom content type I created my custom content type 'Proposal' in D7 and used field API to attach fields.
In order to write unit test for it using "simpletest" (core module), do I need to setup my proposal content type in the unit test method from scratch or will the content schema be available to the unit tests?

If the custom content type is set up from within a module you're testing, then no you won't have to implement hooks from within the testing environment or anything. However, if your custom content type is set up through the interface on your site then yes you will need to do the same in your test. It is very important to realize that tests run in Simpletest are from the perspective of an absolutely clean environment - no users, no permissions, no custom content types, etc - so all of that needs to be implemented in code.

It's not such a big task once you get used to writing tests though. You can probably set up your custom content type in the DrupalWebTestCase::setUp() method. A simple series of form posts (with $this->drupalPost('path/to/form', $form_values, t('Save'));) and your custom content type will be set up in no time.


Select data from database when submitting a form I'm trying to learn how to make select queries with Drupal, so I made a form, and when I submit the form I try to query the database and get some results, but instead I'm redirected to an error page, here's how I select nodes from DB :

function my_module_form_submit($form, &$form_state)
{
    $query = db_select('node', 'n')->extend('PagerDefault');
    $query->condition('type', 'myContentType');
    $result = $query->execute();
}

You have missed fields() & fetch type -- fetchAll().

Below is the working example. You can find more details here (db_select API)

$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n'); // This is like select *. You can retrieve specific fields too.
$query->condition('type', 'article');
$result = $query->execute()->fetchAll(); // you can fetch by object, array, etc...
print_r($result);


CKFinder - Clicking 'send it to the server' when uploading an image does nothing I am trying to get CKFinder to work correctly. The file manager and related functionality is recognized.  When I click the little image in the toolbar to upload a photo the window comes up properly. I then select 'upload, browse (to select the file)' and then I click 'Send it to the server.'

At that point, nothing happens - the upload / file field disappears and greys out.

Nothing is actually uploaded, so, upload is not working.

Any thoughts as to why this might be happening?

The answer to this, as inspired by Nikit's comment, was to not use CKFinder at all.

CKFinder / CKEditor combination has to be one of the most frustrating experiences in all of Drupal, and it is the one thing I dread on each project. I have no idea why it has to be so complicated.

I kept CKFinder and used IMCE as suggested. The recipe works great; no complicated configuration; and is a much better module, in my opinion, for managing user images and file content.  I would suggest trying it as well if you find CKE and CKF as frustrating as I do.


Forwarding request to a content page How can I forward a request from module to a content page?

I have got a module that authenticates users; once authenticated, the module should forward the request to a content page or node (not redirecting).

public HttpKernel::forward($controller, array $attributes = array(), array $query = array()) allows to forward the request to a controller.

How do I forward the request to, for example, http://localhost:8080/techlab/evaluations, where evaluations is a created article?

You return a RedirectResponse() with the path. If you're in a controller, you can use the redirect() method from ControllerBase.


Allow user to choose role immediately after registration I have 2 roles (driver, owner) with very different permissions on my site. I want to allow Facebook Connect during registration, so I am resigned to a 2-step registration process:

Register as a basic user via Facebook Connect or standard Drupal registration.
Basic user selects the appropriate role.

I will auto-assign the role "basic" upon registration and present a block to all users of the basic role which asks them to select Driver or Owner as their account type. Upon clicking the appropriate link, their user account will be updated with the new role. I can use Rules to remove the "basic" role whenever an account has been saved with one of the other roles.

How can I assign a role using a link displayed in a block?

Thank you.

I solved this by using the Rules module and 2 basic pages. Not a very scalable solution, but works in this limited application.

User registers using Facebook Connect or the core Drupal registration process.
The new user with the "basic" role is redirected (via Rules) to a "select your role" page with links to a "Welcome new driver" page and a "Welcome new owner" page.
Upon viewing the node, "Welcome new driver/owner", with the role "basic" a rule is triggered which sets the desired new role, removes the "basic" role and triggers role-specific welcome email.


Can i get rid of the 'default' site in multisite? I have a multisite (sub directory style), and am wondering if i can delete the default site (sites/default)? I just want to get a 404 if the site doesn't exist, no fallback.

You can leave the default directory in place. Just make sure there is no settings.php file in the default directory, and only the sites/www.yoursite.com directories will be accessed.

When you upgrade core, the default directory will always be replaced and will receive a new copy of default.settings.php, so it makes no sense to delete it.


Why doesn't my custom library load? I am trying to load libraries in my Drupal 8 site, but it does not seem to be working. Here is my library yaml, is this correct? Why can't I load dexp.slides?

dexp.slides
  version: 1.x
  css:
    theme:
      css/plugins/font-awesome/css/font-awesome.min.css: {}
      css/admin.style.css: {}
      css/plugins/rs-plugin/css/settings.css: {}
  js:
    js/dexp.layerslider.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.revolution.min.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.tools.min.js:  {}
  dependencies:
    - core/jquery
    - core/jquery.ui.draggable
    - core/jquery.ui.dropable
    - core/jquery.ui.sortable
    - core/jquery.ui.dialog
    - core/jquery.ui.tab

I am trying the above way but the dependencies are not being loaded.

You are missing a colon after depx-slides:

dexp.slides:
  version: 1.x
  css:
    theme:
      css/plugins/font-awesome/css/font-awesome.min.css: {}
      css/admin.style.css: {}
      css/plugins/rs-plugin/css/settings.css: {}
  js:
    js/dexp.layerslider.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.revolution.min.js:  {}
    js/plugins/rs-plugin/js/jquery.themepunch.tools.min.js:  {}
  dependencies:
    - core/jquery
    - core/jquery.ui.draggable
    - core/jquery.ui.dropable
    - core/jquery.ui.sortable
    - core/jquery.ui.dialog
    - core/jquery.ui.tab

The YAML is pretty strict about format. You can run it through a linter like YAML Lint - that is how I noticed the colon was missing.

After making that change, clear your cache and require your library (either in the info file or by attaching it with #attached or attach_library in a twig file) it should work.

The official docs page has all the info you need about attaching libraries, but the YAML must always be correctly formatted.

That YAML Lint tool, by the way, works for any YAML. If you ever work on a routing, permission or other YAML files, it can check if it is valid or not which is the first step to debugging YAML - simply eyeballing it is not good enough - use the tool that will just tell you. There is an npm package available to run it from command line (I do recommend).


How do I move conditional library includes out of a twig template? I have a javascript library with several separate files which I would like to include only if necessary. I currently determine which need to be included within the twig template.

{{ attach_library('flot_d8/flot') }}
{% if options['xaxis']['mode'] == 'categories' %}
{{ attach_library('flot_d8/categories') }}
{% endif %}

{% if options['selection'] is defined %}
{{ attach_library('flot_d8/selection') }}
{% endif %}

{% if options['pan'] is defined %}
{{ attach_library('flot_d8/navigate') }}
{% endif %}

{% if resizable == true %}
{{ attach_library('flot_d8/resize') }}
{% endif %}

{% if nodiv == false %}

{% endif %}

Is there a better, or alternative way to perform this logic? I would like to override this template in another module and make the simple
 element more complex. However, I would have to copy all the library inclusion logic with it.

Attaching libraries in Drupal 8 should be done by either attaching the #attached attribute to render arrays or by adding them to the info file to be added to all pages.

For example let's say I have a custom form class that needs my custom javascript and/or css files.

class MyForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'my_module/my_library'
    return $form;
  }
}

If you want to attach a library to an element you didn't initiate then you will need to use an alter hook for that specific element.
If you want to attach a library based on other conditions then you can use the hook_page_attachments(array &$attachments) function


How do I get the domain name How do I get the domain name so that I can put an absolute path for images in my theme? I'm developing on a development server and want to move it live eventually.

I can't figure out a way to get the domain.

While $GLOBALS['base_url'] will give you the domain, it really isn't a good idea to use it directly.  URLs should either use url() or file_create_url().  For example,

$path = drupal_get_path('theme', 'MYTHME');

drupal_add_html_head(array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => file_create_url($path . '/images/touch-icon-iphone.png'),
    'rel' => 'apple-touch-icon',
  ),
), 'MYTHME-touch-icon-iphone');

will add the iPhone icon meta to the <head> from the images/ directory from a theme.  Leveraging the API will allow paths to be altered, which is necessary for module like CDN to do their thing.


Hide user's blog link on blog entries I want to hide the user's blog link that appears on blog entries e.g Anonymous's blog

How can I do this in node--blog.tpl.php?

I tried hide($content['author']); but that doesn't seem to work.

In your node--blog.tpl.php add unset ($content['links']['blog']['#links']); instead of hide($content['author']);


Drupal 7: check login password with DB password I'm working on drupal 7, i'm looking for developing customize user log-in module into my site. but facing a problem in that, when we are submit log-in page then password doesn't match with DB password. because drupal not using MD5 encryption method for storing password into it.

So what would be the batter solution for it? how can i achieve my task without fail.?
Please help me, its appreciate.

Thanks.

You can tweak the existing user login form by implementing hook_form_alter or one of its friends (see link). It allows you to add your own password validation functions.

If you don't know which form ID to use, you can add this code to a custom module to get all used form ids printed out:

mymodule_form_alter(&$form, &$form_state, $form_id) {
    dpm($form_id);
}

You need the Devel module, and appropriate permissions to see the output of dpm().

But there's more. You have to think about password changes, password retrieval, account creation, etc. To let users log in (with your own password check) you need to have a valid Drupal user account for every user. It's not enough to just validate the password against your own database. A possibility would be creating the user accounts in the background once the password check was positive.

A completely different approach: Import your existing users into the Drupal users table, and let them know they have to go through password retrieval.


How to add a description to the node title field in form In my Drupal 8 project I tried to find a way to add a description to the title field of a node form by hook_form_alter. Following code(s) did not lead to success:

$form['title']['widget'][0]['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');
$form['title']['widget']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');
$form['title']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');

What is the correct place to define a description for the node title field?

After several trial and errors this is the code working:

$form['title']['widget'][0]['value']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');


How to put a link in my route title? In my custom module amap, I have amap.routing.yml with (among others) this route:

amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title: 'Update Planning'
  requirements:
    _permission: 'edit distribution inscription entities'

I'd like to have a link in the title of the route, something like
Update Planning Click here

Drupal 8 API documentation says in Structure of routes

  _title: The page title for the route. It may differ from the menu link title.
  _title_arguments: Additional arguments for the title text passed along to t().
  _title_context: Additional context information for the title text passed along to t().
  _title_callback: A PHP callable (typically classname::method) returning the page title for the route.

but I don't know how to use it...
How can I do that?

In you routing.yml change _title to _title_callback as below:

amap.distribution_inscription_many_form:
  path: '/amap/editPlanningMany'
  defaults:
    _form: '\Drupal\amap\Form\DistributionInscriptionManyForm'
    _title_callback: '\Drupal\amap\Controller\TitleController::title'
  requirements:
    _permission: 'edit distribution inscription entities'

Create a "TitleController" controller in you amap module unser "src/Controller"

TitleController.php

<?php

namespace Drupal\amap\Controller;

use Drupal\Core\Controller\ControllerBase;

class TitleController extends ControllerBase {

  public function title() {
    return t('Update Planning Click here');
  }

}

Now your title will be callable from the controller and you can give whatever that likes you here.


Module development - integrating custom content types I want to create a module which would need custom content types from the cck module. I know in the .info I can say a dependency is the cck module.

How can I best have the module create the content type? I want this to be easily distributed rather than when I put it on a website I have to also create the content type using cck.

One way is to create an export of a CCK content type to use in the module. For an example of this method see How to create a CCK content type and fields from a module.

Another exported CCK example


Hide comment box from node for Anonymous users I am trying to hide the comment box for anonymous users. Anonymous users should only be able to view the comments. How can I hide the comment form?

The comment module provides a permission, "Post comments" (post comments). Before using any code option, you should remove that permission for anonymous users.


plupload submit routine is not called I'm having a problem with the plupload module.
The normal upload works perfect, the files are stored in sites\default\files\tmp.
I'd like to "walk" through the uploaded files using the hook_submit.
It seems, this hook is not called, when pressing start upload on the plupload form.
I'm using almost the same hook_submit as the test form in the plupload.module.

What am I doing wrong?

Here is my form definition:

 $form['my_element'] = array(
'#type' => 'plupload',
'#title' => t('Upload files'),
'#description' => t('This multi-upload widget uses Plupload library.'),
'#upload_validators' => array(
  'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'),
  'my_custom_file_validator' => array('some validation criteria'),
),
'#plupload_settings' => array(
  'runtimes' => 'flash,html4',
  'url' => url('plupload-handle-uploads', array('query' => array('plupload_token' => drupal_get_token('plupload-handle-uploads')))),
  'max_file_size' => file_upload_max_size() . 'b',
  'chunk_size' => '1mb',
  'unique_names' => TRUE,
  'flash_swf_url' => file_create_url('sites/all/libraries/plupload/js/plupload.flash.swf'),
  'silverlight_xap_url' => file_create_url('sites/all/libraries/plupload/js/plupload.silverlight.xap')
),
);

Here is the submit function:

function get_upload_form_submit($form_id, &$form_state) {
//handle file uploading
global $user;

$saved_files = array(); //Array to capture file objects
$scheme = variable_get('file_default_scheme', 'public') . '://';
$directoryname = 'imagebank'; // Directory where images are collected
$imagebankpath = $scheme . $directoryname;
dpm($imagebankpath);
file_prepare_directory($imagebankpath, FILE_CREATE_DIRECTORY); // Create the folder if   it doesn't exist
// We can't use file_save_upload() because of
// http://www.jacobsingh.name/content/tight-coupling-no-not
// file_uri_to_object();
foreach ($form_state['values']['uploadfiles'] as $uploaded_file) {
if ($uploaded_file['status'] == 'done') {
  $source = $uploaded_file['tmppath'];
  $destination = file_stream_wrapper_uri_normalize($imagebankpath .'/'. $uploaded_file['name']);
  // Rename it to its original name, and put it in its final home.
  // Note - not using file_move here because if we call file_get_mime
  // (in file_uri_to_object) while it has a .tmp extension, it horks.
  $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
  $file = plupload_file_uri_to_object($destination);
  file_save($file);
  $saved_files[] = $file;
}
else {
  form_set_error('uploadfiles', "Upload of {$uploaded_file['name']} failed");
}
}
}

Did I forgot anything?
Thx.

The submit handler is not executed when clicking on the start upload of the Plupload widget form, this only executes the ajax upload of the files (and the file validators).

To have a submit callback, and handle the logic of the uploaded files (i.e.: move files to a certain directory), you should add a button to the form.

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

The uploaded files are stored in the form_state under $form_state['values']['my_element'] (the name of your Plupload form field)

Update #1

Some sample code to trigger the form submit callback once the upload of the files is finished by the Plupload uploader. Basically what you need:

A submit button attached to the form to have a submit callback (which handles the uploaded files)
A custom javascript which intercepts the UploadComplete event triggered by the Plupload component
On the UploadComplete interception, trigger a click on the submit button

function YOURMODULE_form($form, &$form_state)
{
    // your form elements with plupload form element

    // add a submit button
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save file(s)'),
        '#submit' => array('YOURMODULE_form_submit'),
        '#attributes' => array(
            'class' => array('file-upload-submit'),
        ),
    );

    // attach the custom js to the form
    $form['#attached'] = array(
        'js' => array(
            drupal_get_path('module', 'YOURMODULE') . '/js/YOURMODULE.js',
        ),
    );

    return $form
}

function YOURMODULE_form_submit($form, &$form_state)
{
    // put uploaded files in a 'uploads' directory
    $directory = sprintf('%s://%s',
        variable_get('file_default_scheme', 'public'), 'uploads');

    // be sure directory exists (and create it)
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

    // loop through each uploaded file
    $saved_files = array();
    foreach ($form_state['values']['files'] as $file) {
        if ($file['status'] !== 'done') {
            //handle error on upload fail
            continue;
        }

        // move files from tmp directory to defined directory
        $destination = file_unmanaged_move(
            $file['tmppath'],
            file_stream_wrapper_uri_normalize($directory . '/' . $file['name']),
            FILE_EXISTS_RENAME
        );

        $saved_file = plupload_file_uri_to_object($destination);
        file_save($saved_file);

        $saved_files[] = $saved_file;
    }

    // keep saved files in form state to be able to stuff afterwards (if needed)
    $form_state['saved_files'] = $saved_files;

    drupal_set_message(t('Files have been uploaded and saved.'));
}

The javascript (under js/YOURMODULE.js)

(function ($) {
    Drupal.behaviors.YOURMODULE = {
        context: null,
        attach: function (context) {
            var that = this,
                uploader = $('.plupload-element', context).pluploadQueue();

            this.context = context;

            if (!uploader) {
                return false;
            }

            uploader.bind('FilesAdded', function() {
                // start upload automatically once files have been added to queue
                that.start();
            });

            uploader.bind('UploadComplete', function() {
                // trigger click on submit button to submit form once upload completed
                that.complete();
            });

            return this;
        },
        start: function() {
            $('.file-upload-submit', this.context)
                .attr('disabled', 'disabled');
        },
        complete: function() {
            $('.file-upload-submit', this.context)
                .removeAttr('disabled')
                .click();
        }
    };

})(jQuery);


Routing in Drupal 8 for basic pages I've just begun the transition process from D7 to D8.  I installed D8 and added a basic page w/ a menu link.  I then began to explore the new D8 routing system and expected to find a .yml file that contained information about where to find the added page but I don't see it. This is not a added module so it doesn't have a moduleName.routing.yml.

I'm looking for a conceptual description of why this does or doesn't follow the new .yml convention.

Node routes are declared using what is known as a route provider.
The node route provider class is \Drupal\node\Entity\NodeRouteProvider and it is declared in the annotation of the node class:

/*
 * @ContentEntityType(
 *   id = "node",
 *   label = @Translation("Content"),
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     ...
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
 *     ...
 */
class Node extends ContentEntityBase implements NodeInterface {
//  ...
}


Can I show an image in place of a Drupal 6 message? I have a form, that upon completion, goes back to the page it was called from and displays a message of success when everything is done. Is it possible to just display an image on that same page, or do I have to redirect to a new page to show the form submission success image?

There is a way to do this.

One problem here is that the confirmation message is just that, a confirmation which is unrelated to any context.

What you could do is to use jQuery to react to the string of the message is being put out ... so if it's something along the lines of: "Success, your message was sent" - which you "could" assign a string-match on and create a reaction to it. Most likely you would append/prepend a container with a custom confirmation message or image at this point. This would involve a bit of a work-around however (Assign a .js script to handle it -  which in Drupal means editing your template.php file).

I usually opt for the confirmation page either way. Users also often don't see the little confirmation message on the same page and a dedicated confirmation page can go a long way in keeping a user on your site - you could for instance use this to display a range of your latest blog entires/products etc. as a block on that page or even have an ad block to collect a few clicks, depending on the kind of site you're working on atm.


Override argument passed by URL I think I must be missing something basic. I have a template that is usually called via a URL but I also want to be able to call it manually using theme()

/**
 * Implements hook_menu().
 */
function signup_menu() {
  $items = array();

  $items['list/signup/success/%'] = array(
    'title' => 'Sign-up Successful',
    'page callback' => 'theme',
    'page arguments' => array(3),
    'page arguments' => array('signup_success'),
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function signup_theme() {
  return array(
      'signup_success' => array(
      'arguments' => array('node' => NULL),
      'template' => 'signup-success',
    )
  );
}

function signup_preprocess_signup_success(&$variables) {
  $signup = signup_record(arg(3));
  $variables['signup'] = $signup;
}

How do I override the argument that is usually passed through the URL? So I can call it like this:

theme('signup_success', $signup-id);

The preprocess function only ever takes the argument that comes from the current URL which is incorrect.

Definitely you will have to change your preprocess hook to replace arg(3) that is hard coding it in an aspect and definitely not make it suitable for manual call.

Can you please investigate $variables for the value being passed as argument to theme()? I hope you will get it there.


How to render a node with different DS View modes depending on taxonomy term? I have a Content type containing a term reference field and some other fields. I have created 3 Display suite view modes for this content type. I want each node of this content type to be displayed in one of the defined DS view modes depending on the value of the term reference field of that node.

You can switch view modes using hook_entity_view_mode_alter. In pseudo code, something like:

function your_module_entity_view_mode_alter(&$view_mode, $context) {

    //check that this is a node of typex, and check current view mode
    if ($context['entity_type'] == 'node' && $context['entity']->type == 'typex' && $view_mode == 'full') {

      //check current taxonomy terms
      [code]

      //code to set view mode
      if (condition based on taxonomy terms) {
        $view_mode = 'new_view_mode';
      }
    }
}


How do I make an external URL open on a new tab? When I try putting a link like <a href="http://www.example.com/" target="_blank"> on the link path, I get the following error message:

  The path '//www.example.com/" target="_blank">' is either invalid or you do not have access to it.

Is there a way to have the external URL opened in a new tab?

If you can target your menu tag with jquery using its ID you can put something like this in an JS file that you'll add in your theme via your_theme.info

Drupal.behaviors.externalMenu = function(context, settings) {
    $('#menu_id').attr('target', '_blank');
};

Or you can use the Menu attributes module.


How to set order of Grouping Field in Format Settings I'm on D7. I have a taxonomy "projects". A project can be "ongoing" or "completed. I currently have a view that get's all projects (projects are a taxonomy/vocabulary). The "ongoing" and "completed" are project types which are also a taxonomy/vocabulary.

In the view, I set Grouping field Nr.1 to Taxonomy Term: Project Type

I want to make sure that "ongoing" is above "completed". How can I do that? Somehow the order changed from "ongoing, completed" to "completed, ongoign" after I updated an ongoing project to completed.

The order of the taxonomy terms seem to not matter.

First, you can set the weight of the Project Type terms in the vocabulary.
Then you have to create the following relationship:

Entity Reference: Referenced Entity
A bridge to the Taxonomy term entity that is referenced via field_project_type

Then, add a Sort Criterion (first) Taxonomy term: Weight using the above relationship.


When exporting .sql via phpMyAdmin do you need to include cache tables? So I built the D7 site on one server and then moved it to other server and I noticed that .sql size is 8MB in total. I then exported .sql without any cache tables, including cache_* files like cache_block, cache_views and etc. I skipped all tables starting with cache_ and the total .sql size was below 2MB!

So when moving site from one server to other do I need to include cache tables when exporting the .sql or not? Because looks like those cache tables takes 80% of .sql size. And as I understand cache is something temporal?

I came up with this question after moving site to new server and I noticed that tmp folder has 100% copies of images that I uploaded to nodes, but those original images are held in separate files/ folder. So now I got those original images 50MB and copies of those images in tmp/ dir and its also 50MB. So I get extra 50MB taken. I was thinking maybe its because I moved the site with all caches without running cron and etc. and maybe somehow those images in the tmp dir got lost and forgotten by Drupal system or something? I now removed those from tmp dir and it seems to be all working fine.

Strange, can't really understand that.

You can typically skip the data in all of the cache tables.  That is temporary data that Drupal will recreate when as needed.  Basically, the cache tables store data the Drupal creates so that it doesn't need to create it the next time.

You can also usually skip the data in the watchdog table if you don't need the system logs.  Depending on your situation, you may also be able to skip sessions.

There are a few others you can skip (like flood), but they don't usually don't have much data in them in most situations.

Just remember that you want to back up the table structure (ie, the CREATE statements) and just skip the data.

The Backup and Migrate will take care of most of this for you.  drush sql-dump can skip table, data too.

Normally, I just transfer everything when moving between servers.  I just clear cache as part of the restoration process.  I would rather have a bigger file than have the chance of missing something.


Can't change quantity of line item with rules I created a rule that checks for the quantity of a product while adding to cart and while proceeding to the second step of checking out.  The action sends a warning message to the site that says you can't have over one qty of the 'gift card' product type and is also supposed to set the quantity back to 1.  The problem is that while the message appears when it is supposed to, the quantity is not being set back to 1 at any point.  I made sure that I also save the cart after changing quantity as well.

Here is the rule export:

{ "rules_1_gift_card_per_cart" : {
    "LABEL" : "1 Gift Card per cart",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart", "commerce_rules_extra" ],
    "ON" : [ "commerce_cart_product_add", "line_item_quantity_changed" ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "gift_certificate" } },
      { "AND" : [
          { "data_is" : {
              "data" : [ "commerce-line-item:quantity" ],
              "op" : "\u003E",
              "value" : "1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : {
                "data" : [ "commerce-line-item:quantity" ],
                "op" : "\u003E",
                "value" : "1"
              }
            },
            "DO" : [
              { "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },
              { "entity_save" : { "data" : [ "commerce-order" ] } },
              { "drupal_message" : { "message" : "Only one gift card per order.", "type" : "warning" } }
            ]
          }
        ]
      }
    ]
  }
}

EDIT: I dpm($commerce_line_item) in the action as well and it actually says the quantity is 1 while the cart display is still showing 2, though I believe this is only per item qty in the cart.

The total of the order is still being updated when the gift card quantity is being increased.

EDIT 2: I created a custom rules action to manually update the quantity in the commerce_line_item table which also does not seem to work:

function commerce_giftcards_action_change_qty_one($current_order, $current_line_item) {
  dpm('Current Order ID: ' . $current_order->order_number);
  dpm('Updated Line Item ID: ' . $current_line_item->line_item_id);
  dpm('Updated Line Item Type: ' . $current_line_item->type);

  db_update('commerce_line_item')
    ->fields(array('quantity' => '1.00'))
    ->condition('line_item_id', $current_line_item->line_item_id, '=')
    ->execute();

}

The correct fields are printing in the messages but the database is not updating unless I am going back to the product's page and adding another to the cart.  It only keeps the quantity at 1 if I hit add to cart more than once.  If I change the quantity of the item on the cart page it still increases the quantity in the database while also displaying the message that says only 1 qty of that item is allowed.

I played around with the rules actions and got it to work with these settings & the function I created to manually update the table:

    { "rules_1_gift_card_per_cart" : {
    "LABEL" : "1 Gift Card per cart",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "rules",
      "rules_conditional",
      "commerce_giftcards",
      "commerce_cart",
      "commerce_rules_extra",
      "entity"
    ],
    "ON" : [
      "commerce_cart_product_add",
      "line_item_quantity_changed",
      "commerce_line_item_update"
    ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "gift_certificate" } },
      { "AND" : [] },
      { "data_is" : {
          "data" : [ "commerce-line-item:quantity" ],
          "op" : "\u003E",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : {
                "data" : [ "commerce-line-item:quantity" ],
                "op" : "\u003E",
                "value" : "1"
              }
            },
            "DO" : [
              { "data_set" : { "data" : [ "commerce-line-item:quantity" ], "value" : "1" } },
              { "drupal_message" : {
                  "message" : "Only one gift card per order.",
                  "type" : "warning",
                  "repeat" : 0
                }
              },
              { "commerce_giftcards_action_change_qty_one" : {
                  "order" : [ "commerce-line-item:order" ],
                  "line_item" : [ "commerce-line-item" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Drupal Views to Display Fields for Each Nodes of One Content Type I have a Content type which has Term reference type of fields called Tags and Categories and a default field like Body (Long text and summary).

What I want to be able to do if possible is to have a View display these fields such that when this Content type is viewed, Tags and Categories are brought up by a View which will list the values in that field specific to that node, and any other field will be brought up the default way (through Manage Displays).

I figured that since that Tags and Categories are fields I didn't want to be visible, I set them to Hidden in Manage Display. So at least this part is done.

As for making Categories and Tags appear as a View in a Block, is it possible to do this by using Views Relationships and Contextual Filters? If so, how?

Here's a little graphic to help you visualize what I'm trying to do"

http://i.imgur.com/Rn5ukNn.png

Any help is appreciated. Thanks in advance!

There are a couple of ways to this using Views. Chances are that you will have to visit the display settings of the content type to hide its content so that it does not show duplicated.

Solution 1. Create a block for each section of the page you want to relocate using Views using the argument or contextual filter so that the block use the node ID to show the right content in the right page. Then enable the blocks and make them visible by content type and you can play with the position of the block using CSS and/or the module block class.

Solution 2. Use the module EVA that it will let you create an view attachment to the node content type entity and that you can re-arrange like any other field in the content type display settings screen. The rest of the setup is similar to the way you created the blocks in solution 1.

Solution 3. You don't need to use views at all, just CSS and you are good. Reposition the fields using the content type display manager make the tags field first, then the body and last the category. Since each field will have a wrap div then use a simple "float", "with" and "margin" css to accomodate the content.

CSS Example (classes are not real)

.div-wrap-for-tags {float:left;margin-right:20px;width:200px;}
.div-wrap-for-body {float:left;width:400px;}
.div-wrap-for-category {clear:both;}


How to normalize / resolve membership ID to all account UID per group_content I'm trying to add the owner's membership to every GroupContent. By default ownership is only identified by the Account ID.

It seems a Normalizer and/or custom resolver is necessary. Beyond my struggles to get the correct dependency injection to add my serialization service to my controller, I'm not even sure if this is possible since it seems the $context variable never includes anything related to the URL or parent entity (Group).

So far, I'm basically parsing the group's ID from $_SERVER['REQUEST_URI'] and then SELECT id as memberid from group_content_field_data where type = 'groups-group_membership' AND entity_id = :uid AND gid = :gid.

Could some caching making $_SERVER['REQUEST_URI'] unreliable from within a Normalizer?
How can I add normalize GroupContent to include both the owner's account ID and membership id?

I was using extending Drupal\serialization\Normalizer\FieldItemNormalizer. I added this service extending
 Drupal\serialization\Normalizer\ContentEntityNormalizer to get the group id from group_content

  serializer.normalizer.group_content:
    class: Drupal\tam_api\Normalizer\GroupContentNormalizer
    arguments: ['@entity.manager']
    tags:
      - { name: normalizer, priority: 8 }

<?php
namespace Drupal\tam_api\Normalizer;

use Drupal\group\Entity\Group;
use Drupal\group\Entity\GroupContent;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;

class GroupContentNormalizer extends ContentEntityNormalizer implements NormalizerInterface {

  protected $supportedInterfaceOrClass = 'Drupal\group\Entity\GroupContent';
  const FORMAT = 'json';

  public function normalize($entity, $format = NULL, array $context = []) {

    $attributes = parent::normalize($entity, $format, $context);
    $gid = $attributes['gid'][0]['target_id'];

    $connection = \Drupal::database();
    $sql = "SELECT G.id as memberid, G.label, F.field_name_value, P.field_headshot_target_id as fid
            FROM group_content_field_data G LEFT JOIN group_content__field_name F
            ON F.entity_id = G.id
            LEFT JOIN group_content__field_headshot P
            ON P.entity_id = G.id
            WHERE G.type = 'groups-group_membership' AND P.deleted = 0 AND F.deleted = 0
            AND G.entity_id = :uid AND G.gid = :gid";

    $fields = ['uid', 'field_leaders', 'field_editors']; // my fields that need the membership data
    foreach($fields as $field_name) {
      if (isset($attributes[$field_name])) {
        foreach($attributes[$field_name] as &$entry) {
          $uid = $entry['target_id'];
          $membership =  $connection->query($sql, array(':uid'=>$uid, ':gid'=>$gid))->fetchAssoc();
          $entry['target_gc'] = intVal($membership['memberid']);
          if (!empty($membership['field_name_value'])) {
            $entry['target_label'] = $membership['field_name_value'];
          } else {
            $entry['target_label'] .= ' FALLBACK';
          }
          if (!empty($membership['fid'])) {
            $file = \Drupal\file\Entity\File::load($membership['fid']);
            if ($file->getSize() > 600000) {
              $entry['url'] = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($file->getFileUri());
            } else {
              $entry['url'] = $file->url('canonical');
            }
          }
        }
      }
    }

    return $attributes;
  }

  public function supportsNormalization($data, $format = NULL) {
    return $format === static::FORMAT && $data instanceof \Drupal\group\Entity\GroupContent;
  }

}


"Global: Custom text" field translation Is it possible to translate this type of view field, Or use t() in this field for single words?
I'm using the Internationalization and the Internationalization Views modules, but I can't translate these fields.

In Drupal 8 and 9, use t ( or trans) filter in twig element in your Global: Custom text”.
for example, create a Global: custom text field and paste
 {{ 'this text will be available in translate interface'|t }}

Ref for reading more: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/filters-modifying-variables-in-twig-templates


Migrate content of cck fields from drupal 5 to 7 I need to transfer the content of a specific content type with bunch of textfield cck's to new D7 website, the thing is I found lots of ways to do such thing over the internet, I want to know what's the best and easiest and fastest way to do so.

I'm migrating from drupal 5 to 7.

Once I had a same problem and after couple of hours testing/working with couple of approaches I figured out that the best way to deal with this is using views bonus pack module to get a CSV export file:

  This group of modules is sort of a recipe module that makes things
  easier by showing how to integrate some other modules as well as
  providing miscellaneous features that aren't distributed by Views
  itself. Sometimes these modules are only base recipes that will need
  to be themed and spiced up to fit your needs so be creative!

and import it via feeds module:

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


How to add tags to View-created RSS feed? How to add tags to View-created RSS feed?

I have added some tags to each of my articles, but the RSS feed generated by Views does not show the tags.

You can include them in the fields for the view display. If they are taxonomy terms, you can add them from the views fields list.


Content REST view does not work because of moderation states I've created a simple view using the REST export to export all published content in JSON format, but I get this error:

Symfony\Component\Routing\Exception\RouteNotFoundException:
    Route "entity.moderation_state.canonical" does not exist.
    in Drupal\Core\Routing\RouteProvider->getRouteByName()
    (line 191 of core/lib/Drupal/Core/Routing/RouteProvider.php).

Drupal\Core\Routing\UrlGenerator->getRoute('entity.moderation_state.canonical') (Line: 285)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('entity.moderation_state.canonical', Array, Array, 1) (Line: 110)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('entity.moderation_state.canonical', Array, Array, ) (Line: 754)
Drupal\Core\Url->toString() (Line: 291)

Moderation states have indeed been added, but I have no idea why that's throwing this kind of error...

The route is not in core. Probably it is in a contrib or custom module. You have to search for a *.routing.yml file, where it is defined and then look for an error in the yml file and then clear the cache.

You can get a complete list of all routes with drupal console:

drupal route:debug


Exposed Filter Alteration I have a custom content type that has a date field.
I have created a view with a exposed filter. The issue i have is that the exposed filter is in the form Y-M-D and i wan it to be just M-D. I have altered the exposed form, setup the #format to M-D and now the Y field is hidden. But it's still trying to validate it. and nothing shows up when you select values in the filter.

i have created a custom module.

function date_filter_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-birthdays-sliders-panel-pane-1') {
  $form['field_birthday_date_value']['value']['#date_format'] = 'm-d';
}
}

And query alter looks like:

function date_filter_views_query_alter(&$view, &$query) {
  if ($view->name == 'birthdays_sliders') {
    if (!empty($query->where[1]['conditions'][2]['field'])) {
    $query->where[1]['conditions'][2]['field'] = "DATE_FORMAT(field_data_field_birthday_date.field_birthday_date_value,
     '%m-%d') = :field_data_field_birthday_date_field_birthday_date_value";
}
  }
}


I need to unset terms from the drop down I'm writing a module to unset taxonomy terms using D6 hook_form_alter(). The object is to only present the current user terms which they have created themselves.

The trouble is that I don't know which variables to alter. I'm thinking it should be something like $form['taxonomy']['2']['#options'], but I cannot see a path in a DSM print_r($form).

I have gone through hierarchical_select.module again and again, but can't work out whether I need to be amending the results of $storage, $elements, #names, $hsid or any of the other variables; I am not sure about which hook to use too.

I just need to know how to apply the results of this db_query() in my custom module code which you can see on http://pastebin.com/RbwKB0rt.

Can anybody please help?

I think I need more information.

In general, I believe you set the #default_value on your dependent form element to be the parent element, and also set the #ajax callback and wrapper on the parent. Check out the Ajax example and the form API reference.