What instantiates a CacheBackendInterface?

You're using an old version of libraries module it seems. There was a core change that changed how the cache backends are defined.

Update it, clear caches and it should work.


How do I get the Subscriber UID in Simplenews to Create Personalized Newsletters?

This isn't possible in Drupal 6.

Simplenews 7.x-1.x now provides a simplenews_subscriber variable for the body template. It also automatically switches the global user to the one that is receiving the mail while it is generated.


Nodes not get indexed after running manual cron

To turn off delayed indexing, navigate to the /admin/config/search/search-api page then click on the 'edit' button for the index.

On that page, at the very bottom, just above the Save button, there is a collapsed panel titled 'INDEX OPTIONS'. Open the panel and it should look like this.

This is where you can control whether indexing is immediate and the cron batch size.


How do I add the ability to change font size in CKEditor?

Kevin's comment was spot on and it was in fact the Basic HTML configuration that was preventing the button from rendering. Specifically, the filter "Limit allowed HTML tags and correct faulty HTML" was the issue. The buttons rendered correctly in Full HTML mode so that was the hint.

In the filter configuration at the bottom of the /admin/config/content/formats/manage/basic_html page, I modified the allowed tags. By default the filter allows plain span tags without any attributes. However, this plugin uses span tags with inline style attributes. As a result, I had to change  to  in Allow Tags list.

I can now see the font and size buttons in the editor, and using the tool injects HTML like the following:

The Quick red fox jumps over the lazy brown dog


How can I create a simple non-CRUD resource action with Drupal 7 / Services 3?

Actions outside the normal CRUD roster must be wrapped in an array under the key 'actions'

function module_services_resources() {
  return array(
    'actions' => array(
      'username' => array(
...


How can i delete user profile picture in drupal 7?

use code below in hook_user_delete($account)

// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);


How to not hide a taxonomy term if it has no content

You can add output to be displayed even if the taxonomy term has no content related to it by adding a field under the settings "No results behavior".

Try adding "Global: Unfiltered text" and add the text that should display when there is no content assigned to the term.


Fluch cache on all sites in multisite platform

An easy way is via the views bulk operations.
When you select some or all sites you can expand the operations menu at the top, where you should find 'Site: Flush_cache'. It's part of the hosting_tasks_extra module (which is included by default now)

Note that you currently do have to enable the operation in the sites view. See https://www.drupal.org/node/2715945


How to print a table create with views, using a submit button below the view?

If I am interpreting this correctly, you want to click on a link and then have a page painted on your screen with JUST the view in it, no other blocks of information, just a clean display of the view information so the user can right click (or what have you) and then print this page and have it printed out without all that extra "stuff" on the page.

If that is correct, what you would need to do is:

Have a link created in your table that links to another page, let's call it print/thisview.
In the Views UI, create a duplicate page display that calls the view in question with print/thisview as the path.
In your theme, create a page-print-thisview.tpl.php template that contains only the content region, none of the other regions.
Clear all caches.

Now, if all is correct in the world, meaning I have oversimplified this a great deal, when you click on that link, it will paint the screen in a clean format that is nice for printing.


In hook_user_presave how to check if account is being activated and account is new?

To check if the user is new:

$account->isNew()

To check if the user is active:

$account->isActive()

See User API isNew or User API isActive for more information.


Clone a SelectQuery instance : what am I doing wrong?

As you have seen in bug report #1671848 the special getters of these special drupal objects breaks the clone behavior. The problem is that by reference getter are used and this imply hazardous behaviors in PHP internals of returned values.

I think it will be quite very long until this bug get fixed. So one of the solution is to avoid such writings:

$fields = &$q0->getFields();
$fields = array();

This is not the way to empty something in an object. here the & is the fault. after such a write the internal array stored in the object is broken and the object record it as a reference, you've been breaking object encapsulation and bad things happen (sse the bug report). Use a setter, And if there is not setter to do that clone the queries before havinf any field added to the query (so it's empty).


How to avoid duplicate entries when changing the text inside t() function in Drupal 7

I think there is not a better way, because all those strings are stored/returned in the database as the code is being read out.

I think there is no way to know if they are actually exists in code to be used or not.


The $items['redashboard/project/%/edit'] declaration needs to be made inside of re_dashboard_menu(), and there needs to be a re_dashboard_edit_project_form_submit() function to pipe $form_state['values'] into db_update().

Other than that, it looks like it will get the job done.  You could use db_query() instead of db_select(), since it's faster, and the query conditions are static.  Also, make sure you have a way to handle db_select() not returning any results, since fetch() will return FALSE in that case.


Pass multiple ids as Views Arguments in the Rule action Save PDF as file on server

If I would like to save those files using vbo then I would try to create drupal action in your own module. And in this case you wouldn't need rules. Or you could revoke rules event if you would want to with rules_invoke_event function;

function mymodule_action_info() {
  return array(
    'dosomethinggoodfunction' => array(
      'type' => 'node',
      'label' => t('Do something'),
      'configurable' => FALSE,
      'triggers' => array('node_save'),
    ),
  );
}
function dosomethinggoodfunction($node) {
  // function to do some good stuff.
}


Subtheme install settings in config but not showing

Although the documentation shows to place the settings under the "settings" key, I was then told to put it at the top level without the settings key. That is working.


Why am i getting a blank UI in filedepot module in drupal 7?

I found this solution at "https://drupal.org/node/1268336"

Renaming it solved the issue for me.

"rename /sites/all/libraries/jquery.blockUI.js to /sites/all/libraries/jquery.blockui.js. It is case-sensitive, and the JS file is not being loaded after following the instructions provided."


Wave tool used to evaluate web content for accessibility issues giving Broken ARIA reference errors

The attribute is only added if the element has a description. This is the code from the FormBuilder that does it:

// Add the aria-describedby attribute to associate the form control with its
// description.
if (!empty($element['#description'])) {
  $element['#attributes']['aria-describedby'] = $element['#id'] . '--description';
}

The idea being that when the input is rendered in form-element.html.twig, the description is rendered alongside it with a matching ID. For example this is how the core stable theme handles it:

{% if description_display in ['after', 'invisible'] and description.content %}
  <div{{ description.attributes.addClass(description_classes) }}>
    {{ description.content }}
  </div>
{% endif %}

So it seems likely there aren't that many possible sources for the problem. These are the only ones I could come up with:

You're using a core theme, or a derivative of one which still renders the description in form-element.html.twig, and something in the system is setting the description display to a value other than 'after' and 'invisible', causing it not to be rendered.
You're using a non-core theme, which overrides form-element.html.twig, and doesn't render the description.
Something in the system is changing either the value in the input's aria-describedby attribute, or the ID of the description element in the element template, causing them not to match.
Some combination of the above.

Hopefully that's enough to go on.


How should I deal with a vocabulary with many terms?

Since i can't answer it in comment. i'll try to answer here. I've solve similar problem, my solution is using redis caching and entity cache module

Since then, my site going well with 256MB RAM configuration in php.ini.


Populate second node reference field based on what first node reference field is selected

You can use custom coding to achieve this, here the idea

Add a script to call a ajax call back on change your first node reference select list.
Define the menu callback in your custom module.
On change of first select list, get the selected node id and pass to above defined function
Write the query to get depended node ids
Output it as

$options .= "nid." ".$selected." >".$data->node_title."";
     echo $options;
In your jquery ajax success part, add it eg:
success: function(data) {
f(data){$('#your-second-noderefernced-field').html(data);}

Hope this idea help you to proceed on


How can I remove decimals when I award user points via commerce-order-total:amount

Have a look at the Drupal Commerce issue about "Revise the way we handle price amount values". Especially comment nr 37 in it, which states:

  The price field is and will continue to store price amounts as integers ...

So rounding an amount of 1500 dollarcents is ... still 1500, right? And that is the amount of user points you're granting. And because of that, your rule works as implemented: you're using that value of 1500 as the amount of userpoints to be granted.

Obviously, all you need to do next is to expand your rule to devide the price by 100 first (before rounding it). I assume you know how to do that, if not use this link ... bonus hint: have a look at the example rule included in the answer to "How to add up all items of a field collection field using Rules?", especially the "Calculate a value" Rules Action.


Use one textfield for searching in two or more fields in Views

Using Vies or/and funcionality I set (using more fields not related to this question):

filed1 AND
 field2 AND
 ...
 fieldN
AND
 title OR
 body

title is not expsed, but body is.

My solution is to implement hook_views_pre_build(&$view).

if ($view->name == 'my-view') {
  // Look for the search string, is it present?
  if (!empty($_GET['search'])) {
    $view->filter['title']->value = check_plain($_GET['search']);
  }
}

I've renamed body key in GET to be search.

This way search is performed as I want. The drawback is I can't position search element anywhere becasue it must be in its own group, but I can live with it.


Drupal 7, creation of new node, how redirect to the edit page of the new node

In a custom module, use this code, and don't forget to replace MYMODULE_ with your module machine name :

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_content_type_node_form': // Replace my_content_type with yours
      $form['#submit'] = array_merge(array('MYMODULE_my_content_type_node_form_submit'), $form['#submit']);
    break;
}

function MYMODULE_my_content_type_node_form_submit(&$form, &$form_state) {
  $initial_values = $form_state['build_info']['args'][0];
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = array('destination' => 'node/' . $initial_values->nid . '/edit');

  unset($_GET['destination']);
  $_GET['destination'] = 'node/' . $initial_values->nid . '/edit';
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}


How to print Json data from Facebook in a block?

Normally I would look for a contributed module that might already be written, but at this time none of Drupal for FaceBook, FaceBook Like Button, Views FaceBook Like, FaceBook Social, or Social Media Links have Drupal 8 releases. It would be a good idea to look at contributing to the above projects.

In order to accomplish this, you will need to create a Block plugin in a custom module. There are a few of options. Code examples are sort of pseudo-codeish.

Contribute and port one of the modules above to Drupal 8.
In PHP, you may use Guzzle in the build method in the block plugin. The advantage here is that the block will be cached and save performance on subsequent loads.

```

$client = \Drupal::service('http_client');
$options = [
  'query' => [
    'query' => "select like_count from link_state where url = 'http://drupal.stackexchange.com/'",
    'format' => 'json'
];
$response = $client->request('https://api.facebook.com/method/fql.query', $options);
// the "serializer" service could also be used if deserializing into a known Drupal typed data type.
$data = json_decode($response->getBody());

```

You may also add a JavaScript asset to the render array of the block, and then code some JavaScript that makes a request. The advantage here is that this is that this is done after Drupal render, but it will make an additional http request on each page load.

```

(function($, Drupal) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $.ajax('https://api.facebook.com/method/fql.query?query=select%20like_count%20from%20link_stat%20where%20url=%27http://drupal.stackexchange.com/%27&format=json', {
        dataType: 'json'
      }).done(function(data) {

      });
    }
  };
})(jQuery, Drupal);

```


How to create a child page that has the same content type as parent page?

I found a module that does the job, which is Book made simple. This module add the setting on content type and have the option for "SELECT CONTENT-TYPES ALLOWED AS CHILD.", "SELECT CONTENT-TYPES ALLOWED AS PARENT" and "Other Settings". Then a dropdown listbox will be added in the books link like the one on screenshot. I hope Drupal 8 has a similar feature like this.

PS: One of the issue is "Printer" module also print "Add child page" on each page.


How to get hal_json format as Drupal output?

Send a GET to http://theurl.com/node/1?_format=hal+json

This should work! Make sure you enabled the Resources to read out nodes.


How to add a role to specific product type customer?

You're using $user before setting it. You have a CustomId it looks like, but have not created an instance of User with that Id.

Perhaps something like this:

public function onOrderPlace(WorkflowTransitionEvent $event) {
  $userId = $event->getEntity()->getCustomerId();
  $user = \Drupal\user\Entity\User::load($userId);
  $user->addRole('darshan');
  \Drupal::logger('mycustom_module_name')->notice('Role "darshan" added to user ' . $user->getDisplayName());
}


Integrate Radioactivity with Apache Solr (sort by popularity)

You should be able to do this without modifying schema.xml. At a minimum, you'll need to implement hook_apachesolr_update_index(), and you may also need to implement hook_apachesolr_modify_query() to add the Radioactivity data to each query.

Good examples for this can be found in the apachesolr_search.module file itself (and the apachesolr_date module that comes bundled with apachesolr), and also in the additional contrib modules apachesolr OG and apachesolr attachments.

The apachesolr_date module in particular has some code related to adding an available sort option.


How to create multiple variants of a page in page manager

Create a page with the url /brands and add your variants. Use the "String: URL Path" selection rule to manage each one.

How to:

Under selection rules for the main (panel) page add the "String: URL Path" rule with a single line "/brands"

Do the same with the variants but:
Under the first variant use /brands/brand1
Under the second variant use /brands/brand2
...
...


How to generate URL alias without %20 in URL?

It is proved that I wrote wrongly in the beginning, thanks @Beebee.

  I have read through the code of pathauto module. The module
  implements the token replacement after replacing the space with
  defined separator. So there is no clue by configuration. I would
  consider it is a design fault of the module.

pathauto module clean the url only when the token name does not match with the pattern /(path|alias|url|url-brief)\]$/. You can find it in the function pathauto_clean_token_values(). Obviously, the module author would like to prevent the url alias to be clean twice. As your field name is custom_url, so it is escaped from the checking.

You can fix this by changing your field name or writing your own module as I stated before.

If you know how to create custom module. I would recommend you to implement hook_pathauto_alias_alter for the purpose.

/**
 * Implements hook_pathauto_alias_alter().
 */
function mymodule_pathauto_alias_alter(&$alias, array &$context) {
  $separator = variable_get('pathauto_separator', '-');
  $alias = preg_replace('/\s+/', $separator, $alias);
}


Why/How I could remove index.php in the URL

I suggest you look at the .htaccess file supplied with Drupal, beside index.php. In the standard one, it has rules for both redirecting http: to https: (line ~104) and for rewriting URIs to index.php (line ~136)

Some servers are configured with these rules in the main config file because relying on .htaccess results in slower response from Apache (it reads the main files on startup but .htaccess per request).

So:
- Remove any additional rules you have added (i.e. revert to "out of the box") and check for expected behaviour;
- Uncomment the protossl conditions in .htaccess and check again;
- Optionally, move some of these into the .conf file for faster response.


How to display fields of an entity reference field?

You can choose rendered entity instead of label.

After that click the options button (cog wheel) and choose the view mode of the rendered entity.

You can go the referenced content type's manage display and modify the chosen view mode to display the fields that you want

NOTE
you can enable more display modes from manage display > Default > custom display settings

and can also create your own view mode by pressing manage view modes on the bottom of the same screen


Basefield 'string' shown as select list widget in entity form

Create a list_string base field and use as widget OptionsSelectWidget.

$fields['entity_definition'] = BaseFieldDefinition::create('list_string')
  ->setLabel(t('Entity Definition'))
  ->setSettings([
    'allowed_values' => [
      'value1' => 'Value 1',
      'value2' => 'Value 2',
    ],
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
  ])

To update the options dynamically add a callback to the base field settings allowed_values_function, see How do I programmatically update the allowed values of a list field?


How can you hide "Your search yielded no results." when no keywords have been entered on the search page?

First find out how this string got there in the first place. Simply search your codebase for the exact string Your search yielded no results.. In a Vanilla Drupal you'll find only 6 occurrences of this string. 5 of them in tests, and only one in a controller, the SearchController.

Looking into the SearchController you'll see that this string is part of a render array. Keyed as '#empty' and themed with '#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],. This means you can target that pretty easily with a preprocess function. Let's go for item_list__search_results since you don't know of any plugin yet.

In your theme or module implement hook_preprocess_HOOK. Replace hook with your theme or module machine name and HOOK with the '#theme' key from earlier.

Now find out if any search query has been entered at all via if \Drupal::request()->query->has('keys'), and for safety let's also check if there's an 'empty' key in the $variables and then unset it. If you want you can tighten the condition now also on the plugin you'll find in $variables['context']['plugin'].

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE/MYTHEME_preprocess_item_list__search_results(&$variables) {
  // ksm($variables);
  if (!\Drupal::request()->query->has('keys') && isset($variables['empty'])) {
    unset($variables['empty']);
  }
}

Hint: Use the Devel sub-module Kint and its debugging function ksm() to have you any variable pretty-printed in the messages block of your site for easy debugging.


Datetime values in storage are UTC, if you are storing datetime values by your own, you have to pay attention on this and display datetimes to users considering your timezone ('Pacific/Noumea' probably declared in your php.ini or user's timezone present in user profile).

Storing 2018-05-02T08:23:25 as your current datetime in caledonia in database is a nonsense considering timezone, because the format DateTimeItemInterface::DATETIME_STORAGE_FORMAT do not include timezone.

$date = strtotime($node->field_paiement_date->value);
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', drupal_get_user_timezone());
\Drupal::service('date.formatter')
  ->format($date, 'custom', 'Y-m-d H:i:s', 'Pacific/Noumea');


Why might form values not be passed from input to values?

Apparently, around line 1162 of FormBuilder.php, Drupal checks to see if there is a #name element to the field element you're using.  If there's not, it uses the parent's name, which seems to be the previous form element's name.

The clone function wasn't setting unique #name's.  I could have sworn it worked before, but maybe not.


how can control of number word show in article in frontpage

Select your body field within your view.

Click the "Rewrite results" fieldset and check "Trim this field to a maximum length".

Set your maximum length and then check "Trim only on a word boundary".

This will prevent your body text from being cut off.


Use Code per Node module, that is the easiest way to add custom CSS or JavaScript on node page, content type or block...

Look at THIS for other ways to add custom css...


Can the same entity type (bundle) have different fields in different instances?

field_create_instance already adds a field instance to a bundle. You can't add fields to an entity type or an entity itself.

I'm not quite sure if I understood you right:

Guess 1:
You want for example two nodes of type person where one has a field phone number and the other one not, which is not possible. Your node type has to define all possible field types, but they may be optional, so if the external system doesn't provide data for it, simply leave it empty.

Guess 2:
You want to adjust a whole entity type (this means all existing entities) based on external systems, user input or whatever. Thats possible with the Field CRUD API.


You should ideally be using the Field Attach API to avoid these problems.

Or for a quick solution have a look at field_attach_update where at the end of the function, it clears the field cache:

$entity_info = entity_get_info($entity_type);
if ($entity_info['field cache']) {
  cache_clear_all("field:$entity_type:$id", 'cache_field');
}


Attach #ajax to submit button created in hook_form_alter with #markup

You cannot, since the #ajax attribute is not used for the markup item. You can use an image_button form element.

If the image_button form element doesn't render as you want and it is not possible to alter it the way you want, you need to implement a new form element with hook_element_info(), using the definition of the image_button form element as guide.

  $types['image_button'] = array(
    '#input' => TRUE,
    '#button_type' => 'submit',
    '#executes_submit_callback' => TRUE,
    '#limit_validation_errors' => FALSE,
    '#process' => array('ajax_process_form'),
    '#return_value' => TRUE,
    '#has_garbage_value' => TRUE,
    '#src' => NULL,
    '#theme_wrappers' => array('image_button'),
  );

The theme function that renders that form element is theme_image_button(). Changing the value of #theme_wrappers, you can alter the way your form element is rendered.
Keep in mind that theme wrappers, as any other theme functions, need to be declared with hook_theme().


A views & CSS only solution for a previous post & next post buttons in a blog-node?

This you can do easily with the Core Book module. As you can see on the any Drupal.org page for example, Drupal.org page.

Using Book module

You can create a Book which is like index and add the nodes in-order you want, and it will show Next and Prev as shown in above page as title of that node.

D8 site scree shot:

Configuration page

Example Page:


Selected/Restricted Autosubmit with Better Exposed Filters in Drupal

The documentation in CTools suggests adding the class ctools-auto-submit-exclude in the element #attributes key for the form element you don't want to processed:

function MODULE_search_submission_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form") {
    if (isset($form['keys'])) {
      $form['keys']['#attributes']['class'][] = 'ctools-auto-submit-exclude';
    }
  }
}


Why does pagination create duplicates in Google's results?

This is definitely bad for SEO.

You need to set related links on the each page of the view so that google doesn't crawl all of the variations via parameters. Example:

<link rel="next" href="http://example.com/view?page=2">

Apparently the metatag module will help with this, or you can find some discussion about how to do it on this issue.


How to use linkit package after uplaoding file with filedepot package?

this is an older thread, but maybe Linkit Upload is a nice solution for this problem.
With that module enabled you can upload files directly from the Linkit popup.


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

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

My suggestions:

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

As for your problem, either:

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

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


Using hook_node_presave to auto-select a reference field from a field list selection

As Darvanen said above, the function name is wrong, replace HOOK by the module's name in HOOK_node_presave().
About the || operators, you could use in_array instead or a single associative array:

function grouphideandselect_node_presave($node) {
    $field_type = $form['field_type']['und']['#options'];
    dpm($field_type);

    $field_type_to_icon = array(
      1 => 1,
      2 => 1,
      3 => 1,
      4 => 2,
      5 => 2,
      7 => 2,
      8 => 6,
      9 => 6,
      98 => 6,
    );

    if (isset($field_type_to_icon[$field_type])) {
      $form['field_icon']['und']['#options'][] = $field_type_to_icon[$field_type];
    }
}

EDIT: from another question of yours I see that you already tried renaming the function to grouphideandselect_node_presave. You need to make sure that:
- the function's name is right
- the module is enabled
- you cleared Drupal's cache afterwards


How to unset field in views conditionally

Drill down in the field_field_company_logo field to its ['rendered']['#access'] property and set it's value to FALSE.


You can achieve that using the OpenID Selector module

This module integrates Javascript OpenID Selector with Drupal's OpenID client.
This module substitutes Drupal's default OpenID form with Javascript OpenID Selector widget, so users do not even need to know what OpenID URL is.


I used hook_node_access() and had the same issue: It wasn't firing and driving me nuts.

What worked for me was NOT to be logged in as an admin. I went in as a different role and all worked as expected.


To change drupal http-header information check out drupal_set_header() (D6) or
drupal_add_http_header() (D7).

Looking at the documentation for _drupal_bootstrap_page_cache, it seems the header shows 'HIT' if the page is displayed from cache, and 'MISS' in the case it is not.

Check out Set X-Drupal-Cache header during page_cache_fastpath and Implement better cache headers for reverse proxies for more information about the X-Drupal-Cache header. It seems to be a Drupal 7 or Pressflow only thing.


Display Suite custom function field not firing

Here is the code that worked for me... My Module name is drup_custom

function drup_custom_ds_fields_info($entity_type)
{
    if ($entity_type != 'node') {
        return;
    }

    $fields = array();

    $fields['test_title'] = array(
        'title' => t('Split product title'),
        'field_type' => DS_FIELD_TYPE_FUNCTION,
        'function' => 'drup_custom_ds_field_splittitle'
    );

    return array('node' => $fields);

}

function drup_custom_ds_field_splittitle($field)
{
  return 'My Content';
}

Steps to follow to see results..

Cleared Caches
Enabled Layout in Content Type Settings

Now, you can see your field in disabled list

Assign the field to which ever region you would like, Save Settings

I can see the field content in Node View Page


You try code:

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if($type == 'comment' && !empty($data['comment'])) {

    foreach($tokens as $name => $original) {
      switch($name) {
        case 'flag-helpful-count':
          //$comment = \Drupal\comment\Entity\Comment::load($data['comment']->get('cid')->value);
          //$count_flag = \Drupal::service('flag.count')->getEntityFlagCounts($comment);
          $replacements[$original] = 10;
          break;
      }
    }
  }
  return $replacements;
}

function mymodule_preprocess_comment(&$variables) {
  $token_service = \Drupal::token();
  $token_count_flag = $token_service->replace('[comment:flag-helpful-count]', array('comment' =>
    $variables['elements']['#entity']));

}


Each comment runs through comment.tpl.php template, where the php variables are replaced with actual values and from where you get the actual html

Before going to tpl files, execution passes through template_preproces functions, preprocess function allows you to add new variables or override existing variables which you use on tpl files.

Now in your case it is comment.tpl.php, if you see the file in bartik theme the code

    <?php print $picture; ?>

        <?php print $author; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

is responsible to show comment author information. In order to override the html you can simply copy the comment.tpl.php from parent theme to your base theme and start overriding the html. If you want to introduce new variable to the template, then use template_preprocess_comment(), for example on your theme template.php

function your_theme_preprocess_comment(&$variables) {
  // To Debug what is inside variables already
  dpm($variables);
  // To override exisiting variable
  $variables['author'] = 'my test author';
  // To add any new variable to comment.tpl.php
  $variables['author_comment_count'] = _some_function_fetch_comments_count($user_id);
  $variables['author_nodes_count'] = _some_function_fetch_node_count($user_id);
  $variables['author_user_points'] = _some_function_fetch_user_points($user_id);
}

Now you will have three more variables to use on comment.tpl.php as
$author_comment_count, $author_node_count, $author_user_points

Use them on template, example

    <?php print $picture; ?>

        <?php print $author; ?>

        <?php print $created; ?>

        <?php print $permalink; ?>

        <?php print $author_comment_count; ?>

        <?php print $author_node_count; ?>

        <?php print $author_user_points; ?>


Reset all votes on a content type every week

There's many ways to accomplish this. The voting data for the Voting API module is stored in the votingapi_vote & votingapi_cache tables. Essentially, you need a way to target the vote data you wish to eliminate in these tables (e.g. via a DB query) and then build some process on which to regularly execute it (e.g. a cron run).

A crude example would be a custom module that evokes hook_cron() to check the last query execution and fire it if it hits its time threshold:

/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Clear the vote every week.
  $vote_clear_timestamp = variable_get('MYMODULE_vote_clear_timestamp', 0);
  if ($vote_clear_timestamp <= strtotime('-1 week')) {

    // A more targeted process would use db_delete() to target criteria
    db_query("TRUNCATE {votingapi_vote}");
    db_query("TRUNCATE {votingapi_cache}");
    variable_set('MYMODULE_vote_clear_timestamp', time());
  }
}


urol executed via bash throws exception error if role has a space in it

Use

drush @comply-all urol "teaching\ assistant" sdf --y

Might be helpful to you.


More link not displaying in content pane

I had the same problem.

I solved it by creating a page view as well as an original block view.

Hope this helps


Add payment to a commerce order using Rules

I ended up doing some sql statements that seem to have done the trick. One challenge was raising the event Paid in full via sql, which I ended up doing via executing a component manually. Not the most elegant solution but it did get the job done.


Since its an alias,

For Drupal 8

In your THEME_NAME.theme file:

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Checks for node pages.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $current_path = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    $alias = ltrim('/', $alias);
    $clean_alias = str_replace('/', '__', $alias);
    $suggestions[] = 'page__'.$clean_alias;
  }
}

You would like to check out clive answer from here for drupal 7

Template file naming with alias


field_get_items / value when creating new content

One option would be to take advantage of states (see states and/or forms reference).

Here is an example... It's by no means perfect but hopefully it will give you an idea of how states work:

$options_1 = array('Option A', 'Option B', 'Option C');
$options_2 = array('Option D', 'Option E', 'Option F');
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_1,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible1" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible1'),
    ),
  ),
);
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_2,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible2" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible2'),
    ),
  ),
);

Hope that helps... :)


How to make DrupalChat more stable, to have it recognise online users?

In the module config page admin/config/drupalchat/configuration see Chat List Latency says

  The delay, in seconds, after which the user will be shown offline in
  the chat list(i.e. removed from the chat list) from the time he/she
  goes offline. Increase this value if you find the chat list is
  unstable and keeps on changing a lot (for example - when a user
  navigates from one page to another he/she goes offline and then comes
  back online again). Decrease it if you find that the users are shown
  in the chat list for too long after they have left your website.


How do I choose the "date_popup" widget for custom date field from code?

If you install the version 2.x of the Date module, you will be able to use more form fields, including a "date_popup" field, which shows a pop-up to select the date.
The module has an option that allows the user to decide if the pop-up should be shown; if you want to override that option, you should use variable_set('date_popup_timepicker', 'default'). That is the default option used by the module, but if the user selects "none," then the pop-up will not appear.

About setting a custom format with the "date_popup" field, the form field uses the "#date_format" attribute that, in the development snapshot 7.x-2.x, is said to accept most of the formats. The default value for that attribute is the one returned by variable_get('date_format_short', 'm/d/Y - H:i').
The complete list of the attributes used by the form field, reported in the comment for date_popup_element_info(), is the following one:

"#date_timezone"
The local timezone to be used to create this date.
"#date_format"
Unlike earlier versions of this popup, most formats will work.
"#date_increment"
Increment minutes and seconds by this amount, default is 1.
"#date_year_range"
The number of years to go back and forward in a year selector, default is -3:+3 (3 back and 3 forward).

Drupal core modules have only the "date" form field, and it doesn't use any "#widget" attribute. Third-party modules could define new attributes, though; as far as I know, no module defines "#widget" as attribute for form fields.


I had the impression that in Drupal 8 all entity tokens are provided
  automatically since it uses the new field structure but I don't see
  anything available for my entity.

That impression is wrong. Drupal (core) doesn't provide any generic tokens for entities, all that are in core are hardcoded.

Now, token.module, just like in D7, provides some tokens for configurable fields. Simply because the existing functionality was ported to D8. It is possible to extend that to all fields and it shouldn't even be that hard. In fact, there's an explicit check that ignores anythig that's not a configurable field, so we just have to remove that and see what happens.


How to add sub title name in the header using pixture reloaded sub theme of drupal 7.x?

The "sub title name" you are referring to is called the "Site Slogan" in Drupal.  In Drupal 7, you can add or edit your site slogan on the Site Information page (/admin/config/system/site-information).

Then, on the Pixture Reloaded settings page, just make sure that the "Site Slogan" checkbox under "Toggle Display" is checked.  You don't need any custom code.


Get the values of a checkbox field in node when evaluating in block condition plugin

Original Answer

The proper way to access field values is $entity->get('my_field')->getValue() in your case this will return an array like:

Array(
  0 => Array(
    'value' => 'value1'
  ),
  1 => Array(
    'value' => 'value2'
  ),
  2 => Array(
    'value' => 'value3'
  ),
  // And so on as many values your field has.
)

Also you can check if the field is empty by calling $entity->get('my_field')->isEmpty(). Calling only your field like $entity->get('my_field') will NOT return the field value but the field instance. Calling for an unexisting field will throw a runtime exception.

UPDATE

To check if the value exists you can either iterate over the array or do something like this

$arr = [
  0 => [
    'value' => 'value1',
  ],
  1 => [
    'value' => 'value2',
  ],
  2 => [
    'value' => 'value3',
  ],
];

$arr = array_map(function ($v) {
  return $v['value'];
}, $arr);

assert(in_array('value2', $arr, TRUE), 'Assert that contains value2');
assert(in_array('other', $arr, TRUE), 'Assert that contains other. This will fail');

You can try it here.


Problem with home page misaligned on website

Found it.  You have a custom content pane when you have an image that is inside of a p tag.  That p tag has a margin of 12px on the top and bottom and the image has 10px border on all sides.  Remove that and you should be good to go.

I got this from http://johannabolhoven.co.uk/personal_shopping.

Let me know if there were other issues that you had, but the home page being higher than the other pages was the only thing I could find.


How can I achieve basic authentication in Drupal?

Drupal 7 will not set a session cookie unless it has to, for performance reasons. If there is no form under http://127.0.0.1/drupal/node, and no module requires sessions, you will not get any session, simple as that.


As noted elsewhere, $delta allows one module to return many blocks. It may also be easier to understand if you keep in mind that the $delta need not be numeric. It's simply an identifier.

You use the $delta first when responding to the 'list' $op. Each key in the $block array you return will be a $delta that can be used to configure or render that specific block.

switch ($op) {
    case 'list':
      $block['sidebar-links']['info'] = t('Sidebar Links');
      $block['footer-links']['info'] = t('Footer Links');
      return $block;

What this is telling the Drupal system is that the module in question has two blocks, one of which is identified by "sidebar-links", the other by "footer-links".

This will place two blocks on the admin/build/block config page. Should you enable both blocks, they will then be rendered by calls to the 'view' $op with the identifying key as the $delta:

    case 'view':
      switch ($delta) {
        case 'sidebar-links':
          $block['subject'] = t('Sidebar Links');
          $block['content'] = "super weak";
          break;
        case 'footer-links':
          $block['subject'] = t('Footer Links');
          $block['content'] = "super weak";
          break;
      }
      return $block;
  }

As an added bonus, using semantic keys for your blocks will result in easier to read CSS id's. :)


Drush make command error when unzipping superfish module / library

Unzipping files needs, simply, the unzip program. Check that you have unzip-package installed on your server.


How can I get an absolute path to a theme?

The base_path() function would return the base bath of the Drupal installation

  Returns the base URL path of the Drupal installation. At the very
  least, this will always default to /.

and path_to_theme() will return the path to the current theme.

  Return the path to the current themed element.

  It can point to the active theme or the module handling a themed
  implementation. For example, when invoked within the scope of a
  theming call it will depend on where the theming function is handled.
  If implemented from a module, it will point to the module. If
  implemented from the active theme, it will point to the active theme.
  When called outside the scope of a theming call, it will always point
  to the active theme.


What Hook to Use to Execute a PHP on Every Page?

I would look into hook_init() if you don't require this to be run on cached pages, hook_boot() if you do.


You can use the https://www.drupal.org/project/devel_themer module to see what tpl file is in use. You should see the path to your subtheme. If you see the path to the base theme, then your tpl file is not found.


So u upgraded Ubuntu, anything else? Php, apache etc? First verify using VMware it is in fact Ubuntu upgrade only that is causing the issue. You say you redeployed an older version of the db.  I would be tempted to do a full deploy just to try to reproduce including Drupal code. It's an odd problem, my instinct says possibly a difference in php version could potentially cause this.


create multilingual node programmatically

It depends on is your body field translatable or not. Please, look at this explanation about translatable fields: https://drupal.stackexchange.com/a/31639/2466

$node_lang = 'ru'; // I am a Russian girl

$node = new stdClass();
$node->title = "Test ".mktime();
$node->type = 'article'; // Your type
$node->language = $node_lang;
$node->uid = 1;
$node->status = 1;

// Get proper langcode
$body_field_info = field_info_field('body');
if (field_is_translatable('node', $body_field_info)) {
  $body_language = field_valid_language($node_lang);
} else {
  $body_language = LANGUAGE_NONE;
}

// Some lorem ipsum.
// You can add custom summary:
// $node->body[$body_language][0]['summary'] = 'Summary';
$node->body[$body_language][0]['value']   = 'Lorem monotonectally iterate resource-leveling innovation before timely core competencies. Globally coordinate sustainable strategic theme areas and intermandated infomediaries. Monotonectally brand customer directed solutions and high-quality bandwidth.';

node_save($node);

There is an issue for Drupal 8 to make Field Language API more usable.


How can I add extra classes to the title of a node?

You have to enclose the class in single quotes:

{{ title_attributes.addClass('article-full__title') }}

Otherwise this is interpreted as a variable name. In Twig unknown variables don't trigger an error, they return silently NULL.


How to generate a styled image with out actually creating it?

The only way would be to use CSS and put a div with a background transparent image of the watermark overlay on top of the actual image using the z-index: attribute.

You would risk that people could inspect element or view page source and find the direct link to the image, or use a tool to strip all css and then save the image.

For total security, I'm pretty sure there is no other way than having the watermark on the image itself.


It was a lot easier than I thought. I dsm the query and did it like below. Not sure it's the perfect way to do it but it's working.

function distprox_mini_views_query_alter(&$view, &$query) {
//dsm($query);
  if ($view->name == 'search' && $view->current_display == 'page_3')
    unset($query->where[1]['conditions'][0]);
    unset($query->where[1]['conditions'][1]);
  }
}


I think the best method would be to use the cweagan patch manager package with composer and a local patch file.  This would allow the module to be updated normally with composer and the patch applied. If the code changes too much for the patch, it will fail and you can update the patch.

Just require cweagans/composer-patches and then modify your composer.json to include the patch.

Also, this is a good way to add patches from Drupal.org or github issues.  If your fix is something that should be generally available, sumbit an issue with the patch.  Then set up your composer patch section to use the URL to the patch in the issue.  For d.o. patches, this makes it easy to find the issue related to the patch since it issue number is in the url.


Cannot login to turn off maintenance mode after 7.24

7.24 has a security update and needs to add or change your .htaccess file for you public and temp files directory.

See what you have to add/change in drupal.org and here. I haven't done the 7.24 update yet so, this is as much i can help.


External class (migration class) not found

The class name in your include file is MhtAuthorDestinationMigration, but you list its class name in hook_migrate_api as MhtAuthorDestination. Uncomment the line and try:

$api = array(
  'api' => 2,
  'migrations' => array(
    'MhtAuthorDestination' => array('class_name' => 'MhtAuthorDestinationMigration'),
  ),
);

return $api;


When the access to a route doesn't depend uniquely on a single permission, you need to implement what Access checking on routes describes.

Implement a service tagged access_check
Associate it with the route

Since you are altering the route defined from another module, you need to also follow Altering existing routes and adding new routes based on dynamic ones.

example.services.yml

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

  example.access_checker:
    class: Drupal\example\Access\CustomAccessCheck
    tags:
      - { name: access_check }

RouteSubscriber.php

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', 'example.access_checker::access');
    }
  }

CustomAccessCheck.php

namespace Drupal\example\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;

/**
 * Checks access for displaying configuration translation page.
 */
class CustomAccessCheck implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return ($account->hasPermission('access content overview within business hours') && $this->checkTimeAccess()) ? AccessResult::allowed() : AccessResult::forbidden();
  }

}

The checkTimeAccess() method I didn't write should check if the user is trying to access the route during the business hours.

I cannot tell what happens with a route using the _permission requirement when it is altered to use also the _custom_access requirement. I didn't find the Drupal core code handling the access to a route, so I cannot say which requirement is used first.
I didn't also find a way to remove requirements from a route when altering it.


How to eMail a file uploaded to a Webform to a sysadmin using the Rules module?

Yes it is possible to use the Rules module for sending an eMail with an attached file. To do so, make sure you have the Mail System and Mime Mail modules installed/enabled.

The Rules Event you want to use is probably when the Webform is submitted.

Then create a rule with a Rules Action to Send an HTML email. Specify the eMail body content, and then the email's attachment(s). If you have multiple attachments, make sure to specify 1 file (only) per line. The tricky part you probably run into is to correctly specify the filename of the attached files. The correct way to do so is like so:

[node:field-file-attachments:file:path]

That is also what is suggested in Comment # 25 of support issue (not bug ...) #1431572.

In your case, make sure that this path refers to the webform that is submitted and contains the attached file. Using the "Webform Rules" module, you should be able to have Rules react on an event like "Webform submitted". And if you then add a Rules Condition like "entity has field" (with the field corresponding to your attached file), you should be able to "do something" with that filename of your attachement. E.g. trigger another Rules Component that uses as a parm ... the path of your attached file. With that, your Rules Component should then take care of sending the actual eMail, with the correct value of the filename for the file to be attached.

Use Rules debugging

This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor I suggest you also consider 2 variations of Rules debugging, which are:

Within the rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
(Temporary) enable the Devel module, so that you can (temorary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


How to programmatically select a view display in a view based on some node data

The simple way to do this is

print $view views_get_view('yourviews_name','yourdisplayname');

for more information you can read documentation here


In Drupal 7 the _field_info_field_cache() function retrieves the FieldInfo which gives you access to various field data.

function get_field_label($entity, $bundle, $field) {
  $field_info = _field_info_field_cache();
  $fields = $field_info->getBundleInstances($entity, $bundle);
  return isset($fields[$field]['label']) ? $fields[$field]['label'] : FALSE;
}

//Retrieve the tags label from an article node in a D7 Standard install
get_field_label ('node','article','field_tags');


"basic page" content type: how would I restrict access to a page for only 1 role

This can be acheived by using a combination of content access and login toboggan modules. You'll be able to restrict pages and prompt user to login to access them.


nice menus - how can I keep all sub-menu expanded in my  page?

Use Menu Block.
Duplicate the menu with the children already expanded and then style it as the other one.


Using filter strtolower in custom Twig Extension return no result

You have to render the array and then use the custom twig filter:

{{ title|render|removeSpaces }}


Administer Users permission too vague. How can I restrict functionality for this permission?

I believe the Role Delegation module does what you need to do. Here is a quote about it (from the module's project page):

... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions in the Permissions page.
If an administrator has the administer users permission, a role assignment widget gets displayed in the account creation or editing form, and bulk add/remove role operations become available on the user administration page. Otherwise, if s/he has at least the access user profiles permission, the module adds its own Roles tab to the user profile so that roles can be assigned.


Exposed filters and taxonomy. How to make a redirect to a term page when exposed form submit?

Here is the code that should work for your use case. Create a custom module and replace YOUR_CUSTOM_MODULE part:

function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    // Exclude cases when query contains 'field_color_tid'.
    if (strpos($_SERVER['QUERY_STRING'],'field_color_tid') === FALSE) {
      // Act only if query string contains 'field_size_tid'
      if (strpos($_SERVER['QUERY_STRING'],'field_size_tid') !== FALSE) {
        $selected_tid = $form_state['view']->exposed_input['field_size_tid'];
        // Check if such taxonomy term exists.
        $term = taxonomy_term_load($selected_tid);
        if (!empty($term)) {
          // Redirect to taxonomy page.
          $path_alias = drupal_get_path_alias('taxonomy/term/'.$selected_tid);
          drupal_goto($path_alias);
        }
      }
    }
  }
}


Diferences between: migrate_d2d and migrate

From Drupal-toDrupal data migration (migrate_d2d) module page:

  migrate_d2d provides a framework based on the Migrate API

So the diference is - migrate is an API module for migrations, and migrate_d2d uses it to perform task like yours. Either way you will use migrate, only difference is - do you feel you need to write what authors of migrate_d2d already wrote? Or maybe you want to use or modify their work to save some time?


Weirdly, I solved this by replacing the standard library with the full library. Seems odd as Div container is part of the standard library but it works.

When replacing the library, make sure to clear both Drupal's and your browser's cache.


How can get my site out of maintenance mode?

There is a few things you can try.

1. Using drush

Go to root of the website and run this drush commands one by one:

drush vset maintenance_mode 0
drush cc all

2. Using database query

Go to phpmyadmin and run this db statement in order to update the "maintenance_mode" property in the variable table to "i:0;":

UPDATE `variable` SET `value` = 'i:0;' WHERE `name` = 'maintenance_mode';

3. Login as admin programatically

Make copy of the index.php file and call it what every want (maintenance.php for example) and at the end of the file replace

menu_execute_active_handler();

with

global $user;
$user = user_load(1);
drupal_session_regenerate();
drupal_goto('user');

go to that file (like [your_website]/maintenance.php), after that just disable maintenance mode and don't forget to remove this file after you finish.

4. Manually set maintenance_mode variable in index.php

Edit index.php file and put

variable_set('maintenance_mode', 0);

just before

menu_execute_active_handler();

5. Configure maintenance mode in settings.php file

At the end of your settings.php file put

$conf['maintenance_mode'] = 0;


how can I export table content to excel or csv

May the below custom code will helpful for you.

set  the header

$filename= 'export.csv';
  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

you can write a function(just an example below) by sending the row values, filename, and column title

<?php

function export_to_excel_page($row_array, $filename,$column_titles) {

  drupal_set_header('Content-Type: text/csv');
  drupal_set_header('Content-Disposition: attachment; filename=' . $filename);

  foreach($column_titles as $key => $value) {
           $keys[] =$value;
  }

  if($keys) print implode(',', $keys) ."\r\n";
  unset($keys);

    //fetching the field values
  foreach($row_array as $key => $value) {

   $values[] =$value;

  }
    print implode(',', $values) ."\r\n";
    unset($values);
    }
    exit;

?>


"Declaration of  must be compatible with " in Drupal 8.6.10

It is a global issue on this new Twig version 1.38.0.

I can be temporarily fixed by downgrading its version using composer require twig/twig:1.37.1

You can follow this issue to know when the Twig version can be updated again.


jquery.cookie.js is loaded only for authenticated users, by jQuery update module

The jQuery.cookie library is not always included, it depends the user state and the visiting page.

For example, the login form includes this library by attaching (#attached) it to the form.

What you could do is include it yourself in a custom module or in your theme.

// hook_init()
function YOURMODULE_init()
{
     drupal_add_library('system', 'jquery.cookie');
}

// or in theme preprocess
function YOURTHEME_preprocess_page(&$vars)
{
     drupal_add_library('system', 'jquery.cookie');
}


I am using the module Entity reference in conjunction with Field collection to achieve that goal. That means you

add a node with an Entity reference field, where you save the rows
(if they actually are entities in your case),
attach that Entity reference field to a Field collection.
Now you can use the delta value of the Entity reference field to sort the row and the delta value of the Field collection field to sort the sections.

Note! You can use core's node edit form as sorting interface. If you would like to have more than one sort you could do that adding a node for each sort. Draggable view becomes useless that way.

Here is an example:

If you want to have an interface, which does not allow to alter other data than the order you could replace the autocomplete field with text an remove the buttons with hook_form_alter().


Try this

(function($) {

  Drupal.YOUR_MODULE_NAME = {
    form_id: 'FORM_ID'
  };

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

    for (ajax_el in settings.ajax) {
      if (Drupal.ajax[ajax_el].element.form) {
        if (Drupal.ajax[ajax_el].element.form.id === Drupal.YOUR_MODULE_NAME.form_id) {
          Drupal.ajax[ajax_el].success = Drupal.YOUR_MODULE_NAME.success;
       }
      }
     }
    }
   };

 Drupal.YOUR_MODULE_NAME.success = function (response, status) {
    // HERE YOU GET THE response
 }

 });


Using drupal behaviors for a Bootstrap carousel

Finally fixed it. I modified the code this way

drupal_add_js(drupal_get_path('theme', 'bootstrap_subtheme') . '/js/carou.js', array(
                                                                                'type' => 'file',
                                                                                'group' => JS_LIBRARY,
                                                                                'weight' => -1));

I added group and weight to it then then drupal.behaviors code had some few errors in the structure. The last line was})(jQuery);
But i fixed it to }(jQuery));


How do I implement hook_views_query_alter()?

In Drupal 8, best practice is to use hook_views_query_alter() in MYMODULE.views_execution.inc file. If instead it is placed in MYMODULE.views.inc, it will be executed only when rebuilding the views cache, causing your view to function properly once and then not subsequently.

MYMODULE.views_execution.inc file should have this structure...

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  // Only for my_view view.
  if ($view->id() == 'my_view') {
    // some action
  }

}

Ref: views_test_data.views_execution.inc


Navigation block title no longer defaulting to user name in d7

Have you set "user" in the contexts? It sounds like you do not have access to the %user:name token, and that's why it sets the actual text instead of the username.


I would use a db_query to find all nodes that that field appears on and then update them with a node_load here is the code:

$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
    $node = node_load($record->entity_id);
    // update node
}


One more way to check for admin rights, sure it works in Drupal 6.

if (user_access('access administration pages')) {
    // do something
}


Ubercart Feeds Mapper module:

Refer to the answer to the question about "How to import products to UberCart 3 using CSV data?". It contains a link to Drupal 7 Port of uc_feeds, which seems to include everything that's needed to make this to work by using the Ubercart Feeds Mapper module.

Note: from your recent question "Ubercart Product import containing HTML formatting in product description", I'm assuming that you are referring to the Ubercart Feeds Mapper module (instead of "Ubercart 'product' mapper" ...

From Ubercart.org:

Importing from CSV files also details the steps required for such import. The process consists of 3 steps. Here is a summary of these steps:

Prepare product data.
Activate the Node Import module.
Import process.

Attention, the 'Node Import' module does not have a D7 version, only a D6 version.


Content: Has taxonomy term ID depth modifier

The taxonomy term ID depth modifier option allows you to reuse the same view to query nodes according to varying depths in the taxonomy tree. For example let's say this is your taxonomy.

North America (term id:7)
- Canada
- Mexico
- United States
-- California
--- San Francisco
--- Los Angeles
--- etc

With a term id of 7 and a depth modifier of 0 your query would include nodes tagged with "North America". With a depth modifier of 1 your query would include nodes tagged with "North America", "Canada", "Mexico" and "United States", and so on.
The term depth modifier is passed as the second argument (Contextual Filter in Drupal 7) to the view separated by a slash. So if the term id is 7 and the depth modifier is 2 the arguments for the view are '7/2'.


How to restrict creation of content based on unique field values?

I'm not aware of an existing module with that functionality, but it wouldn't be too hard to code your own custom module to do the job.

This is an example using the 'article' node type:

function MYMODULE_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  if (empty($form['nid']['#value'])) {
    $form['#validate'][] = 'MYMODULE_article_node_form_validate';
  }
}

function MYMODULE_article_node_form_validate($form, &$form_state) {
  global $user;

  // See if this user has already created a piece of content of this type.
  $args = array(':uid' => $user->uid, ':type' => 'article');
  $count = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid AND type = :type', $args)->fetchField();

  // If they have, check for another node created by the user with the same field value
  if ($count > 0) {
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('uid', $user->uid)
      ->fieldCondition('field_some_field', 'value', $form_state['values']['field_some_field'][LANGUAGE_NONE][0]['value']);

    $results = $query->execute();

    // If we have a result, invalidate the form.
    if (!empty($results['node'])) {
      form_set_error('field_some_field', t('Error message here'));
    }
  }
}

That'll need a bit of massaging to match your exact situation, but it should be a good place to start.


delete URLs of all terms for a specific taxonomy vocabulary

To delete the aliases you will need a custom module or perhaps a custom VBO action based on the update taxonomy term alias action.  Here is a quick and dirty version of a custom module

aliases_delete.info

name = delete aliases
description = will delete vocabulary aliases for specific vocabulary
package = aliases_delete
version = 1
core = 7.x
dependencies[] = pathauto

aliases_delete.module

<?php

function aliases_delete_menu() {
  $items['aliases_delete/%'] = array(
    'page callback' => 'aliases_delete_delete_vocabulary',
    'page arguments' => array(1),
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
  );
  return $items;
}

function aliases_delete_delete_vocabulary($vocabulary_name){
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));
  foreach ($terms as $term) {
    pathauto_entity_path_delete_all('taxonomy_term', $term, "taxonomy/term/{$term->tid}");
  }
  return 'Deleted aliases of all terms in ' . $vocabulary_name;
}

If you enable and install this module you can visit as admin aliases_delete/tags to delete all aliases of terms in vocabulary tags

To update the path aliases of specific taxonomy terms (instead of deleting) you can use VBO - views_bulk_operations

install and enable the module
create a view of taxonomy terms and use appropriate filters for vocabulary
add field "view bulk operations" and save your view
go to your view and select all terms that will be updated (VBO can select multiple pages of results)
choose the update taxonomy term alias action and press execute
all terms should be updated according to the new pathauto rules


I recommend you to use eva module. visit this link (comment 3), I tested this solution and it works.


Show a message after file_transfer is executed

By default, you can't - when someone clicks a link to a file that's force-downloaded, it happens as a separate request/process entirely. For security reasons your web site will not be able to tell when/if that download has completed.

I think the easiest thing you can do is implement some javascript on the download link, which auto-refreshes the page as soon as you've clicked it, and while the file is still downloading. You could use a query string or similar to note that a message should be displayed or that a redirect should happen.

If you need something more complicated, you might be able to implement an AJAX-based polling mechanism, which contacts the server and checks the connection status for that file. It's not a trivial task though, and I think you'd need to change the file_transfer module quite a bit to implement that. It also might require some advanced server configuration. All beyond the scope of Drupal, so I'd advise getting a solution working independently first, and only then worry about getting it inside Drupal.

There are some ideas here, and related logic here


Regarding term clarification in the database api

Yes, you are doing it wrong by calling \Drupal::database.

Look at Drupal\block_content\Plugin\Block\BlockContentBlock in core as an example. The create() method gets the services and passes them to the __construct() method. That is the proper way.


do some action when order status is changed to complete

According to the details provided by you in comments, your rule is assigning new role to the user who is currently editing the order [site:current-cart-order:owner].

You need to use [commerce-order:owner] token in "Add User Role" action.

[commerce-order:owner] represents the user who created the order, and not the user who is editing it.


Menu tree from taxonomy terms and nodes which belong to them

That's probably an opinion-based thing and actually also a too broad question. But here's what I'd do:

Programmatically create a new block.
Provide a hook_theme and your own template to later render the output the way you want.
Follow one answer from How to get all node entities tagged with a specific term? to get the data you need.
In the block's build() function pass the data to your custom template and build the markup you need.
Optional: Improve performance by either storing the data from step 3. in some Drupal variable that can be purged from some admin settings form button click. Or add some custom cache tags that get invalidated as soon as taxonomy or node CRUD operations take place.

You probably can achieve what you want with some Views voodoo, and maybe should try that first, depending on your programming skills.


I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly
...
I want to know if it's a good practice and if Drupal 8 work like that.

No, what you described is not good practice. For a Drupal entity to interact easily and correctly with a field, you should add the field to the entity, not add the widget to the form.  It is probably possible to make it work but it will be harder to build and maintain.


Separate urls for child node with multiple parent nodes?

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


Change the value of a piece of content using a comment

Assuming your content type is called your_content_type and your module is called yourmodulename, you can use the following code:

It will set some state when a none-priviledged user posts a comment, and show a state selection UI for priviledged users. The state will be saved to the CCK field_erledigt_warten in the node in either case.

<?php
/**
 * Implementation of hook_comment().
 * Fill a CCK field  in Drupal 6
 */
function yourmodulename_comment(&$comment, $op) {
  global $user;

  if (is_array($comment)) {
    $node = node_load($comment['nid']);
  }
  else {
    $node = node_load($comment->nid);
  }

  if ($node->type == 'your_content_type') {
    switch ($op) {
      case 'insert':
      case 'update':
        if (user_access('edit field_erledigt_warten')) {
          // QD-Mitarbeiter
          if (isset($comment['field_erledigt_warten']) && $comment['field_erledigt_warten']) {
            if ($node->field_erledigt_warten[0]['value'] != $comment['field_erledigt_warten']) {
              $node->field_erledigt_warten[0]['value'] = $comment['field_erledigt_warten'];
              drupal_set_message(t('Status wurde auf %v ge&auml;ndert.', array('%v' => $comment['field_erledigt_warten'])));
              node_save($node);
            }
          }
        } else {
          // Kundenaccount
          $node->field_erledigt_warten[0]['value'] = 'neu';
          node_save($node);
        }
        break;
    }
  }
}

/**
    Implementation of hook_form_alter
 * Add a input box to the comment form
 */
function yourmodulename_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    if (is_array($form) && isset($form['nid']) && is_array($form['nid'])) {
      $node = node_load($form['nid']['#value']);
    }
    if (isset($node) && is_object($node) && isset($node->type) &&
      $node->type == 'your_content_type' && user_access('edit field_erledigt_warten')) {
      $states = array_flip(array('some', 'values', 'come', 'here'));
      foreach($states as $text=>$index) $states[$text] = $text;
      $status = $node->field_erledigt_warten[0]['value'];
      $form['field_erledigt_warten'] = array(
        '#type' => 'select',
        '#title' => 'neuer Status dieser Forumseite',
        '#default_value' => $status,
        '#options' => $states,
      );
    }
  }
}


The test:run command is missing, but other commands work fine

You need to enable Drupal Test module, then run drupal cache:rebuild, and command test:run will appear.


In the absence of any other answer, I've decided to try using the Organic Group module to solve this case.
I made this choice after reading this article which is the closest I've found to my needs.

However, I'm still not entirely sure that this is the only or even the best solution, so any other suggestion is still welcome.


In this example you should inject dependencies via the controller create method, pass the container there, and return an array. The first item in the array is the service you’re passing to the constructor.

Then, add a constructor that expects this object as an argument, and then set $this->membership to the container object you passed as an argument. This should also be a protected member of the class.

But to see your example actually work first, remove the container from the test method and remove the line about $memebrship. Clear cache and hit that route to see Hello world!

Here is a similar question demonstrating this: How do I use dependency injection on \Drupal::moduleHandler() to a Controller?


Funny you should say that. I just fixed a bug in leaflet module that was preventing me from showing linestrings (i.e. a route).

There are other ways of doing this but this is a good efficient way and leaflet maps are beautiful!

Install the patched version (i.e. the latest and greatest version) of leaflet module - http://drupal.org/node/1707882
Apply the tiny change I put here - http://drupal.org/node/1667780
Install http://drupal.org/project/geofield (7-1.x-dev version) and http://drupal.org/project/geophp
Install http://drupal.org/project/leaflet_more_maps to get a whole bunch of ready made tiles.
Add a field to your node using geofield with WKT format.
Add a node with your points using the WKT linestring format for your route = LINESTRING(lon lat, lon lat, lon lat)
Change the display format for the field to leaflet and choose which map style you want.

http://en.wikipedia.org/wiki/Well-known_text

http://leaflet.cloudmade.com/

Add a comment here if you get stuck at any point.


Any module which even comes close to frontpage slider module

Views Slideshow is incredibly configable and I am sure it will cater for that type of display. However is it not an off the shelf product like the wordpress example so dont expect to install it and it just work.

Instead like much of Drupal it is more like a construction box, complex but hugely powerful.


unset the timezone and group in the profile form

The reason is because your module in which you write you hook_form_alter has a weight of 0. In your database table "system" for your site look for your new module's row and edit its weight to a higher value. I set mine to 100. After you do this "clear your caches" just in case. Then you should now see the line item in your $form variable this is "timezone". Now your unset should work.

unset($form['timezone']);

Keep in mind that if you uninstall your module you will have to re set the weight again.

If you add this in your "MYMODULENAME.install" file you will be able to set this on intall

    /**
     * Implementation of hook_install()
     */
    function MYMODULENAME_install() {
      // New module weights in core: put MYMODULENAME as the very last in the chain.
      db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULENAME'");
    }

Hope this helps


Can the path of Search module (/search) be changed without altering the module, to allow use of this path by a custom module?

If you don't like what module sets in it's hook_menu(), alter it with your own hook_menu_alter(). Example code:

mymodule_menu_alter(&$items) {
  // Copy search to another place
  $items['look'] = $items['search'];

  // remove all old search settings
  // optional if you will also follow next step
  unset($items['search']);

  // add your menu item below instead of usual hook_menu
  $items['search'] = array(
    // ...
  );
}

This will unset /search path, and move all it's settings to /look path.

Worth noting is that if module generates links to /search anyway, it means it has it hardcoded somewhere. Happens. If so, you need hook_form_alter() or it's analogue to alter also these links.


string espected but array given in custom pop_date field #default_value

You are getting the "expects parameter 1 to be string" error because the only value the date popup form element accepts as default value is a string with the format described in date_popup_element_info().

  Set the #type to date_popup and fill the element #default_value with a date adjusted to the proper local timezone in datetime format (YYYY-MM-DD HH:MM:SS).

The code you should use is the following one.

$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d'),
  '#size' => 20,
  '#required' => TRUE,
);

If you need to visualize a specific value as default value, then the code should be the following one. (Replace $saved_timestamp with the value you need to show.)

$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d', $saved_timestamp),
  '#size' => 20,
  '#required' => TRUE,
);


Which is the theme template file that contains the logo image of the site?

The $logo variable is printed from page.tpl.php around line 77.

<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
<?php endif; ?>

Depending on what you want to do though you could also use template_preprocess_page().


Views charts with node revision date as x-axis

Ok,

After some struggle, I managed to get the results I needed so, I will share how to do it. Hope it helps anyone with the same question.

At the time of this answer, this will only work with the most recent Dev version. Also, after that, you have to apply this patch. It won't work unless you make these two steps.

On your content type, check if you have the Create new revision option checked.

In views, create a new view to show Content revisions and format as Chart. Change the following inside views:

===== First Display =====

Remove the Content revision: Content relationship.

Remove the Content: Published (Yes) filter.

If you have more than one content type, the way you filter (at least I did it this way) is to add a field to the Filter criteria like this: Content (historical data): [your field] (not empty).

Set Use aggregation to yes.

Add a Content revision: Nid field to the display and set aggregation to COUNT.

On the Chart settings, select field Content revision: Updated date to provide labels and COUNT(Content revision: Nid) to provide data.

The result is a display that shows the total of nodes for each revision (x-axis date).

===== Second (and similar) displays =====

Now, you create chart add-on displays for each of the different states/values of your data field (in my case it was a status_field).

The settings for these displays are the same as the first one with one difference:

Add the [your field] field to the filter section and filter by one of the states/values. You will have to do this for each dispay, each one represents the chart for each state.

Combine the chart add-on with parent chart.

Finally, to get the chart as stacked, you have to create some code. Add the following code to your module:

function mymoudle_chart_alter(&$chart, $chart_id) {
    if ($chart_id == '[my_chart_machine_name]__[first_display_machine_name]') {
    $chart['#stacking'] = TRUE;
}

Notes: remove the [ and ] from above example but keep both undersores (__).

And that's it. This is the result I got:

I have the update date of the revision to show as unix timestamp but you can have it as you like!

As suggested, here is a similar chart but using 'bar' type:


Logging URLs in the PHP-FPM Access Log - possible Clean URL Conflict

I am using

access.format = "[%t] %m %{REQUEST_SCHEME}e://%{HTTP_HOST}e%{REQUEST_URI}e %f pid:%p took:%ds mem:%{mega}Mmb cpu:%C%% status:%s {%{REMOTE_ADDR}e|%{HTTP_USER_AGENT}e}"

which logs lines like

[16/Nov/2018:23:54:13 +0100] GET https://realdomain.com/path?param /linux/path/file.php pid:1234 took:1.035s mem:2mb cpu:0.99% status:200 {192.168.1.10|Mozilla/5.0 (full User-Agent)}

More info: https://github.com/php/php-src/blob/master/sapi/fpm/www.conf.in#L257-L318


In response to the original question and to electblake's answer, I would second the fact that the Entity API contributed module is separate and distinct from the core entity system. It is meant to augment the core system by providing a more robust entity controller (the piece of code used to create, load, save, and delete entities), provide some automatic token generation, and allow modules to define metadata for their entities' properties.

electblake mentioned that the core entity system includes a class for querying entities in the database based on their property and field data called EntityFieldQuery. This is in fact the recommended way for making entity queries. The Entity API isn't actually meant to be a querying tool. However, it provides in my opinion the other missing piece for building robust contributed modules using entities and fields - the entity metadata wrapper.

As I mentioned, the Entity API module provides a hook that lets you define metadata for your entity's properties (i.e. $node->uid, $node->created). It combines this information with what it knows about field definitions and instances. It then lets you "wrap" an entity to make it easier to access and manipulate field data and (what I'll call) referenced entity data through the wrapper object. One of the main things this has made easier for me is not having to worry about the language of entities when I'm trying to access their field data. Without the wrapper, you need to know the schema array of the data you're trying to access or manipulate. Using it, you can simply access field data like any other property.

Additionally, it makes it easy to access the data of referenced entities. In Drupal Commerce, I make extensive use of this functionality since a couple of our entities serve primarily as containers of references to other entities. An example approaching the usefulness you mention in your original post would be to have quick access to all the taxonomy terms referenced by a node. A simple way to do this with the wrapper would be to wrap the node and then loop over your taxonomy reference field's data to access the fully loaded term data. It's hard to demonstrate this without including extensive code snippets, but you can easily see how I put this to work by grepping the Drupal Commerce source for entity_metadata_wrapper.

The jury's still out on how useful or widespread the Entity API will be, but as it's a dependency of Rules 2, I doubt it's going anywhere soon. This may be a little too much information based on your response to electblake, but my hunch is the information should be useful for additional people who find this question when searching for more information on the Entity API. : )


How do I add a confirmation form after the user clicks on "Save" in an edit form?

In brief, this is what I think you need to do in a custom module:

After validation, override the submit function on the node form to submit to a new interstitial page (you'll need to implement hook_menu to create the new page)
Pass the node object to the new interstitial page and define whatever logic you need in the interstitial page's callback function.
Create a new form on the interstitial page that runs node_save on submit with node object that was passed to it.


Firstly, check to see that profile2_load_by_user is a function available via a .module file and not something you will need to load via module_load_include() - which will load other files, such as .inc files.

Second, check the argument list for the preprocess hook. Did you define it as &$variables and mistakenly assign it to $vars which would mean nothing in this context? Did you forget to pass by reference via & which makes the array  modifiable?

Third, if you just added this code, clear your site caches so the changes are picked up.

Fourth, the function name isn't preprocess_page. It should be
 MYTHEME_preprocess_page.


Search index only part of custom content type

The search index is a view mode, but it is hidden by default (for some unknown reason).

Goto the Manage Display page for your content type.  Expand the Custom Display Settings at the bottom.  Tick Search Index and save.

A new tab, Search Index will appear.  Click this, and then configure your content type to show / hide the fields you want indexed.

You may need to dump the search index (admin/config/search/settings) and then reindex the site.  I can't recall if saving the search index does this automatically, of if I normally form alter that form to do it.  The easiest way to do this is with drush:

drush -y search-reindex
drush -y search-index

As a side note, I will be releasing a small module to help debug search issues and check things like this.  I am test driving it on a few sites now, and think it will be ready soon.


Is it safe and fine to block external access to sites/all/modules folder and all its subfolders and files?

If you are talking about blocking HTTP access (for browsers), then it won't give you any additional security.

But if you nevertheless want to do so, then exclude *.css, *.js and all images from being blocked.


Two things:

Check your argument to fopen for validity, and two, the $form_state in Webform is missing a key. Example:

  $data = array(
    'full_name' => $form_state['values']['submitted']['full_name'],
    'company' => $form_state['values']['submitted']['company'],
    'phone' => $form_state['values']['submitted']['phone'],
    'email_address' => $form_state['values']['submitted']['email_address'],
    'areas_of_interest' => array(),
    'comments' => $form_state['values']['submitted']['comments'],
  );

You are missing ['submitted'].


Is there a robust, free module for SE-style social signup?

I used Hybrid Auth . It works well. I tried anothers. They were not so good. Yes,  Hybrid Auth does not have another functionality to share content. But It should not have it. It uses the separated library. It does not use third party services. It's free and independent.

If you tell me your successful experience with another libraries I will be pleased.


Access image alt attribute in field template

With twig a preprocess function won't be necessary to get at this data (yay). Unfortunately we still have some weird "drupalisms" to deal with due to the render API. At any rate, here's how you get to it:

{{ item.content['#item'].alt }}

And here's the issue on d.o accounting for the drupalism (linked directly to comment with the above solution and explanation): https://www.drupal.org/node/2160611#comment-9358305


Referenced entity with multiple values making duplicate rows in views

What helped is going custom code. Instead of relying on the fields that would have come out of the Views query, I grabbed the nid of my referenced field of my 'event' content type and loaded the rest of the fields via node_load();. All of this happening in a tpl file views-view-fields--viewnale--block.tpl.php

I used the row object and made a loop that went over the multiple valued referenced entity.

    <?php foreach($row->field_field_evenement_performer_1 as $key => $whatever): ?>
    <?php $performer = node_load($row->field_field_evenement_performer_1[$key]['raw']['target_id']);

    $title = $performer->title;
    $picture = $performer->field_performer_foto['und'][0]['uri'];
    $bio = $performer->body['und'][0]['value'];

    print '

' . $title . '

';
    print '

';
    print '
' . $bio . '
'; ?>

<?php endforeach ?>


It's already built into the Services module, just enable its corresponding resource then do a POST ?q=[my-endpoint]/user/request_new_password.json and send along a name, e.g.: name=john or an e-mail address: name=john@example.com


Does the $form['element']['#disabled'] = TRUE guarantee that the user cannot edit the field or is it just a UI setting

If you disable field in backend, the field value won't be actually changed even if you change it in HTML or by JS.
You can test it:
 - disable element in form alter
 - open element in Chrome inspector (or other) and remove disabled attribute
 - change value in field and save the form
 - changed value will not be saved


Why don't you do this in chunks.I mean schedule you cron using elysia_cron or ultimate cron at every hour or something and export chunks of users at a time,flag users you exported and at every next cron run get the new ones.

One important thing you should have crontab set on your server,do not use drupal's default poormanscron.


How to run Drush commands on a schedule?

Yes, you can use Jenkins, which could be described as an advanced version of cron, though it is more powerful than that.  John Smith made a slideshow about integrating Drupal with Continuous Integration practices.

If you're in an enterprise environment, hopefully you have the resources to get a Jenkins server set up.  You can then also use this to run automated tests, etc. too.


Css redirect to other css file after logging out. Bug?

Drupal serves aggregated CSS. If one or more CSS files are not available (or required) for anonymous users they are not included in the aggregated file for the sake of a smaller file size. This file can obviously not be saved with the same name.

If you disable CSS aggregation (Configuration > Performance), you can see all individual files and this might explain the difference.


How to change filename before it get saved without changing source URL using tamper plugin?

It seems it's not possible using tamper plugins (as far as I've tried).

As workaround, this can be achieved by using hook_file_presave(), for example:

/**
 * Implements hook_file_presave().
 */
function mymodule_file_presave($file) {
  if ($file->filename == 'ShowImageXML.asp') {
    $filename = date("ymd", $file->timestamp) . '-' . $file->filesize . '.jpg';
    $uri = 'public://images/' . $filename;
    $file = file_move($file, $uri);
  }
}

See also a feature request: #2596841


radios options separated into different wrappers

In my opinion you can achieve that with a theme function, specified like this:

$element['example'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Example checkboxes'),
  '#options' => $options,
  '#theme' => array('custom_options'),
);

And then, you can write down the output just as you want here:

function theme_custom_options($element) {
  $output = '
';
  $output .= $element['#options'][0];
  $output .= $element['#options'][1];
  $output .= '

';
  $output .= $element['#options'][2];
  $output .= $element['#options'][3];
  $output .= '
';
  // ETC...
  return $output;
}

Does it seem correct?


Creating a Faculty and Staff Directory with Links to their Profile Pages

The short and simple answer is there is no way to link a custom User field to the user page itself.  However, this can be achieved by manipulating the view to expose the pertinent field data.

The situation is we have a couple of custom fields added to a User type.  These are last and first name fields (field_last_name and field_first_name, respectively).  Unfortunately there's no easy way (or is there?) to link these fields directly to their respective user's profile page through Views.  I have posted an answer below that goes the theming route by creating .tpl.php files, but we don't want to do that because we also work with people who aren't coders.  So how do we do this without code?  WITNESS THIS!

Let's say we want to display a list of users' names, titles, phone numbers, email address in tabular format on a page.  Great, pretty standard.  Do the following (I will assume you've created the page already in Views):

Add the User: Name (the one built into Drupal), field_last_name and field_first_name fields, rearrange them so that they're at the top, and then (this is VERY IMPORTANT), exclude them from being displayed
Add the field_last_name and rearrange it so that it's below the first two instances of field_last_name and field_first_name

Now, we're going to configure the last field that should be in the list: field_last_name.

Set it's label to Name
Open up the Rewrite Results pane
Check off 'Rewrite the output of this field' and 'Output this field as a link'
Under 'Output this field as a link', check off 'Use absolute path'
For the Rewrite text area, enter "[field_first_name] [field_last_name]"
For the link URL, enter "users/[name_1]" (name_1 might not be the same for you, just use whatever == User: Name when looking at the Rewrite Patterns

Apply and Save

You can edit your table settings so that it's displaying the way you want it to display.  You should now have a collection of names that link directly to their users' profile pages.

Essentially, we've exploited the rendering order of the fields.  Since we organized our fields such that the username, first name, and last name came before every other field, their values were available to the Rewrite processor in the remaining fields.

The reason I chose the field_last_name field, was because that if you choose to enable column sorting on the table, then the table will still sort on the initial value provided by that field, and not the rewritten result.  I wanted to sort by last name in my own case, this may differ for you.

Also a note, I have presupposed that you are using Pathauto to create friendly URLs in your website, and so the path to a user profile would look like http://site/users/username rather than http://site/users/uid.  If this is not the case for you, and you'd like to use the UID field instead, substitute out the User: Name field for User: UID, and the procedure shouldn't change besides that.

Hope this helps someone, I was pulling out my hair for a long time until I figured out this little gem.


Use image from taxonomy term as exposed filter option

Use "Better exposed Filters" and choose its Display setting as Checkbox
Now you have to do form alter like this

function THEMENAME_form_views_exposed_form_alter(&$form, &$form_state) {
  foreach ($form['TAXONOMY_ELEMENT']['#options'] as $tid => &$name) {
      $term = taxonomy_term_load($tid);
      $name = '<img src="' . file_create_url($term->IMAGE_FIELD_NAME['und'][0]['uri']) . '" />';
  }
}

In my case ::
TAXONOMY_ELEMENT = field_type_tid
IMAGE_FIELD_NAME = field_term_image


How do I solve the "table '.cache' doesn't exist" error?

To recreate this table for Drupal 6, execute the follwing in a SQL tool:

delimiter $$

CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '',
  `data` longblob,
  `expire` int(11) NOT NULL DEFAULT '0',
  `created` int(11) NOT NULL DEFAULT '0',
  `headers` text,
  `serialized` smallint(6) NOT NULL DEFAULT '0',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

You may need to adjust this if the rest of the database is MyISAM (someone should confirm the CREATE statememt; I converted all of my Drupal 6 sites to InnoDB).

For Drupal 7, use

delimiter $$

CREATE TABLE `cache` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...'$$

It is possible that the old webmaster DROPed this table thinking it would save space.  Drupal will mostly work with without this table.  Then try to clear caches from admin/config/development/performance  When you do this, you should get some exceptions from any other missing cache tables.