How to replace the date field selects with one text field in Drupal 7 web forms I am using webforms in Drupal 7. Is there a way to set the date field to a single textfield instead of 3 select fields?

Since it seems like the webfrom module doesn't support this functionality yet, if found that the easiest way to do this, was to use a textfield and use form_alter to add the datepicker plugin.

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

  if($form_id != 'webform_client_form_2') return;

  // Alter textfield for date to integrate popup calendar
  $form["submitted"]["expected_move_date"] = array(
    '#type' => 'item',
    'finished_after' => array(
      '#type' => 'textfield',
      '#attributes' => array('class' => array('datepicker')),
      '#required' => TRUE,
    )
  );

  $form['#after_build'] = array('custom_form_uidatepicker');

}

function custom_form_uidatepicker($form, $form_state) {
  drupal_add_library('system', 'ui.datepicker');
  drupal_add_js("(function ($) { $('.datepicker').datepicker({
      showOn: 'both',
      buttonImage: 'sites/all/modules/custom/custom_form/images/calendar.png',
      buttonImageOnly: true,
      dateFormat: 'dd/mm/yy',
    });
    $('.datepicker').datepicker( 'option', 'minDate', 'd' );
    })(jQuery);", array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

    return $form;
}

It might be best to use the webform_scheduler as that has the date popup dialog already installed.  More details from the module's project page:

  It adds an optional start date and end date field to the webform form settings. If the current date and time falls outside the specified window, the webform is disabled.


Problem with creating own module Block with an SQL query I’m trying to create a custom module that implements a block to display something I haven’t been able to do with the Views 2 module.
I’ve tried to look at some guides and tutorials, but I haven’t got any result yet.

I can print out the first SELECT attribute in the first row. The first row make sense since I don’t loop through it but still I’m confused on how to do the rest.

function sn_most_contributed_block($op='list', $delta=0) {
  if ($op == "list") {
    // Generate listing of blocks from this module, for the admin/block page
    $block = array();
    $block[0]["info"] = t('Most Contribution this week (custom module');
    return $block;
  }
  elseif ($op == 'view') {
    $mce = db_result(
      db_query("SELECT node.uid, COUNT(nid), users.picture AS users_picture, users.uid AS users_uid, users.name AS users_name, users.mail AS users_mail FROM node node INNER JOIN users users ON node.uid = users.uid WHERE (node.type IN ('leads',  'qa',  'qa_comments',  'til_salg',  'tips_tricks')) AND node.created >= UNIX_TIMESTAMP( CURDATE( ) - INTERVAL 1 WEEK ) AND node.created <= UNIX_TIMESTAMP( CURDATE( ) + INTERVAL 1 DAY ) GROUP BY uid ORDER BY COUNT(nid) DESC LIMIT 0 , 5")
    );

    $block_content .= "Most contributed members are: " . $mce';
    $block_content .= "
In here should be the user image
";
    $block_content .= "
In here should be the username
";

    if ($block_content == '') {
      $block['subject'] = 'contribution test';
      $block['content'] = 'yay';
      return $block;
    }
    else {
      // set up the block
      $block = array();
      $block['subject'] = 'Most contribution this week';
      $block['content'] = $block_content;
      return $block;
    }
  }
}

I’ve tested my query in the database environment for my Drupal site and it works and print everything it should out correctly.

For looping the query, I tried this code with no result.

while ($contriUser = db_fetch_object($mce)) {
  $contriUser [] = $contriUser->uid;
}

I have also tried the following code.

while ($contriUser = db_fetch_object($mce)) {
  var_dump($contriUser);
}

Any help on how to solve this or if someone has an alternative solution to get the most contributing members last seven days it would be much appreciated.

For most contributing members you may want to look at the user points modules, they give you a lot of very nice features.

A couple of quick pointers with your code as you are asking.

Your query should use parameters and be formatted according to drupal coding standards, this helps for security and portability. The coder module can help you with this.

To get the results you will probably want something like db_fetch_array in a loop

 $result_set = db_query("SELECT ...");
 while ($result = db_fetch_array($result_set)) {
   $block_content .= ...;
 }

I hope this helps a little.

If you have views 3, dereine has kindly posted an import for this http://drupal.org/node/1186598#comment-4593972


A simple field to hold date value For a content type, I need a field holding the value of a certain date in history. The content type will be used to hold some historic events and when the current date matches (September 17th, for example) the node will be displayed.

I know that the date module can handle such things but it is quite comprehensive and I will not be using calendars or event content types. All I need is to hold a date value and compare its day and month part with the current date's.

Is there a simple solution?

The Date module will store date time in this format: "2012-05-25 hh:mm:ss" . Using PHP's date_parse function you can extract all those values. What easier thing do you need?

I think another solution is to create a long text type field and change Text processing to Filtered text (user selects text format) and give Default value (write your logic in PHP (include  tags)). And save it. Then edit it one more time and change Text format to PHP code.


Custom exposed filter for year in date field with ajax I am trying to create a custom exposed filter which would be a select field with years (2015-2025).
This would filter the result with the year of the date they are created.
I followed this tutorial https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8
But here there is no solution for ajax submission, so the page does not refresh and the filter does not apply.

Currently I have this year as a contextual filter and the form field in the hook_form_views_exposed_form_alter():

$options = [
    'all' => t('- All -'),
    '2015' => '2015',
    '2016' => '2016',
    '2017' => '2017',
    '2018' => '2018',
    '2019' => '2019',
    '2020' => '2020',
    '2021' => '2021',
    '2022' => '2022',
    '2023' => '2023',
    '2024' => '2024',
    '2025' => '2025',
  ];

  $form['year'] = [
    '#title' => t('By year'),
    '#type' => 'select',
    '#options' => $options,
    '#size' => NULL,
    '#default_value' => 'all',
  ];

Is there a possibility for the filter to work with ajax submission?

You can use this custom filter to filter by year:
https://github.com/DarkteK/d8-views-custom-filter/tree/master/d8_filters
Just change the years you want to use in the file 'ViewsYearsFilter.php'
This will work with Ajax

I believe Views Better Exposed Filters can achieve this: What else can I do with BEF?: Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed


How do I send an email to all users that has flagged a node using rules? I need to send an email when there is a new comment on a node to all users that have flagged that node? How do I do this?

The flag is called "Follow" and the content type is "Blog"

The exported code assumes use of Flag module to have a flag type as "follow" attached to Blog content type.

As a summary:

set rule event as "After saving a new comment of type Blog comment".
leave condition as none.
set actions as

step 1: get all users
who have flagged "Fetch users who have flagged a Node".
step2: loop
through the list.

step2.1: send email

Here is the export for my Rule configured as per your requirement.

{ "rules_email_on_blog_comment" : {
    "LABEL" : "Email On Blog Comment",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "blog", "email" ],
    "REQUIRES" : [ "flag", "rules", "comment" ],
    "ON" : { "comment_insert--comment_node_blog" : { "bundle" : "comment_node_blog" } },
    "DO" : [
      { "flag_fetch_users_node" : {
          "USING" : { "flag" : "follow", "node" : [ "comment:node" ] },
          "PROVIDE" : { "users" : { "users" : "Users who flagged" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "mail" : {
                "to" : "[list-item:mail]",
                "subject" : "New Comment",
                "message" : "There is a new comment on the flagged blog post",
                "from" : "[site:mail]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

You can use a loop to get all the users who have flagged, and you can add an action to send mail to all those users under that loop.


Force rebuild of aggregated css/js I have manually removed all aggregated css and js files from sites/default/files.

I would like Drupal to regenerate these, but it does not. Drupal is still looking for the old files, the ones I have deleted.

Clearing the cache does nothing.

How do I force Drupal to recognize that the files are missing and need to be recreated?

In D7 you might want to clear also the variables drupal_js_cache_files and drupal_css_cache_files:

drush vdel drupal_js_cache_files && drush vdel drupal_css_cache_files

Other than that, do you have any other cache on top of drupal (varnish?). Your pages could be cached with the reference to the old JS files. Is your site broken (404 on CSS/JS files) or is it just referencing the old ones? Usually drupal regenerates aggregated files if it can't find it.


Trying to enter an argument with multiple words into a Views argument I'm using Organic Groups with Views in Drupal 7  with OG Tokens to create a view which returns all content with a type associated with it, so groups/foo/article would return all articles where the content type is article and the group is foo. This works fine for a group audience where the audience is one word, such as foo, or two run together without spaces, such as FooBar. However when I create a group like foo-bar, the view returns the no content page even when there is content attached the group. The contextual filter that I am using is OG Group: Label.

I've tried putting PHP to explode the results in the 'WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED', following the posts that I've seen but although I can see it printing out the "foo bar", it is not calling the types attached to the group. Is there somewhere else that I can explode this data and remove the spaces so that the group details can be presented in the view, or even look at the query to see what is being passed into it by the argument?

Thanks for your help and time.

UPDATE:
Having run a slightly orthogonal search, i came across the following code:

    $handler->argument = str_replace('_', ' ', $argument);
    return TRUE;

Having replaced the underscore with a dash, the multi-worded OG audience type can be used as I outlined above. Put the code into the "PHP Validate" code on the specify validation code and apply. The original came from PixelClever . I'll mark as answered when the site allows me to do so as I don't have enough user points to do so immediately.

If the arguments are not in a taxonomy term then add a vocabulary to contain them
Under the contextual filter section for When the filter value is in the URL check validation, set it to a Taxonomy term  and pick the vocabulary.
Select the Filter type or term name from the term ID
Check the box for Transform Dashes.

The view should now read the name from the URL and access the term id.


How know what theme/theme name a Drupal site is using? Like in Wordpress, we can know what theme name a site is using by look at the page source and it will show something like

wp-content/theme/theme-name

Well, how we can know what theme a Drupal site is using? I try to look at the page source of a Drupal site but i cannot figure out what theme or theme name the site is using.

Is there any trick to unlock this?

You can get it from source of any page. Have a look for the javascript array at the top/bottom of the page that begins with:

jQuery.extend(Drupal.settings, {...

There's a setting in that array called "theme" which contains the name of the theme being used for that page.

Just right-click on the drupal logo image or any Drupal site's logo image that appears at the top, and select "Inspect element". In the src of the image the name following "themes/" is the name of current theme; e.g. http://sitename.com/themes/bartik/logo.png then bartik is the current theme.


Prevent directory permissions of sites/default from being protected in a local environment? Drupal automatically changes the directory permissions of sites/default to 555 (i.e. read-only), which means that if I'm editing sites/default/settings.php, even if I've set the permissions for that file to read/write (which it again reverts on a page load), PhpStorm still gives me a permission denied error on the swap file it's attempting to create in the same directory.

Is there a more flexible way to update settings (especially on
a dev machine) other than manually setting the file and directory
permissions every time you need to edit those files?
Do I just have to do it via sudo?
Can I disable permissions checking for a specific environment?

If you are on Drupal 8, you can configure settings.php to include a settings.local.php with a simple environment check (to ensure you are running a local env).

In that file, you can add this:

$settings['skip_permissions_hardening'] = TRUE;

This will allow you to open and write to settings.php without it being locked back down.

Filezilla allowed me to change the permissions from the the Filezilla console when cpanel could not Drupal Docs


Skip to Main Content link not working? The theme I'm using (AT Panels Everywhere subtheme for Adaptivetheme) has the following skip navigation link:

Skip to main content

but that link goes nowhere when I hit Enter when that div becomes focused as I tab through on the keyboard.

I tried adding the "content" anchor tag like this:

<?php print $content; ?>

but it still doesn't work. I'm still forced to tab through every link on the page.

What am I doing wrong?

Try changing your code like this

Skip
<?php print $content; ?>


Get future node id (nid) of nodes being programmatically created (future node) I want to create multiple nodes using one form, but I'd like to have connection between them stored in Entity Reference, so I need to know their nids. But they aren't created yet, so they hasn't nids.

Question: Is there a way to predict future nodes nids and preserve them for a while or do something similar to deal with task above?

Unfortunately, there's no a clean way to do that!

If you insert a new node say node/71 then next node will always be node/72
NIDs are auto incremented in mysql tables.
To get the NID of recently inserted node you can do this query.
SELECT MAX(nid) FROM {node}
You can increment it by 1 to predict next node nid.


Problem w/ Migrate Source CSV importing Body content w/ HTML I am using migrate_source_csv to import node body fields. The header for my CSV file is: "nid, title, body". The body fields contain HTML. My problem is that, on import, the HTML is being encoded into literals. See the screen grab below. Here is my migration YML file:

id: news_article_nodes
label: News article data we want.
migration_group: gdg_group
source:
  plugin: csv
  path: 'modules/custom/gdg_migration/import/news_article/news_articles.csv'
  ids: [nid]
  header_row_count: 1
process:
  nid: nid
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: full_html
destination:
   plugin: entity:node
   overwrite_properties:
     - body
   default_bundle: news_article

I must be missing something. Is there a plugin that imports the data as plain text?

You could try to use PHP's html_entity_decode() on the source field:

process:
  nid: nid
  title: title
  body/value:
    plugin: callback
    callable: html_entity_decode
    source: body
  body/format:
    plugin: default_value
    default_value: full_html

PS: You've written that your source CSV doesn't contain encoded entities... have you checked the display settings for your field? (Manage > Structure > Content types > NODE_TYPE > Manage display). It could be that the import is correct, but the render settings are incorrectly set to something like plain text or a |raw filter in a Twig template file.

you have just to remove de /0/ from body field

 body/value: body
 body/format:
  plugin: default_value
  default_value: full_html


Two different front pages? I have a website at mydomain.com. I am creating a clone of it on mydomain2.com. The only difference is that I want the landing pages to be different. Both domains are running the same codebase.

How do I make the landing page differ, depending on what domain you are on?

(Note: Without using i18n)

You can do this by using the Domain Access module which is meant for creating a site (with one code base and one database) where certain content is accessible by DomainA and other content is accessible by DomainB. In your case you can set all content to be accessible to both domains and just change the site settings for the front page based on current domain. In D8 there is the Domain Site Settings module which makes this easier, but in D7 you should use Domain Variable to change site_front based on the current domain.

This method will allow you (for example) to create two view pages or nodes or whatever (one for each domain) and display completely different content (or content in a different order) depending upon the domain.

you can use hook_theme in your template.php file to introduce two different theme to drupal, then in page.tpl.php file check if user is visiting current page (use $is_front variable for that) or you can use page--front.tpl.php, the you can check $front_page value which has the address of front page, based on different address you can print one of your themes

example :
in template.php :

function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'first_front' => array(
      'render element' => 'page',
      'template' => first-front-page,
    ),
    'second_front' => array(
      'render element' => 'page',
      'template' => second-front-page,
    ),
  );
}

then in page--front.tpl.php, use this code:

<?php if($front_page == "first_url") : ?>
  <?php print render(theme('first_page', array('page' => $page))); ?>
<?php endif; ?>
<?php if($front_page == "second_url") : ?>
  <?php print render(theme('second_page', array('page' => $page))); ?>
<?php endif; ?>


How to set default role as 'Member' in drupal 7? If I have a role i.e. Member. How to set 'Member' as a default role for the users after they registered yourself ? Please help. Thanks

Use Auto Assign Role module to set a default role at the time of user registration.

You can also use registration_role module to fulfill your requirement.

click edit column on People page on specific user who will have role Member, and tick Memeber checkbox on that edit page.


Undefined variable: nid I put this code in Rules Action PHP Evaluation. What I want is getting the field_price's value, changing it for negative and returning it for Rule. With this I will be able to charge points because in Rules (Drupal 7) it is impossible to put "-" before data-selector (in this case, field_price's value) and make it negative to charge these points instead of adding them.

<?php
if (arg(0) == 'node') {
   $nid = arg(1);
}
   $node = node_load($nid);
   $value = $node->field_price['und'][0]['value'];
   return $value;
?>

The reason you're getting the error "Undefined variable: nid" in some cases is obvious. You're only assigning a value to $nid if the following is TRUE: arg(0) == 'node'. If arg(0) is something else, $nid never becomes defined, causing the error.

Since it doesn't make sense to use $nid unless it is defined, you can get rid of error by moving the construct where you use the value of $nid inside the if-test, like this:

<?php
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $value = $node->field_price['und'][0]['value'];
  return $value;
}
else {
  return FALSE;
}
?>

Note that this will return the value stored in the field field_price if arg(0) is equal to the string 'node', and return FALSE otherwise.

You write:

  What I want is getting the field_price's value, changing it for negative and returning it for Rule.

Please note that your original code does not do that.  Nor does mine.  I just told you how to fix the bug. The business logic is still up to you.

Please also note that this has nothing to do with Drupal - it is Programming 101.

Assumptions:

You have a numeric array named arg where you are storing node type in even indexes and node id in odd indexes.
You want to load the specific node into memory and call the member function field_price of node object which is a custom field added using the hook node_field_extra_fields().

Now if my assumptions are correct, then the solution to you problem should be :

<?php
function get_node_price{
if ($arg[0] == 'node') {
   $nid = $arg[1];
}
   $node = node_load($nid,NULL,FALSE);
   //Not sure whether the args and the method are correct here as it's custom.
   $value = $node->field_price['und'][0]['value'];
   return $value;
}
?>


Pulling Possible Select Values From A Field (Drupal 7) I have been looking if there is a function that return all the possible values for a field. I have a select field that is a Node Ref. So, function list_allowed_values() is out of the question. Because, list_allowed_values() is not compatible with Node Ref. Does anyone know a function to get all the possible Node Ref for a field?

Or do have to code my own function?
Thanks,
Nate

Ok, I did some digger on google. ychaugule made a nice function for this problem. Here is the post.
Also, reference to the information here:

"But the above code will only work for select list, not for node reference or other types of references. _field_allowed_values() function is a custom function which returns allowed values of reference type field. The function returns allowed values for node reference and term reference field and can be extended to get allowed values of other reference fields as well. - See more at: http://yogeshchaugule.com/blog/2013/get-allowed-values-select-list-field#sthash.xnf89Cgn.dpuf"

<?php
function _field_allowed_values($field_name) {
      // retrieve field configurations from DB.
  $allowed_values = array();
  $query = db_select('field_config');
  $query->condition('field_name',$field_name)
  ->fields('field_config',array('type', 'data'));

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

// Allowed references type
  $ref_type = array(
    'node_reference',
    'taxonomy_term_reference',
    );

  $field_config = unserialize($result['data']);
  if (in_array($result['type'], $ref_type)) {
    if ($result['type'] == 'node_reference') {
      $node_types = array_filter($field_config['settings']['referenceable_types']);

      $query = db_select('node');
      $query->condition('type', $node_types, 'in')
      ->condition('status', 1)
      ->fields('node', array('nid', 'title'));
      $allowed_values = $query->execute()->fetchAllKeyed(0, 1);
    }
    elseif ($result['type'] == 'taxonomy_term_reference') {
      $allowed_values = taxonomy_allowed_values($field_config);
    }
  }
  else {
    $allowed_values_raw = unserialize($result['data']);
    $allowed_values = (!empty($allowed_values_raw['settings']['allowed_values']) ? $allowed_values_raw['settings']['allowed_values'] : array());
  }
  return

  $allowed_values;
}

$field = _field_allowed_values('FIELD_NAME');


How do I translate a meta tag? I want to translate the title meta tag added to views on a Drupal 8 site, but I didn't see any option in the Translate View section.

How can I translate meta tags?

I've added a title metatag to the default Content view. Then went to translation page where I found the string to translate under Displays-> Page Display Settings-> Display Extenders-> Test Metatags

For Meta tags to work with views you will need to enable Metatag module and Metatag: Views submodule both part of the Metatag module download.

You need to go to Extend from the admin menu and enable the 2 modules


Adding an Image field in webform module I am a newbie to drupal 7 and just started working with it a couple of months ago. My problem is I am making a "webform" where the user filling the form should upload his image. But as there is no such field I am not able to understand how to do it.....

I also tried the "entityform"  but as I install it and enable it, the edit links all over my website starts throwing an exception...

So please help me. Any help will be appreciated.

Thanks in advance.

To add an image field to a webform:

To go the webform tab where you manage the fields.
Add a new field of type file:
On the new field configuration page it's a good idea to set an Upload directory for your images. This means all the images upload from this field will sit in a particular folder in your files directly and help prevent too many files from sitting in one folder. You can also choose what types of files you want to allow users to upload. For an image field I would suggest only gif, jpg, and png.
Set any other settings such a label or display settings as required.
Finally save the component.
Now when you visit the frontend of your webform you should see your new field:

I'd recommend you to try Webform Select Image. This module adds a new image component to the webform.

The purpose of this module is to add an images select component for webform (checkboxes or radios buttons).

Download and enable this module

Go to webform components admin page

Choose "Select image"

Upload your image, choose image style and other component settings


Sending Email verification when registering programmatically I have created multi-step form through custom module. I am using user_save() function to register the user and user_mail_notify() to send the email.

Now I am not sure what should I send in _user_mail_notify() so email verification link will work.

I have account settings in the backend as shown in screenshot

and sending op value as 'register_no_approval_required' in _user_mail_notify() function. I am receiving verification email in inbox but when I click it then it doesn't work.

However it works when we register through default registration form. Please let me know if anything I am missing to add.

When you create a new account using "user_save()", What status you passed "0" or "1", If you required email verification then it should be 'status' => 0, in user_save().

Solved, My problem are email service on server.

Now I use smpt (https://www.drupal.org/project/smtp)

It's ok.


Drush installed but all commands could not be found I have drush installed on a remote server and was able to successfully run commands this morning, however I tried executing Drush Self-Update and got a permission error probably because I don't have sudo rights etc and now any drush commands I try run return the error The drush command 'drush_command_here' could not be found.
when I run which drush it returns /usr/bin/drush so I know its installed + other users on the server can run drush commands without issue.
I tried adding the drush alias in my .bashrc file like this alias = '/usr/bin/drush' and also tried using the alias pointing to usr/share/drush but no luck.

Ended up uninstalling and re-installing drush and seems to have fixed my problem. Thanks.


Load a file entity by URI Is there a way to load a file by URI in Drupal 9 and/or Drupal 8?
In Drupal 7 it is possible using the following code.
$uri = 'public://file.xyz';

// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files); // If empty, $file will be false, otherwise will contain the required file

Taken from here https://www.drupal.org/forum/support/module-development-and-code-questions/2012-06-06/load-a-file-by-uri#comment-6493610

There is the loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface that allows to define required condition in searching the file entity by the given file URI:
/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;

All answers here work, but what about if you don't know the file URI but only the URL like www.mysite.com/sites/default/files/blog-images/stack.jpg for which we want to get the ID.
We could do it like this:
Answer for Drupal 8 & 9
function _mymodule_get_file_data($file_url) {
  $file_name = Drupal::service('file_system')->basename($file_url);
  $target_file = Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['filename' => $file_name]);
  $file_data = reset($target_file);
  if ($file_data) {
    return($file_data);
  }
  else {
    return FALSE;
  }
}

// Usage.
$file_url = 'https://drupal.stackexchange.com/sites/default/files/2020-10/blog-images/stack.jpg';
$get_file_data = _mymodule_get_file_data($file_url);
// File ID.
$file_id = $get_file_data->get('fid')->value;
// File URI.
$file_url = $get_file_data->get('uri')->value;
// Should print 'public://2020-10/blog-images/stack.jpg' or 'private://2020-10/blog-images/stack.jpg'.

// Uploader user ID.
$get_uploader_user_id = $get_file_data->get('uid')->value;

Answer for Drupal 7
function _mymodule_get_file_data($file_url) {
  $file_name = drupal_basename($file_url);
  $target_file = file_load_multiple(array(), array('filename' => $file_name));
  $file_data = reset($target_file);
  if($file_data) {
    return($file_data);
  }
  else {
    return FALSE;
  }
}

// Usage.
$file_url = 'https://drupal.stackexchange.com/sites/default/files/2020-10/blog-images/stack.jpg';
$get_file_data = _mymodule_get_file_data($file_url);
// File ID.
$file_id = $get_file_data->get('fid')->value;
// File URI.
$file_url = $get_file_data->get('uri')->value;
// Should print 'public://2020-10/blog-images/stack.jpg' or 'private://2020-10/blog-images/stack.jpg'.
// Uploader user ID.
$get_uploader_user_id = $get_file_data->get('uid')->value;


Adding Adsense on a CCK field First of all I'm using drupal 6.19.
I'm trying to add adsense on my site unsuccessfully. =/
I want to put my adsense on a CCK field but isn't working.
When I put the code on a block everything works fine. But in a CCK field I'm in trouble.
Both, block and CCK field, are set to input format FULL HTML.
I don't know why doesn't work in the CCK field. Can anyone help me?

Try stripping the line breaks. Like they should be all going in one line.


How do I use the Rules module to unpublish content when End Date is hit? I have a Content type called Event, has a Start Date and End Date.

How do I use the Rules module (version 8.3.0-alpha1) to:

Publish the Event on the Start Date and
Unpublish it on the End Date?

My priority is to Unpublish the content when the End Date is hit.

Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content based on a supplied End Date?

I have this functionality on a D7 site I run, and we use the Scheduler module instead. Looks like there is an alpha release for D8 you could try: https://www.drupal.org/project/scheduler

You may want to look at https://www.drupal.org/project/business_rules module which seems to be much further along than D8 version of Rules. It, unlike Rules, does have an Unpublish action. The rest, at least in D7, would be to use Views Rules to make a View of all items past their end date and then you could use this View in Rules to loop through all the items and unpublish. Sadly, Views Rules is another module which has not made the D8 cut; but perhaps Business Rules has some sort of Views integration.


MAC -> Drush higher bootstrap level? Since a couple of days now, i switched from a ubuntu machine to a macbook pro retina for my development works.

I installed XAMPP on it, without to much trouble.
But I have been struggeling with drush for quite some time now, and I am hoping to find a little help here.

Drush partially works...
I can download Drupal, download modules etc.
I CANNOT enable the modules, perform sql-cli commands (however sql-connect DOES work?!).

The error i get is:

Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                                           [error]
The drush command 'en token' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.28
 Site URI               :  http:// default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  root
 Database name          :  drupal_site
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /Users/myusername/drush/php.ini /Users/myusername/drush/php.ini
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/XAMPP/htdocs/drupal_site
 Site path              :  sites/default

Now I have been googling around for this for days and found numerous topics, stating all kinds of things (change your settings.php file to use 127.0.0.1 instead of localhost => did not work)

One thing i would like to add is that i discovered that my OS runs a different php version as the XAMPP instance?!

Ps: My drupal_site is fully functional! Just drush won't work with me.

Any help would be very much appreciated!

Best,

Your drush is using system php, whereas Drupal is using XAMPP's. This reliably creates drush problems.

Look into XAMPP and figure out where its php binary is and then set your path accordingly in .bashrc or whatever other shell init files you have sitting around.

Check your progress with drush status, in particular what it reports for the database connection.

Use "127.0.0.1" instead of "localhost" as the hostname.


PaymentMethodManager() get plugin on NULL ubercart error Hi when trying to create an order in checkout state, the order gets created however when trying to view the order it errors out with the error below:

  Error: Call to a member function getPlugin() on null in Drupal\uc_payment\Plugin\PaymentMethodManager->createFromOrder() (line 45 of /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc_payment/src/Plugin/PaymentMethodManager.php) #0 /srv/bindings/6204a08fb5564631b33e310ef75fe465/code/modules/contrib/ubercart/payment/uc_payment/src/Plugin/Ubercart/OrderPane/Payment.php(50):

Ubercart version: Version: 8.x-4.0-alpha5+227-dev

My payment methods are all setup however in order creation code we don't need payment method. Anyone facing the same issue?

You can fix this error by applying the patch here: https://www.drupal.org/project/ubercart/issues/2826324


How to show thumbnails gallery images in the footer first section? i have installed node gallery module as well media gallery but media gallery is not working for my drupal version now i am using node gallery but its show like below image

but i want like

To do that you can use a views block to list all the pictures you want. After that you can use an image style to crop them like you want.

For the theming, feel free to use Views Theme Suggestion and Views Preprocess(ex : here) to add features et style images and content wrappers.

I hope it helped you.


Change background for authenticated user I'm pleased with my body background for my site; it looks great when not logged in.  But when a user is logged in I need a different one.  I need to specify a slightly different background because of the fact that my Marinelli-based D7 site's custom body background (2 horizontal bands of green and black) stays in position but all content moves down almost 100px due to the administrative menu at the top.

An authenticated user would not be able to see the navbar due to this color change  (green words on a now green background).

Can I specify an alternate background for authenticated users vs. visitors?  Or perhaps better:  Is there a way to specify that the body background should move down when the user logs in and all the admin menus show up at the top?

Here's my present CSS for body:

body.marinelli{
    background: #fff url(../img/backgrounds/body-background.jpg);
    background-repeat:repeat-x;
}

I think your solution would be the class "logged-in" and the CSS property "background-position" to move the background image down 100px for logged-in users:

body {
  background: #fff url(../img/backgrounds/body-background.jpg);
  background-repeat: repeat-x;
}

body.logged-in {
  background-position: 0 100px;
}

Drupal adds the logged-in class to the body if the user is logged in.

you can write your css like this

body.logged-in {
  /* add custom css here */
}


How to detect mobile viewport with in twig? Is there a way to detect screen display with in twig? I have a block and I want to render in a twig template using the twig tweak module, but only in mobile screen. It is surely possible to just hide it in CSS, but can it be done in twig? - https://www.drupal.org/project/twig_tweak

There is a Browser Object in twig which using that you can get some data about user's browser but it does not provide properties like screen width.

its recommended to use css or javascript in these situations but if you want to hide your block in server side so user might access only using a mobile phone then I recommend this steps:

first of all you should provide a value to check if user is using mobile or not, for this you should use a preprocess function (hook_preprocess_page I guess as will fire for any pages loaded) , there use a code like this to detect mobile, then add a boolean value to page which should be TRUE if user is using mobile.
after that in twig you will have that value, check if it is true and display your block


How do I Install Drupal Locally I have a html doc and css for a site that I do not currently have live. I want to use Drupal for the site but have a question about testing when changing the html/css into something compatible with Drupal: How do I check my progress to make sure things are working?

With an HTML doc, all I have to do is click the doc and it opens up in my browser. How do I test with Drupal in that way?

What steps do I take to install Drupal locally? I am running Windows, so do I use WAMP? I am a total noob, any help would be more than awesome.

Yes, you need to install Drupal locally to test the theme progress. There is a nice guide at http://drupal.org/node/307956, I hope it works for you. Please post back if you need more guidance. It is the easier way I know to get started with Drupal on your computer.

Check this out: https://github.com/cyberswat/drupal-lamp  It is pretty dang easy to install.


How to redirect to www without editing .htaccess file? What alternative methods are there for redirecting all page requests to the www version of a domain?

I know how to eidt the root .htaccess file but find that this method does not survive core updates.

Is there another way? Perhaps with a module?

It's always going to be better to do this with .htaccess, or in other web server config, but if you need to do it in php, put this at the top of settings.php:

if ($_SERVER['HTTP_HOST'] == 'example.com') {
  header('Location:http://www.example.com' . $_SERVER['REQUEST_URI']);
  exit();
}

You can change this behavior in your domain controller section of your cPanel


How can I theme field collection forms? I have a field_field_collection in content type (used to field collection module and have unlimited value). It has a number of fields as in the picture below:

And I want customize theme for it as template as in the picture below:

How I can I achieve that? I tried to write a template for it, but the result is bad. When I click "add another item" the result looks like shown in the picture under my code below.

Here is my code:

    <?php
    kpr($form);
    print drupal_render($form['title']);
    $i = 0;
    foreach($form['field_field_collection']['und'] as $items){
    if(isset($form['field_field_collection']['und'][$i])) {
        ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_01']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_02']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_3']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_4']);
                    ?>

    <?php
        $i++;
        }
    }
?>
<?php
    print drupal_render($form['field_field_collection']['und']['add_more']);
    hide($form['actions']);
    hide($form['additional_settings']);
    print drupal_render_children($form);
?>

And here is the result when I click "add another item":

If your requirement is to format Field Collection in Table Format, then Field Collection Table Module will help.


Admin toolbar default left / vertical On page load I need to

show the toolbar on the left / in vertical mode when in admin theme
collapse/minimize the toolbar when in frontend theme

I'm looking for the event and the function to trigger those actions programmatically, e.g. something like

$(document).on('toolbar.loaded', Drupal.toolbar.setOrientationLeft);

and

$(document).on('toolbar.loaded', Drupal.toolbar.closeToolbar);

(I'm using the Admin Toolbar plugin)

Please note that I'm looking a solution that does not check CSS classes or triggers DOM clicks, in order to avoid timing problems due to asynchronous loading or exisiting toolbar settings.

If you go through its possible to make it as horizontal. Try this code wherever needed:

jQuery('#toolbar-bar button').each(function(){
  if(jQuery(this).html() === 'Vertical orientation'){
    jQuery(this).click();
  }
  if(jQuery(this).find('span.label').text() === 'Tools'){
    var open = jQuery(".toolbar-box").find('.open').length;
    if (open > 0) {
      jQuery(this).find('span.label').click();
    }
  }
});

For checking try this in the console first and add snippet to your JS file.

Try please this code:

Drupal.behaviors.changeToolbar = {
  attach: function (context, settings) {
    // Your code (if) ...
    $(context).find('#toolbar-bar').click('.toolbar-toggle-orientation button'); // Change orientation.
    $(context).find('#toolbar-bar').click('.toolbar-item-administration'); // Close.
  }
};


extend('PagerDefault') doesn't call pager_default_initialize My code:

   $num_per_page = 1;

   $query = db_select('redagavimas', 'r')
      ->fields("r");
   $query->join('dusers', 'd', 'd.id = r.user');
   $query->join('companies', 'c', 'c.id = r.company');
   $query->join('documents', 'doc', 'doc.id = r.doc');

   $query->addField('d', 'name');
   $query->addField('d', 'surname');
   $query->addField('c', 'name', 'company');
   $query->addField('c', 'id', 'companyID');
   $query->addField('doc', 'name', 'docname');
   $query->addField('r', 'user', 'did');

   $query->extend('PagerDefault')->limit($num_per_page);
   $query->extend('TableSort')->orderByHeader($header);

   ....

   $result = $query->execute();

   ....

     '#suffix' => theme('pager', array( 'tags' => array())),

I don't see any pager; If I call somewhere pager_default_initialize(), then I see the pager. What I did wrong?

EDIT :

I try:

echo $query->extend('PagerDefault')->limit($num_per_page)->getCountQuery();

and get query, which return >100 rows.

As documented on the See the Extenders page on drupal.org:

  To use an extender, you must first have a query object. From the query object, the extend() method will return a new object that should be used in place of the query object. For example:

$query = $query->extend('PagerDefault');

  The above line takes a select query, creates a new PagerDefault query object that contains the original select query, and returns the new object. $query may now be used as if it were the original query object but with additional methods now available.

  Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost. For example, the following will not do what you expect:

So, you first line should looks like:

$query = db_select('redagavimas', 'r')->extend('PagerDefault')->fields("r");

You have to print the theme function like this:

print theme('pager', array('tags' => array());


How to change pager class to view I have HTML desing of pagger ,How to I assign my own class to pager in side view ?I dont have any idea about it so will you plese tell how can I ?

I believe there are two ways you can do it:-

In template.php , you can use theme_pager. Then overrite it.
You can make a views template and overrite it. For this just goto advance option in views and search for template suggestion.

I could not find a way to add a class to theme_pager() using the hook_preprocess_HOOK system, so here is a slightly different template.php solution that won't involve having to override a core function.

I noticed that views pagers are also run through theme_item_list() which does allow you to add classes.

function MYTHEME_preprocess_item_list(&$vars) {
  $vars['attributes']['class'][] = 'my-class';
}

You can/should add an if condition check to see that the list really is going to be a pager, e.g. use if ($vars['attributes']['class'][0] == 'pager') or some other identifier to confirm that you're adding the class to a pager ul.


Count results in Views using aggregation Is it possible to count results (e.g. count the nodes of the content type x) in a view, using aggregation (not programmatically)?

Yes, it is possible in Views 3 out of the box.
The idea is the same as in SQL aggregations. Lets see an example:

Edit your view and enable Views aggregations:

Remove default sort criteria.
Add fields “Content: Type” and “Content: Nid”:

Select COUNT function for Content: Nid:

To see what happens just turn on checkbox “Show the SQL query” at global Views settings page.

SELECT node.type AS node_type, COUNT(node.nid) AS nid
FROM
{node} node
WHERE (( (node.status = '1') ))
GROUP BY node_type
LIMIT 10 OFFSET 0

So, we are grouping nodes by node_type and calculating count for this groups.

Just in case someone comes across this.

I used the Views Date Format SQL to format the date to the granularity.

  The Views Date Format SQL module allows to format date fields using
  SQL. This enables group aggregation for date fields using the choosen
  granularity.

  The core functionality is to remove the date formatting from render()
  and put it in query(). I.e. format date values using SQL's DATE_FORMAT
  rather than PHP's format_date.

  This is achieved by assigning a new default handler to node 'created'
  and 'changed' date fields. This handler extends and overrides views's
  build in views_handler_field_date.

Worked right out of the box - easy as!


Undefined variable node in Drupal 7 I am using zaptech theme in Drupal 6 while I am upgrading existing site to Drupal 7 it give me the error: Undefined variable: node in include() ,themes\zaptech\page.tpl.php can anyone tell what the solution for the node object

Remove it unless you have an automatically loaded node associated with it.


How to reply to a comment through services in Drupal 7? I am using Drupal 7 as back-end for a mobile application. I am using comments in my application.

Can anyone help me to reply to comment through web-service?

This is how I was able to reply to a comment through web-service.

 URL:- example.com/rest/comment
 Method : POST
 Parameters:-
 nid :6
 pid: 4
 comment_body[und][0][value]: Some text

I hope you are using Services Module 3.x. So you can have a look at the unit test case file
http://cgit.drupalcode.org/services/tree/tests/functional/ServicesResourceCommentTests.test?id=refs/heads;id2=7.x-3.x#l100
There have a look at the method testCommentCreate.

public function testCommentCreate()

This may solve your problem.


theme() parameters sent to output.tpl.php What I am trying to do, is to set some variables in my function and to send this to my output.tpl.php.

My steps are the following.

Declare my theme template

function mymodule_theme() {
  return array(
    'my_file' => array('template' => 'output')
  );
};

Define the following function

function mymodule_myfunction() {
  $build['variables'] = array(
    '#theme' => 'my_file',
    '#variables' => $my_vars
  );
  return $build;
}

I use the following code for my output file (output.tpl.php)

<?php echo $my_vars[0]; ?>

I get an error saying $my_vars is unknown.

What am I doing wrong?

As described in Override template files based on template filename as well as hook name, if you theme function is my_file, your template file needs to be my-file.tpl.php; you cannot use output.tpl.php because Drupal would not recognize it as template file, at least until Drupal code is not changed as per the issue I linked.
The variables that you pass to the template file needs to be defined in your implementation of hook_theme().

Your code should be similar to the following one.

function mymodule_theme() {
  return array(
    'mymodule_output' => array('template' => 'mymodule-output', variables => array('my_vars' => NULL))
  );
};

function mymodule_myfunction() {
  // Add here the code that initializes $my_vars.
  // …

  $build['variables'] = array(
    '#theme' => 'mymodule_output',
    '#my_vars' => $my_vars
  );
  return $build;
}

// mymodule-output.tpl.php
<?php echo $my_vars[0]; ?>

I used mymodule_output as name of the theme function and mymodule-output.tpl.php as name of the template because the coding standards used from Drupal suggests to use the module name as prefix; it would not change if you used output where I used mymodule-output or mymodule_output.

If all you are doing is printing a variable, then you don't need a theme. Theme functions (and template files) are used when you plan to allow themes or other modules to alter the output of your module. That is why Drupal uses node as theme function: to allow themes to alter how a node is rendered. The Node module defines its own node.tpl.php file, and the Bartik theme uses its own node.tpl.php.

To simplify the task use the following code.

function mymodule_myfunction() {
  $my_vars = array()
  $my_vars[0] = 'bla bla bla';
  $my_vars[1] = 'some other value';
  return theme('my_file', $my_vars);
}

And your theme function will look like

function mymodule_theme() {
    return array(
        'my_file' => array(
            'template' => 'output',
            'variables' => array(),
         )
    );

}

Now in output.tpl.php you simply print

<?php print $variables[0]; ?>


Overriding the Blog username breadcrumb in the native Blog module I want to disable the blog username in the breadcrumb which reads:
Home > Blogs > John's blog > Blog post

I have found the function in the core Blog module:

/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));

  }
  return $node;
}

How should I best override this function in my theme?

A node preprocess function in your template.php file would probably do the trick:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'blog' && $vars['view_mode'] == 'full') {
    $bc = function_to_get_breadcrumb();
    drupal_set_breadcrumb($bc);
  }
}

This should happen early on enough in the page build process for the changes to make their way through to page.tpl.php. You could also look at doing this in hook_node_view() in a custom module if you'd prefer.

Just edit the "modules\blog\blog.module" file, and look for the function where get the breadcrumbs array:

/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog')));
  }
  return $node;
}


Add extra text input for file field For Drupal 7, in page content type there is a multiple file upload section. Description is enabled for the file upload, but I need to add one more text input for each images to ask user enter the year file belongs to.

I am not very good at Drupal. So if I can find a clear solution it will save my day. Thank you from now.

I would recommend using the field collection module instead. Create a field collection with a file upload field, description field and file owner field (can be a text field or user reference field. Set the field collection to unlimited. Then add the field collection to your page content type. It will allow you to do more custom things moving forward.

https://www.drupal.org/project/field_collection
https://www.drupal.org/project/references


How to determine if the current page is a search results page? How can I determine from within a module or theme if the current page is an Apache solr search results page?

If you're trying to determine from a module then you can check if the page is the search results page via the path arguments using the arg() function.

if (arg(0) == 'search') {
  TRUE
}
else {
  FALSE
}

In case you are talking about a theme or module you could check the current URL/path if it begins with "search".


How to have two domains for same site, but site working in directory in second domain? Example:

www.domain1.com -> Drupal site in root dir (Managed by Apache)

www.domain2.com/usa -> Drupal site of domain1.com (Managed by Nginx)

The idea is that www.domain2.com/<countrycode> points to the real domain but in a transparent way (User must not see the existence of the real domain).

What I did:

1) Configured nginx as reverse proxy:

## HTTP server.
server {
    listen 80; # IPv4

    server_name emed.com, www.emed.com;

    access_log /var/log/nginx/drupal.log;
    error_log /var/log/nginx/drupal.log;

    keepalive_timeout 75 75;

    root /opt/www/web/drupal;
    index index.php;

    include apps/drupal/drupal.conf;

    location /fr/ {
        proxy_set_header Host $host;
        proxy_pass http://localhost:8080/fr/;
        proxy_redirect http://localhost:8080/fr/ http://www.emed.com/fr/;
    }

}

2) Configured Apache

<VirtualHost *:8080>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
        Alias "/fr" "/var/www/html/drupal7"
</VirtualHost>

The problem is that Apache must have the Alias fr directive, otherwise Drupal generates incorrect URLs:

www.domain2.com/usa tries to load assets from www.domain2.com/sites/... instead of www.domain2.com/usa/sites/...

Is this even possible withouth using Alias? Because the first domain serves on / (root)

I think you have to check this module  https://www.drupal.org/project/domain
it has the solution for this


Managing large volume of content in tree hierarchy Firstly I apologise if this has already been answered. I thought it would be a common problem and I'm surprised that I haven't found a general solution anywhere.

I have a large corporate website (about 8000 pages) which is currently organised in our existing CMS in a multi-level tree structure. The navigation menus, breadcrumbs and URLs are all automatically built based on the position of content nodes in the tree. This makes it particularly easy for content editors to create new content in the right place and have the menus, breadcrumbs and URLs always consistent.

We are probably going to move to Drupal 7. What is the standard approach to large, tree-structured sites like this? I don't want to have to create new tag names (taxonomy terms?) for every single section since there are hundreds of 'container' type pages that contain lists of other pages. It seems far easier to just slot the node into a tree.

I suspect there is something obvious I'm missing - I would think it is pretty normal to have a tree like structure of content. Any help much appreciated.

Good strategy is to utilize Workbench and create sections from your menu.

So you would have your main menu, lets say 3-4 levels deep and mimic those in Taxonomy. Its easier to create taxonomy first as there is a module that will create menu from taxonomy.

So you create your taxonomy that has your structure going 3-4 levels deep. Then create a menu from it.

Install Workbench and Workbench Access and Moderation modules.

Configure Access to use Taxonomy for section assignment and then configure URL parameters to pull from Taxonomy as this will take care of your URL and breadcrumbs. Use Custom Breadcrumb module to generate breadcrumbs if you need them.

Then on each content type add a new filed for Sections which will pull from your taxonomy. So when adding content you select where in the tree it should live.

For example you are adding "Help" node which needs to live in About Us > Services  and About Us and Services are in the menu. Help does not need to be in menu but needs to follow the About Us > Services > Help path.

By using Workbench modules you can easily achieve that. In a sense your taxonomy acts as buckets into which content is placed. This drives URL, Breadcrumbs as well as left or right nav menu if you need one using Menu Block.

So to summarize the steps:

Create taxonomy of the items you want to be in menu.
Create menu from taxonomy using Taxonomy 2 Menu module.
Install Workbench suite of modules.
Configure workbench access to pull from Taxonomy.
Adjust content types to add a fields for Taxonomy selection, make it only 1 as you don't want multiple paths for nodes.
Configure URL Patterns to pull from taxonomy parents.
Install and configure Custom Breadcrumbs to also use URL path.
Install and configure Menu Block to use URL path.
Start adding content and assigning sections.

Additional benefits of this approach is that you can also restrict which roles or users can edit content in each section so you can have HR only have access to edit content in their part of the site.

I'm looking at Drupal for the first time and I found the lack of hierarchy support  troubling and I think constantly updating taxonomies would be too much overhead for any large site, especially with a distributed authoring base (e.g. large corporation or government agency).

I think I have found a solution using module Node Hierarchy (primarily) and some other modules.

Essentially you specify which content types are allowed to be children and/or parents, and then when editing a node you have the option to 'create child'.  Once child nodes are created, the parent node will have an option to view child nodes, and ordering can be controlled from this screen.

Use module Pathauto to automatically render URL alias based on parent-child-[child] relationships.

Finally use module Menu Block to add menus based on parent-child hierarchies.

A more detailed description/instruction is here:

https://www.youtube.com/watch?v=oz3xkF819c0

EDIT: Updated my answer to better conform to guidelines.


Validation with hook_form_alter() In Drupal 8, for the Comment entity, I want to validate an integer field (stored as field_nieuwe_waarde_value).
In each comment posted for a node, it needs to be greater than the value for the previous comment.

The code doesn't give any errors, but the validation doesn't work.

use Drupal\Core\Form\FormStateInterface;

       /**
        * Implements hook_form_alter().
        */

       function waarde_validatie_form_alter(&$form, $form_state, $form_id) {
         if ($form_id == 'comment_waarde_van_dit_voorwerp__form'){
           $form['#validate'][] = 'start_drupal_waarde_voorwerp_form_validate';
         }
       }

       /**
        * Validation form for the waarde_voorwerp form.
        *
        * Check if the value is > then the last submitted value
        */
       function start_drupal_waarde_voorwerp_form_validate($form, FormStateInterface &$form_state) {
         // Look for the just submitted value.
         $nieuwste_waarde = $form_state->getValue('field_nieuwe_waarde');
         // Look for all early submitted values.
         $alle_waarden = $form_state->getUserInput('field_nieuwe_waarde');
         // Search for the last submitted value.
         $laatste_bod = end($alle_waarden);
         if ($nieuwste_waarde <= $laatste_waarde) {
           $form_state->setErrorByName( t('Gelieve hoger dan'), $laatste_waarde, t('in te stellen'));
         }
       }

Adding a validation handler in hook_form_alter() is the Drupal 7 method of adding validation for a field. It will still work in Drupal 8, however the preferred method of adding validation to Field API Field in Drupal 8 is to add a Constraint to the field. Constraints will be applied when the Node is created, no matter the means of creation. Adding a validation handler to the form only validates the field when the node is created using the Form API - IE through a browser. If a node is created by any other means - IE through an API or programatically, the validation is not applied. Constraints are applied no matter the method of creating the node.

Documentation on how to add a constraint can be seen here: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

See Method 2 - adding constraints to fields added to an entity you haven't defined, or fields added through the UI

It is achieved by creating a new table in the database. Insert data by a hook_node_insert. And then fetch this data to validate. The getUserInput did not worked in this case.


Hook to change display widget in facet api from template.php In my site i have search api with one block facet option "Display widget" set to "Links with checkboxes"

but now i want to change the value to "Links"

because when the website is displayed on a mobile device i need to change to this option value.

Is there a way to change this option through any hook or another way to get this accomplished?

Maybe put a hook in template.php is my closes approach.

Thanks :)

Create another index and configure facet display differently


Why cant I configure or remove this module? I was trying to figure out Google Analytics and installing it broke my site so I uninstalled it.  Now I have reinstalled it, There is no link to configure it and the configuration page isn't even accessible from the URL.

So I tried to uninstall the module again and when I try to uninstall it goes to white screen and when I refresh I get back to the modules list and the module is still there.  I cannot configure or uninstall or get the module to work. It seems to be stuck there.

I have even tried to WinSCP into the server and straight up delete the module.  This removes the file from the list but when I reinstall the module I am back to square 1 where I cannot do anything with it.

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: "Call to undefined function google_analytics_clear_js_cache()"

Is there anything I can do?

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: Call to undefined function google_analytics_clear_js_cache()

This means that there is a bug in this module (and off-topic here).

But this is a general problem, and this anser provides is a general solution to this problem, that can also be used with other modules.

Whenever you get a WSOD upon uninstall and the log tell you it is because a "Call to an undefined function" - locate that call in the module's source code, and just delete the statement with the call.  Then try to uninstall again.

After doing this, make sure you report the problem to the module's issue queue on Drupal.org to make the maintainer fix it (and alert others about it).

Just uninstall the module and clear the cache.May be it will work.


Find out if you're viewing a taxonomy page Clicking on a Taxonomy term generally takes you to a page showing several nodes which use that term. Is there a way to find out if you're viewing a specific vocabulary and save it to a variable? That way you can change the layout at will:

<?php if( $is_vocabulary_fruits ) : ?>
    Load this layout
<?php if( $is_vocabulary_cars ) : ?>
    Another layout different from the first
<?php else : ?>
    Nope, use this layout instead
<?php endif; ?>

I'm looking to place this in page.tpl.php. This means that the markup outside of the node.tpl.php is changed when viewing a taxonomy and not the node itself. How is this done in my template.php file?

When a taxonomy page is rendered, the template file used is taxonomy-term.tpl.php that receives, among other variables, the $term variable, which contains the term object for the taxonomy term associated to those nodes.
Basing on the vocabulary that owns that taxonomy term, you can change the layout of the page.

If you want to find out in page.tpl.php the taxonomy term associated with the nodes shown in the page (where the page's URL is example.com/taxonomy/term/[tid]), then you can use the following code:

$term = menu_get_object('taxonomy_term', 2);

If the page's URL is not example.com/taxonomy/term/[tid], then the function returns FALSE. The code can also be executed in a preprocess function, such as hook_preprocess_page().

No.

For that kind of functionality are Panels.


Contextual Links not appearing in Panels I use panels to display almost every page on my website. I display content type article as a panel, configured from

structure->content type->article->manage display

The contextual link cogwheel is not appearing on the full content type display rendered through panels, whereas it is displayed on the teaser view, rendered on the site home page, also rendered through panels as a panel page. What might be causing the error? Is there a workaround?

Please apply a patch from Impossible to set attributes on Panels panes on Drupal.org.

This is a patch to the module I believe will fix the problem you have.


First time user login, page redirect I am having difficulty getting drupal to redirect a user to a specific page after completing the registration form.

In the user.module file there is this:

// No e-mail verification required; log in user immediately.
elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
    _user_mail_notify('register_no_approval_required', $account);
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
    drupal_set_message(t('Registration successful. You are now logged in.'));
    $form_state['redirect'] = '';
}

I would have assumed that by entering the path you wish to redirect to, in the form redirect  ,it would redirect. For example:

$form_state['redirect'] = '/page/I/Want/To/Redirect/To';

However this is not the case. When the user is logged in after completing the registration form they are taken to the homepage.

Once the user is logged in (from the registration form) I wish to send them to our services page. But for them to be sent to the homepage every subsequent time they login.

There is a very simple way to that using the Rules module.

You can use multiple modules Rules, Login Destination and LoginToboggan.

Check Reference link from Drupal Document for more help.


Minimum schema version I am updating my site from Drupal 8.2.1 to 8.2.4, while running update.php I encounter this problem

  The installed schema version does not meet the minimum.
  Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported. You must migrate your site to Drupal 8 first.

I am unable to proceed any further. What exactly is causing this problem?

Use Drush. The following commands worked for me.

drush updb -y
drush cr


Check Content Type in Paragraph Preprocess I've written a paragraph preprocess function that is working perfectly. The only issue is that I need it to only work when that paragraph is embedded in a certain content type.

function mytheme_preprocess_paragraph__paragraph_type(&$variables) {
   // Do things here if content type == 'specified_type'
}

I'm unsure of how to check the content type, though. How can I accomplish this?

The correct way of getting the entity data referencing to your paragraph is to use Paragraph's entity API.

/**
 * Implements template_preprocess_paragraph().
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */

function mytheme_preprocess_paragraph(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  // Get the parent bundle.
  $parentBundle = $paragraph->getParentEntity()->bundle();
}

There is another post with either the same or similar answer here. https://stackoverflow.com/questions/31116325/how-to-programmatically-get-content-type-name-in-drupal-8

The poster Jose points out you can use

$node = \Drupal::request()->attributes->get('node');

to get the content type.


How to expose age range in views? I'm trying to add an exposed filter for an age range with the Views module.

I made a select age field for age 18 to 80, but I can't find how to add a filter range in views.
For Example, I would add a filter saying "from age__ to age__".

From the filter criteria choose the age field tick the exposed filter.
Choose grouped filters from the filter type to expose.
Choose the widget type. Then add values after changing the operator to 'is between'

I would give this module a shot: Views Contextual Range Filter

Module Page Description:

  Views Contextual Range Filter is a simple plugin for Views that adds
  the option to contextually filter not just by a single value, but also
  by range.

  Numeric, alphabetical (string) and list ranges are all supported. Node
  ids, user ids and even taxonomy term ids are all special cases of
  numbers so will work also. Range-filtering on the "created" (posted)
  and "updated" (last modified) node properties is also supported,
  provided you use the correct format as dictated by Views. So, YYYYMMDD
  for full dates or one of the shorter formats, i.e. year+month,
  year-only, month-only, week-only or day-only.

  You may use the OR operator (i.e. +) and the negate operator. You
  negate by ticking the "Exclude" box on the Views Contextual filter
  configuration panel, in the "More" section.


Multilingual Valid Path (Domain Access) I have a path controlled by page manager & domain access selection rules.

Let's say I'm on the Main (US) version of the page, and I need to know of the spanish version of the page is valid.

/contact-us

/es/contact-us

I've tried things like drupal_valid_path, drupal_lookup_path, etc.

The only option I've found is to do something like
menu_get_item()
Then hack the global language, call the callback from menu_get_item with

//hack global language here
$router_item = menu_get_item($path);
$page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
if (MENU_NOT_FOUND != $page_callback_result) {
   //url is not valid
}
//set global language back to original

Is there a simpler more generic way to programmatically do this? If there were some function like drupal_valid_path that would just say if the path results in 404 or not, that would be great, though I haven't found something like that yet.

We use the Link Checker modules on our sites. This would scan all links and give a report back as to which are broken, if any. I don't see any reason why this would not work on any site, including multi lingual.

Whether or not you use the module, you should be able to look at the code to get an idea of what functions and logic it's using to create similar functionality, if you're looking to do it programmatically.


Unable to install Pathauto, pathauto.settings already exists in active configuration After upgrade from 8.7.10 to 8.9.13, i updated the pathauto module from ftp and trying to install from drupal admin but it showing an error like
"Unable to install Pathauto, pathauto.settings already exists in active configuration."
Based on the post
https://www.drupal.org/forum/support/post-installation/2016-01-29/already-exists-in-active-configuration-issue
i deleted the pathauto.settings row from config table and cleared the cache and trying to install the module , but still showing the same error.
Please help me.
Thanks in advance.

Before trying to do whatever I suggest below first of all have a full backup of the site.
It seems pathauto module is not uninstalled properly.
To solve your problem you can just delete the pathauto.settings from config using drush.
Use the below command to delete the conflicting config.
drush cdel pathauto.settings
It will delete the existing pathauto configuration.Then you can install the pathauto module.
You should consider using composer for the module management.

You can use the following Drush command.
drush ev "\Drupal::service('config.manager')->uninstall('module', 'pathauto');"

After running it, you should be able to re-install the module.


Get fid from file path I've to create a custom function to display images because I've to add values from custom fields.

I've added a function to template php, like this:

function mytheme_image($variables) {
}

The problem is that in $variables I haven't the fid of the file, but only the path. I have to load the file to get values from field, how should I do?

I'm looking for functions to get fid from path but I haven't found something..

@pvorb, you can also use EntityFieldQuery.  See the first comment on https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load_multiple/7 for an example.  Something along the lines of:

$filename = 'myfirstpony.png';
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', $filename)
  ->execute();
// if you are guaranteed there is exactly one result, then:
$file_object = reset($result['file']);
$fid = $file_object->fid;
// but beware you might get 0 or many results

If you have more information -- such as the path (from which you can generate a URI) -- then change the query condition to something like ->propertyCondition('uri', 'public://path/to/myfirstpony.png').

This seems to be the way to do it In Drupal 8

$files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $uri]);

Where $files will be an array of file objects, keyed by the file id.


Not able to connect to remote database after migration I am moving a running site from staging to production. The production environment has 2 servers, one for frontend and the other for the database.

The issue is when I try to browse the website, I get this error

  PDOException SQLSTATE[HY000] [2002] Permission denied in [ROOT]/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php on line 79

The real problem is I am sure that the database connection is set right. Permissions and ports are set right.

I tried the same database connection info from an external PHP file on the same server and I got successfully connected.

Also, I tried drush st and it told me that database status is Connected, and Drupal bootstrap status is Success.

Even tried drush sqlc and I got connected to the remote database. I can list tables, execute queries, etc.

Any ideas what might be the problem?

In case you're using SELinux see this article.

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1

In the sites/default/settings.php file, change the value of host key from localhost to 127.0.0.1.

Code sample

$databases['default']['default'] = array (
  'database' => 'foo',
  ...
  'host' => '127.0.0.1',
);


alterRoutes() is not triggered I am trying to alter the route for the login and registration pages. I followed Altering existing routes and adding new routes based on dynamic ones. I cleared the cache repeatedly, and re-enabled the module several times, but it looks like alterRoutes() is not triggered, even when I try to add a kint() debug or any code.

What I noticed is that alterRoutes() -> kint() is triggered when I use Drush to enable the module. In this case, I see kint() output in my terminal. However, alterRoutes() is not triggered when viewing the site.

This is the code I am using.

md_routes/src/Routing/RouteSubscriber.php

namespace Drupal\md_routes\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;
/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    kint($collection);
    // Change path '/user/login' to '/login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/login');
    }
    if ($route = $collection->get('user.register')) {
      $route->setPath('/register');
    }
  }
}

md_routes/md_routes.services.yml

services:
  md_routes.route_subscriber:
    class: Drupal\md_routes\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

I did clear the drupal caches using the interface (admin/config/development/performance), it seems like drush is not clearing ALL caches. It does work now and i guess it was a caching issue. Thanks anyways!


Where to include javascript instances in drupal I've added my.js using js injector module and updated .info file.
Where do I have to create those instances?
Sorry, I'm new with technology.

To Add any js file to your Drupal site , a good way is to create a custom module and add your js file there.Following points may help you.

Create one custom module of yours. Useful Link. https://www.drupal.org/developing/modules/7
In your module , create one folder name js.
Add your js file here.You can copy paste your js file also here.
Now in yourmodule file the following code to tell drupal about your js file.

function YOURMODULENAME_init(){

 drupal_add_js(drupal_get_path('module', 'YOURMODULENAME') . '/js/yourjs.js');

}

At the end enable your custom module.You are ready to go.


Disable node summary using Page Manager There are a few modules and methods specifically for disabling / removing the node summary page (at /node), like Node Page Disable, but I'm wondering if there's a way to redirect or override the page using the Page Manager module.

There's a good summary of other methods on this stack exchange question and answer and this Drupal forum post. One problem I'm running into with Page Manager is that the /node/%node path is already in use, and I'm not sure how to set it up for just the /node page without any additional arguments.

Yes, you can do that with a variant. I've used that methodology on a personal project. Here are screenshots of the configuration.

The first variant (which returns a 404) checks, the node type (I have a content type called 'person'), the taxonomy terms applied to the node, and the role of the user.


1 Better exposed Filters for 2 views blocks I would like to make a page with 2 Views blocks. The views show the same content type, but in a different format.

Block A contains an OpenLayers map.

Block B contains a listing result.

I want to filter both Views based on taxonomy, but with one exposed filter block.

I've made one Better Exposed Filter for block A, but I don't know how to control both blocks with one exposed filter.

Can anyone help?

You want to create an attachment view display and add it to your main display. For example, if you currently have the OpenMaps display working, create a listing display as an attachment and attach it to the OpenMaps display. Make sure you set "Inherit exposed filters" to "yes" to ensure both displays are using the same set of filters.
In views 3 you can find this settings in the Attachment display settings:

My solution is just to add a hook mymodule_form_alter.


How can I generate thumbnails for PDF files? I am working on this website which has a documents gallery that will be updated periodically. One of the core requirements is to generate a thumbnail from the uploaded PDF file(First Page of the PDF file) and to be displayed in the documents gallery page(Implemented with views). I have installed Imagemagick on my test server and configured it in PHP.ini and also installed the drupal module successfully. But I have not been able to go beyond that because of the following:

I can't upload a pdf to an image field so there is no way of applying an image style to the uploaded pdf
I can't find any Drupal 8 Module that can generate the thumbnail and attach it to an image field in the content type.
I tried installing spatie/pdf-to-image, which is supposed to be able to do that, via composer but it doesn't show in the admin/modules page and I can't find any folder with it's name in the modules directory

Please can anyone point me in the right direction on this? A module which can perform this task or how I can create one myself. This is my first drupal website and this requirement has made life hell for me in the past two weeks. Any help on this will be really appreciated.

For similar purpose i was using Media Entity in Drupal 8, so on this way you can use reference field to upload document and get preview like thumbnail.


How can I remove "please wait..." from a form? I saw this Remove the "Please wait" text on Ajax Call but I can't find the form element. <?php dsm($form);?> and <?php dpm($form);?> return errors. This is what I found in $node:

I may have missed it. I tried using the ID path in the unset form function but it didn't work. This is what I'm putting in template.php:

function fivestar_form_fivestar_custom_widget_alter($form, &$form_state) {
  unset($form['field_funny']['#ajax']['progress']['message']);
}

I also tried theme_fivestar_form . . .

this can be done in css:

.fivestar-widget .ajax-progress
{
    display:none;
}


Zen theme not compatible with IE8? I am using a zen theme, the default styles and template and while the Main content displays correctly in Firefox, it is all the way to the left in IE.

In firefox, Navigation menu on top, sidebar on the left, main content on the right.
In IE, Main content area on top, with navigation menu underneath and sidebar first underneat that. All left align...

What am I missing?

I just overrode all the css and everything and it is still displaying the same...

"I fixed the issue by setting the bandwidth optimization to: Aggregate and compress CSS files." said kine456.
kine456 answered his own question.

This is because js files like respond.js that comes with the zen theme must get applied after you aggregate the css files for it to look correctly in ie8. I'm pretty sure its documented in the theme's readme.

you problems solved by just using the powerful omega theme: drupal.org/project/omega -- version 4 is out...


Get Field Collection Array From Field Collection ID I'm using the following code to return array of all field collection IDs for a node's field collection. How do I use these IDs to get an array of the values of the fields within the field collection?

case 'field_collected_dates':
$fid = field_get_items('node', $node, $key, $node->language);
$return[ $key_clean ] =  $fid;
break;

this is how you can get values from field collection

if(isset($node->field_field_collection['und'])) {
  foreach($node->field_field_collection['und'] as $field){
    $colection_node = entity_load('field_collection_item', array($field['value']));
    $name_from_collection = $colection_node[$field['value']]->field_field_name['und'][0]['value'];
  }
}

now you can understand how to get value from field collection try to fix this in your code

THANKS


How do I properly detect if region is empty? I have condition for printing regions in my page template as is not empty, but it will always print empty regions no matter what. What is the proper way to detect empty regions?

For example, {% if page.local_tasks is not empty %}{{ page.local_tasks }}{% endif %} prints out

.

If I render the region in themename_preprocess_page() with var_dump(drupal_render($variables['page']['highlighted'])); I will get SafeString with placeholder token:

<drupal-render-placeholder callback="Drupal\Core\Render\Element\StatusMessages::renderMessages" arguments="0" token="a8c34b5e"></drupal-render-placeholder>

So, technically the region is not empty but I can do nothing about it.

try to apply filters after render, like this :

{% set has_sidebar_first = page.sidebar_first|render|striptags|trim is not empty %}
{% if has_sidebar_first %}
    {# ... #}
{% endif %}

To detect if region is empty or not code like this:

{% if page.local_tasks %}
   {{ page.local_tasks }}
{% endif %}

In above code it checks if local_tasks region is empty or not and if empty then it will not print that region


How to prevent views from loading the results upfront I have views block with exposed filters and ajax enabled which was rendered in home page, the problem is when the block is loaded with exposed form views is loading the results too. However I want the results needs to be shown only when the user clicks on the submit button.

If I enable input required, this will work, but the client doesn't want this.

Here is the way to solve your issue:

Add Contextual filter of "Global: Null" type
In "When the filter value is NOT available" section check "Provide default value" and specify "Fixed value" and "all". Notice! If view still display results - then try select "Raw value from URL" here.
In "When the filter value IS available or a default is provided" section check "Specify validation criteria" and select "PHP code"
Specify this code

if (count($view->exposed_input)) {
  return TRUE;
}
In "Action to take if filter value does not validate" select "Display all results for the specified field" value
Don't forget to add any "No results behavior"!

Now results will be shown ONLY if filters are sent. View will be empty on       first display.

$view = views_get_view("VIEW NAME");
  $view->set_display('DISPLAY ID');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $form = drupal_build_form('views_exposed_form', $form_state);
  return drupal_render($form);

Just add the above code in a block.


Composer updating to 8.9.0beta2 instead of 8.9.0 I'm currently using the drupal/core-recommended project and I'm having issues updating to 8.9.0.

Some reason composer is updating it to 8.9.0-beta2.

Steps I took to update was go into my composer.json file and changed:
"drupal/core-composer-scaffold": "^8.8",
"drupal/core-recommended": "^8.8",

TO
"drupal/core-composer-scaffold": "^8.9",
"drupal/core-recommended": "^8.9",

Then ran composer install

Then it just downloads the beta version instead of the stable version.

Anyone know why?

This and similar dependency conflicts can typically be solved by asking composer to also update symfony packages as described in Drush blocks update from 8.9.0-beta2 to 8.9.2.
composer update drupal/core-recommended symfony/* --with-all-dependencies

Have you tried these commands for updating Drupal?

Just Core:

$>composer update drupal/core --with-dependencies

or for Core and Contrib Modules:

$>composer update --with-dependencies

Personally I don't edit the composer files and then run install. I just run these commands and so far has always worked well.


How to set and inherit variables within different twig templates? I'd like to set a variable in my node.html.twig template:

{% set title = label %}
{{ content }}

The content consists of one field visible only, which has it's own template:

file-link.html.twig

How can I access the title variable of the node template in the file template? I am not sure if importing or extending is the right way since that might cause infinite recursion?

Edit

The file template looks like this (from the bootstrap theme):

{% spaceless %}
  {%
    set classes = [
      icon_only ? 'icon-only',
      not icon_only ? 'icon-' ~ icon_position|clean_class
    ]
  %}

    {% if icon_only %}
      {{ icon }}

        {{ link }}
        {{ file_size }}

    {% else %}
      {% if icon_position == 'after' %}
        {{ link }}{{ file_size }}{{ icon }}
      {% else %}
        {{ icon }}{{ link }}{{ file_size }}
      {% endif %}
    {% endif %}

{% endspaceless %}

Within that template I'd like to print the title of the respective node:

{{ link }}
{{ title }} {# << #}
{{ file_size }}

EDIT

You could write a theme hook in your "mytheme.theme", modifiy the "variables" array and add title to the specific field AND then move the template file (in the original post) to your own theme template directory, make the changes using your new variable (called maybe title) which was provided from theme hook.

OLD:

First of all, "node.html.twig" is TOO general to claim that it's content in the future will consist only one field (file-link).

At least rename it to "node--my-content-type.html.twig".
In the file-link.html.twig you won't able to reach the "title" variable (label) of the node.

You have the following work around:
{{ content|without('field_file_link') }}
{% include directory ~ '/templates/my-custom-twig.html.twig' with {'title': title}  %}

Which means:
 1. exclude your field from content.
 2. create your own twig template
 3. Pass any variable from the caller template you would like to pass.

Twig syntax / semantics is still changing, maybe my twig codes of lines can lead to error, but at least it will give you a hint / clue how to achieve this.

What about hook_preprocess_HOOK with a relevant HOOK_ID (page, node, view ...) and declare your variables into it ?

In the youtheme.theme file

function MYTHEME_preprocess_page(&$variables) {
  $variables['foo'] = "bar";
}

In the twig one,

The content of Foo var is : {{ foo }}


How can I upload multiple images all at once? Is there a way to upload multiple images all at the same time in Drupal 7?

See the Plupload integration module. From the project page:

  Provides integration between for the Plupload widget to upload
  multiple files and Drupal. Plupload is a GPL licensed multiple file
  uploading tool that can present widgets in Flash, Gears, HTML 5,
  Silverlight, BrowserPlus, and HTML4 depending on the capabilities of
  the client computer.

For an Image field, you can set the number of images you wish the user to upload.

(Image module must be enabled)


What hook_form_alter code do I need to change an exposed filter from a text field to a select box search? I have a view that has an age to and and from fields, and others also that I want TO and FROM.

These are integer fields, so drop down select doesn't work, better exposed filters is also not an option.

What CSS, or Java script can I put in the Hook_form_alter to make this work?

Website that has the form is www.vuxi.com

If you would like to go for specific implementation using hook alter this would be great option.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
      $addition[$field_name] = array(
        '#attributes' => array(
          'class' => array(
            // you can define you class overhere
          ),
        ),
      ),
    }
  }
}

You can change textfield to select box using following code

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "your view name"  ){
    $options = array('your options');
    $form['your field name']['#type'] ='select';
    $form['your field name']['#size'] = null;
    $form['your field name']['#default_value'] = '';
    $form['your field name']['#options'] = $options;
  }
}

Change the field attributes as your field attributes.

Hope this will help you...


Add trailing slash to URLs when generating Sitemap with Simple XML sitemap I am trying to generate Sitemap for my site using Simple XML Sitemap module. I have checked the Documentation for Extending the module features. Since I am newbie to Drupal 8, I am in confusion how to get this achieved. tried some hooks but failed it may be my lack of understanding regarding drupal8 module development. Can anyone help me to get this done. What are the namespaces I should add to my custom module.

Currently my URLs are generated like www.mysite.com/country/india but I want it to be like www.mysite.com/country/india/ since I use trailing slash with URLs.

I've used htaccess to add trailing slash to URLs with 301 redirect.

You can use hook_simple_sitemap_links_alter() to change the links generated before the sitemap is saved.

function example_simple_sitemap_links_alter(&$links) {
  global $base_url;
  foreach ($links as $key => $link) {
    if ($links[$key]['url'] != $base_url . '/') { // Excluding base url
      $links[$key]['url'] = $link['url'] . '/'; // Here Trailing slash will be added
    }
  }
}

Before using the hook:

After using the hook:

have a look at this ... it does not do exactly what you want but could be a good place to start.

  hook_sitemap_menu_tree_main_alter(array &$menu) {
      /**@var \Drupal\Core\Menu\MenuLinkTreeElement $menuLink **/
     foreach ($menu as $menuLink) {
       dump($menuLink); <-- do stuff with this
     }
  }


How to change the order of banners using the weight module? I have add banners. I want to change the banners order. I have installed the Weight module. I have also added weight in content type but it does not reflect in node.

So how can I change the order of banners?

Check out these modules :
weight

This module adds a weight option to enabled node types. Nodes with
lower weight will float to the top of lists, while heavier items will
sink.

Field_weight

Customise the weight/order in which fields on nodes can be displayed
on a per node basis and not just globally per type. Individual fields
can also be hidden from display.
For any node types that are enabled, a 'Field display weights' tab
will appear on nodes (for users with adequate permissions). From this
page administrators can customise the order in which fields are
displayed on each node by using a draggable table (or manually select
weights).

Nodequeue

The Nodequeue module allows users to collect nodes in an arbitrarily
ordered list. The order in the list can be used for a any purpose,
such as:

A block listing teasers for the five top news stories on a site
A user’s favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface
to manually order any queue. Additionally, it allows nodes to be added
and removed from queues without needing edit permissions to the node.
Nodes can be added to queues either from a queue management tab or by
links on the node teaser.