How to have multiple users in a user reference field I'm using Drupal 8.

Can I have multiple users by comma separating each users? When I was doing by this way, after I input a comma, I can choose another user again. But after I submit it. Only the last user I have chose that had been saved (only 1 value).

If I set the field as "Allowed number of values to Unlimit or a number". There will be many user reference text box. I only want one user reference text box and have multiple users with comma separating. How to do it?

Yes, you can do that.
You need to select "Autocomplete (Tags style)" as the widget you use in the Form display.

After you have done that, you can use commas to add multiple users in the same widget (provided you have set cardinality to > 1).


Can you create a script to programatically run update.php on multiple drupal sites We have a multi-site install that uses the same core files but different databases.  As of right now, we have over 40 sites. When I do module and core upgrades, I have to login to each site and manually run update.php.

Is there a way to automate this process so that I do not have to spend so much time logging into every multisite, run update.php and clear the cache?  If so, what is the exact command to run update.php? I've tried wget and that doesn't seem to work.

I've written a similar script on a 50+ site multisite install. You want to use the command line powertool drush for this, and then run the command

drush updb

from a shell script, ex:

cd /var/www/site1-environment/
drush updb --uri=http://site1.com
cd /var/www/site2-environment/
drush updb --uri=http://site2.com
... etc

Of course if all of these sites are in the same multi-site structure than you won't need to repeat the cd command in your shell script.


How to access an external MySQL database in a view if SQLite support is not installed? I would like to display other MySQL database by Views, and having the similar situation as this question. Except, I'm not able to enable the "SQLite", because I have no control on the server end. While adding the data block on New Forena Report, I got the message "PDO driver support for sqlite not installed", as shown in the screenprint below:

My question: Is it possible to display other MySQL data by Views without installing and enabling support for SQLite? What are my other options?

===== Updated June 6, 2015 at 12:45pm - Data block format ====
Below are the screenshots where I fix the Data Block format for data column with double quote.

screenshot 1 - While you edit the Forena Reports, you actually can configure each column(block) by left click the gear as screenshot from blow.

screenshot 2 - Choosing the "drupal_text_format" format will remove double quotes

The Forena module is shipped with 3 types of "sample" reports:

Reports about your own Drupal database (the drupal/* 'data blocks' in your screenprint), typically in MySQL database format.
Forena tutorials, which are actually also delivered in the format of "Reports" which refer to datablocks in XML format (the forena_help/* 'data blocks' in your screenprint).
Reports about some Sample database which is also delivered with Forena, in the format of an SQLite database (none of these Sample/* 'data blocks' are shown in your screenprint, as they are normally shown when PDO driver support for SQLite is available).

So the error shown in your screenprint is to inform you about something like "sorry, there is no SQLite support available here, so I can't handle the Sample database (which is in SQLite format)".

If however you have MySQL support available on the server where your MySQL data resides (eg: if it's on the same server as where Drupal resides, but just another MySQL database), then you should be able to use Forena for creating reports about that MySQL database. To access that MySQL database, you need to define (within Forena admin) a Data Connection to that MySQL database and 1 or more data blocks (SQL queries). And from then on you should be able to build your custom reports about that MySQL database, e.g. using the WYSIWYG report writer that comes with Forena.

Note: if you're interested in trying out Forena, use SimplyTest.Me to do so. If you do, and after you login to such site, you'll also get the same PDO driver support for sqlite not installed error message, after you visit the "/reports" link for the first time (or use the "My Reports" menu option in the Navigation menu). That error is shown because support for SQLite is not enabled on SimplyTest.Me. You get a similar error message if you visit the reports/sample.toc link (because the sample reports and graphs are using an SQLite database). However, reports such as these run just fine (they don't require SQLite):

/reports/help.toc.
/reports/drupaladmin.enabled_contributions (by the way: shows all enabled modules in such simplytest.me setup ...).


Hiding an image field based on theme in Drupal 7 I want to hide an image field(field_image) of a node when a different theme is selected.

How can I do it?

I'm not able to find any sample code in internet but I know it can be done both in tpl.php and template.php files.

It can be done in node.tpl.php

hide($content['field_image']);

or in hook_preprocess_node

hide($variables['content']['field_image']);

It works with views as well if you are using content row plugin.
For fields you have to override views-view-fields.tpl.php and remove image field from $fields variable.

unset($fields['field_image']);

Also take look at this modules:

https://drupal.org/project/cs_adaptive_image

https://drupal.org/project/adaptive_image


Select the same number of results for every group I have views where I select nodes and group all results in 3 groups by field. When I select for example a limit to 30 I get results but with the different count in every group (for example 20/7/3). What I can use to select for example 10 most relevant results in every group. I can do it with query alter or maybe need to create some plugin?

Yes, query alter helps.  Views flexible pager might serve as an inspiration for the code changes. Do contribute back if you find a solution, it has been requested before.

This problem is usually "solved" by creating different Views displays, as many as you have Groups, and filter each field value in its own display. Then show all 3 displays one after another and use styling to make them seem like they're from the same Views.


Display message on initial login only once without a module What method is there to show a message on a user that just logged into the site without using a module? I know rules can do it, but I dont want to install a module just to do that. Is there some type of indicator variable that gets set upon initial login?

I propose you to have a look at this: hook_user_login, it fires exact on user log-in. A sample code is provided on its documentation page ready to be configured and used.


Daily cron job send email Webform submissions file create an automatic excel extract of all requests and send it a specific email address every day.

How would I do this? Is there any existing Module to do this in Drupal 7?

You could create a view that shows the days submissions, use the data export module to convert it to excel, filter it by day (currrent day). Use rules module to send an email (not sure how to attach it, may need to send link). Not sure if this would work exactly how you need it.


Token for first media Image in the body I need to display an image url in a metatag item.  The problem is on one of my node types, the editors only upload an image as a media entity inside the body.

What is the best way to handle this?

I feel like there is a better way but I just quickly created a custom token.

<?php

/**
 * @file
 * Node custom functionality.
 */

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_token_info().
 */
function my_custom_module_token_info() {
  $type = [
    'name' => t('My Custom'),
    'description' => t('My Custom Tokens.'),
    'needs-data' => 'node',
  ];

  $node['body_first_media_image_url'] = [
    'name' => t("Body First Media Image Url"),
    'description' => t("Body's first media image url."),
  ];

  return [
    'types' => ['node' => $type],
    'tokens' => ['node' => $node],
  ];
}

/**
 * Implements hook_tokens().
 */
function my_custom_module_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node'])) {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // The first media item embedded in body.
        case 'body_first_media_image_url':
          $dom = new DOMDocument();
          @$dom->loadHTML($node->body->value);
          $embedEntities = $dom->getElementsByTagName('drupal-entity');
          if ($embedEntities->length > 0) {
            $uuid = $embedEntities->item(0)->getAttribute('data-entity-uuid');
            $media = \Drupal::entityManager()->loadEntityByUuid('media', $uuid);
            $url = ImageStyle::load('extra_large')->buildUrl($media->image[0]->entity->uri->value);
            $replacements[$original] = $url;
          }
          break;
      }
    }

  }

  return $replacements;
}


Custom Access check for module route I'm working on module that should behave as API endpoint.

I created Controller which handler POST & GET requests from external system, but I need to add user authentication so only authenticated user can acccess these endpoints.

My mymodule.routing.yml:

mymodule.show_content:
  path: 'api/getContent'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ContentController::getContent'
    _format: hal_json
  requirements:
    _method: 'POST'
    _custom_access_check: 'TRUE'

My mymodule/src/Access/CustomAccessCheck.php:

class CustomAccessCheck implements AccessInterface
{
    public function access(AccountInterface $account)
    {
        return ($account->hasPermission('access content')) ? AccessResult::allowed() : AccessResult::forbidden();
    }
}

My mymodule.services.yml:

  mymodule.custom_access_check:
    class: Drupal\mymodule\Access\CustomAccessCheck
    arguments: ['@current_user']
    tags:
      - { name: access_check, applies_to: _custom_access_check }

I created a user called REST with REST role. I gave him 'access content' permission and tried to make request with Postman using POST method and following headers:

{
    Content-Type: application/hal+json,
    Authorization: Basic <base64_encoded user:pass>
    X-CSRF-Token: token obtained from <page_url>/rest/session/token
}

When I make request with admin user, I see in recent logs, that admin access the route /api/getContent but access was denied. When I use my REST user it logs as anonymous user. Even when I log the status of authentication inside CustomAccessCheck::access function I see that user is authenticated with TRUE

I need to keep this authentication separated (out of controller, in service or something) because I need to authenticate every request (re-use auth) so only internal users can use API (and not everyone with URL). I don't understand what is missing and why only my admin user is recognized by drupal and the REST user not.

What happens if you replace:

requirements:
  _method: 'POST'
  _custom_access_check: 'TRUE'

With:

requirements:
  _method: 'POST'
  _permission: 'access content'

Any then remove your CustomAccessCheck code


hook_menu() with enabled languages I'm trying to implement hook_menu() in my module. The problem is, it doesn't add the menu item for English while it does for Turkish. I'm guessing it has something to do with title arguments, but I can't be sure. Below is my code:

function suweb_agi_menu() {
  global $language;
  $lang = $language->language;
  $items = [];
  $items['agi'] = [
    'title' => ($lang == 'tr')?'AGİ (Aile Geçim İndirimi)':'AGİ (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['suweb_agi_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

What am I doing wrong?

The following code does what you seem to need (screenshots attached). The following modules need to be activated:

i18n_menu (part of the i18n)

Further configuration:

I added a new language (tr) and set language detection to "Determine the language from the URL (Path prefix or domain)."
I added a new menu with machine name (menu-sol-menu) and set the translation mode to "Translate and Localize". Also added the new menu as a block to the header region of the theme.
Added the following code in a custom module and activated it.

function agi_menu() {
  $items = [];
  $items['agi'] = [
    'title' => 'AGI (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['node_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

I visited the menu admin page and saw that a new menu item was added:

I checked the language option for that new menu item, it was set to neutral.

I visited the home page of my drupal instance and checked that the menu item appears, for both english (default language) and turkish, using the URL to define the current language.

Finally, I looked in the translate interface for the title of the menu item.

Conclusion: The provided code with the described configuration works as expected by the OP.

Good luck!

N.B.: Especially for the 'title' and 'title callback' properties, the documentation is very clear about how to use them in a multilingual setting

  "title": Required. The untranslated title of the menu item. "title
  callback": Function to generate the title; defaults to t(). If you
  require only the raw string to be output, set this to FALSE.


How do I change cardinality (delta) of nodes? I have a content type, this content type has a Field Collection with cardinality(delta) value 1.

I want to alter it dynamically, when the node add form is rendered.
Each node add form has it different cardinality(delta) value.

Please any one help me to solve it in Drupal 7.

You can use form_alter hook to do it:

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    // Alter your field here:
    // $form['field_collection'][LANGUAGE_NONE][0]['value'];
  }
}

To debug form output, you can install Devel module and use dpm() function.

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}


How to modify .htaccess to serve brotli compressed static assets over gziped ones? I'm trying to use brotli compressed static assets with Advanced CSS/JS Aggregation as detailed here, https://www.drupal.org/node/2773807. The assets are created as they should be, but they're never served because the .htaccess file doesn't know to do that.

lyncd.com has a short walkthrough, https://lyncd.com/2015/11/brotli-support-apache/, but I haven't been able to munge their code into Drupal's.

Here' the lyncd.com example:

    FileETag None

    <Files *.js.gz>
      AddType "text/javascript" .gz
      AddEncoding gzip .gz
    </Files>
    <Files *.css.gz>
      AddType "text/css" .gz
      AddEncoding gzip .gz
    </Files>

    <Files *.js.br>
      AddType "text/javascript" .br
      AddEncoding br .br
    </Files>
    <Files *.css.br>
      AddType "text/css" .br
      AddEncoding br .br
    </Files>

    RewriteEngine On

    RewriteCond %{HTTP:Accept-Encoding} br
    RewriteCond %{REQUEST_FILENAME}.br -f
    RewriteRule ^(.*)$ $1.br [L]

    RewriteCond %{HTTP:Accept-Encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -f
    RewriteRule ^(.*)$ $1.gz [L]

And here's the 7.50 .htaccess bit:

    # Rules to correctly serve gzip compressed CSS and JS files.
    # Requires both mod_rewrite and mod_headers to be enabled.
    <IfModule mod_headers.c>
      # Serve gzip compressed CSS files if they exist and the client accepts gzip.
      RewriteCond %{HTTP:Accept-encoding} gzip
      RewriteCond %{REQUEST_FILENAME}\.gz -s
      RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

      # Serve gzip compressed JS files if they exist and the client accepts gzip.
      RewriteCond %{HTTP:Accept-encoding} gzip
      RewriteCond %{REQUEST_FILENAME}\.gz -s
      RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

      # Serve correct content types, and prevent mod_deflate double gzip.
      RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
      RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

      <FilesMatch "(\.js\.gz|\.css\.gz)$">
        # Serve correct encoding type.
        Header set Content-Encoding gzip
        # Force proxies to cache gzipped & non-gzipped css/js files separately.
        Header append Vary Accept-Encoding
      </FilesMatch>
    </IfModule>

With your powers combined we can make the web about 20% cooler!

Give this a try

# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
  # Serve brotli compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.css $1\.css\.br [QSA]

  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

  # Serve brotli compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.js $1\.js\.br [QSA]

  # Serve gzip compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

  # Serve correct content types, and prevent mod_deflate double gzip.
  RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
  RewriteRule \.css\.br$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.br$ - [T=text/javascript,E=no-gzip:1]

  <FilesMatch "(\.js\.gz|\.css\.gz)$">
    # Serve correct encoding type.
    Header set Content-Encoding gzip
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
  <FilesMatch "(\.js\.br|\.css\.br)$">
    # Serve correct encoding type.
    Header set Content-Encoding br
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
</IfModule>


admin approval required for specific roles registered using profile2_regpath I am using profile2_regpath for registrations .

I have 3 roles. Students, Centers and Organisations. Is it possible to activate the users which are registered for Student role without admin approval ?

The users who registered for centers or organizations role must need admin approval.

Default "Account settings" in Drupal have the option to activate users without admin approval but I can not specify the roles there.

Any clue? or any other module which I should be using instead profile2_regpath

You may be able to use Rules to accomplish this. Create a new Rule that is triggered when a user account is created. Then add a condition that checks what the role of the user is. And finally, an action that activates the user account. I think that would work - although I'm not sure if those triggers/conditions/actions exist. They probably do. :-)


How to format JSON data response from a view defined by relationships to content types related by entity reference fields I have a content type event with content name of the event, event image, a relatioship to organizer another relatioship to participant and another relationship to self event that i call programs. Now I want to make a view which return me a datasource json like

{
    date:"10/10/2017"
    event:[
        {
            img:"image",
            description:"description",
            date:"date complet",
            program:[
                {
                    title:"titre",
                    description:"description",
                    date:"",
                },
                {
                    title:"titre",
                    description:"description",
                    date:"",
                }
            ],
            organizer:[
                {
                    name:"chis",
                    description:"description"
                },
                {
                    name:"chis1",
                    description:"description"
                }
            ],
            participant:[
                {
                    name:"zina lacina",
                    titre:"consultant"
                }
            ]
        }
    ]
}

The result is grouping by the date.

Try the Views Field View module. It gives you exactly what you need. Just add a view in your view wherever you have 1:n relationships. Setup views for program, organizer and participant and add a contextual filter for the event.

The result will be one event appearing once in your view.


Adding meta tag to a view I am working with Drupal 8. I want to add meta tags for title and description for a view. Is there any option?

Enable the Metatag Views module (part of Metatag)
Visit a View edit page
Configure your meta tags


How to delete unwanted block I've created a new block in my views.

Let's say the block name is 'slideshow'.

I've put the block into "Main Content" region and it's showing up.

The problem is that "Main Content" region is also displaying a list of nodes of "slideshow" with unformatted. So basically, "Main Content" region is displaying both unformatted version of "slideshow" and "slideshow"

when I inspect unformatted slideshow block, it has an id of "block-system-main".

How do I remove block-system-main ?

Are you talking about the front page or a custom view?

If you are in the front page view, you have probably set the content type for slideshow images to be promoted to front page. Disable that in

admin/structure/types

by clicking manage and in the footer untick 'promoted to front page'

and they will stop showing up unformatted.
In that case you aren't actually talking about a 'block', but the system content that is displayed in the main content block defined in the themes page.tpl.php page with

<!-- Page Content -->
<?php print render($page['content']); ?>


Conditional class on  element a la boilerplate This might be a totally mundane question, but I hope not.

I want to add conditional classes onto the <html> element of my theme like boilerplate. I'd like to keep things neat and not complicate my page.tpl.php.

<?php
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $language->language . '" lang="' .
    $language->language . '" dir="'. $language->dir .'"';
?>

<!--[if lt IE 7 ]> <html class="ie6" <?php print $htmlvar ?>> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7" <?php print $htmlvar ?>> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8" <?php print $htmlvar ?>> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <html <?php print $htmlvar ?>> <!--<![endif]-->

Reactions? Suggestions? Taunts?

There isn't really a great way to do this: Drupal 7 modified drupal_add_css() to make adding conditional CSS possible outside the template file, but not for arbitrary HTML.  Drupal 6 doesn't have anything.

In Drupal 6, and for arbitrary conditional HTML, you either need to add the markup directly  to page.tpl.php, or you could create a variable in your theme's implementation of template_preprocess_page() that contains the relevant markup as a string:

Drupal 7

function foo_preprocess_html(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

Then add $condtional_html to the appropriate place in html.tpl.php.

Drupal 6

function foo_preprocess_page(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

Then add $condtional_html to the appropriate place in page.tpl.php.

If you're interested in Drupal 7's conditional CSS handling, you can see Bartik's implementation of template_preprocess_html() for an example:

function bartik_preprocess_html(&$variables) {
  // ...

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}


Generating Images from image styles in drupal 7 I'm just getting accustomed to the changes in drupal 7, I've created a number of nodes that have an image field. The nodes were created as dummy content from the Devel module. I then created a view, added a number of fields, and chose my image style as a formatted for one of the fields. The only thing I can't figure out is how to get Drupal to generate the the images, I tried re-generating the dummy conent, but it still does not create the thumbnails.

Any Ideas?

Are the folders where the images go writable? Also check the tmp folder


Can't access my administration panel I was playing around with my website, which was built by a developer long time ago, and I remove the permission for the "administrator" role, and now as a "superadmin" I can't access the Drupal panel of my own site.

Can someone help me figure out how can I access the control panel?

Thank you!

Use Drush commands instead like

Drush urol command

Or update existing role with the proper permission to access your backend admin

Drush add permistion command


How to get field value after getting a node? I have a content type which contains school information. School name and school id are two fields in the content type. I have the school ID and I am able to retrieve the node. How do I get the school name? Below is how I retrieve the particular school node. I used the getValue() to retrieve the school name however, I get an empty array as a response for that. I am able to see the school name if I var_dump the school node.

$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$schoolNode->field_school_name->getValue()

If you want to use node object from entityTypeManager, you need to get current value from the array after loading like below:

$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$node_load = current($schoolNode);
$schoolname = $node_load->field_school_name->getValue();

This is only for a single node. If you have multiple nodes, foreach node as

foreach(schoolNode as $node){
  $schoolname = $node->field_school_name->getValue();
}


simple back button in drupal? I was using window.history.back() ,

Back

and

but it is not working in d7

Using jQuery we can

(function ($) {
  // Go back
  $('a.back').click(function(){
     parent.history.back();
     return false;
  });
})(jQuery);

and add class="back" to your link

Back


Assigning a role in code isn't working I want to add a user to a role when a checkbox on the profile has been checked.
It's printing the dpm() message but not adding the user to the role. What am I missing.

function mycustom_form_user_profile_form_alter(&$form, $form_state, $form_id) {
  $form['#validate'][] = '_user_profile_validate';
  ...
}

function _user_profile_validate(&$form, &$form_state) {
  if (($form_state['values']['field_restricted']['und'][0]['value']) == 1) {
    dpm('role added');
    global $user;
    user_multiple_role_edit(array($user->uid), 'add_role', 6);
  }
}

Your code seems fine. Maybe you could add an additional condition to see if your role argument is proper:

$role_name = 'Role to add'; // The name of the role to add.
  if ($role = user_role_load_by_name($role_name)) {
    user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
  }

I would try adding this condition to make sure all arguments are as intended. Maybe 6 is not a valid index? With this extra condition you will be sure.

Hope this helps, cheers!


Slide image bottom on mouse hover I have some kind of image that I want to have in all my pages of my website to use to return to my homepage.

So far, I managed to get the image in position I want and I already have displayed in all my webpages with reference link to the homepage.

But I want to go a bit far and had an animation to it, so when somebody use the mouse to hover the image I wanted the image to move some px (50px for example) to the bottom.

Yet, all I could do so far was this:

.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: -200px;
  right: -200px;
  margin-bottom: -500px;
  -webkit-transition: bottom 0.3s;
  -moz-transition: bottom 0.3s;
  -o-transition: bottom 0.3s;
}

But with the piece of code above the image was in fact moving but it originated other problem that it would move all the content beneath it.

I tried this other code:

CSS:

.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: -200px;
  right: -200px;
  margin-bottom: -500px;
}

figcaption {
  position: absolute;
  background: rgba(0,0,0,0.75);
  color: white;
  padding: 10px 20px;

  opacity: 0;
  bottom: 0;
  bottom: : -30%;
  -webkit-transition: all 0.6s ease;
  -moz-transition:    all 0.6s ease;
  -o-transition:      all 0.6s ease;
}

figure:hover figcaption {
  opacity: 1;
  left: 0;
}

HTML:

            aye!!

Still with this code the image wasn't moving, only appteared a text sliding. And that is similarly to want I want, that is, slide my image a bit to the bottom. But when I try to alter this latter code the page unconfigured itself.

Ok, now with this code I have my image doing the animation/transition that I wanted, moving down smoothly:

CSS:

.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: 0px;
  left: 200px;
  margin-bottom: -500px;
  display: block;
  position: absolute;
  z-index: 2;
  height: auto;
  margin-right: auto;
  margin-left: auto;
  overflow: hidden;
}

.penduricalho:hover{
  -moz-transform: translateY(50px); /* Firefox */
  -webkit-transform: translateY(50px); /* Safari | Chrome */
  -o-transform: translateY(50px); /* Opera */
  transform: translateY(50px);

  -moz-transition-duration: .5s;
  -webkit-transition-duration: .5s;
  -o-transition-duration: .5s;
  transition-duration: .5s;
}

HTML:

Run it here if you want to see the result:

https://jsfiddle.net/sn1hs9hp/


Render/display Panel's page outside 'content' I'm fairly new with Panels. By default Panels content will be displayed inside

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

Is it possible to display it outside the content?
For example if I made another placeholder and display inside it?

 <?php print render($page['content_panel']); ?>

NOTE: I'm using Drupal 7.

The reason I want to do this because the
 <?php print render($page['content']); ?>
is sitting inside

<div class="container content-main">
  <?php print render($page['content']); ?>
</div>

All contents/pages will be displayed inside content-main except 1 page which I don't want it to be inside the content-main div.

The content-main class have css which I don't need it in the panel.

The 1 page I want it to have its own <?php print render($page['content_panel']); ?> so that I can assign the panel to it and located outside the content-main div.

I think you need to use mini panels, mini panels shiped with panel module and you can use it as block, any mini panels you create will be listed under blocks, just assign it to the region you want


Create any number of paragraph fields in a multiple value field on node create form I have a paragraphs field that takes a term reference.

I need to count how many terms there are for a specific vocabulary and then create that many instance of the paragraphs multiple value field for when creating a node of a certain type. Can this be done with Hook_form_alter ?

It is important that these fields are loaded when the node creation form is loaded rather than the user having to click add more

Any help would be greatly appreciated

I have tried this but when saving the node it doesn't save the new fields

function hook_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'my_form') {

  $item = $form['field_features']['widget']['0'];

  // get taxonomy terms
  $query = \Drupal::entityQuery('taxonomy_term');
  $query->condition('vid', "my_voc");
  $tids = $query->execute();
  $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);

  $count = count($terms);

  $i = '1';
  foreach($terms as $term){
    $form['field_features_para']['widget'][$i] = $item;
    $form['field_features_para']['widget'][$i]['#delta'] = $i;
    $form['field_features_para']['widget'][$i]['#weight'] = $i;
    $i ++;
  }
 }
}

Instead of adding the multi value field items after the form is built you can try to do this on the entity before the form is built:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {

  if ($node->getType() == 'my_content_type') {
    // get taxonomy terms
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "my_voc");
    $tids = $query->execute();
    $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);

    $count = count($terms);

    $i = '1';
    foreach ($terms as $term) {
      $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([
        'title' => 'Paragraph ' . $i,
        'type' => 'my_paragraph_type',
         // more field data
      ]);
      $node->field_features_para[] = $paragraph;
      $i++;
    }
  }

}


Update Drush in Docker4drupal I have to upgrade Drupal core to 8.4 with Composer. Drush version is 8.1.12.

I use Docker4drupal for my local development environment. How do I update Drush to 9 within my docker container setup, so I can upgrade Drupal to 8.4?

Assuming you're using the default wodby/drupal:8-7.1-3.3.2 container image, the drush launcher is already installed in the PHP FPM container.

Thus, your next step is to update your Drupal 8 composer drush dependency via composer:

composer require 'drush/drush:^9'

When drush launcher executes under your web root it will pick up the version 9 that's installed in your vendor dir.


Is there a better way to style fields? I'm learning twig and using it to format and style my fields. The problem I am running into is that I need to create a new twig template for each individual field.

In the example picture, I have field--parent-task.html.twigwhich allows me to edit 1 field (or the first field), but I will need to create 6 more templates with identical code structure, just to style and move the fields around.

Is there a more efficient way to do this? In the end, I will have 7 templates just to target different fields, but yet they are all on the same page. I know I can target classes, say field__label, but that is not what I need, since I will be moving these fields around, giving them unique positions on the page.

If it cannot be done and this is how it is in D8, that is fine, I will deal with it. But if not, is there a better approach? So I don't end up having a endless list of field templates just to add/tweak a few css styles?

I had a project that needed some specific markup for different fields, using field.html.twig only at least saved managing multiple files.

field.html.twig:

{%
  set themeGroupOne = [
    'first_field',
    'second_field',
  ]
%}

{%
  set themeGroupTwo = [
    'third_field',
    'fourth_field',
  ]
%}

{# field markup option #}
{% if field_name in themeGroupOne %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# field markup option #}
{% elseif field_name in themeGroupTwo %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# Final option, default field template #}
{% else %}

{% if label_hidden %}

  {% if multiple %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}

{% else %}
{{ label }}

  {% if multiple %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}

{% endif %}

*Note that the two fields:

field.field.paragraph.paragraph_type.field_h2
field.field.node.node_type.field_h2

will both register as field_name == 'field_h2' in field.html.twig, making it even easier to theme fields across your site.


How to limit search results based only on OG group membership? I followed the tutorial about How to Create Custom Search Pages Using Just Views in Drupal 7.

I have selected the blocks option instead of page option in views as I want to add it as a block in the organic group homepage.

How do I restrict the search using relationship and context filtering in the Views settings so each logged in user can only search for published content of their group only (NOT SITE-WIDE)?

EDIT: I have already tried the following:

Contextual filters > (OG membership from node) OG membership: Group ID
Relationships > OG membership: OG membership from Node

(Which I got the idea from the default og_content view that comes with OG Groups!)

Can this be done with hooks?

Editing my answer here as there seems to be a glitch in Views. Even with no contextual filters or relationships, just filtering by groups audience and exposed search doesn't work. The SQL query has both values but I don't know enough about sql to debug it.

  Contextual filters > (OG membership from node) OG membership: Group ID
  Relationships > OG membership: OG membership from Node

Instead, here's a hacky way of getting it to work by not using the search module.

Do the same as above to limit results by group.
If you only want to search by title for example, just add an exposed filter for the title and select "contains".
If you want to search by more fields which is likely, add the fields you want to search by (and maybe hide them) eg. Node title / Body. Then create a Global: Combine fields filter (exposed) and select the above fields with "contains".

That will let you search whichever fields but just not as nicely as with the search module.

If anyone else has a solution to the exposed search problem, post please.


I've Featured some Paragraph Bundles, but they are not showing up on the remote site I've Featured some Paragraph bundles and have included them as part of a module.

I've merged these files to my remote site and want to 'activate' the Feature to have the Paragraph Bundles appear. I see my Feature there on the remote site and can 'Revert' it to update it but nothing happens - I don't get my new Paragraph Bundles in the existing list, nor do I get any error messages.

Would anyone know what's going on?

What I've pushed up is:

module_name.features.field_instance.inc

function module_name_field_default_field_instances() {
  $field_instances = array();

  // Exported field_instance:
  // 'paragraphs_item-module_name-field_grid_number_columns'.
  $field_instances['paragraphs_item-module_name-field_grid_number_columns'] = array( etc...

And

module_name.features.inc

function
module_name_paragraphs_info() {
  $items = array( etc...

And in my module's .info file I have included, eg:

features[features_api][] = api:2
features[field_instance][] = paragraphs_item-module_name-field_grid_number_columns
features[field_instance][] = paragraphs_item-module_name-field_paragraphs
features[field_instance][] = paragraphs_item-module_name_item-field_image
features[field_instance][] = paragraphs_item-module_name_item-field_text
features[field_instance][] = paragraphs_item-module_name_item-field_title
features[paragraphs][] = module_name
features[paragraphs][] = module_name_item

Is there anything I'm missing?

You might try manually creating the paragraph bundle and see if the fields pop in once the bundle is made, or once the bundle is made and the feature is reverted.

Might be that the features integration for paragraphs in D7 is still iffy.


Why does composer not work with core composer.json file when adding new libraries? When you download the source from here, and run composer:

php composer.phar require facebook/graph-sdk

I get:

    You are running Composer with SSL/TLS protection disabled.
Using version ^5.6 for facebook/graph-sdk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.4
9m

  Problem 1
    - Conclusion: don't install symfony/http-kernel v2.8.27
    - ...
    - Conclusion: don't install symfony/http-kernel v2.8.5
    - Conclusion: remove symfony/http-kernel v2.8.4
    - Conclusion: don't install symfony/http-kernel v2.8.4
    - ...
    - Installation request for symfony/http-kernel ~2.8 -> satisfiable by symfony/http-kernel[2.8.x-dev, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].
    - Conclusion: don't install symfony/debug v3.0.9
    - symfony/http-kernel 2.8.x-dev requires symfony/debug ^2.6.2 -> satisfiable by symfony/debug[v2.7.6, 2.6.x-dev, 2.7.x-dev, 2.8.x-dev, v2.6.10, v2.6.11, v2.6.12, v2.6.13, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.0-BETA1, v2.7.0-BETA2, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.17, v2.7.18, v2.7.19, v2.7.2, v2.7.20, v2.7.21, v2.7.22, v2.7.23, v2.7.24, v2.7.25, v2.7.26, v2.7.27, v2.7.28, v2.7.29, v2.7.3, v2.7.30, v2.7.31, v2.7.32, v2.7.33, v2.7.34, v2.7.4, v2.7.5, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].
    - Can only install one of: symfony/debug[v3.0.9, v2.7.6].
    - ...
    - Can only install one of: symfony/debug[v2.8.9, v3.0.9].
    - Installation request for symfony/debug (locked at v3.0.9) -> satisfiable by symfony/debug[v3.0.9].

Installation failed, reverting ./composer.json to its original content.

Surely the core composer file that comes with Drupal can work with the facebook SDK. What am I missing?

Hope it helps someone else. The issue was that I only updated drupal's /core folder, not composer.json. So I had a very old composer file. When I updated it with the composer.json from the latest D8 download, things started working again.


Programmatically add a file upload field to all webforms (+more file extensions) I have a set of >100 webforms in my projects.

I need to add an upload field to all webforms in my hook_form_alter().

I guess I need to do something like the following.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_') === 0) {
    $form['file'] = array(
      '#type' => 'file',
      '#title' => t('File'),
      '#weight' => 50,
    );
  }
}

I need to set as on certain attributes such as:

fieldkey
max upload size
allowed file extensions

How can this be achieved?

In this way (hook_form_alter) you will have this field in existing and next created webforms, and you must have own additional _validate and _submit function to process the $form['file'] field.
Other way, the question is how to add programmatically file upload component to existing webform?
To see structure of webform file component, add manually field file to one existing webform and make your setting from the picture, and see devel output tab (enable devel module). Also you may be interested to see http://api.drupalize.me/api/drupal/function/webform_component_insert/7. Then create update script to loop webforms.


URL field in Webforms I see only e-mail and textfield, but no URL.

How can I add to my form URL field with the validation rules for URL? e.g.

http://somesite.com

or

somesite.com

or

www.somesite.com

?

Well if you have tons of time you could implement a component type... but because that is unlikely you should just add a validation hook and a textfield to the webform. You could do a valid_url($form_state['values'][[your_field_name']); in your validation hook.

Someone asked this question on d.o previously here. You can find all sorts of examples on "things you may need to do special with a webform" here.

Another possible solution would be to install the Webform Validation module, add a regex validation to your field, and steal a known usable url validation regex like drupal has.


How to make image alternative text as required be more web accessibility? In Drupal 7, how can I set image alternative text as required in "Body" field (CKEditor), "image" field and file upload by using "Media" module?

---- updated info for betherwisser on Aug. 20, 2014 @ 12:17pm
I know there is a file types section in Media but it is different from what you mentioned. However, It does not have the Alt text field option there. Please see screenshot for details.

ALSO, there is an option on image file for Alt Text but I'm not able to make that as required. See below screenshot.

I found one of the solution by using EIM module. I understand this is not the best solution but this module able to enable Alt field required on image field by content type.

---- updated info on Aug. 22nd 2014 @ 11:12pm
The EIM module adds checkboxes for the fields of image editing forms by content type. Including "Alt field required" and "Title field required". See below screenshot for details.


How can I display seveal menus with different classes I have the "joy" to upgrade a Drupal 6 site to Durpal 8. In my Drupal 8 site I have three different menus, which each display different types of nodes. I want to display them in the region of the sidebar_first, but each of them should have a different background colour. E.g. menu A is red, Menu B is blue and so on. This colour should be in the background if the menu is collapsed and expanded.

I tried it this way:

        {% if page.sidebar_first|render %}
            <div class="sidebar_first">
                <aside id="sidebar-first" class="column sidebar first">
                    {{ page.sidebar_first }}
                </aside>
                <aside id="sidebar-first-person" class="column sidebar first">
                    {{ menu-person }}
                </aside>
                <aside id="sidebar-first-kinder" class="column sidebar first">
                    {{ menu-kinder }}
                </aside>
                <aside id="sidebar-first-kunst" class="column sidebar first">
                    {{ menu-kunst }}
                </aside>
                <!-- /#sidebar-first -->
            </div>
        {% endif %}

But instead of displaying the menu I get a 0. So my guess is that I have to  fill the twig placeholder with values somewhere first. Which would be the approach for this? Write a module? Including other Twig templates?

Here you can see the old Drupal 6 site, which I try to rebuild with Drupal 8.
http://claudiazeppenfeld.de/kunst/fadenerzaehlungen-fuer-porzellan

In Drupal 6 I achieved this with Blocks and Context. I am not sure to solve that in Drupal 8.

Why not just add each menus through block layout interface? visit admin/structure/block.

You will get unique id each.


Add payment method to Billy PDF? Is there a way to add a billing method/status line to invoice, generated by module Commerce Billy PDF?

I've been looking for a way for days and still cannot figure it out......

Go to the template directory of Billy PDF (commerce_billy/modules/commerce_billy_pdf/templates) and copy the file

commerce_order--commerce_order--pdf.tpl.php

to your theme directory. Thats the template of the generated pdf. You can simply edit this template and add the billing method i think.

You can access the order object via

$order = commerce_order_load($variables['elements']['#entity']->order_id);

inside of the template.


Prevent redirect after node save I have overlay turned off in Drupal. When I am editing a node, I want to prevent the redirect to the node after I hit save and just stay in the back-end. (It is really a pain to have to hit "edit" and have the page re-refresh each time when one is making a little tweak. As this can be easily achieved by having to tabs open; one for the node view and one for the backend edit form)

Is there an easy way to solve this in the configuration UI?

You can alter the form and add your own submit handler in which the user will be redirected back to the edit form:

function <MODULE>_form_alter(&$form, $form_state, $form_id) {
    if (strstr($form_id, '_node_form')) {
      $form['actions']['submit']['#submit'] = array('<MODULE>_form_submit');
    }
}
// Custom submit handler for '_node_form'.
function <MODULE>_form_submit($form, &$form_state) {
  // Call default action.
  node_form_submit($form, $form_state);
  // Redirect back to the edit page for this node.
  $form_state['redirect'] = url('node/' . $form_state['nid'] . '/edit', array(
      'absolute' => TRUE
    )
  );

  $_GET['destination'] = $form_state['redirect'];
}

You might have to tweak the above code to suit your needs.


Cannot install Composer because it doesn't contain any .info.yml files Newbie using clean Drupal 8 install on a server.  Installed module "International Telephone," but got error.  Then I read that I needed to also install Composer.  When I tried to install Composer, I received the error that there were .info.yml files.

I've spent hours researching without luck...

IMPORTANT EDIT (2020-04-28):

You are trying to install this project:
https://www.drupal.org/project/composer

But that is not Composer -- it's a Drush extension for managing Composer.

From the project documentation:

  Composer is a PHP package management tool to help manage your project or libraries' dependencies. This project allows use of Composer from Drush.

Installing this module on the server will not allow you to manage your Drupal 8 project using Composer. You need to set up your Drupal 8 project correctly using Composer in the first place, and worry about getting it onto the server later (whether you use the modern DevOps way using git hooks to deploy, the old-school sysadmin way using rsync to deploy, or the stone-age way using SFTP with Filezilla or a similar GUI file transfer utility.)

ORIGINAL ANSWER (2020-04-26):

Welcome to Drupal Answers!

Since you just started from scratch, you won't lose much work if you start from scratch again.

First, install Composer on your local computer: https://getcomposer.org/

Don't try to install Composer on the server. Depending on your hosting, it may be possible to do that, but it is seldom the best way to do things. Composer is a well-known memory hog, and many web hosts will not allow you to run composer install on the server. Even if it is allowed, it's a terrible misuse of RAM and CPU cycles on a production server. Don't do it.

Next, install a new Drupal 8.8 site on your local computer (here called "my-project") using the drupal/recommended-project template:

composer create-project drupal/recommended-project my-project

At this point, I recommend using git init to put your project in version control.

Then use Composer to manage project dependencies such as installing contrib modules:

composer require drupal/phone_international

You can create a .gitignore file to tell git to ignore the core, contrib and vendor directories, which will be recreated afresh whenever you run composer install (from instructions in the composer.json and composer.lock config files). This keeps your git repo and pull requests small by excluding hundreds of thousands of lines of open-source code that are common to all plain-vanilla Drupal 8 (or 9) projects.

Finally, you'll want to set up some method of deploying the code from your local computer to the server. For tips on that, see my other answer:

https://drupal.stackexchange.com/a/292006/80164

Note that you will probably want to see the local Drupal site in a browser before deploying the code to the server. There are many ways to accomplish this.

Personally I like to use Lando to manage my Drupal projects in Docker containers, but other options include Docksal, DDEV, Vagrant/Virtualbox, LAMP (Linux), MAMP (Mac), WAMP (Windows), XAMPP (Linux, Solaris, Windows, and Mac), and others.

There's a lot to learn, and many of your questions will be outside the scope of this forum (which primarily focuses on issues specific to Drupal core and developing custom module and theme code with Drupal APIs). You might get better support for general questions on Drupal Slack.

Assuming that you want to try Lando, you can install it with all its dependencies using the Hyperdrive installer script for Mac or Linux. Then navigate to the my-project directory you created with composer create-project and execute something like this:

lando init --source cwd --recipe drupal8 --webroot web --name my-project

That would set up Docker containers for your appserver and database with a default configuration suitable for a Drupal 8 project. Then you'd just type:

lando start

Then you can view your local site in the browser at http://my-project.lndo.site to finish installing it and configuring it. After this, you can use Lando to manage your project inside the Docker container. Type lando on a line by itself to see what tools are available (including Composer, Drush, Drupal Console, MySQL CLI, log viewer, and tools to import/export database backups.)

Make sure that every time you change the code, you commit it to git and test it locally before deploying it to the server. (Later, you might end up setting up different servers for Dev, Test and Live environments.)

Good luck, and happy Drupaling!


Different product prices per line item options I'm working with Drupal Commerce, and i have a node type called "travel" with a product entity.
This product have some static fields types like "city" which are used to define different prices supplements depending the departure city (Aka NY (+$15  extra transport charge), L.A(+$25  extra transport charge), S.D (+$20 extra transport charge) etc.). These fields are static, that mean i don't have to jump too often in the Store options to add my cities. (But i can set the price in the node edition as it is an option set.)

But i have another field: Range date of Departure/Arrival, this field is dynamic, i may have to set custom entries for each added nodes.

In the example below, my node is a travel to London (base price of $1500).
The departures are: Los Angeles (+$30 e.t.c), New York (+$50  e.t.c), San Diego (+$25  e.t.c).
But in the node i have to set different sojourn range dates:

Available dates:
-2014-01-20 to 2014-01-30
-2014-02-20 to 2014-02-30
-2014-03-20 to 2014-03-30
...

Each of these dates directly alters the travel price. My wish is to set a different travel price per range date like this:

-2014-01-20 to 2014-01-30 ($1600)
-2014-02-20 to 2014-02-30 ($1650)
-2014-03-20 to 2014-03-30 ($1450)

OR
A discount/extra charge to the main sojourn price ($1500) like this:

-2014-01-20 to 2014-01-30 (+$100)
-2014-02-20 to 2014-02-30 (+$150)
-2014-03-20 to 2014-03-30 (-$50)

Of course, those changes are not directly visible on the front-side, the visitor will just see "10 days of travel to London from 2014-03-20 to 2014-03-30 for $1450".

Now the technical problem is not really the front integration, but most likely the back-office configuration. Which product field configuration/combination should i use ?
Remember that prices per dates should be set from the node creation form.

In the first approach, i was thinking about a multi-field field type combined with a sub-option set, but it seem that drupal did not appreciate that combination and doesn't recognize those fields as it mixes html id/classes like hell :/

So i'm now, my head in my hands, awaiting for a Drupal SuperHeroes.

Regards,
Geo

If I understand what you're trying to do here correctly, you may need to create some custom Rules.

Event:  Calculating sell price of product.

Conditions:  This is where it gets tricky.  If the date range is not on the product entity, you'll need a way to get the values from the product display node, that could be annoying in and of itself.
Now, if pricing for date ranges are statically calculated (ie: a 3 day trip ALWAYS adds $50), you could set up some custom code to dynamically do things like that.
On the flip side, if those range rates are different per product, it seems it would be necessary to define those on the product entity.  And furthermore, you would probably need to create products for each variation (as in, variation for every combination of departure city AND date range).

Action:  Add amount to product price (or something like that, I'm not looking at Rules directly).


How do I update the section component configuration? How to update a component in the node's layout builder? I  have used the following code.
$node = \Drupal\node\Entity\Node::load($nid);
$layout = $node->get('layout_builder__layout');
$sections = $layout->getSections();
foreach ($sections as $key => $section) {
      $components = $section->getComponents();
      foreach ($components as $component) {
        if ($component instanceof SectionComponent && $component->getPluginId() === 'myplugin_id') {
          $configurations = $component->get('configuration');
          $configurations['label_display'] = "0";
          $component->setConfiguration($configurations);
        }
      }
}

But now I don't know how to update the section and layout of the node.
Because $section->setComponent($component) is a protected method.

I have done it like this.
$node = \Drupal\node\Entity\Node::load($nid);
$layout = $node->get('layout_builder__layout')->getValue();
$sections = $layout->getSections();

foreach ($sections as $key => $section) {
  $components = $section->getComponents();
  foreach ($components as $component) {
    if ($component instanceof SectionComponent && $component->getPluginId() === 'myplugin_id') {
       $configurations = $component->get('configuration');
       $configurations['label_display'] = "0";
       $component->setConfiguration($configurations);
    }
  }
}

$node->set('layout_builder__layout', $layout);
$node->save();


How to send notification when node similar to flagged one is posted I want to send notifications to the user when a new node similar to one he has flagged is posted.

You need to user RULES module to achieve this functionality. Drupal flag module has full integration with rules modules.

By creating a rule saying condition is "Node is flagged" add an action saying "Send email to author of node."


Is the "www" in the database for the site confguration? I have recently helped launch a site and there are some cross domain issues between "www.website.com" and "website.com"

I was chatting with Cloudways tech support and he mentioned that if I remove the "www" from the database for my site settings I wouldn't be having the issue.

What I ended up doing was modifying the .htaccess to redirect to "www.website.com" for now, but I still have the question: Is the "www" for the domain name in site information stored in the database? If so, would you really want to edit that?

No its not there in database.

It depends on global $base_url variable.

How drupal define this variable is based on super global $_SERVER['HOST'] variable, which is basically depends on how the request was sent with/without www.

But you can override global $base_url in your settings.php
$base_url = 'http://yoursite.com'


"Cannot modify header information - headers already sent by (output started at codefolder\modules\user\user.module:1)" i am using drupal 6, mysql 5.5 on apache 2.2 it is working fine.
but when i migrated my code on xampp1.7.3(contain apache2.2 and mysql 5.5).
it gives issue and error.

  warning: Cannot modify header information - headers already sent by (output started at codefolder\modules\user\user.module:1) in codefolder\includes\session.inc on line 99.
  warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in codefolder\includes\session.inc on line 102.
   Blockquote

and after login pages containing urls like localhost/node/55 shows white pages. while without login it works fine.
while searching on google i found this issue might be due to header but i haven't used any header redirect in my  .tpl.php files.

Check that you don't have any ending php tags at the end of your php files. Sometimes whitespace (spaces, tabs, newlines) will sneak in at the end of the file after the tag and cause php go into html mode and send the headers too early.


Restrict Anonymous Users from accessing/viewing a Customized Form I have created a form. The codes I used are below:

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

    $items['user/%user/myid_print'] = array(
        'title' => 'Print an ID',
        'page callback' => 'myid_print_user_page',
        'page arguments' => array(1),
        'access callback' => myid_print_user_access(),
        'file' => 'myid_print.pages.inc',
        'type' => MENU_LOCAL_TASK,
        'weight' => -10,
    );
    return $items;
}

The code of the function that allows accessing the form:

function myid_print_user_access()
{
   if (user_access('perform_regular_task'))
   {
       return TRUE;
   }else{
       return FALSE;
   }

}

I was wondering that even if the user is not log-in the form can be access.

Looking at the module's permission:

I did not assign any permission for the anonymous user. Why it is so?

The access callback element used in hook_menu() takes a string has a value, you're supplying it the output of myid_print_user_access() which return a boolean. It should be:

'access callback' => 'myid_print_user_access',


Set default value of a custom field attached to a Media file image field I have set up a media image file field on a couple of content types, per the instructions given in the Media 2.x Quick Start Guide.

The image file field has a custom field I added (admin/structure/file-types/manage/image/fields).  This field has a default value.  I would like to be able to change the default value via a hook based on conditions determined at runtime.

While I have found that hook_form_alter is called when the Edit Image modal (AJAX) dialog is displayed (see diagram "Create a New Node and Upload an Image" in the above-referenced documentation page), I would also like to have the chance to alter the default value even if the user does not click on the "Edit" button.  Also, information about the fields attached to the image file field are not populated when hook_form_alter is called for the node create form for the content type that contains the image file field.

I considered hook_node_save, but by the time this hook is called, the file field has already been saved, and I can't tell if the user visited the Edit Image modal dialog or not.  For that matter, even changing #default_value in hook_form_alter will change the displayed value, even if the user has already visited the dialog before and selected a new, non-default value for the field.

Is there an elegant way to determine in hook_form_alter and hook_node_save that the user has already changed the value for the field?  Alternately, is there an earlier hook that can adjust the default value for these fields before either of these hooks are called?

Update:  I thought of a reasonable workaround. If I set the default value for the attached field to "I don't care", then I could calculate the dynamic default value at view time.  I'd rather not have an "I don't care" value, though, and would therefore still be interested in having this question answered.

Update 2: I am now happily running with the "I don't care" workaround deployed on my live site.  I would still be interested in an answer on how to elegantly set the default value for media file fields, though.

Drupal has the capability to dynamically set a default value for a field, but it is not exposed in the UI.

Each field instance can be set a 'default_value_function', which has the following signature:

function my_default_value_function($entity_type, $entity, $field, $instance, $langcode) {
  // Returns a standard field structure.
  return array(
    0 => array(
      // This can be different depending on the field type.
      'value' => 'myvalue',
    ),
  );
}

To set the default value function, either:

Modify the field structure exported by Features to add a 'default_value_function' in the 'field_instance' part (and revert the feature),
Do something like this (once):

$instance = field_info_instance($entity_type, $field_name, $bundle_name);
$instance['default_value_function'] = 'my_default_value_function';
field_update_instance($instance);


Scrolling in chrome shears text and elements the testing version of a portfolio site I'm working on started behaving strangely in the past few days. This might or might not be a problem related to drupal itself, but I've never come across this on a non-drupal project.

http://beta.mattgrossdesign.com/about

On my Win7 machine, Chrome 36, scrolling the page causes all the fixed position elements to be rendered in multiple places or sheared off.

Image Reference: http://imgur.com/a/uCYfC

Firefox & IE aren't having problems, any ideas?

Thanks a bunch

Try to add -webkit-transform: translateZ(0); to your fixed elements.


How to remove contents type drupal advanced search page When Drupal does a search, and returns no results, an advanced search form is displayed. The form contains a list of content types. There are a couple of content types on our site, but these should be hidden from the user, e.g the end user shouldn't see "contentType", "newType".

I don't want to limit the results, just restrict the user's ability to filter the results using the types.

I've tried looking at the search templates, but couldn't find a reference to the fields.

Any ideas on where I find the correct type or turn off this field?

Advanced Search field can be disabled in Permissions settings (it should be disabled by default).

If you rather want to leave Advanced Search, but limit to specific content types, you can 1) Use Custom Search module, as advised by @Lance or 2) Dig through modules\search\*.* directory to see which function controls the content type of the Advanced Search options, after which you can use your own module to override the settings.


Render Teaser Image in search block using Twig I am trying to render the teaser image in my search block using twig. For my views page for rending the articles i am using this:

    {% block teaser_img_container %}
        {{ content.field_teaser_media }}
    {% endblock %}

And it works very nice but on search block it does not display the image, so I am trying other options like

  <picture>

   {% block teaser_img_container %}

 {% endblock %}

     </picture>

Which should solve my problem, but i still don't see the image i am getting no errors, if i go in my page source the link to image appears but when i inspect the code from I get

The link works, but it does not display my image.
Any ideas for fix?

You could use the URL Formatter Module

Then go to Manage Display and for your image field and select URL Formatter as your formatter.

then use: <img src="{{ content.field_teaser_media[0] }}">


How can I change a rendered user display to a combination of fields linking to the user? I have a set of users on the site I'm building that have First and Last name fields in their profile.  How can I create a display that will show the user link as "Last name value, First name value" all inline?

There are a number of places where this is how I want user references to show up.  In some other places, it would be ideal to show those fields, and a couple of others along with the user's image.  Then of course there is the full profile view.  I had though this must be done with different display types, but can not see anyway to bring fields inline with each other, or adjust what text makes up the link.

One option would be to use:
Real Name

The RealName module allows the administrator to choose fields from the
user profile that will be used to add a "real name" element (method)
to a user object. Hook_user is used to automatically add this to any
user object that is loaded. It will also optionally set all nodes and
comments to show this name.

For Example:

By default only the raw username is being shown, as you can see at the
top of the page.

Change this to:

Result:

source: Change Drupal Usernames with the Real Name Module


How to restrict who can VIEW content of selected content types using Organic groups? Using Organic groups 7x-2.7, how can I restrict which users are able to view certain content types?

Maybe you want to give it a try to use the Group module, either as an alternative for Organic Groups (as more and more people seem to be doing), or as an addition to it.

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to show all subterm nodes of a parent term with the simple_hierarchical_select module? I use drupal 7 and simple_hierarchical_select module.

I have a vocabulary called "news group" that has two level term (parent term and subterm) like the attached picture:

When I use exposed filter and simple hierarchical select for this (select term reference filed for "news group vocabulary") views filters show me two select list.first level list show parent terms (like HSE) and when select any option from first select list another select list appear that contain subterms of this parent term (like 5 subterm of HSE term) So I must select a option from Secound select list (subterms)  to have any result for my view.

I want to filter views results by first level (parent term) of taxonomy (like HSE) . But the Simple_hierarchical_select module Does not support first level of terms.must select deepest term for result.

I am not selected "force use to select deepest level" in field settings of term reference field.

Is any way to force SHS module to filter all subterms of a parent term?  Is another module for add "select all subterms of a term" feature to views exposed filter?

I found this issue solution after 2 weeks searching and experiments.
in views filter add "Simple hierarchical select - taonomy with dept" and in dept field of settings of this filter select 1 .
Now , when select a parent term , secound term with dept 1 has been showing too.


Why are the labels for two different form elements so different? Can I make them the same? I created a webform that has one textfield and two radio button fields.
When displaying, the textfield label is themed correctly, but the radio button labels are not.
When I look at the tags and classes, the texfield label has a "label" tag with "control-label" class like this
Textfield label

but the radio labels have "span" tags with "fieldset-legend" class, inside "legend" tags, like this
<legend>
    Radio element question
  </legend>

Why are they different? Can I ake them the same, or is add a CSS style to make the span.fieldset-legend match the label.control-label the only way to make them the same?
I am using the Bootstrap 3 theme and I enabled the webform-bootstrap module.

The differences here come down to the differences in the two types of form elements.
From the MDN docs for the label element:

The HTML  element represents a caption for an item in a user interface

From the MDN docs for the legend element:

The HTML  element represents a caption for the content of its parent .

Looking at the example from the legend documentation, we see how the two types of elements, labels and legends, are semantically different.
<fieldset>
    <legend>Choose your favorite monster</legend>

    <input type="radio" id="kraken" name="monster">
    Kraken

    <input type="radio" id="sasquatch" name="monster">
    Sasquatch

    <input type="radio" id="mothman" name="monster">
    Mothman
</fieldset>

Each radio button has its own label element with text describing it. Meanwhile, the set of radio buttons is wrapped in a fieldset with a legend element to describe the group as a whole.
While you may be able to alter the markup for your radios, to replace the legend element with a label, you should not, especially if you're trying to build an accessible website (and you should be). This answer to Is it good practice to use  for non-input/non-interactive elements? provides a more detailed explanation for why you shouldn't use a label in a context like this.


Edit view link redirected to preview link automatically I have opened edit view option on localhost using Drupal 7. firstly, the requested page i.e http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14?destination=node open successfully, however, It automatically redirected to edit preview link i.e http://localhost/xxx/drupal/admin/structure/views/view/products/preview/block_14. I have tried to find the problem but not able to do.

kindly assist me.

Thanks in advance.

It is not a problem, it's done on purpose for convenience of being able to quickly edit the view and return to the page where you were at initially.

If you want to stay at edit page then just remove the ?destination=node part from the URL: http://localhost/xxx/drupal/admin/structure/views/view/products/edit/block_14


Change / Set Node Reference field in hook_form_alter I am trying to set the value for an existing Node Reference drop-down field in a content type via hook_form_alter as part of an AJAX call.  The form needs to set values based on a selection, which is does correctly for dozens of fields, but I can't get or find the array structure to change/set the value for a Node Reference field. I've looked around and tried every permutation I can find, including dozens of guesses at what the array structure should look like without any success. Any help would be appreciated.

With Clive's help, I was able to figure out the array structure I needed. To set the node ID for a Node Reference field (References Module) in hook_form_alter, this structure worked for me:

$form['field_name'][LANGUAGE_NONE]['#value'][0] = {node id}


Where is the jquery.cycle.all.js file? So i have install views_slideshow_cycle module, and it always shows "cycle" is not a function. after some googling, I found out I have to install jquery_cycle.

In views_slideshow_cycle.libraries.yml file, I found this section:

jquery_cycle:
  remote: http://malsup.github.io/jquery.cycle.all.js
  version: 3.0.3
  license:
    name: MIT
    url: http://jquery.malsup.com/license.html
    gpl-compatible: true
  js:
    /libraries/jquery.cycle/jquery.cycle.all.js: {}
  dependencies:
    - core/jquery

Where is that libraries directory?

OK, I have found out, you have to create a libraries folder under web root.


I can't figure out the difference/relationship between menus and menus One of those fundamentals I skipped over because it gave me a headache to think about thinking about it:

Can someone explain, (or point me to documentation that can explain, and won't make me want to punch myself), the difference, the logic, relationships and/or whatever for "menus" (seemingly misnamed collection of page markers the things you make with HOOK_menu) versus "menus" (thingees that you click on to make events happen the things you make with menu_save())?

...bonus points if you can tell me why in the name of all things holy are log-in, log-out, register, my account, and hell, even "switch back" not built into a single core menu block so that I could continue to live in blissful ignorance...

hook_menu : Is used to define a path in Drupal. It also says what should be present in that path, who should have access to it and so.

Documentation of hook_menu

Menus : Is a list of links that fall under a category. For example Admin Menu(Admin Links), User Menu(Account, Logout) and Primary Menu(Home, Contact and so on)

Documentation of Menus


How to programatically change a user image field to match the user's latest completed goal? I created several goals with the Goals module. Every goal has an associated image.

My users have an image field 'Last goal' and I'd like to change it to the image associated with their latest completed goal. As this doesn't seem possible with the Rules module, I'd like to create a custom module. I found in the Goals API that I can use hook_goals_completed_goal($goal_id, $uid), but I'm stuck there.

How can I grab the user's 'Last goal' field and change it to goal_img?

I finally found the answer thanks to the Devel module and the user_save API page! After investigating a random goal with dpm(goals_load(GOAL_ID));, I wrote the following code:

 function top_goals_completed_goal($goal_id, $uid) {
    $user = user_load($uid);
    $goal = goals_load($goal_id);
    $fid = $goal->goal_img['und'][0]['fid'];
    $img_title = $goal->goal_img['und'][0]['filename'];

    $edit = array();
    $edit['field_last_goal']['und']['0']['fid'] = $fid;

    user_save($user, $edit);
}


How to insert value to user entity custom field while creating new account? I am trying to insert a value into a custom field(field_custom_referral) which is created in the backend.When a user creating a account in our application, this particular custom field should be updated with custom value. Can anyone help me out here.

I tried below code in .module file but not working out:

function module_user_insert(Drupal\Core\Entity\EntityTypeInterface $entity) {
  $entity->set('field_custom_referral', '3');
  $entity->save();
}

Any suggestion will be appreciated.

The hook_ENTITY_TYPE_insert in case of entity user expecting Drupal\user\UserInterface instance not Drupal\Core\Entity\EntityTypeInterface

change your hook to:

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MYMODULE_user_insert(Drupal\user\UserInterface $user) {
  $user->set('field_custom_referral', '3');
  $user->save();
}


How to create a single image style for both landscape and portrait images? In a Drupal 7 environment, I want to apply a style to all images within a view. I want every image to be 180px wide & 128px high -OR- 128px wide and 180px high depending on the orientation of the original image.

Can this be done with an image style or do you know any module that would help in achieving this?

ImageCache Actions

  Aspect Switcher new 2009-08 - lets you perform different actions or
  use different dimensions based on whether the image is 'landscape' or
  'portrait'


How to differentiate token replacement from array index How to escape left square bracket - [ and Right square bracket - ] when used in views so that it is not mistaken for a token.

I have what I hope is a simple question to answer. I have tried searching online but have been unable to find an answer (perhaps using the wrong search terms - I don't know). I am using Drupal 7 with views and the fillPDF module. I have modified one of the outputs of my view to use token replacement. The issue I am having is that the string that is being used for the token replacement has an array with an index that is the same as the token. Here is the code:

Create a PDF

As you can see, I need away to make sure webform[nid] and webform[sid] doesn't become webform1 and webform2 after token replacement. How do I accomplish this? There must be a way to escape the array.

Thanks.

You can escape the left square bracket - [ using - %5B
and Right Square Bracket - ] using - %5D

So you should change your code in question to the following.

Create a PDF


Unsubscribe module issue I installed the Unsubscribe module. I have also set this module's permissions for both authenticated and anonymous user.

.

Now the unsubscribe checkbox is appearing on the edit account form, but not yet on the user register form, where I want it to appear too.

Is there a way to do so? As an alternative, do you know any other module that provides a similar function/feature?

Using module Unsubscribe
About the "not appearing in fields of user register form" in the question: it seems to me that the unsubscribe module might just be working as designed, and implemented. From its project page (I added some markup here):

The module design is very basic. When a user unsubscribes, they are added to an "unsubscribe list," which is stored in the database. Whenever Drupal sends mail, the unsubscribe module will check to see if the recipient is on the unsubscribe list. If so, the email is blocked. You can exempt specific modules from this blocking via the configuration page. You can also use hooks to alter exemptions, or override the blocking.
Emails sent by the system and user modules are currently exempt by default.

From the question it is not clear to me what you have done regarding the "exempts" (on the module's configuration page). If nothing yet, then that might be the explanation for why it is not appearing on the user register form, no?
Using some other module
As per your "any other module that provides a similar function/feature": it appears to me that the Rules module should be worth considering, possibly combined with the Message module.
If you're not familiar enough with these 2 modules, then I suggest to review this great introduction to the Rules module: Rules for admin notifications, Part 1: New user registrations. Maybe also the related Rules for admin notifications, Part 2: New comments and content.


How to add specific field to article node twig template? I want to customize the article type node pages. I created a twig file :

node--article--full.html.twig

What code should I put in this file to display the "Description" field ?

/admin/structure/types/manage/article/fields

Rendered output of this field

{{ content.field_article_description }}


User registration form I am using drupal 7 built in form name user_register_form, when clicked on submit or save button I want to store the value of uid column value  and status value (if the request is active or blocked) to be stored in another table? How can I implement this , can anybody please guide me ..

UPDATED
My table name is expiry_user, expiry_status and expiry_uid are two columns in my table

function mymodule_user_insert(&$edit, $account, $category)
{
db_insert('expiry_user')->fields(array(
'expiry_status' => $account['status'],
'expiry_uid' => $account->uid,
))->execute();
}

Use hook_user_insert() to take action on the user account after creation:

function mymodule_user_insert(&$edit, $account, $category) {
  //@TODO: use $account->uid & $account->status to do stuff
}


Problem with swfobject_api or jwplayer module I have a problem with swfobject_api or jwplayer module.

When I use this code in node.tpl.php everything is fine.

$config='sample';
$flashVars=array( 'file' => 'path to flv' );
print theme('jwplayermodule_render_player', $config, $flashVars);

When I use this code in front-page.tpl.php the code is not working.

In node-tpl.php this JavaScript is added.

<script type="text/javascript" src="/projects/theme/sites/all/modules/drupal/jwplayermodule/jwplayermodule_jwembedder.js?c"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "jwplayer": { "files": { "jwplayer-1": { "flashplayer": "http://localhost/projects/theme/sites/default/files/jwplayermodule/player/player.swf", "width": "400", "height": "280", "controlbar": "bottom", "wmode": "opaque", "file": "/projects/theme/sites/default/files/1057680_0.flv", "config": "http://localhost/projects/theme/sites/default/files/jwplayermodule/configs/sample.xml", "events": [  ] } } } });
//--><!]]>
</script>

In front-page.tpl.php, it is not added.

I put <?php print $closure ?> in footer.php, and included it in front-page.tpl.php and node.tpl.php.

Your template file should be called page-front.tpl.php, not front-page.tpl.php. Once you've renamed it flush your caches and it will work!


User Folder Access Control I work at a university that has switched to Drupal. We have several hundred departments making their own "sites" in our system. Most departments need to be able to upload and change ONLY their own pdf files, images, and documents.

We can make folders for departments but no user will want to scroll through the list to upload something each and every time.

Can a folder system of some sort tie in to individual users or groups?

IMCE is an image/file uploader and browser that supports personal
  directories and quota.

You'll need to integrate this file browser with your WYSIWYG editor (supports almost every editor), and you can work with personal or shared folders for users or permissions per directory.


Separate urls for child node with multiple parent nodes? I have a question. I am currently building a site with different sections (a content type with childrens of type normal-content), where some content is identical on parts of the site but some pages have their own version of the page. Se example below

section1/about_us (nid 45)
section2/about_us (nid 45)
section3/about_us (nid 62)
section4/about_us (nid 45)

The issue in my example is that when using pathauto to create the urls the url and the hierarchy is created correctly but only one of the nodes is treated as a parent in regards of the url. They all get the same url section1/about_us (except the one that is created separately). Which I think is the correct way to create the urls but in my case I need separate urls even if the page loaded is the same since it reflects a virtual hierarchy. Is there a way for me to hook into some function to let the pathauto create separate urls for each section?

Best regards,
Jocke

Though I agree with Clive, nodehierarchy module should help you out on your issue.


How to edit default Commerce Order status? I am trying to edit the label of a default Commerce Order status (Pending:pending).

I have tried through commerce_order.api.php like it is explained in this post: Change order status string from "Completed" to "Shipped" and on this page but unfortunately it did not work for me. More, in this PHP file, the Completed status should display Finished and it doesn't work either??

The Commerce custom Order Status works fine with new statuses but I did not find any way to edit default ones.

Thanks for any tip.

Ryan's solution in Change order status string from "Completed" to "Shipped" works finally, my code was wrong.

So, for anyone having the same need, create a mini-custom module using the function hook_commerce_order_status_info_alter (dependencies commerce_order) and paste your new label like it is done for Completed status.

You may find the exact status machine names (e.g. "pending") in commerce_order.module.


Get ID from a URL in drupal? I have cretad a menu for edit a form in drupal...

Code:

function pricepackages_menu()
{
    $items = array();
    $items['membership/packages'] = array(
        'title' => t('Add Membership Packages'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form'),
        'access arguments' => array('access administration pages'),
    );
    $items['show/packages'] = array(
        'title' => t('Manage Membership Packages'),
        'page callback' => 'view_packages',
        'access arguments' => array('access administration pages'),
    );
    $items['package/%/edit'] = array(
        'title' => 'Edit Membership',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('pricepackages_form_update'),
        'access arguments' => array('access administration pages'),
    );
    return $items;
}

3rd menu is for eidt purpose...

The codd to show form i worte is:

function pricepackages_form_update($form, &$form_state)
{
    $form['packagename'] = array(
        '#type' => 'textfield',
        '#title' => 'Package Name',
        '#required' => TRUE,
    );
}

Please let me know how can get the value of the id in the url :

URL :  http://somedomain.com/package/1/edit

I want to get the id 1 from the url and than want to add a select query... please let me know how can i get that value so i can wrote teh select query...

Also do i have to specify a new parameter in the pricepackages_form_update() or not?

Thanks in advance...

Try It works for me.

$items['package/%/edit'] = array(
'title' => 'Edit data Row',
'page callback' => 'pricepackages_form_update',
'page arguments' =>array(1),
'type' => MENU_NORMAL_ITEM,
'access callback' => TRUE,
);

function pricepackages_form_update($arg){
$my_object = db_select('your table name', 'a')
->fields('a')
->condition('your node id parameter', $arg )
->execute()
->fetchAssoc();
return drupal_get_form('your form menu', $my_object);
}


Should I choose MyISAM for notification tables? Using Drupal6 with a MariaDB 10 InnoDB engine for all tables, I have noticed that insert queries into notifications_* tables are very inefficient on InnoDB tables. For example, these frequently in my slow_query_log:

INSERT INTO notifications_event (module, type, action, oid, uid, params, created, counter)
VALUES ('XXX', 'XXX', 'XXX', XXX, XXX, 'XXX', XXX, XXX);

INSERT INTO notifications_fields (sid, field, value, intval)
VALUES(XXX, 'XXX', 'XXX', XXX);

QUESTIONS

Would be a good idea to convert such tables into MyISAM?
Any downside for using such mix of storage engines?
Is there a better solution to shorten the insert time?

DISCLAIMER : Pure MySQL Perspective
IMHO, you should leave it as InnoDB. MyISAM is not good in high-write situations. Why ?
LOCKING GRANULARITY
Each time you issue an INSERT, UPDATE, or DELETE query on a MyISAM table

The query performs a full table lock
All other queries needing to do the INSERT, UPDATE, or DELETE queries are handled on a first-come first-serve basis

InnoDB has row-level locking. In order to accommodate this, InnoDB caches INSERTs, UPDATEs, and DELETEs in the Buffer Pool, Log buffer, and Undo Logs.
DATA CACHING
MyISAM caches index pages from each MyISAM table's .MYI file in the key buffer.
MyISAM does not cache data. It has to piggyback from the OS for that. You can change the row format of the MyISAM to increase read speed from disk at the expense of double the table's disk usage. Write speed may be adjusted with concurrent INSERTs.
InnoDB caches data and indexes pages in the InnoDB Buffer Pool. You may need a decent size to accommodate data and indexes.
EPILOGUE
You just have to tune some vital settings. Here are some of my past suggestions from the DBA StackExchange.
In favor of InnoDB

Jan 11, 2013 : Very poor insert performance MySQL / Percona Server
Dec 06, 2012 : InnoDB insertion faster
Aug 03, 2012 : Slow insert performance in mysql innodb table for solr indexing
Jul 04, 2012 : Capabilities of InnoDB INSERT Performance

In favor of MyISAM

May 03, 2012 : Which is faster, InnoDB or MyISAM?
Jan 03, 2012 : Optimized my.cnf for high-end and busy server
Sep 20, 2011 : Best of MyISAM and InnoDB
Aug 12, 2011 : Which DBMS is good for super-fast reads and a simple data structure?

Although I lean towards InnoDB, I will leave it to you to decide which storage engine you want to use and tune for.


How to create a product display view showing all users who purchased a product through a specific display Im looking to create a view which will have an exposed filter of Product Display Titles in a select list and then display a table of users who purchased a product which originated from that display. The product will be used on multiple displays so this is important to get that filter. Im really struggling to achieve this and so far am getting it to display users for a product but not the display.

It seems the only indicator of the original product display is the display path. I thought I had cracked it but its just not working. If anyone can have a go or walk me through it that would be amazing.

Thanks all

Your view needs to have this relationship setup, with multiple relationships added so you can relate your entities in this way.

Product Display > Product > Order > User

I should be able to provide a stronger answer if you can provide a little more detail, but have struggled with a similar view I had to create about 2 years ago and remember it taking a few days for me to resolve :)

Good luck!


Can I use a theme done for the previous version in the latest core version? Is it possible/advisable to use a Drupal 7 theme on a Drupal 8 installation?

I'm starting my first Drupal 8 project. Generally, I hit up a place like ThemeForest for a theme, but their D8 theme selection is depressingly slim. Can I use a (highly rated and actively maintained) D7 theme instead? Is there a better place to look for professionally built D8 themes?

No. You could convert one if you have the time - which involves turning all tpl files to twig, updating the syntax, and making necessary changes to the template.php file (which gets renamed to template.theme). That also includes replacing any functions that don't exist anymore, and using the new D8 equivalent. Again, not too hard, but it can be if you are brand new to D8.

For smaller themes, this can take few hours to a day or two; for more involved themes, it can take longer.


Add a select list to the content of the view Could we add a select list in a view content?

I have below view and I want to add a select list that has (Approve and Reject items) for each row under 'Status' column. Also, there will be a 'Save' button to save the changes in database.

Can we do this in view or there is another way? Please help..

Please read post Programmatically Creating Forms with Views in Drupal 7 which is very close to your requirement.


How do I hide one word from a view result column I have a view which displays content overview using a table. I have joined two columns, a and b, in the table.

I want the column to display like the red square... currently they show as the red ellipse. Column a is "moderation state" and column b is "publish time".

Since I want to display an item from two different tables, I used an if-else statement.

if ($row->state == 'published') {
  echo "$date";
}
else {
  echo "$row->state";
}


Accessing hreflang in a preprocessor or twig layer How do I access this link in either the twig layer or a preprocessor in Drupal 8. I need to modify to edit the hreflang.  Thanks

<link href="http://www.drupal.com/au" rel="alternate" hreflang="au" />

function MODULE_page_attachments_alter(array &$attachments) {
 foreach ($attachments['#attached']['html_head'] as $can_key => $can_value) {
       foreach ($can_value as $low_value) {
          if (isset($low_value['#attributes']['rel']) && $low_value['#attributes']['rel'] == 'alternate') {
             // Unset canonical tags if present there.
             $attachments['#attached']['html_head'][$can_key]['#attributes']['hreflang'] = 'your value';
           }
        }
     }
}


Print fields a different node I have a News page which links to a bunch of news articles and I'm looking to print the header of the News Page on the individual articles.

The field_get_items doesn't return anything right now.  Any advice would be greatly appreciated!

if ($node->type == 'article') {
         $news_header = field_get_items('page', $node, 'group_header'); print_r($news_header);

             //$url = file_create_url($node->field_header_image['und'][0]['uri']);
             //echo '<img src="' . $url . '" width="100%">';
            // }
        }

Are you loading the node first? If you are not getting anything returned then it's probably because $node isn't set. Also is the 'News node' a node type of article?

I would start by trying to retrieve the node information first:

$node = node_load(arg(1));
var_dump($node);

Also I think your field_get_items is not working as your entity type is 'page' but you are inside a check for a node type of article try:

$news_header = field_get_items('node', $node, 'group_header');


Configuration Management Module Keeps Saying 'needs attention' I've just started using the configuration module to keep my Drupal database in sync between my development and live environments.

Documentation for this module is sparse, and I'm trying to understand how it works.

I went to the UI and started tracking a single custom content type. It goes ahead an tells me it is tracking that content type, plus all its custom fields and everything which is great.

But then when I go to the 'tracking' tab, it lists all the stuff it is tracking, and in the side tabs, it says that things 'need attention', for example the 'content type' tab says '1 needs attention'. Yet, when I look at the status of the tracked configurations, it simply says 'In sync'.

What exactly 'needs attention', and how do I make it stop saying this?

It means that there is a difference between activestore and datastore for those items.

Below you see that those items are overriden. The ones in data store are old versions. If this is a dev environment and those changes are necessarry, you can write these changes to datastore and push/migrate to prod environment.

The below changes are for example purpose and they are not necessarry to put to prod version, since they are about things like last running of cron, etc.

The below image a real change in activestore. You can write that down on datastore by clicking Write Activestore to Datastore.