Views not showing date field in proper time zone I created a node type with a date field (from the date module).  I list nodes of this type in a view.  The problem I have is that the date values being shown by the view are in UTC (ie as they are stored in the db) not in the user's local timezone.  I have tried the following to no avail:

1)  Unchecked "Administration » Configuration » Regional and language » Users may set their own time zone".  I then logged out and cleared the cache.

2)  Verified that if I view the node outside of the view (ex: going to http://mysite.local/node/123), the time appears in the proper timezone.  The proper dates are also shown when editing the node.

3)  Tried to format the date using this code:

format_date($date, 'custom', 'D d/m/Y - g:ia', date_default_timezone_get())

$date is a timestamp and date_default_timezone_get() returns the proper timezone.

4)  Tried this with the date_views modules enabled and disabled.

For some reason the view pulls the date field value straight from the db without converting it to the proper timezone.  Unfortunately, I don't know how to either 1) tell views how to convert it properly, or 2) convert it manually in a template.

Note: I refuse to hard-code my timezone into my template.  This is a terrible option I've seen when searching for an answer to this.

You can use Global PHP filed to convert the date in user's proper timezone using code. Your date field value will be the input here. If it works then use this field instead and set the original date field to 'exclude from display' in your view.


Using prefix and suffix form api layout I have created a form, though I'm having an issue with using the prefix and suffix to place items into rows rather than the list they appear as standard.

For example I have these 3 form elements, how would I go from having them appear as standard on a new line, to on the same line. Normally I would just chuck them into a table and place each one in a different column. I have read that I should possibly use floats?

I have tried  '#prefix' => '
',

'#suffix' => '

' , But this seems to affect the navigation on the left and shuffle it down.

$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => ,
    '#suffix' => ,
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

I cannot answer for 7 hours but here it is:

The solution was to close the DIV, I had forgotten, which meant the styling was effecting the whole page.

     '#prefix' => '
',
    '#suffix' => '

',
    [Useful link to aligning form elements horizontally][1]

I think you want to keep it in table. Lets try with putting it in one like this --

$form['orange'] = array(
    '#type'=>'select',
    '#title' => t('Select Orange'),
    '#options' => $Orange,
    '#multiple' => false,
    '#prefix' => '

',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['apple'] = array(
    '#type'=>'select',
    '#title' => t('Select apple'),
    '#options' => $apple,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '	',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,
);
$form['strawberry'] = array(
    '#type'=>'select',
    '#title' => t('Select strawberry'),
    '#options' => $strawberry,
    '#multiple' => false,
    '#prefix' => '',
    '#suffix' => '

',
    '#attributes'=>array('size'=>0),
    '#required' => TRUE,

);

I haven't tested this code, so please try this & let me know if it works :)


Us js file in a theme already use by a module I need to use in my theme a js file used originally by a other module: View slideshow.

View Slideshow take the jquery plugin Cycle from the libraries folder, on the root of the App, something like

libraries/js/cycle/jquery.cycle.js.

Now i need to use the jquery plugin Cycle in my theme, but drupal put it after my main theme js file

<script src=mytheme.js>
<script src=....cycle.js>

So it can't use it, because cycle must be before.

I add the file in my libraries.yml file like this:

mytheme
  js :
    - ...cycle.js: {}
    - mytheme.js: {}

but cycle steel remain after.
How could i move Cycle on top ?

Okay this was easy...
I realise that the js file is in the library views_slideshow_cycle/jquery_cycle, created by the module.

So i just have to add it has a dependencies to my theme

mytheme
   dependencies :
     views_slideshow_cycle/jquery_cycle.


Field and storage settings on base fields I am rewriting my config fields (Field API fields) into base fields and I am unsure about one thing: settings.

Field API has storage and instance settings. Looking at base fields, there is the setSettings() method which I presume is equivalent of field instance settings. Then, there is getFieldStorageDefinition()->setSettings() which I presume is equivalent of storage settings.

When I look at the entity reference item and the user ID field on the node entity, the user ID field calls setSetting('target_type', 'user'), which is storage setting and not instance setting. Do I get these two wrong? What is going on?

\Drupal\node\Entity\Node::baseFieldDefinitions() contains the following code.

$fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The username of the content author.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user') <---- this

\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem contains the following code.

  public static function defaultStorageSettings() { <---- STORAGE, not field
    return [
      'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
    ] + parent::defaultStorageSettings();
  }

The base field definition implements the FieldDefinitionInterface and the FieldStorageDefinitionInterface, so it can act like a form API field, though it's not managed by the field module.

So the base field definition contains the settings of both, which you can see how the default values are set in BaseFieldDefinition::create():

  public static function create($type) {
    ...
    $default_settings = $field_type_manager->getDefaultStorageSettings($type) + $field_type_manager->getDefaultFieldSettings($type);
    $field_definition->itemDefinition->setSettings($default_settings);
    return $field_definition;
  }


Addressfield change max size of column I'm working with the addressfield module. I need to change the thoroughfare column to have a max length of 960 (or make it a text instead of varchar) instead of the default 255.

However I'm not sure how I should do it.

I've created an empty module with a hook_schema_alter()

function hook_schema_alter(&$schema) {
  $schema['addressfield']['thoroughfare'] = array(
    'description' => 'The thoroughfare of this address. (i.e. Street address)',
    'type' => 'text',
    'default' => '',
    'not null' => FALSE,
  );
  return $schema;
}

However I suspect that the part "$schema['addressfield']['thoroughfare']" is not correct. Nothing is changed when I install the module with this hook.

How to change it? In the original addressfield it returns only columns in the schema hook, it's not really linked to a schema itself?

That approach won't affect the column type or size as I get you need to make it store more chars.

You could do hook_update_N() that execute a sql query to change the field type and size.

Then yo have to change field settings see


Trusted Host Patterns Settings Not working with IP So I am trying to get this drupal(drupal845.localhost) site accessible by my VM. But the Trusted Host Settings are not working.

Here are the settings in my settings.php

$settings['trusted_host_patterns'] = array(
   '^drupal845\.localhost$'
   '^.+\.drupal845\.localhost$'
   '^192\.*\.*\.*\.drupal845\.localhost$',
);

I have another drupal(drupal.localhost) site on the same machine and the trusted host patterns work. This is what I have in my settings.php for trusted host patterns:

$settings['trusted_host_patterns'] = array(
   '^drupal\.localhost$'
   '^.+\.drupal\.localhost$'
   '^192\.*\.*\.*\.drupal\.localhost$',
);

Why does it work on the drupal.localhost but not on drupal845.localhost

Also to note is I have .localhost masked to 127.0.0.1. I have to specify the port because windows is using 80 so my WSL(Ubuntu) Apache server I set to use 8080.
They both work without the ip specification as well.

So I figured out what was wrong. I didn't have my apache site config set correctly.
I had:

snip...
<VirtualHost *:8080>
           ServerAdmin webmaster@localhost
           ServerName drupal845.localhost
           ServerAlias www.drupal845.localhost
           end snip...

What I needed:

snip...
<VirtualHost *:8080>
           ServerAdmin webmaster@localhost
           ServerName drupal845.localhost
           ServerAlias www.drupal845.localhost *.drupal845.localhost
           end snip...


Internationalization -- impact on other modules? I installed the internationalization module because the site I'm developing is in a different language, but I can no longer index the site in Drupal's search engine, and Tagadelic isn't working either. I'm assuming all of these issues are somehow related but I'm actually not entirely sure... is there anything specific I need to do when I install the internationalization module to ensure other modules keep working are compatible with other languages?

The i18n modules can have a huge effect on a site, as they integrate with a large number of modules. Many modules for example deal with taxonomy terms and displaying them, so they all need to be compatible with i18n.

The main problem is that many content elements (like menus, taxonomies, ..) are not designed to be translatable or even just language aware. So the i18n project needs to alter a lot of things and build data structures and API's on top of those provided by core.

Also, there have been a number of API changes unfortunately, so it's possible that the modules you mentioned have a broken i18n integration due to that.

You need to provide more details on what exactly isn't working to get more help than this. You can also try to check the issue queue of the broken modules to see if there already is an issue for this and if not, open one.


How can I get a checkbox to return True/False? I'm working with the form API and I have a series of checkboxes. I need them to return true or false instead of 1 and 0.

$form['checkbox1'] = array(
    '#type' => 'checkbox',
    '#return_value' => 'true',
    '#title' => t('Checkbox title'),
    );

This works if the box is checked, but if it's left unchecked it still returns 0. Is there a way I can get an unchecked box to return false?

It depends how you want to use the true/false value.

Case 1

You could change the data in a validation handler. In hook_form_alter, something like:

$form['#validate'][] = 'my_great_handler';

Then:

function my_great_handler($form, &form_state){
  $form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value']
    = ($form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] == 1);
}

Not sure what that would do for you, though.

Case 2

If you want to show users true/false rather than 1 or 0, you could change that in a template. Create a template for the field, and add something like:

Checkbox: <?php print $checkbox1 == 1 ? 'True' : 'False'; ?>

Case 3

If you want to save the data in a custom data store, you would add similar code right before the save, in hook_node_save, or some such.


What code should I use where I used db_query()? I want to execute SHOW TABLES in Drupal 8. In Drupal 7, I would use db_query("SHOW TABLES"), which is deprecated in Drupal 8.

What should I use for Drupal 8?

As quick replacement for queries on the database Drupal uses by default, you can use the following code.

use Drupal\Core\Database\Database;

$db = Drupal::database();
$result = $db->query("SHOW TABLES");

Keep in mind that:

db_query() will not be removed before Drupal 9 goes off; you can still use it, even if it is preferable to refactor your code to be more object oriented
The code I shown should be used in legacy procedural code; when possible, you should consider refactoring it to be object oriented and use Drupal 8 services and Dependency Injection Container


How to find the ID of a views block that is not assigned to a region? The title pretty much says it all. I need to find the ID of a Views block that is not assigned to any region, in Drupal 7.

you can edit that view, move your mouse on the "block" that you need to analyze and see the url.Like this one:

http://mydomain.ext/admin/structure/views/view/flag_bookmarks/edit/page_4

The last url path is the page id: page_4.
In your case all start with "block_".


How to finally disable comments on content type? I am trying to disable comments on webform.
I tried all settings I could find, but:

Link to comment form still appear
Name field and submit button still appear on comment form

Could somebody give me any advice?

As juampy wrote, node_revision should be updated as well. You need to execute 2 queries:

Step 1:

UPDATE node SET comment = 0 WHERE type = 'your_content_type'

Step 2:

UPDATE node_revision nrev
INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
SET nrev.comment = 0

Step 3: Clear cache


How do I get Facebook latest uploaded images for an account? I am new in Drupal, I want to get all the images from my Facebook account and want to display them into front end.

I tried Facebook Album Fetcher module but this module give me the facility to get images only for a particular album not for overall. I want to get and display only the latest uploaded images from my whole account (Images will be anywhere like profile images or timeline images or album images etc).

So can anyone please tell me, is there any module which can fill my above requirement? If not then how can i get all the latest uploaded images to display them into front end?

Please help.

Thanks in advance.

I have resolved this in two ways.

First I use Facebook FQL query to get the image of Facebook page posts image. You can find the code from here. Facebook Platform API versions after 2.0 will not support FQL. So I get the images using Facebook graph API.
Then I get Facebook post images using Facebook graph API. Here is my code: Firstly you should have to get page id from where you want to get post images. From here you can get the Facebook page id.

After that use the code:

$data = file_get_contents("https://graph.facebook.com/page_id/photos/uploaded");
$results = json_decode($data);
foreach ($results as $value) {
  echo '<img src="'. $value->source .'">';
}


what can be removed when minimizing hook_views_default_views in a module? I'm working on a new drupal 6.x module (currently in sandbox awaiting review - http://drupal.org/sandbox/sdague/1072704) which exports it's data via views.  When I implemented hook_views_default_views() I just used the export functionality on views for a few basic views to get things started.

That works, but those are both very verbose, and don't implement any i18n. Is there a standard way of trimming down the default values in those views so this becomes a bit more sane and maintainable?

I find that the features module does a better job exporting the view. It adds an array of translatable strings. I haven't compared the verboseness of the views exported, but most they are probably the same. Most of the verboseness comes from defining fields. Some options might not be strictly needed - compared to the UI, but when importing/exporting things, it's better to be a bit over verbose, than to rely on default values.

With some practice, you can learn to spot the important stuff and ignore the rest.


Choose a destination after drush cex In my sites/default/settings.php I changed:

$config_directories = array(
    CONFIG_SYNC_DIRECTORY => 'sites/default/config-sync',
);

I created the folder config-sync in sites/default/
When I do drush cex I get this message in my Terminal window:

  Choose a destination.
  [0]  :  Cancel
  [1]  :  sync
  [2]  :  staging

What do I have to do? Because I want all my configuration files in sites/default/config-sync because this directory is tracked by Git.

You just need to execute the command with the "destination" parameter:

$ drush cex sync

as CONFIG_SYNC_DIRECTORY is the same as $config_directories['sync']


How to prevent closing CTools modal window with ESC during AJAX? How can I prevent closing CTools modal window with ESC key during AJAX request?

Try this one

/**
 * Override Ctools modal content function to prevent closing the modal with
 * the escape key.
 */
Drupal.CTools = Drupal.CTools || {};
Drupal.CTools.Modal = Drupal.CTools.Modal || {};
var modalContent = Drupal.CTools.Modal.modalContent;
Drupal.CTools.Modal.modalContent = function(content, css, animation, speed, modalClass) {
  modalContent(content, css, animation, speed, modalClass);
  $(document).unbind('keydown', modalEventEscapeCloseHandler);
}


Where is the .htaccess file? I have just installed a Drupal 8 website using drush dl drupal-8 --select.
I have rewrite issues because there is no .htaccess in my root directory.

Where can I find the default .htaccess file for Drupal 8?

If you download Drupal from here, there is the .htaccess file in main directory.

How do you downloaded Drupal source code?


How do I change the order of the form elements? I am using Drupal 7, and trying to make a custom register form to fit my needs.

I am also using a contrib module named "Auto Assign Role" to let the user choose his role.

Now heres the issue, the fields are appearing on the form but the order is messed up.

I have 5 fields on the form total:

First Name
Last Name
Role
Username
Password

The first i added via the manage fields section of Account area, the role field is added by the contrib module, and the other two field are built-in, I guess..

Above is the order i seek, but its not doing that even though i think it should. I ordered the field like that in the manage display screen, yet it still doesn't do what i want it to.

The order i get is:

First Name
Role
Last Name
Username
Password

If i set the weight of the above two fields (first & last names) to 0 instead of dragging and dropping to order in the manage display screen i get the following order:

Last Name
First Name
Role
Username
Password

This is almost what i want, but i want first name to be above last name.

Is there some way i can accomplish this?

Thanks!

@AjitS Credit to you for resolving OP's issues.. Adding more details so that it will be helpful for others..

Drupal weights works using below logic...

  Lighter weights Float.... Heavier weights sink...

That means field weight with low value comes to top... Field with Weight high values goes to bottom...

You can also set Negative weights to Fields...

Please find different scenarios of ordered fields with weights below..

Field A : 0

Field B : 1

Field C : 2

Field D : 3

Field E : 4

Field F : 5

Field A : -5

Field B : -4

Field C : -3

Field D : -2

Field E : -1

Field F : 0

Field A : -2

Field B : -1

Field C : 0

Field D : 1

Field E : 2

Field F : 3

In your case Click on Show Row Weights to edit Weights and set weights base on above logic and click save..


How do I set up a site to use Redis as cache handler? I'm trying to enable Redis on my Drupal site but when I check the status of the module I keep getting this warning message.

  No Redis client connected, this module is useless thereof. Ensure that
  you enabled module using it or disable it.

The steps I followed to enable Redis are the following.

I edited the config.yml file to add the following lines

installed_extras:
  - redis
  - php-redis

I enabled the Redis module
I edited the settings.php file to add the following lines

$settings['cache']['default'] = 'cache.backend.redis';
$settings['redis.connection']['interface'] = 'PhpRedis';
$settings['container_yamls'][] = 'modules/redis/example.services.yml';
$settings['container_yamls'][] = 'modules/redis/redis.services.yml';

I also tried to execute the following code in index.php and the cache appears to be working.

$redis = new Redis();
$redis->connect('127.0.0.1');
$cache = $redis->get('key');
if ($cache === false) {
  echo "miss";
  $cache = "test";
  $redis->set('key',$cache);
}
else {
  echo "didn't miss";
}
// At this point $cache is either the retrieved cache or a fresh copy, so echo it.
echo $cache;
exit();

It appears that Redis is working but for some reason it isn't used by Drupal.

How do I set up Drupal to use Redis as cache handler?

For Drupal 8, use this code in the settings.php file:

$settings['redis.connection']['host'] = 'localhost';
$settings['redis.connection']['port'] = NULL;
$settings['cache']['default'] = 'cache.backend.redis';
$settings['redis.connection']['base'] = 101;

You can check whether or not Redis is running by viewing the status report at: /admin/reports/status


Preprocess image: how to get parent entity? I'm using responsive images (single img tag with srcset and sizes attributes). My content editors can manipulate the displayed size of the image with a custom field on a shared parent entity. Therefore I can't meaningfully use the sizes field from the responsive image module, because my editors can set the image size from 10% of a fixed container up to 100vw on per paragraph level.

I know how to preprocess the sizes attributes, but I don't know how to get to my shared parent entity, which holds the field determining the size of the image's parent container:

function template_preprocess_responsive_image(&$variables) {
  // pseudocode: don't know how to this
  $imageField = $variables['whatever'];
  $parentParagraph = $imageField->getParentMediaEntity()->getParentParagraphEntity();
}

My question is how do I get the parent paragraph entity as written above in pseudocode?

Here is the the "real" code counterpart to the pseudecode from the question:

function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  // get the imagefield's parent entity
  $fieldParent = $variables['item']->getEntity();

  // this line is only needed if using media entities (= entity references)
  // must disable entity view caching to work correctly
  $fieldParent = $fieldParent->_referringItem->getEntity();

  // get the image width from the custom field
  $myImgSizes = $fieldParent->get('field_image_size')->getString();
  // can't change attribute here => store it temporarily
  $variables['responsive_image']['#attributes']['data-overridesizes'] = $myImgSizes;
}

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //override sizes attribute with my calculated value
  if (key_exists('data-overridesizes', $variables['img_element']['#attributes'])) {
    $variables['img_element']['#attributes']['sizes'] = $variables['img_element']['#attributes']['data-overridesizes'];
    unset($variables['img_element']['#attributes']['data-overridesizes']);
  }
}

If using media (=entity references) you also have to disable view cache for entites (see this question)

function MODULENAME_entity_view(&$build, $entity, $display, $view_mode) {
  if ($entity->getEntityTypeId() == 'media' && $entity->bundle() == 'image' && $view_mode == 'my_uncached_viewmode'){
    unset($build['#cache']['keys']);
  }
}


Exposed Views Combine filter not working Exposed Views Combine filter is working fine for administrator role, But its showing "Page not found" when I am trying to access with authenticated user role. I rebuild the cache so many times and rechecked the permissions.

For authenticated user its showing result on :
    http://localhost/example/testfilter?combine=&title=abc

But showing "Page not found" on
    http://localhost/example/testfilter?combine=textdata&title=abc

Again for administrator , Both URLs are displaying correct result.

Check which fields you are combining.

If e.g. you have a user field as combined field, Drupal needs the "Administer users" permission to use this filter.

An issue about this can be found at
https://www.drupal.org/project/drupal/issues/3030696


Adding custom text to each user profile In D7 i want to let admin add custom text(description) to each user profile and add point to users .
for example the user profile must be like this :

  John
     Description : You'r not good at speaking
  point : 12

  Joe
    Description : You'r perfect
  point : 20

Thx

Use field permissions module.

Add fields for these info & restrict the permissions for them to admin only.


Simple Oauth oauth/debug?_format=json Internal Server error When i try to test the ooauth/debug?_format=json endpoint through Postman i get the internal server error and error code 403 forbidden.
Even though i use a valid Authorization header with Bearer and the access token for a certain user. The endpoint works fine for anonymous user.
So i guess it's a permission error or the token expires even though i've set a big expiration date for testing purposes.
Has anyone encountered the same issue as me? If yes did you manage to solve it? I follow the tutorial step by step from the official simple_oauth module page in drupal. Thanks in advance for reading this.

I fixed this issue by going to admin/people/permissions and selecting all of the Simple OAuth permissions for Authenticated User. I'm sure a more refined approach to selecting permissions will be possible, but initially selecting all of them has fixed this issue for me.


Multiple submits form and Ajax: Select which submit button is triggered As I can't find a way to split a Drupal Commerce pane into several forms (so far it creates several field-sets) I had to create several submit buttons in the same form. But it's the same submit button that always gets triggered.

I have these 2 "forms":

- Field 1.1
- Field 1.2
-> Submit 1

- Field 2.1
->Submit 2

I believe this would not be a problem if I would not use ajax to submit the forms, but I do by using 'event' => 'click' so that the form is submited when ENTER is pressed.

My problem is that if I press ENTER from the field 2.1 it's the Submit 1 that gets triggered.

Any idea on how to select the right submit button with the click event?

My solution was to remove the Drupal click event:

'event' => 'click',

And to manually add it via jQuery by finding the next input button:

$('input.form-text', context).once('field_validation_keydown').keydown(function(event) {
  if (event.which == 13) {
    $(this).parent().nextAll('input.ajax-processed').trigger('mousedown');
  }
});

But if anyone has a better solution, I'm curious to know about it.


When using a dev version of a module, how can I easily get a notification of the next stable release? From time to time I need to install a dev release of a frequently updated module (Views, etc.) Usually, this is because I need a patch that has been applied to the dev branch that has not yet made it into a stable release.  For this reason, I don't want to stay on the dev branch, and I don't want to keep updating to new dev versions-- once I have a dev version with the patch, I am happy to keep that version until the next stable release.

I usually use drush up to get a list of modules that need updating.  However, this will prompt me to update to newer dev releases.  Is there any way to tell drush to ignore a dev module until its next stable release?  I assume nothing that convenient actually exists, so how else can I handle this situation?  I have a large number of modules and it's a real pain to check for updates manually.

Some of your question seems a little ambiguous to me, but it might be answered here: drush: How to upgrade to a stable module release instead of dev?


User profile custom style (per user) Is there a way to theme a user's profile but make it per user instead of globally on all users?

You can use the Drupal theme suggestions to specify templates based on any of the users fields.

I've implemented a theme for each of the different roles on my site for instance:

function [theme]_preprocess_user_profile(&$vars) {

foreach($vars['elements']['#account']->roles as $role):

    $vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $role);

endforeach;

}

To do the same with a users name for instance you could do:

$vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $vars['elements']['#account']->name);

Then make sure you've got the corresponding theme files inside your theme folder. All underscores are converted by Drupal to dashes so a suggestion of user_profile__dave would become user-profile--dave.tpl.php for instance.


List of favorite articles based on number of visitors I am working at a magazine type web project. I would like if someone would suggest me a way to display in a block the list of favorite articles based on numbers of visitors.

I assume views can do that but I need a counter for visitors who access the articles.

Thank you. Any idea is welcomed.

In the module list, you've a module named Statistic enable it and you'll have a block that show the articles most visited in the past 7 days or 24 hours.

Also, with Views you'll able to create blocks/pages as you want.


Get authenticated user details from a remote database I have 2 domains say site1.com and example.com. I have separate databases for both these sites .

How could I perform or allow users from my site1.com to login to my second site example.com without registering. If a person is an authenticated user in site1.com, he or she could login to the example.com site without signing up, i.e by using the login credentials of site1.com. Are there any modules that would help or be suitable for my task?

Also I would like to know is I could access some table details from a remote database. Thanks in advance

I recommend separating these questions.

1) Drupal Single Sign on module: https://drupal.org/project/sso

2) Again, I recommend posting this as a separate question, but could you be more specific? which table(s)?


Is there a Drupal module that can create a content type from an SQL Query or a CSV file? Is there a Drupal module that can create a content type from an SQL Query or a CSV file?

I am looking for a module which can carry out the process itself, at least based on simple types like strings, dates, floats, and integers, something that can use an SQL table definition to create it.

Another option is one that provides a form similar to the table creation dialogs in database applications like SQLite Manager or Microsoft Access, where you specify the name of the field, the size and the type and  the system goes off to carry out the task.

A module referred to as ECK has the functionality you're looking for.

Although, it works in the entity system to create new entity types. You might be looking for something to pragmatically create entity bundles (node content types). I would suggest researching the difference between Entity's and Bundles if you're not familiar.


Form submit not firing For some reason I am unable to get into my form_submit function. I have attempted to add a custom handler to the #submit to force the form to submit to it however I haven't gotten any where. Any advice on what I'm doing wrong would be appreciated.

function cheo_whiteboard_admin_form(){

 if(user_access('administer')){
   $form['admin_menu'] = array(
    '#type' => 'fieldset',
    '#title' => t( 'Admin Menu' ),
   );
$form['admin_menu']['admin_menu_archive'] = array(
  '#type' => 'submit',
  '#value' => 'Archive Search',
  // '#submit' => array('cheo_whiteboard_admin_form_submit'),
);

$form['admin_menu']['search_date'] = array(
  '#type' =>'date_popup',

);

$form['admin_menu']['special_instructions'] = array(
  '#title' => 'Special Instructions:',
  '#type' => 'textfield',
  '#size' => 75,
);
$form['admin_menu']['staffing_officer'] = array(
  '#title' => 'Staffing Office Status:',
  '#type' => 'textfield',
  '#size' => 75,
);

 $form['#submit'][]='cheo_whiteboard_admin_form_submit';

return $form;
}

  function cheo_whiteboard_admin_form_submit($form, &$form_state){
    dpm($form);
}

You are checking for user access within the form builder function. Make sure that control is going to the actual form by adding a dpm. It is better to check permissions at the menu definition level unless you have a better reason not to do so.

Next try $form['#submit']='cheo_whiteboard_admin_form_submit';

This makes sure that cheo_whiteboard_admin_form_submit is the only form handler function and hence easier for you to debug.


I cannot update because of Ubercart and Google Analytics module error I tried updating my Google Analytics module today, but when I went to the update.php page I got this error:

Unresolved dependency. Google Analytics (Version !=7.x-2.4 required)
Google Analytics for Ubercart requires this module and version.   Currently using Google Analytics version 2.4

I've tried everything to resolve this error. I found this page pretty easy, but none of the suggestions work. I installed Google Analytics 7.x-2.6, so I shouldn't be getting this error.

So far, I've tried:

Clearing my cache
Installing Google Analytics 7.x-2.3 and 7.x-2.x-dev
Downloading the latest version of Ubercart
Refreshing update.php and clearing browser's cache
Modifying ubercart module's uc_googleanalytics.info like the link above describes

I can't disable the Google Analytics module either because the checkbox is greyed out

If you are seeing the message Unresolved dependency. Google Analytics (Version !=7.x-2.4 required) when you have Google Analytics 7.x-2.6 installed, then almost certainly you have a duplicate copy of the Google Analytics module somewhere under your web root. That is not allowed in Drupal. When Drupal scans the file system looking for modules it will find both copies, and you don't know which copy Drupal will end up using (you can even have a case where some files from one copy are used and some files from the second copy are used!). Make sure you delete the old module entirely, or if you really want to save a copy then move it somewhere NOT under the Drupal web root.


How can I change the date format? I'd like to change the Date format of recent log messages (/admin/reports/dblog) in Drupal 8.9.1 from short date to something with the time. In Drupal 7 using watchdog I just edited the view and it was done. Since moving logging into core, I can't figure out where to edit the view. There is no view listed for Recent Log Messages or dblog and I can't find any other way to edit the date format. It's not an option in /admin/config/development/logging.
I know I can change Short Date globally to include time but I'm hesitant to change it everywhere just for an admin page. It seems like my only option is to create a new view with what I want and then replace the Recent page altogether.
Any help would be greatly appreciated.

This is still a view. The "Watchdog" view. Go to /admin/structure/views/view/watchdog and edit the date format. That's all.


How to add a contextual action link to a View? I want to replace the default EntityListBuilder from a custom entity with a View, as it is much quicker to build that list interface with it.

However I want to retain the action button from the EntityListBuilder on the View itself, which is in the links.action.yml:

entity.room.add_form:
  route_name: entity.room.add_form
  title: 'Add Room'
  appears_on:
    - entity.room.collection

Would I just add the view identifier under appears_on? What would the format be for that string?

Figured it out not long after posting. The format is view.(view_id).(display_id):

entity.room.add_form:
  route_name: entity.room.add_form
  title: 'Add Room'
  appears_on:
    - entity.room.collection
    - view.rooms.rooms_admin


JS compression ratio in Advagg module I am trying to use AdvAgg in my Drupal 7 site. I am using a local server for running tests.

The issue is that the module doesn't compress (php-jsmin) all the JavaScript files, which is causing a bad score in page speed insights.

After some debugging, I found out the problem: The uncompressed file didn't have a compress ratio between 0.1 and 0.9 so it was being aggregated as it was.

I'm talking exactly about advagg_js_compress.module file, lines below 143:

// Set to "-2" if compression ratio sucks (it's already compressed)

Why is necessary a min ratio? Could set min ratio to 0 so that all JavaScript files are processed?

Sometimes things compress too well; ie empty string. Sometimes things don't compress at all; ie already compressed. In both cases I opt to use the original file since minification of already minified js can sometimes cause js errors. You can variable set it if you want to adjust the min/max cutoff.


how to make a field in a view be the link destination to another field? I am trying to create ads on the sidebar to my site. I have created a content type that has 2 fields; an image field, and a link field. I now want to display the ads in a view by having the image appear, and when you click on the image, it brings you to the link that was specified by the link field. I know how to do this in a block with HTML, but I want to do it dynamically through a view. Is there any way to do this?

Make sure the Row Style is Fields. Add both fields, link field first and then image field.

Edit the link field (in the Views UI) and check exclude from display and use the URL as plain text formatter.

Finally, edit the image field and check output this field as a link. There are replacement patterns you can use for the link destination, the link field should be available there. You will need to check use absolute path.


SSESS Cookie (Session ID) is being changed when loading images that don't exist I have a Drupal 8.6.10 site which has a very confusing logout bug:

I have a page that has various elements on it as images, js, css and so on.
I load that page and everything works fine
I add an image to that page
I load the page again, everything fine, also the image is showing.
I delete the source image and the image style derivatives of that image
I reload the page -> I get logged out!

I can see on the call to the image (which returns a 404 because the image is not existing), the value of the SSESS Session cookie is changed (so the session ID) thus I'm losing the connection to my session and get logged out.

I have already proven that this happens inside the execution of PHP and has nothing to do with varnish (logging at the very end of index.php, before the answer gets sent, shows already the changed session id using session_id() ).

I have a parallel installation which is still on Drupal 8.3.7, and which contains various fixes of this issue: https://www.drupal.org/node/2743931
When I remove the fixes for the issue, the bug does no more appear.

However after the update to 8.6.10, I removed all the fixes because the issue has been fixed in core, and despite the fixes being removed, the logout bug still appears.

How can the session id even be changed? Calling session_start() a second time does not work and session_regenerate_id (the only one in the symfony core) is never called.

Please help me on this one, as I'm currently at the end of my latin. Thanks!

I finally found out what was the exact problem in my case:

I had varnish which per default, strips all cookies from the request to images. So when an image style is called, the request won't get any cookies and is thus an anonymous request.
The image is not present, so PHP is called to generate it.
A custom module invokes code that includes private tempstore (via Event listener but could also be hook_init() or something similar).
The SessionStorage is not aware that there was already a session because varnish stripped the cookie away. It therefore just started a new session (with the same cookie name but with another value). That was the return cookie.

At least it's solved now. An alternate way could also be that varnish could also filter all returned cookies, but this has to be configured / coded in the varnish config.


node type not getting in search template I am referring to document search-result.tpl.php on Drupal.org. Here they say $info_split['type'] has the node type information, but when I print in the file search-result.tpl.php in my theme folder, it does not print anything, as that key does not exist.  So is there something that I should do to get this info?

I took a look into the code and it seems to be that is not implemented. So maybe it's a bug or just mistake in the documentation.

At least, you can reach your goal with the hook_node_search_result or even with template_preprocess_search_result if you don't want create a module.

For information, the $info_split for node is filled by node_search_execute that call the hook said above.


How to redirect everything to 404 not found? I need to block an entire Drupal 7 site from being indexed for a while. So, I think it is best to redirect everything to 404 instead of actually deleting all my files. How can I do that?

PS: using the following code on .htaccess does not seem to work.

RewriteEngine On
RewriteRule ^ - [R=404,L]

-- Update 03/04/2015 --
The server is nginx

If you are just trying to keep it from being indexed, you can just add

User-agent: *
Disallow: /

To the top of your robots.txt


Drupal 7.14 image upload unstable I am setting up a site in Drupal 7 for a photographer which includes uploading a large number of photos to the server. My problem is that image upload is extremely unstable. Sometimes it works, sometimes it does not. It seems I am hitting some kind of memory or bandwidth limit, but I don't get any errors.

I created a custom content type for photo albums, with each category (e.g. "portrait", "wedding" etc.) as a node with a number of attached images that I display using views slideshow. Everything works on the front end.

Image upload is handled by an image field and the Media file selector widget. The problem is that sometimes during upload the page will just refresh and the image does not show up in the list of attached images.

I also tried using the Plupload widget that allows uploading several images at once. With this I get a slightly different behavior. The images will "break" after two or three images meaning that they show up as corrupted images with part of the image missing. Sometimes refreshing the page or clearing all Drupal caches will allow me to upload maybe four images at once.

It looks like this

What is strange is that the same exact image file will sometimes upload, and sometimes not.

I am not uploading huge images. They are all manually resized to less than 1600x1600px before uploading, with file sizes between 200 and 600 KB.

Drupal 7.14

Media 7.x-1.2

Plupload library 1.5.4

Plupload integration module 7.x-1.0

Plupload widget 7.x-1.0-alpha1

PHP settings:

PHP version 5.3.10

Max upload size: 5M

Memory limit: 1024M (increased from 128M using ini_set() in settings.php)

Any help will be greatly appreciated! I have been googling for days trying to solve this

:::UPDATE:::
I found a temporary workaround. The module Multiupload Imagefield Widget allows multiple image uploads that seem to work for me apart from a few error messages. At least this makes it possible to load my images on to the server effortlessly.

However, this module does not show thumbnails for uploaded images which is crucial for this particular project.

I believe you are experiencing a problem that Plupload has with PHP 5.3.x. I built a site for a client that uses photo galleries (Media and Media Gallery), and via the Pupload Integration Module galleries could be built by simple drag-and-drop of multiple image files. The site is hosted on Rackspace Cloud, which recently upgraded from PHP 5.2.x to PHP 5.3.14. That's when the problems began.

There is a bug report for the Plupload Integration module that shows the error I'm now getting. If you're getting the same error message, I'd recommend that you also take part in the thread, as I just did.


How to implement a simple shopping cart without Commerce and Ubercart? I need simple solution for shopping cart without big monstrous modules like a Ubercart or Drupal Commerce. I've a small site (catalog) with a few products. I need add to each of them an Add to cart button, cart block and page (can be made using Views). Checkout must be just a form with few a fields (like Name, Address etc), which can be made using Webform.

Why Commerce and similar modules are not good for me: I don't need specific fields like SKU, product displays facilities, online payments, registration for user, tax calculation and other. I just want to keep it all simple.

Any suggestions?

The Basic cart module is the best solution for you...

  Basic cart is a very simple shopping cart / checkout process for
  Drupal, that just sends 2 emails after each order. Along with the
  shopping cart, this module also provides a block where you can view
  your cart's content. It's ideal for small websites with only a few
  products or other content types being sold, for example touristic
  offers.


How to trigger an Action on an Entity from a button in a Views row (without VBO)? I know actions can be done with Views Bulk Operations (VBO), but I just want a button in each row of a view of entities. When I press the button, the action is executed for that entity.

What you're asking for is perfectly possible using the Rules Link module (no need for VBO). Some details about this module (from its project page):

  Features: ... The links are usually displayed using Views...

  Usages: ... The Rules Link module will create a Views field for each link, which can be hidden, using the visibility conditions ...

However, assuming you're familiar with the basics of Views, it isn't obvious at first about how to actually add such extra column. The clue to get it to work, can be found in this part of the module's README.txt:

  Rules Links link
  will create a Views field for each link, using the title of the link as title
  for the field. So if you have link for nodes with the delete 'Delete node',
  you'll find the Views field under name 'Content: Delete node'.

Example

Below is a list (= Views result) of "All blocked/active users" shown to a user with role Administrator:

User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

Note the extra column added (to the right), with links labeled Unblock user which are only shown for the blocked users, and not for Anonymous. After using (clicking) that link, for some user with Active=No, the user's status becomes Active (an example of "an action triggered on a user entity", as in your question), and the link is no longer shown for that user. If you wonder how to create such extra column (using Rules Link), refer to my answer to "How to show authorized users a link for relevant Views results using the Rules Link module?". Obviously, transforming such link into a button is just a matter of some (basic) CSS to be applied to that link.


Updating Large Number of Sites At my current job we have a large number of Drupal installations(not multisite) and we are facing some issues regarding things like applying security updates (really any kind of update).  Currently we have a mix of D6 and D7 sites, though all new sites are D7....hopefully we can eventually move all to D7.

I was curious what strategies you guys would suggest for approaching mass updates in this environment.  Do you think it would be worth converting our sites to using Aegir for update administration?  Will this come down to manually updating/working through each site?

Thanks,
Ryan

There really isn't any right answer to this question. I do something similar to what tenken suggests; see:

https://github.com/greg-1-anderson/utiliscripts/blob/master/drupal-backup-all

The basic idea is, every time I back up a site, I also make a second local copy, and run pm-updatecode on it.  The backup and update sites are live (but accessible only on the internal network), so it's possible to look at either and see if they are running or not.

My experience in doing this is that the task of copying a site and running pm-updatecode is not the main bottleneck in upgrading sites promptly and frequently.  The main bottleneck is testing.  You have to set aside time to do this, or you won't be able to confidently deploy your sites.  Upgrades rarely, but sometimes do break your site, so you cannot really automate this last critical step.

One thing that can really help is good automated tests.  Behat and Selenium are really useful here.  See the small project below for a quick start template:

https://github.com/arithmetric/badcamp2014-behat-travisci


Programmatically change placeholder text of form input Inside a custom block plugin I'm creating, I programmatically load the user form and return it like so

public function build() {
    $fb       = \Drupal::formBuilder();
    $userform = $fb->getForm("Drupal\user\Form\UserLoginForm");

    $render = [
        '#type'       => 'container',
        '#attributes' => [
            'class'      => ['row', 'expanded'],
            'id'         => ['login-page-block']
        ],
        'userlogin' => [
            '#type'    => 'html_tag',
            '#tag'     => 'h3',
            '#value'   => 'Welcome Members!',
            'caption'  => [
                '#type'   => 'html_tag',
                '#tag'    => 'p',
                '#value'  => 'To access member-exclusive content on our website, you must login.',
            ],
            'form' => $userform,
        ],
    ];

    return $render;
}

It creates labels for the inputs for Username and Password, but I'd rather ditch the labels and put 'Username' and 'Password' as placeholders inside the input fields. However I'm not sure how I would go about doing that. I performed a die(print_r($userform)); to get a list of fields in the array but I didn't see anything applying to the array.

Is there a way to place placeholder text inside the text input fields of a form that was programmatically retrieved and rendered?

UPDATE: I attempted changing the placeholder by writing

$userform['keys']['#attributes']['placeholder'] = t('Username');

But that didn't seem to do anything.

I was able to add the placeholder text by entering

    $userform['name']['#attributes']['placeholder'] = t('Username');
    $userform['pass']['#attributes']['placeholder'] = t('Password');

After looking at the results of die(print_r($userform)); more closely I saw that the username input was called 'name', and password was 'pass'


Disable menu link for certain languages I'm looking for a way to disable a single link in a menu for a certain language. From my understanding with similar issues, I'd like to activate translation for the menu link field Enabled since this is set for all languages by default.

Is there a way to activate the translation of this field for menu links?

This wasn't quite exactly what I was looking for, but it suits my case and is simple to use, so just in case anyone stumbles upon this looking for a solution:
The Menu Manipulator module hides menu links that are pointing to contents without the current translation. You can specify which menus will be managed by this, so this is at least a little bit customizable.


Attaching more than one feeds url to a single content type I have a feeds setup in which i have a content type discount travels.I have created a feeds import using xpath xml parser.Now i want to attach one more link to the same content type.I know currently there is no provision for this in the feeds module.Instead we can create one more new feed importer with new link and attach it to the same content type.I doubt is it possible to have 2 unique fileds in the same content type.I have mapped one field from first URL to guid and marked it as unique.Then i mapped another field from second URL to guid and marked it as unique.Then i attached the new import to the same discount travels content type.Has anybody achieved this before using feeds and feeds import.Any help will be appreciated.Thanks in advance.

Instead of using the GUID field method that comes with Feeds, it is possible to use Feeds with the Field Validation module. See the discussion at patch at the bottom of this thread.

I haven't tried it, but Field Validation might let you set multiple unique fields as it provides validation options for every field in a content type.


What is right way to modify a node field in a multilanguage system (LANGUAGE_NONE or $node->language or ...) Let's say we want to modify the body field.

$node->body[LANGUAGE_NONE][0]['value'] = "test";

This will work if the node is language neutral (?)

$node->body[$node->language][0]['value'] = "test";

This will work if the node has the same langauge as the field.

But is this always the case? I found nodes where this is not the case:

(Object) stdClass
...
language (String, 2 characters ) de
...
body (Array, 1 element)
  und (Array, 1 element)
        0 (Array, 5 elements)
            value (String, 4 characters ) test

So if this is a correct node, how can we access the body field value?

field_language() returns the field's display language. You should use code similar to the following one:

$language = field_language('node', $node, 'body');
do_something_with($node->body[$language][0]);

Of course, note that field_language() will determine the right display language ('en' or LANGUAGE_NONE or whatever); if you're modifying fields you might want to modify more than one language.


Exposed Filter of Child Terms on Parent Page I'm looking for a dummy's guide on how to configure the default taxonomy term views so that I can display an exposed filter of child terms on the parent page.

Assuming I have the taxonomy structure below.

Sports

Football
Basketball
Boxing

Entertainment
Politics

I want when I'm on Sports page, there is an exposed filter where I can select either of football, basketball or boxing.

I have followed all tips I could find online but the option to add contextual filter of "Taxonomy Term: Parent term" was not available.

You can create a separate Views of type Taxonomy term (not content!) display Block that is showing taxonomy term names, add the Relationship to the parent term and require it, and a Contextual filter to taxonomy term ID using that relationship.

Test it by entering parent term ID into Preview, you should see the parent's children.

Edit the Format to set the fields to display inline, or use CSS (later) to make them appear horizontally.

Then in your Content (original) Taxonomy Term views add View area into Header and choose the above Block with Inherit contextual filters option ticked.


Show the logged in user their account status How do I make a Views block(or by other means) to let the user who is logged in know of their account status i.e. when it is awaiting approval, or was not approved?

A user that has not been approved by the admin can not login as far as I know.


Specific user-based admin view For testing whether Drupal 7 runs on an local nginx server:

One of the user should get more rights than an editor/writer, but less than an admin. Is there a way to create a 2nd specific admin role without certain permissions (e.g. Admin VBO Views)?

Regards, bolshii

I am not 100% sure, but I think you just need to create a new role and specify what the user can do and what he cant? I have for example a role which can add new content and nothing more. So they see the admin bar in the top and it only lists add content :) and which types of content they can add.


Exported feature with roles not imported when loading module TLDR; I'd like to export the permissions I've added to the authenticated role, and have them appear on a different server when installing the custom module. However, when I install the module on a fresh server, the permissions for the authenticated user remain as default, but I can see in admin/config/development/features that there are pending changes, and once I import them the settings are correctly applied. Why aren't they applied on loading the module?
Steps to reproduce
First I log into a blank dev site, navigate to admin/people/permissions and add the Article: Create new content permission for the authenticated user (which I know is create article content from looking at the page source in my browser).
I now navigate to admin/config/development/features/edit and select Roles->Authenticate user (authenticated), pick a module name, enable Mark all config as required and click Download Archive.
The result is a module that contains 3 files:
my_module.features.yml
required: true

my_module.info.yml
name: 'my module'
type: module
core: 8.x
dependencies:
  - user

Since I'm using 9.0.7 I changed this to;
name: 'my module'
type: module
core_version_requirement: '^8 || ^9'
dependencies:
  - user

config/install/user.role.authenticated.yml
langcode: en
status: true
dependencies: {  }
id: authenticated
label: 'Authenticated user'
weight: 1
is_admin: false

For some reason Features didn't pick up my permission changes, so I changed this manually to;
langcode: en
status: true
dependencies: {  }
id: authenticated
label: 'Authenticated user'
weight: 1
is_admin: false
permissions:
  - 'create article content'

Now I tried to install the module by copying it to /modules/custom/my_module and running drush en my_module on a completely clean site. However, when I navigate to admin/people/permissions I see this:

When I go to admin/config/development/features/diff/my_module I can see that my features were correctly interpreted, just not applied:

If I now select Import Changes the permissions apply correctly. But why aren't they already applied, when the my_module module is clearly enabled?
I tried playing around with the weight value in user.role.authenticated.yml to no avail (I changed it to 9999 and -9999 but it didn't seem to have any impact).
The fact that I had to modify my user.role.authenticated.yml indicates that something has perhaps gone wrong at the export step, but I don't know enough about the features module to know if these events are related.

You need to un-exclude user permissions first.
Go to /admin/config/development/features > Select your bundle > (Tab) Configure Bundles > Alter (Configure) > Uncheck "Strip out user permissions."
Then recreate the feature.

I've also already been there.


How to restrict access to view a block for a certain role? I have some custom roles such as Premium Membership and I don't want to allow access to this category.

The authenticated role is included to Premium Membership or Moderator users because every registered user has this authenticated role assigned to them by default.

I want to hide a block and display only for authenticated users that do not have other roles assigned to them.

What can I do?

Visibility Block base on the Role is built-in Drupal 8 feature.

go to admin/structure/block and click on your desire block configure button

then in Visibility section, there is Role that you can define for which role your module  show , or not to show.


Recommended techniques for changing the appearance/design of my Bootstrap sub-theme? I use Bootstrap (7.x-3.0 for Drupal 7 which I already created my own sub-theme and I enabled this sub-theme as my default theme. It seems to work so far.

Now, I want to change the appearance/design of my menu. Here is the appearance with the Bartik-theme:

And here is the equivalent using the Bootstrap-theme:

If I want to customize the Bootstrap theme to look similar to the Bartik theme, how do I do this? In the base-theme folder of Bootstrap I found menu-tree.func where the menu tags are generated, which looks like so:

/**
 * @file
 * menu-tree.func.php
 */

/**
 * Overrides theme_menu_tree().
 */
function bootstrap_menu_tree(&$variables) {
  return '
' . $variables['tree'] . '
';
}

/**
 * Bootstrap theme wrapper function for the primary menu links.
 */
function bootstrap_menu_tree__primary(&$variables) {
  return '
' . $variables['tree'] . '
';
}

/**
 * Bootstrap theme wrapper function for the secondary menu links.
 */
function bootstrap_menu_tree__secondary(&$variables) {
  return '
' . $variables['tree'] . '
';
}

Do I have to edit this file? I don't really think so. Further, each element of the menu uses the class called leaf which I couldn't find at all in any files of Bootstrap.

Hope my point is clear. I just want to edit the appearance of my menu and also of further elements without creating an entire custom-node.tpl.php. Is that possible or do I have to create an entire new file?

Since you're using Bootstrap as a style framework already, I'd recommend you simply restyle the navbar to look like Bartik. You'll have to modify your page.tpl.php template to move the various elements of the header around to put the site title and user menu on top of the main menu.


Hook for adding values to add node page I'm searching for a hook in Drupal 8 API for adding values to a add content form.
What hook can I use to alter values from /node/add/movies_movie page?

Think you are looking for the form alter hook here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x


Use wget to mirror a site to a static site I'm trying to use the following command to mirror a Drupal 6 site which needs to be archived as a static site. Unfortunately, I've only been able to find a static generator for Drupal 7, not 6. I'm having issues because it seems that

By logging in as different roles, the wget command will pull down completely different directory structures. This is not unanticipated, but in some cases as an administrator there is quite a lot of content missing which is pulled down with accounts that have lesser permissions.
There are links on the main page in separate blocks whose directory and pages do not get pulled down in the file directory structure by logging in with any role, including administrator.

So far I've successfully been able to mirror the site (with the above limitations), but I'm not sure if the command is actually mirroring the entire site as I need it to do. Here is the code I am using for wget:

wget --mirror -w 2 -p --convert-links --load-cookies cookies.txt -e robots=off https://url.org/user

where the cookies file is created like this:

wget --save-cookies cookies.txt --post-data 'name=MY_USERNAME&pass=MY_PASSWORD&form_build_id=FORM_ID&form_id=user_login&op=Log+in' https://url.org/user

I am very new to Drupal, so am not sure how roles and permissions, or the structure of the content might affect a wget mirror operation. Any suggestions would be appreciated!

It appears that the issue had to do with the fact that a "Logout" block was in the header of the main site. As a result, when wget went to pull things down, it would actually go to the logout link, and thus the rest of the files would either display a login screen or wouldn't be downloaded. By disabling the logout block OR adding --reject logout to my wget command, it seems to have fixed the issue and now the full directory structure is being downloaded. The command I ended up using was:

wget --mirror -w 2 -p --convert-links --load-cookies cookies.txt -e robots=off --reject logout https://url.org/user


Has anybody figured out how to add videos to a node gallery? I've just finished building a node gallery image gallery system in drupal that lets my users add lots of photos easily to the site, and create their own galleries. However, I'd like them also be able to add video files. Node gallery says this is not available "out of the box" but possible, but I cant find any instructions on how to do this. I'm hoping someone out there has figured this out.. thanks in advance.

http://drupal.org/project/video    This maybe is the module you need to try?

or users add simple link to youtube http://www.youtube.com/watch?v=-LF30SUwr5Q


Add a subquery in a WHERE condition, using hook_views_query_alter() I tried to add a subquery like this:

function mymodule_views_query_alter(&$view) {
  $view->query->where[1]['conditions'][] = array(
    'field' => 'node.nid',
    'value' => 'SELECT SUBSTRING(source, 6) FROM {url_alias} WHERE alias LIKE "pros/%"',
    'operator' => 'in',
  );
}

I have a specific case where nodes are created with aliases starting with pros/ or not, and I want to get only them.

In a simple raw SQL query, I'd go with this:

SELECT *
FROM node node
WHERE node.nid IN (SELECT SUBSTRING(source, 6)
                   FROM {url_alias}
                   WHERE alias LIKE "pros/%")

But I can't find out how to do this using hook_views_query_alter().

Ideally I think its right to use views_join_subquery. But the subquery you are using is with IN keyword is always slow and will produce same result as using a LEFT JOIN joining with node.nid field.

You can try creating a views_join and adding the url_alias table by add_field method while the node table will be the left table.

I don't have the code at the moment but you can have a look at the below links.
https://stackoverflow.com/questions/6851945/add-table-join-where-and-order-by-to-views-query-in-views-query-alter

http://www.wordpressecoder.com/2014/01/how-to-alter-views-query-with-multiple.html
http://www.yellowpencil.com/blog/last-ditch-fix-programmatically-changing-drupal-7-view


Replace a specific integer value with a string? I have a View that displays a list of all the content types, with price as one of the fields you can sort and filter by.

However, the client wants to have some items show up without a price, i.e something like "Price on demand" / negotiate.

Therefore I want to replace '0' value to show up as that text (translated for other languages), how would I best do this?

I use some exposed range filter in my view but couldn't see any extra functions to replace values of field items with strings etc.

I would need it changed in the View as well as the items' individual page (and generated PDF file, but that part I can do)

EDIT:
I have Better Exposed Filters, but after setting the replacement as:

0|Price on demand

It didn't seem to work or do anything. However my views uses a template, and I output the price by doing:

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

So I would first need to check if $content['field_price'] value is 0, then output my text string? Ideally I would prefer using some settings that can handle replacing the value for me.

This seems like the simplest method:

print $content['field_price'][LANGUAGE_NONE][0]['value'] == 0 ? 'Price on demand' : render($content['field_price']);


Post update hook fails to run via Drush, but works via update.php I've implemented hook_post_update_NAME to bulk import some files into Drupal (creating file and media entities for them). This hook runs correctly when I use update.php. But it seems to silently fail via drush updb.
My update hooks looks like this
/**
 * Creates SVG icons as media entities.
 */
function my_module_default_content_post_update_create_icons() {

  $module_handler = \Drupal::service('module_handler');
  $module_path = $module_handler->getModule('my_module_default_content')->getPath();

  \Drupal::logger('my_module_default_content')->notice('Importing icons from @path', ['@path' => $module_path]);

  $dir = new DirectoryIterator("$module_path/icons");

  \Drupal::logger('my_module_default_content')->notice('Directory contains @count items', ['@count', count($dir)]);

  foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {

      \Drupal::logger('my_module_default_content')->notice('Importing file @file', ['@file' => $fileinfo->getFilename()]);

      my_module_default_content_create_icon($fileinfo->getPathname());
    }
  }
}

This works fine via update.php. All the files are copied, relevant entities created, and messages logged to watchdog. When running drush updb I only get

[ok] Update completed: my_module_default_content_post_update_create_icons
[success] Finished performing updates.

None of my log messages are output (while using --debug option) to the screen or to watchdog.
My initial thought was a permissions issue, but if it's not outputting any of my log messages. I'm not positive the function is even being run. Adding in a die() on the first line of the function gave the exact same output/outcome.
Any ideas on what could cause this to silently fail when running via Drush?

For anyone else who runs into this, make sure that the post-update hooks are defined in a MODULE_NAME.post_update.php file. It seems as though update.php will happily invoke post-update hooks defined in the MODULE_NAME.install file, while Drush will not.


Returns a list of nodes as XML? I'm trying to do something like this with Drupal 7.

I need to generate either an XML file or a number of xml files based on the sub-parts of the over-all "Navigation" menu.

I have multiple "Portals", each with a list of pages... I need to generate an XML file for each portal, and be able to customize the hell out of it.

I've been trying Views... with XML Sitemap, feeds, etc... I just can't seem to get anything workable.

Will Views RSS do what you want?  It typically throws articles/nodes out as RSS(XML),  and you can modify it to produced more structured output if you wish.


How to change path of public files Drupal Public files in Drupal have a relative path that is similar to /sites/default/files/file.txt; private files have a relative path similar to /sites/default/files/privates and system files have a relative path similar to /system/files/file.txt.

How can I make the relative path for public files be /public/files/file.txt?

You can change the path using below step.

Go to Administration -> Configuration -> Media
Click on 'File system' link
Change the directory in text-field 'Public file system path' and save the configuration.


Grouping fields together Is it possible to generate fields which are "grouped" together when marked as Unlimited? For example, a select field with label "What time do you wake up?" lets the user select the day of the week (Mon-Sun) then beside it an empty textfield to type in the time they get up. These 2 fields are "grouped" together. Then if they want to add another day of the week (Unlimited), the new field generates a dropdown menu and a textfield together all over again.

NOTE: No CCK please. I'm using Drupal 7 and it's already in the core.

Try the Field Collection module. It's not stable yet (beta 1) but it looks promising.


custom node template involving the use of quick tabs in drupal 7? I have products that I want to display divided up into quick tabs. Originally I was thinking of using multiple views to do this, but then I realized that there has to be a way to do it using a node--product.tpl.php. the way they are divided up are as follows:

One quick tab that has a basic image, title, and a little paragraph about the product.
The second tab should have features of the product.
The third should be a description of the product. the fourth should be files (images, and videos, and audio files, etc).
And the last one is a tab for technicians of the product.

I want it so that I only have to use one CCK to do this, and it would be the content it's self, instead of multiple views put togeather in quick tabs. here is the kind of thing that I am looking for:

1. Product Tab:

2. Features Tab

is this possible to do in a node--product.tpl.php?

Go forth and tabbify with Quicktabs 3.0 for Drupal 7 gives some good examples of how to add custom content to quicktabs.


How to summarise different date ranges using this week, last week, etc? I would like to display a table or graph showing revenue over the last year with sums divided into weeks or months.

I record every sale/value in an entity, and can show ie "total this week" or "total this year" with Views and aggregation, but I would like to show it like "this week", "last week", "last week -1" without having to make a view or attachment for each value.

Is this possible without making a new entity ?

Notes:

I want to use Views, but I wonder if there is a way to group/aggregate values without having to make a new view for each aggregation (week or year). Then I will have to make 52 views/attachments for showing weeks and 12 to show the year.
I can create a date field in my view and format it as year-month eg 2014-12 and then group by that and use aggregation. But then I will have to make one for 2014-11, 2014-10, 2014-09, etc

"Date Views" (date_views) sub-module of the Date module extends the "Configure filter criterion" used in Views. It allows for using "Relative dates" that are computed when the view is displayed.

Some examples are:

now
now + 1 days
-2 months
Monday next week
...


Passing arguments from Panel to View without url or using contextual filter from panel to field of taxomony term within view Using Drupal 7, Panels 7.x-3.3, & Views 7.x-3.5.

I'm unsure the best way to approach what I'm trying to accomplish.

I have taxonomy vocabularies classifying people in my department.  One example would be fellowships.  Within fellowships there are terms 'Surgical Pathology', 'Transfusion Medicine', etc and within those terms there are terms such as 'Director', 'Faculty', Coordinator, etc with which people are associated.  Each fellowship page will be a panel with various content and a view listing the people within that taxonomy.

We have numerous fellowships and would like to create a view that could be used for all via contextual filters or argument from the panel.  The issue I'm running into is that I'm not going to use the full taxonomy term name in the url.  For example 'Surgical Pathology' might be mysite/education/fellowships/surgical or 'Transfusion Medicine' might be mysite/education/fellowships/transmed.  I can't use the full term name or term id as my hands are tied with keeping those urls.

I'm not sure if its possible to send an argument that is set in the panel (not from url) using 'Input on pane config' or 'From panel argument' in views but I haven't been able to figure it out or find any tutorials on how to.

The other method I tried was to add a field to the taxonomy called Manuel_Context which I put in 'transmed' or whatever the url argument actually is.  So I have the Contextual Filter set in the view to '(Parent) Taxonomy term: Manuel_Context'.  When I use the preview, the view works how I would like however I haven't been able to figure out the panel settings to get this to work.  When I'm in the panel Settings>Arguments I can only select for the 'Context Assigned' Taxonomy Term: ID.  I don't know how to get the panel to look for the field Manuel_Context of the Taxonomy Term.

Any suggestions on how to approach this would be greatly appreciated.  Thank you

The easier (semi-automatic) way I can think of
is to

Override the path /taxonomy/term/%taxonomy_term
(enable the *term_view* page provided in system) in Page manager.
Build a page with panels for this path.
Now your content panes, when used in this page, can get their arguments
with the 'From panel argument' option.

You can always have SEO-friendly URLs like
mysite/education/fellowships/surgical or mysite/education/fellowships/transmed
with path (in /admin/config/search/path/add).

The other way is to use the 'Input on pane config' option
for your content panes.
You will have to set the arguments for these panes manually
in their settings dialogue.
In your case, the argument should probably be the (numerical) term ID.
This way your content panes don't need to be tied
to a specific path pattern, and you can have
some logical combinations in your contextual filters,
such as 1+3+5 (term 1 OR 3 OR 5).
This can get quite laborious, though.


php code in block - Load node I have previously used <?php print $node->field_listing_artist[0]['taxonomy_term']->description; ?> on page.tpl.php. What this does is prints the description of the related taxonomy term of the node being displayed.

But I am looking to use this piece of code in a Block or a Custom Content Type in Panels.

From searching around, I can see (I think?) that i need to load_node, but cannot seem to get the code to work.
Similar Drupal Answers Question

So what i am trying to achieve is create a block/'Panels custom content type' that will correctly process <?php print $node->field_listing_artist[0]['taxonomy_term']->description; ?> of the node currently being viewed.

You should check out What are Ctools plugin (content type, access, etc), and how does one create them?, and in addition make sure the content type has a required context on nodes so that you can't accidentally render it without a node. Check the examples on the ctools module to see how to add required contexts.


Taxonomy as exposed Filter -> showing extra Field I have a taxonomy with german umlauts in terms. This taxonomy I use as exposed filter in a view (with better exposed filters). To work with views arguments I named the terms WITHOUT umlauts (Oesterreich for Österreich). And I have an extra field where I have the names WITH umlauts.

Now I want to get the values of these fields shown in exposed filters to have the correct spelling.

Does anyone know how I can get this done?

I found my solution:

With views reference filter I created a view with taxonomy terms. I added the field WITH umlauts and added this view as filter in my actual view: taxonomy term (referenced). In the next step I selected the refernce filter view.


Taxonomy formatter that shows a list of links to related nodes I have a Taxonomy field on a Node. In the display of the node, I'd like a list of links to other related nodes, not a link to the Taxonomy category.

Is it best to build or find a formatter that can do this?

Or, is it best to make a View, and if so, what is the proper way to enforce the relationship between the selected Taxonomy Term item in the Node and the View?

Update: I found another StackOverflow answer. Though seemingly complex (I don't yet understand how it works), the initial results are promising.

You set up a contextual filter on the View Block to Content: Has taxonomy term ID.

So we need to hand this view a term ID. Since we're going to be calling this block using Context. There won't be a default value given in the URL. Therefore we have to give it one.

Select

Provide Default Value
Load default filter from node page, that's good for related taxonomy blocks
Choose your default vocabulary


translate the page title in search template file What is the best way to translate the title in search template file

I use a commercial theme. In :

page--search.html.twig

I can modify the tytle by replacing :

{{ title }}

by

Recherche

It works but it is obviously not the best way.

Since search result page is not a node, where is this title ?

I’ve searched in blocks, content, module and I can't find this title.

Drupal 8 has extensive multi-lingual support and French is one of the supported languages.

As administrator, turn on the language module at Administration -> Extend

Then go to Administration -> Configuration -> Regional and Language -> Languages, click on Add Language and select French. If you want it to be the default language set it as the default and Save Configuration. (This can cause issues if the site is already live!)

The User Interface Translation module (also in core) can be used to import additional translations and to allow you to translate strings manually as needed.


creating a function that can create GET url variables as object when I need it I am trying to parse my form's GET method and create a function that can get all the parameters from the URL in DRUPAL 8. I have a form that I am gonna use it to filter my library items as search( I know I can use search api or advanced search but my client wants this way ) So I have a few fields such as keyword, title, description, location, author, from, to, collection. and when I add all the fields after the redirection to result page

http://example.com/advancedsearchresult?keyword=test1&title=test2&description=test3&author=test4&location=test5&from=&to=&collection=&media=all

I would like to do nice job with using OOP and Symfony service features. My question is how could i create a function in my controller for this result page that is gonna parse all the parameters from the URL so I can use them to create an object in service to create individual query for each parameters to make search mechanism for this form?

UPDATED:

After @oknate pointed out, I updated my controller like this:

namespace Drupal\advancedsearch\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\advancedsearch\AdvancedSearchQuery;

class SearchResultController extends ControllerBase {
 protected $advancedsearchSearchResult;

public function __construct(AdvancedSearchQuery $advancedsearch_search_result ) {
 $this->advancedsearchSearchResult = $advancedsearch_search_result;
}

public static function create(ContainerInterface $container) {
return new static(
  $container->get('advancedsearch.search.result')
);
}
private function setupAdvancedSearchQuery() {
$params = \Drupal::request()->query->all();
foreach ($params as $key => $value) {
  if (!empty($value)) {
    $params[$key] = $value;
  }
}
}
}

on the other hand, I created my service file, I created my variables which matches with parameters, so am I gonna be able to use setupAdvancedSearchQuery() when I call the object for each parameters, if so can anyone give a hint?

If these $_GET parameters are also route parameters (set up in a module's routing configuration), you can use

 \Drupal::routeMatch()->getParameters();

Or for a specific parameter:

$keyword = \Drupal::routeMatch()->getParameters()->get('keyword');

If the $_GET parameters are not route parameters, you can get all the parameters this way:

$params = \Drupal::request()->query->all();

If you want to set default parameters for parameters that aren't in the URL, you can merge the $params with an array of defaults.  Then depending on how you're going to use the parameters, you may want to XSS filter the params to prevent cross-site scripting attempts.  As @Berdir points out, this is rarely necessary, as twig auto escapes and if you are passing parameters into the query abstraction layer properly, it will also filter your input.  But you could filter your params this way:

foreach ($params as $key => $value) {
  if (!empty($value)) {
    $params[$key] = Xss::filter($value);
  }
}

(If you are using arrays in your $_GET params, this foreach loop would need to be altered to handle that use case.)

Here's some more info on XSS security.

After you have pulled-in and cleaned up your $_GET variables, you could then save these parameters to your object, and then use them conditionally in your query.

Since you asked specifically about Controllers, you can pass the request object to controller in the constructor:

  public function __construct(Request $request) {
    $this->request = $request;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')->getCurrentRequest()
    );
  }

Then you could use the request object from the container.

If you set up the parameters as route parameters, you can just pass them in as arguments to the controller.


Author only access to tab menu of node I have created one menu tab in the node page to show statistics  of the article using my custom module.

I have implemented hook_menu() as follows:

function mymodule_menu() {

    $items = array();

    $items['node/%node/menu_title'] = array(
        'title' => 'Page Title',
        'page callback' => 'get_statstics',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );

    return $items;
}

It is working fine. But I wanted only author of the node to have access to this link and also for specific content type. Now it is showing this link to every node and for every user.

How can I restrict it to specific content type and for author only?

-- Many thanks for your time

Under access callback you have TRUE, just change this to a function that evaluates whether the current user is the author of the current node. The function would look like this

function yourmodule_check_author() {
  global $user;
  $node = menu_get_object();
  return $node->uid == $user->uid;
}

Check this post. You will get more insight on the inner workings of the function.


Showing child taxonomy terms if the parent is selected I want to show one drop-down with a list of parent vocabulary terms and then when one of those select corresponding child terms displays in page.

I am using Drupal 7 with views 7.x-3.0-rc1.Any one guide me do this.

Views doesn't have any built in way of creating an exposed filter like you explain, which means that you either need to create this functionality yourself for Views - which is very hard unless you have messed with Views APIs. The other option is to create this functionality in a custom module which a lot easier but also quite time consuming, so you will have to code it all in a custom module.

As a side note you should update your views install, currently up to date version is 3.3, This is quite important as 3.1 or 3.2 had a security fix, meaning you site has a known security vulnerability.


How to include task links in twig node template I have created a custom twig node template. It displays the content in the manner that I want but it is not displaying the task buttons. How do I include the display of the task buttons if the user who is viewing the page has the permission to see them?

I have tried Googling for a solution, but haven't found anything. I figure this should be pretty straight forward to do (at least I would hope it is).

Thanks.

https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links
The manual says:

Contextual links are stored in title_suffix. This variable needs to be printed in the html.twig file, such as in this example from block.links.contextual.yml.

<div{{ attributes }}>
  {{ title_suffix }}
  ...
</div>


How do i get parent ID of a taxonomy term? When i try to get data using the JSON API module, the field parent is always empty even if a term hierarchy exists.

For example, for a request to http://mysite.local/jsonapi/taxonomy_term/my_vocabulary/1a2a1fc1-b6d8-40be-a482-766ccab4aed1?_format=api_json&include=vid,parent, part of the response is the following one.

"parent":{
        "data":[

        ]
     },

How can I fix it?

See this core issue: https://www.drupal.org/node/2543726

This will address this. Right now, parent is a special pseudo-field that only supports saving parent relationships but not actually loading them. That's why serialization doesn't work.

You would have to write your own serializer that uses the getParents methods of the taxonomy_term storage to load the data


How to add description like: "Comments for paragraph 1" to comments I have written a module that allows users to put comment on each paragraph. So in comment form there is a field that asks the user which paragraph do they want to put comment on.
I have to mention that I have added a column to my comment table, which saves that paragraph number.

function Annotations_form_comment_form_alter(&$form, &$form_state, $form_id) {
$form['paragraph_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Which paragraph you want to put comment on?'),
    '#required' => TRUE,
    '#size' => 10,
    '#maxlength' => 2,
    '#default_value' => !empty($form['#entity']->paragraph_id) ? $form['#entity']-   >paragraph_id : NULL, // set the default value to the current paragraph value
     '#weight' => $form['subject']['#weight'] + 1, // place after the subject   field by setting the weight to +1 of subject weight
);

$form['#validate'][] = 'annotations_form_comment_form_validate';
$form['#submit'][] = 'annotations_form_comment_form_submit';

 }

I also have Annotations_form_comment_form_validate  and Annotations_form_comment_form_submit functions for validation and submitting.

I have also written the following code to sort the comments based on the number of the paragraph. So first you see the comments on paragraph 1, and then 2, etc.

    <?php

  define('COMMENT_SORT_OLDER_FIRST', 1); // default
  define('COMMENT_SORT_Paragraph', 2);
 /* Alter node type form: allow user to decide comments sorting */
  function Annotations_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Paragraph Number')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']->type, COMMENT_SORT_OLDER_FIRST),
 );
  }

  /* Alter comments query */
 function Annotations_query_comment_filter_alter(QueryAlterableInterface $query){
  if ( ($node = $query->getMetaData('node')) && (get_class($query) == 'PagerDefault')             ) {
  $sort = variable_get('comment_default_sorting_' . $node->type,              COMMENT_SORT_OLDER_FIRST);
    if ($sort == COMMENT_SORT_Paragraph) {
  $orderby =& $query->getOrderBy();
  $expressions =& $query->getExpressions();
  if (isset($orderby['torder'])) {
      unset($expressions['torder']);
      unset($orderby['torder']);
      $orderby['c.paragraph_id'] = 'ASC';
  } else {
    $orderby['c.cid'] = 'DESC';
    }
   }
 }
}

I want to have a line like: " Comments on Paragraph 1 " and then show the comments for paragraph 1, and the same for rest of the comments.

Does anybody know how can I do that  or which hooks I can use? Do you know some other modules or examples that do something similar, so it will give me some idea that how to do it?

I don't think it will really be answerable without the code you wrote.

General answer is:

alter query that gets comments to include paragraph number (hook_query_alter)
alter their rendering, so paragraph number is sent to .tpl files (hook_comment_view_alter)
change tpl file of your theme to display that number.


Add value to field using hook_webform_submission_presave() I am at my wits end trying to use the hook_webform_submission_presave function on a webform that I have created for a Drupal 7 site. Ideally I would like to capture a list of nodes that a user has flagged and transfer that data into a field before the user submits their form. But the function is just not adding the data.

First I get the flags:

$flags = flag_get_user_flags($node->type);

Then I want to transfer that variable into a field with a component ID of 32.

// Update some component's value before it is saved.
  $component_id = 32;
  $submission->data[$component_id]['value'][0] = $flags;

Here is the full function:

function get_flags_webform_submission_presave($node, &$submission) {
$nodes_list = array();
$title = '';
  // Get the flags.
  $flags = flag_get_user_flags($node->type);

  // Get the nodes.
  if (!empty($flags)) {
foreach ($flags as $flag) {
    $nid = $flad->entity_id;
    // Get node data. Delete to not get node titles.
    $node = node_load($nid);
    $title = $node->title;
    // Combine data.
    $nodes_list[] .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 32;
  $submission->data[$component_id]['value'][0] = $nodes_list;
}

What am I doing wrong? I'd love some help!

flag_get_user_flags will return an array. so you have to handle it as an array not like a value.


How to get the File Description programmatically? In Drupal 8, like Drupal 7, you can enable the file description in the file field setting.

But once my file entity is loaded in my preprocess, I don't know how can I get the description value entered for my file.
I've tried (without success) :

$myfileentity->toArray();
$myfileentity->get('description');
$myfileentity->get('description_field');
$myfileentity->label();

Any Idea ?

Thanks.

The description is stored on the file field, not on the file entity. To access it, use $node->yourfilefield->description.


Output Path to File Content in Views In a view I would like to output just the path to the piece of content where the file is referenced like the below:

http://www.example.org/file/1

I DO NOT want to link directly to the file itself.

I thought it would be a simple task but most of the fields are adding html (like View).

I am filtering by a file type of "Video".  I have tried adding the below with no success:

File: Download Link
File: Edit link
File: Link
File: Path

And have also tried using a relationship:

Content: Link
Content: Path

I have been able to get it working by rewriting the File: File ID field and hard-coding the url with the [fid] as a token, but that's a horrible solution.

Please try to locate another relationship named "File Usage: File"
After that you should be able to add a field type "File: Path". In the field options you can decide how the output is formatted: as server-path (public://yourpath) or as download path.


Add product fields to cart form through line items So I have a Product field called "Quantity Per Box". It's a field that says how many items (in this case, screws, nuts, and bolts) come in each box. I want to display this number in the view when the customer goes to cart.

I have the field as part of the product already. What I have done so far is added the existing field to line items, and checked the box to add that field to the cart. Then I edited the view to add that item. The label shows up "Quantity Per Box" but there is no value in the field from the product. I've tried this several different ways with no success. Can someone help me out here, what am I missing?

To be absolutely clear, you want the "Quantity Per Box" field present on product entities to display on the cart view?  For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view.  That should give you access to the product fields, with no need to copy a field from product entities to line item entities.

Since the cart is a Commerce Order view:
Relationships needed to reach products can be visualized as:
commerce_order->commerce_line_items->commerce_product


Remove header and footer of the page when export node to pdf using print module When I use the print module for export node to the pdf file are facing a problem that I could not handle that it automatically generates header and footer for my page pdf. I want to remove the header and footer of the page. Can someone guide me how to deal with it. Thank you very much.

Go to

Home » Administration » Configuration » User interface » Printer, email and PDF versions

then in SETTINGS page, check option none in FOOTER OPTIONS tab.


How do I set up user's "Favorite Tags" and "Ignored Tags" tag subscriptions? This website shows user-specific "Favorite Tags" and "Ignored Tags" listing tags the user subscribed to. Based on these subscription lists, content is being sorted in "views".

How do I let the users pick favorite tags?
How do I create a "favorite tags" block like it is done on this site?
How do I up Views to prioritize content assigned to subscribed tags?
Is it possible to use a Flags-like module to assign flags to taxonomy terms?

I would recommend using the Flag module to allow your users to pick "favorite tags".  It is still in beta for D7 however.

Also, in the future you could look at the Flag Terms module to allow your users to flag taxonomy terms.  That module is still in dev.

You can use Views to create lists of "favorite tags", etc.


Drush Remote Aliases Line Wrapping Different Than Local Line Wrapping We are using Drush version 5.9 and Drupal 7.27 and 7.26.

We have a variety of drush aliases, some marked specifically as REMOTE and one for the LOCAL instance.

Example for REMOTE:
$aliases['ALIASNAME'] = array(
   'root' => 'PATH',
   'uri' => 'URI',
   'remote-site' => TRUE,
   'remote-host' => 'REMOTEHOSTDNS',
   'remote-user' => 'DRUSHUSER',
 );

Example for LOCAL:
$aliases['ALIASNAME'] = array(
   'root' => 'PATH',
   'uri' => 'URI',
 );

When we run a drush command for the LOCAL instance, the line wrapping in the output looks as expected.  For REMOTE instances, the line wrapping is different and difficult to interpret.

Example of REMOTE Drush line wrapping:

Other        Fusion Starter Lite                Theme   Disabled       7.x-2.0
          (fusion_starter_lite)                                     -beta2

Example of LOCAL Drush line wrapping:

Other                                  Fusion Starter Lite (fusion_starter_lite)                           Theme   Disabled       7.x-2.0-beta2

What can we do to get the REMOTE line wrapping to match the LOCAL line wrapping style?

Thank you for your help.

I'm surprised no one has brought this up before.  Perhaps it has come up, but I do not remember an incident about it.  In any event, Drush does not pass the COLUMNS information to remote servers, so the remote side defaults to wrapping at 80 columns.

I added a commit to the master branch (Drush 7), 17c18fb331, to do this.  I'll also open an issue to discuss backporting to Drush 6.

UPDATE:

I also committed this fix to the Drush 6.x branch.  https://github.com/drush-ops/drush/issues/662