How to get multiple value with token_get_values()? I have a field which accepts unlimited values so the values of the field get saved in an array.  If I use token_get_values() to get the corresponding field value, I only get the first element of the array.

How can I read the whole array value or get an imploded string of values with token_get_values()?

You cannot, using token_get_values(). The code that is returning the value of the token for a CCK field uses just the first value of the field. The function that gets the value of a token for a CCK field (content_token_values()) contains the following code. (See in particular the code between // [1].)

  $content_type = content_types($node->type);
  $node->build_mode = 'token';
  $node->content = array();
  content_view($node);
  // The formatted values will only be known after the content has been rendered.
  drupal_render($node->content);
  content_alter($node);

  $field_types = _content_field_types();
  foreach ($content_type['fields'] as $field_name => $field) {
    $items = isset($node->{$field_name}) ? $node->{$field_name} : array();
    $function = $field_types[$field['type']]['module'] . '_token_values';
    if (!empty($items) && function_exists($function)) {
      // [1]
      $token_values = (array) $function('field', $items, $options);
      // [1]
      foreach ($token_values as $token => $value) {
        $tokens[$field_name .'-'. $token] = $value;
      }
    }
  }

The function called in $function('field', $items, $options) is, for a text field, text_token_values(), which contains the following code.

  if ($type == 'field') {
    $item = $object[0];

    $tokens['raw']  = $item['value'];
    $tokens['formatted'] = isset($item['view']) ? $item['view'] : '';
    return $tokens;
  }

Despite content_token_values() passing all the CCK field values, the function just uses the first value.


Drupal 7 - load view programmatically How do I load a view programmatically passing a language attribute?
Tried with module_invoke and views_embed_view but none of them worked;
Data is returned but not filtered by language;

Please advise.
Thank you!

If your view is set up with a Contextual Filter for language, this should work:

print views_embed_view($viewname, $display_id, $languagecode);


Setting up drush ini path in my site alias Unfortunately, i use shared hosting for my dev site to show to clients.

I'd like to specify an ini path in my example.aliases.drush.php file.

I couldn't find that particular custom variable in the example file.

Is it possible to set the drush.ini path so i don't get these nagging open basedir errors?

<?php
        $aliases['dev'] = array(
        'remote-host' => 'foohost',
        'root' => '/home/xxxxxx/users/.home/domains/xxxxxx/html',
        'php' => '/usr/bin/php',
        'path-aliases' => array(
         '%drush' => '$HOME/bin/drush/',
         '%drush-ini'=>'/home/xxxxxx/etc/drush.ini',
         '%drush-script' => '$HOME/bin/drush/drush/drush.php',
         '%dump' => ' ../db/dev.xxx.sql',
        '%files' => 'sites/all/files',
        ),
    );

Drush processes drush.ini in the drush bash script prior to calling drush.php.  Here is the relevant code it uses:

for conf_dir in $(dirname "$SELF_PATH") /etc/drush $HOME/.drush ; do
  if [ -f $conf_dir/php.ini ] ; then
    drush_php_ini=$conf_dir/php.ini
  fi
  if [ -f $conf_dir/drush.ini ] ; then
    drush_php_override=$conf_dir/drush.ini
  fi
done

You will need to make sure that your drush.ini file is in one of those location in order for it to be found and processed.  Note that the drush bash script never acts on command line parameters; those are parsed in php.  There are some environment variables that affect the drush bash script, but there are no environment variables that affect the selection of drush.ini, and there is no facility in site aliases to pass environment variable values to drush on the remote machine.

Sorry.

Edit: You could try setting %drush-script in your alias file to point to a script on the remote machine that called php /path/to/drush/drush.php.  Read the advice in the README.txt for Drush-4 on how to make an alias to drush.php if you do this; you will want to make sure that --php is passed to Drush correctly, etc.


template suggestion not working (page--front.tpl.php) in windows 7 env I do my development in a windows 7 env. Using XAMPP to run D7 and supporting apps.

I am giving the template suggestion of page--front.tpl.php for my D7 theme. For whatever reason the file doesn't seem to be getting recognized by D7. I pushed my code to my development server (linux) and page--front.tpl.php is picked up without issue.

has anyone seen this behavior? I can't lock down what is happening here.

I've seen this happen when there is another page--front.tpl.php lurking around in your directory structure and it is being picked up and used instead of the one you are looking at.  And, if that one is a copy of page.tpl.php, it will appear that it isn't being picked up. So, I'd look around and make sure you don't have one anywhere in your theme directory as Drupal will recurse through the entire tree looking for templates.  Another edge case is permissions so make sure it is readable to the world.  If all else fails, strangling the pc with the mouse brings some level of relief and entertainment :)


Can we upgrade a site directly to latest version (without an extra fresh site)? As far as I understand, the only way to upgrade Drupal (core-only) sites today is with having two sites: One is the Drupal 7 site with its own folder, and another which is a fresh Drupal 8 site in another folder; We then enable the core-based Drupal 8 migration modules in the fresh Drupal 8 site and with them Migrate-upgrade the Drupal 7 site into that fresh site.

Is there a way, maybe with Drush or with Drupal console, to actually Upgrade the existing Drupal 7 (core, or core&Ctools&Views) site directly as it is, without actually opening a fresh Drupal 8 site, besides it?

In other words, can we use the Console or Drush to update an existing Drupal 7 site directly, without any kind of migration?

No.

The old method of upgrading Drupal through update.php has been dropped in Drupal 8 in favor of the Migration framework & UI. The idea here is to provide a clean way into a new database schema without any problems of update.php trying to accommodate many diverse scenarios (as it was prone to do with moving complex sites from D5 to D6 & D6 to D7).

D8 has some significant changes to its architecture; trying to patch code & alter the DB schema for a D7 site to move it to D8 could be fraught with problems. It could theoretically be done, but you'd probably spend more time doing that than to just devise a content / custom code migration path.

For more information read Upgrading from Drupal 6 or 7 to Drupal 8 on drupal.org.


How do I add cross symbol in textbox? I have a view with an exposed filter for the node titles. I want to add X in that exposed filter.

I know html5 provides feature to have cross symbol when the input type  is search. I tried changing #type in hook_form_alter() for the text-field to  search, but it doesn't work.

Is it possible in Drupal 7?

You can do something like below:

write below code in any module

function modulename_theme() {
  $themes = array (
      'search_input' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
 * Implementation of hook_element_info()
 */
function modulename_element_info(){
  $types['search_input'] = array
  (
    '#input' => TRUE,
    '#theme' => 'search_input',
    '#theme_wrappers' => array('form_element'),
  );

  return $types;
}

write below code in template.php:

function themename_search_input($variables){ //echo "<pre>";print_r($variables);exit;
  $element = $variables['element'];
  $element['#attributes']['type'] = 'search';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-number'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input']))
  {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

In cs file:

input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

and use #type = search_input. It may help you


Can I disable the #required form attribute temporarily? I have functionality set up where an admin can create a user with a content profile. The content profile has a required field but I want the user himself to fill it out. How can I disable the required-ness of that field when the admin is creating the user so he can submit the form. I tried setting #required to 0 or unsetting it, but that does nothing.

function mymodule_form_contenttype_node_form_alter(&$form, &$form_state) {
        $form['field_reviewer_instruments']['#access'] = FALSE;
        $form['field_reviewer_instruments']['#required'] = FALSE;
}

This is most likely because of the ordering. THe module which is altering the form and setting the required element is being run after yours.

In the system table set your module weight to be higher than the module which is affecting the form.


How to redirect to another drupal site/alias after file upload I use the drupal standard to upload files + File Entity. After uploading file eg this is the current URL: https://blabla.com/en/file/abc.pdf. I want to redirect the users to file/add.

Matroschker

You can add a custom submit handler onto your form and add a $form['#redirect'] attribute to the target destination. There are many examples of form redirect questions on this site, and also examples for custom submit handlers for forms.


Make flippy pager appear in full content view I love the simplicity of the Flippy pager, and it works exactly as advertised until I display the node it's supposed to appear on in a view. Basically, I want the latest node of a specific content type to appear as the front page. Okay, I can use a view with the full content style and number of results set to 1. That works, but the pager (generated by Flippy) is missing. This is a webcomic site, so it is critical that the pager appear. Is there any way to make the pager appear exactly as it does if I navigate to the actual node?

I found an answer to this. I am also going to post the answer to drupal.org. I modified flippy.module using the following changes:

--- flippy.module.orig  2013-03-10 13:14:53.000000000 -0500
+++ flippy.module       2013-03-10 13:19:09.000000000 -0500
@@ -233,6 +233,8 @@
   // for getting node type
   if ($node = menu_get_object()) {
     $vars['node'] = $node;
+  } else {
+    $vars['node'] = node_load($vars['list']['current']['nid']);
   }

   $label_type = variable_get('flippy_label_type_' . $vars['node']->type, NULL);
@@ -315,7 +317,8 @@
   if (!is_object($node)) {
     return FALSE;
   }
-  return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  //return node_is_page($node) && variable_get('flippy_'. $node->type, NULL);
+  return variable_get('flippy_'. $node->type, NULL);
  }

 /**

Notes: This should be an option selectable in the module UI. Probably not everyone wants the pager in a view. Also, I'm not sure why menu_get_object() is really needed at all, since the current node is already available in $vars['list']['current']['nid'].


Add additional information to a field of a content type Let's say I have a content type Order. It has two fields:

Product1 with values 1-10 and Product2 with values 1-10. I am looking for a way to assign prices to the fields.

For example:

Product1*1 = 10

Product1*2 = 20

...

Product2*1 = 20

Product2*2 = 40

So if someone chooses value 2 of Product1 and value 2 of Product2 the system should calculate 40. I will do the calculation with a custom module, I am just looking for a easy way to define these prices.

Some solutions you have:

1) create field Product with multi values to content type Order bases on a table field. Module : https://www.drupal.org/project/tablefield

In this table you can attached the prices and with a custom module do the counting.

2) Create content type Order, create content type Product. In content type Product add a field price. Make a relation to entity from Order to Product.

3) Make use of ubercard. This will define products, cards and as far I can remember the recalculation of the card can be refreshed easily

4) Make use of Drupal Commerce, I know it is possible in there but never used it.

Let me know if you need more details.


How to change price in shop based on location? If in US then US dollars etc I really hope that someone can help me out here..

We set up our shop with drupal commerce, but we ran into a problem regarding currencies..

On old shop (Custom) we had option enabled if visitor is in US, currency will be set to US dollars else GBP.

Any advice on that? Im sure that somehow this could be done.. Maybe with geolocation?

Or if you have any other ways to do this, I will be happy to see what we can do.

Thanks for any advice!

Start your search at Commerce Multicurrency and find ways to detect the customer's country from there. Here is an excerpt about it from the module's project page:

... enhances some of the multi-currency capabilities of Drupal Commerce.
Current features:

UI for fine granular definition of exchange rates.
(Every currency combination can be defined separately if needed)
Synchronization of currency exchange rates directly from the European Central Bank (ECB).
UI to specify which rates shall be synchronized and which are handled manually.
Generation of currency specific price fields inclusive generation of rule-set to handle them.
hooks for easy integration of custom currency exchange rate sources.


How can I track download statistics for private files? One of the most important metrics for the publications database I'm working on will be file downloads, looked at in various combinations with things like publication type, date published, etc.  With the system I'm migrating from, I parse the server logs with a python script, and then reconstructing information about publication type, etc. is time consuming or impossible.  Google analytics doesn't work because a lot of the file downloads come from direct requests to the file, not via the page itself.

My hope is that with drupal's private file system, the system should know about and be able to send to google analytics (or some other counter failing that), information about all file downloads in that private file system.  Ideally it would carry with it information on the node that the file is attached to, making it much easier to look at, for example, the number of journal article downloads for material published in FY2015.

I'm fairly new to drupal, and honestly I'm so tied up with other parts of the build that I haven't been able to do much to dig into this yet, beyond searching here and on google a number of times.  My searches so far have been fruitless, so I'm trying to find out whether I need to try to make sure enough detail is implicit in the file system to allow me to parse the log files better.

Can anyone help me figure out how counting file download statistics can be accomplished without relying on server logs?  I'm happy to explore modules, my initial thought was that the google analytics module might take care of that on its own, but I realized it still relies on someone clicking a link.

I should mention that I am using the media and file_entity module.

Give these modules a try
Download Count

The download_count module tracks downloads of private files attached
to nodes via the core upload or contributed filefield modules for d6
and private core file fields for d7.

File download count

An API for tracking file downloads. Recommended use is by using
file_entity's file/[file:fid]/download callback page. Basically the
difference between this and other file download tracking modules is
this module does not intend to track every single time the file is
viewed. It only wants to track when a file is actually triggered for
download. It is up to the site to implement links to the file download
URL.

AJAX Download Counter

This module uses AJAX to count file downloads. It's optimized for
medium to large sites (such as my own site, OpenGameArt.org) where the
total number of file downloads might be in the hundreds of thousands
or even millions. Using this module has some advantages and some
limitations versus other methods of counting downloads:


Moving the Views header I've enabled the Result summary in the Header for my view... However, it is being displayed at the top of the conetnt. I would like it to be display in between the search form and the search results. Is the only way to do this via a template?

The view is made up of nodes being imported using a Feeds module.

They are displayed in a table, and there is a search on top...

I think using a template file will be the easiest way to do this.

In your view => click Theming information

  => Select the tpl file that suits you best

  => place that tpl file in your templates folder under your theme

  => for the content of the file

  => under Theming Information in your view click Display output

  => copy that content to your tpl and change the position of your header

  => come back to Theming Information and click Rescan template files - your newly added tpl(under your theme directory) should be highlighted(bold) now, which means you tpl is up and working!

Hope this helps.

[I am sure you might know how to do all this, yet putting it in details might help somebody else looking for the same solution who hasn't yet learned how to :)]


A Product Page with dynamic variants without using Commerce I have a page that is product page for an offline product. This product will never be sold through the website, so the Commerce module would be serious overkill I think. There are some features of the the product pages I've seen possible in Commerce that I need though. Like product colors.

For what I'm working on, the product model has different builds, (see the wireframe image) and each build has different color options. I need to be able to toggle back and for between color options for a build, and build options for the model.

I would like the model to be all one content type. There are common elements in the model that should stay the same no matter what the build, but items that are build specific that should update when a build is clicked. I'm  still trying to figure out the best way to structure the content type fields and such too.

I'm sure someone has had a similar need and I'm looking for tips in the right direction for the content type and the display. Since everything is part of the same content type, I figured I'd use a specific layout and use Panels to stitch it together, especially since I have related content to the model below the product.

Here are my direct questions:
How would I go about segmenting the different build levels in the same content type?

What would be the best way to pull all this back into a display and have the right areas work to allow the large image of the product be able to be switched when the color links are actioned and then have all the right parts change when a different build is selected?

As the user eluded, display suite or perhaps panels would be the go-to way to dealing with customized multi-column content type displays. Often on commerce sites, the quick tabs module is used to display tabbed product information.


How to create path for taxonomy term pages with parent terms if they exist I have a taxonomy vocabulary which will only ever contain 2 level deep hierarchy.

I need the url to be just [vocabulary]/[term] for any parent term.

But for a child term I need it to be the following

[vocabulary]/[parent_term]/[term]

Is this possible with a pathauto token? If not, is there another solution to this?

You can use pathauto token like this.

 [term:vocabulary]/[term:parents:join-path]/[term:name]


Where is the service container compiled to? Where is the service container compiled to in Drupal 8, in the database or in a file?

As @mradcliffe described in a commment, the normal Symfony way to compile and cache the service container is a single php file. Drupal used this until Sep. 2015. If you have an older installation, you still find the compiled container in php/**/, because it was never deleted by newer versions.

For better performance Drupal has changed this and stores it now in database in the table cache_container. The change record and how to take a look inside the container to debug it:

Change record: The service container definition is now stored in the database by default


how to add a class div on drupal 7 webform element? webform generated each form component in this structure

  <input></input>

I like to add a div class on each input element

<input></input>

I looked into the form alter to alter form element with #field_prefix and #field_suffix

$form['submitted']['chinese_name']['#field_prefix'] = '
';
$form['submitted']['chinese_name']['#field_suffix'] = '
';

but it didn't work.

You are using the incorrect keyword, the correct way to add a prefix to the webform field is:

$form['submitted']['chinese_name']['#prefix'] = '
';
$form['submitted']['chinese_name']['#suffix'] = '
';


View only works for root user I have a really strange issue occurring within a view I've created. I have the same code base on two servers, one is a stage server one is on a Vagrant instance on my local machine.

The view displays messages for a user (the UID is retrieved from the currently logged in user via a contextual filter). If I pass the UID of a user I know has messages into the contextual filter preview box in the Views admin panel while logged in as root then the view returns a record. If I try the same with another user it does not even though I am specifying the same UID, and the other user has the "administration" role checked in their profile so they should have the same permissions.

Does anybody have any ideas as to what may be causing this? I have a feeling it's something to do with configuration as like I said, the code base is mirrored yet works on one site but not the other.

Views hardcodes RIDs in when you export or featurize a view. That means that if the role has a different RID on one site than on the other, you'll have issues with Views giving permissions to the wrong users.

One way I've gotten around this is to hack the exported view, and where it would say something like

$handler->display->display_options['access']['role'] = array(
  4 => 4,
);

I have

$rid = ($role = user_role_load_by_name('administrator'));
$handler->display->display_options['access']['role'] = array(
  $rid => $rid,
);


How do I theme a link with twig for a specific content type? I'm trying to create a custom file-link.html.twig for a particular content type. I've looked at https://www.drupal.org/node/2354645 which doesn't link plugin theme twigs like file-link but tried file-link--<CONTENTYPE>.html.twig anyway. It doesn't work.

None of the variables passed include the node or content type. Any ideas on how to proceed?

There are a number of things you would need to do to accomplish this.

Enable Twig debugging
Create a hook theme suggestions preprocess function
Get the node object within your theme hook.
Craft the theme hook suggestion to get a template name with the node type in it.

Once you have Twig debugging enabled, you can inspect your file link. As a default for file_link, I see:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'file_link' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/file-link.html.twig' -->

In my case, I use Classy as a base theme for my sub-theme, thus the classy path above. but what is missing here is any useful theme hook suggestions out of the box. Next we will remedy that.

Since we are given the theme hook name above, I can craft the theme hook suggestion based on that and by getting the node type and incorporating it into the theme hook suggestion. (see function hook_theme_suggestions_HOOK_alter)

My theme hook alter then would be:

  function MYTHEME_theme_suggestions_file_link_alter(&$suggestions, $vars, $hook) {

  // Get the node type.
  $node = \Drupal::routeMatch()->getParameter('node');
  $type = $node->getType();

  // Create the theme hook suggestion.
  $suggestions[] = 'file__link__' . 'type_' . $type;

}

Once I do this and drush cr, I will see my new theme hook template suggestion as such:

<!-- THEME DEBUG -->
    <!-- THEME HOOK: 'file_link' -->
<!-- FILE NAME SUGGESTIONS:
   * file--link--type-news.html.twig
   x file-link.html.twig
-->

In my case, my node type is "News" and you can see that in the template suggestion name:

file--link--type-news.html.twig

Now you can create that file and theme away! For more insight on this, I just wrote a blog post about this: Drupal 8 Theming Tutorial: How to Craft Custom Theme Hook Suggestions and Templates


The login doesn't show a username anymore I can't login into my Drupal anymore and I'm not sure why.
I've got the BOTCHA Spam Prevention module and commerce (enabled with anonymous checkout).
Now my login looks like this:

I can't create a new user:
"the field username is required"
and I can't request my password (there is no username/email field).

I repaired the session table already. Tried several browsers and computers and the admin account has the User ID 1.

Don't know how I can get back into my Drupal :-S
Any ideas?

Thanks,
Chris

You could try to disable the module that causing the problem. There are multiple ways of doing that.

Using Drush

  drush dis modulename

Database hack

In the system table find the module and set its status to 0

  UPDATE {system} SET status=0 WHERE name='modulename'


How do I render a form from a controller? Render form in Drupal 8.

In modulename.routing.yml

modulename.fp:

path: '/formpage'

defaults:

_controller: '\Drupal\modulename\Controller\*Controller::formpage'

Write code in controller.php

public function formpage() {

$form = '';

$form = 'Form Title';

$form .= \Drupal::formBuilder()->getForm('\Drupal\modulename\Form\fp');

return [

  '#type' => 'markup',

  '#markup' => $form,

];

}

and write form code in modules\modulename\src\Form\fp.php.

but showing
Form Title Array

how to render form.

First of all why use a _controller if all you need to do is print a form? Instead it should have _form something like this: Drupal\example\Form\DefaultForm in the routing definition.

Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

And if you really want to embed a form in a controller response check this out How do I embed a form in a controller response?


Joomla to Drupal module - migrating issues Notes: Drupal 7.x. Joomla to Drupal module version 1.0 ALPHA3

I was playing with the Joomla to Drupal module, which is currently in alpha. I had imported some 100 content items from a Joomla install using this tool. However, making changes to some of the content was producing errors, so I decided to start fresh; I deleted all of the imported content.

I then attempted to redo the import, however, it threw additional database entry related errors stating that it was unable to overwrite tables.

I decided to start anew by disabling and then removing the module and its related tables all together; logged into mysql and removed tables joomla_categories joomla_content joomla_sections and joomla_users as well as the joomla directory under ../sites/all/modules.

I proceeded to reinstall the module, and went to configure it; all of the settings were intact i.e. database name, password, etc. from the previous install (caching?).

I go to perform the import, and a database error shows up stating that the joomla_users table does not exist. I log back into mysql and notice that the module did not recreate the joomla_ database tables.

Isn't the module responsible for creating these tables? Can anyone see what I may have done wrong in my process? If the module doesn't create the tables, what does?

From the sounds of it, the module was not uninstalled correctly. You should first disable the module, then when the modules page reloads, uninstall it.  During the uninstall process is when hook_uninstall() is run and the database tables and any saved variables (from the variable table) should be deleted.

If you didn't uninstall the module correctly, Drupal never performed these actions, and therefore still believed the module was installed.  Since it believed the module was already installed, the database tables would not be created.

For more information regarding uninstalling modules see the article: Uninstalling Modules


Copy data from a selected view in a fieldcollection field I have content_type TYPE1 content with two fields:

fiedl_1 is a viewfield type that allows me to display a view inside a node.
fiedl_2 is fieldcollection type.

Is it possible to copy the rows resulting from the view into my fielcollection?

Thanks a lot

Yes, it's possible but you're going to have to do some hoop jumping to make it happen:

Determine when this copy action will happen (e.g. hook_entity_update trigger).
Programmatically retrieve the View's data (e.g. via Views::getView() /  views_get_view() depending on your Drupal version)
Parse the view data an update the update relevant node fields with the view data. (which will also depend on your Drupal version).


How to get the type of Paragraphs entity in the parent node field? I have a "page" node with a paragraphs field field-ref-para-multi and the corresponding template field--node--field-ref-para-multi--page.html.twig.

And I have some paragraphs types that can be used in this field:

para_a

para_b

para_c

I have to place a surrounding html structure in the field depending of the paragraphs types that are used inside.

{# type a #}

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

{# type b #}

{% if multiple %}
    {% for item in items %}

{{item.content}}

     {% endfor %}
{% else %}
    {% for item in items %}

{{item.content}}

    {% endfor %}
{% endif %}

But how to get the type of the used paragraphs in the field template?

I think you can wrap each paragraphs field in any html wrapper of your choice, but you have to edit each field by modifying the appropriate field.html.twig  template file.

In the field template suggested name, for example:

FILE NAME SUGGESTIONS:
   * field--paragraph--field-text-half--text-svg.html.twig
   x field--paragraph--field-text-half.html.twig
   * field--paragraph--text-svg.html.twig
   * field--field-text-half.html.twig
   * field--text-long.html.twig
   * field.html.twig

You will then use the template suggested name to edit the html wrapper of your choice.

Like this :

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}
 --> change div to preferred  html
    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Hope this helps :)


need to replace default drupal user picture with an image field from user profile Need to replace the user_picture with my own field_profile_picture(since i've provided a nice crop with imagefield crop).

I've succeeded in getting the file path using template_preprocess_user_picture and the code

 function theme_preprocess_user_picture(&$variables) {
    $account = user_load($variables['account']->uid);
    if(isset($account->field_profile_picture['und'][0]['uri'])) {
        $variables['user_picture'] = $account->field_profile_picture['und'][0]['uri'];

the user_picture is getting replaced by the file path.... how to render the image???

Anyone Please....

how to render the image???

Sounds like you're probably looking for image_style_url(). Assuming you have an image preset called thumbnail, try something like this:

$picture_style = 'thumbnail';
$picture_uri = $account->field_profile_picture['und'][0]['uri'];
$variables['user_picture'] = image_style_url($picture_style, $picture_uri);


Message if view returns no results? I have a view which generates pages based on taxonomy terms. I have set up a navigation which links to each term in my website. Is there a simple way way I can return a default message if the view is empty?

I believe you are looking for Empty text under Basic Settings.  This will allow you to set some text (message) that will be displayed if the view returns no results.

You can choose any of your available input filters, the above is just an example.


How to alter user's input? I have a form to get some user input in Drupal. I want to add some prefix to the user input.

For example, the user enters "Laptop"; I want to save it in the database as resource_Laptop. I want to add the prefix before the validation is done, to avoid it fails.

How do I do this? Will hook_form_alter() help me here?

I have used this method, but not satisfied with this hack.

function mymodule_form_alter(){
  drupal_add_js("
    (function ($) {
      $(document).ready(function() {
        $('.field-suffix').hide();
        $('#edit-submit').click(function(){
        var s = $('#edit-machine-name').val();

        if (s.indexOf('_resources') == −1) {
          $('#edit-machine-name').val($('#edit-machine-name').val() + '_resources');
        }
      });
    })(jQuery);", 'inline');
}

Use the hook_form_FORM_ID_alter and add a custom submit handler.

function example_form_form_id_alter(&$form, &$form_state,$form_id){
  $form['#submit'][] = 'example_form_id_submit',
}

function example_form_id_submit(&$form,&$form_state){
  $form_state['values']['resource_name'] = 'resource_' . $form_state['values']['resource_name'];
}


Entity Reference multi value fields, filter on parent I have two content types: Family and Members. Family content type has an entity reference field of type Member and can have unlimited values(multiple values).
My question is: How to create a view that enables me to filter Members based on Family.
Thanks

Add a Contextual Filter in your view, use the "Member" field (Entity Reference guess) from your content type "Family".
Then add a relation in Relationship section, using the same field (Member).
Add a Title field and use that relation.
Pass the NID of your family has an Contextual Filter in your preview... you might get all the members of that family.

Notice: in yout Contextual Filter you have to select how will you pass the Contextual Filter (Family's NID in this case). You can add it via URL, etc.


Programmatically select image style for use with custom file entity view mode I have created an empty custom view mode for file entities with hook_entity_info_alter().

I would like to programmatically select settings for it, so that they can be deployed without a user having to go to the file entity display settings GUI and select "image" for type of file display and "original size" for the image style.

I cannot do this with hook_entity_view_mode_alter() because that appears to only fire for nodes, not for file entities.

How can I programmatically set the display settings for my custom view mode for file entities?

Sounds like something like this should work for you, to set the file display for the image file type, view mode name VIEW_MODE (replace with your custom view mode), to display original image. It either adds a new file display or updates an existing one:

$displays = file_displays_load('image', 'VIEW_MODE', TRUE);
$formatter = 'file_field_image';
if (array_key_exists($formatter, $displays)) {
  $display = $displays[$formatter];
}
else {
  $display = (object) array(
    'api_version' => 1,
    'name' => 'image__VIEW_MODE__' . $formatter,
  );
}
$display->status = 1;
$display->settings['image_style'] = '';
file_display_save($display);


Webform - Show the preview page on confirmation instead I have a Webform and there are options that you can set a "preview" page if you want to. I think it's very nice displayed but I want to show this instead on the confirmation page so when a user submits the form it will get posted but the form will be displayed on the confirmation page as it did on the preview page. like a confirmation, this is your Webform that was sent it.

You can achieve that like follows

Go to your Webform form settings, then find Redirect Location and select Custom URL:

Here you can insert tokens but for that you need to install the Token module.

After install and enable the Token module, Click on Browse available tokens link.

Let's say your webform URL path is node/5.

You need to insert Custom URL path like follows

node/5/submission/[submission:sid]

Then whenever user submits the webform, will be redirected to their webform submission results page.

Hope this simple solution helps you.

There is another way you can achieve that by writing some custom code in tpl files. Follow the Print submitted data on confirmation page


reference an entity outside of the node/add or node/edit forms I will explain you with my use case:

I have a content type "job post" and another content type "Exam" For apply to a job you must pass the exam, the "job post" content type has an entity reference field "field_exam" that is referencing the "Exam".

While user creates the "job post" he can create his own "Exam" or he can Call for tender on creation of an "exam" for the "job post". In that case the User will recieve "exams" of other users and he will choose one of them for his "job post".

The list of options is a view of "exams", in front of the title of each "exam" should be a link that says "Choose this Exam", and if I click that link the field "field_exam" of the "job post" must be referencing that "exam".

So the main point of this is, how to change update the "field_exam" value selecting the entity outside, for example in a view or in the node page...

Thanks for your help.

You could use the Views and Rules Link modules (along with the Rules module) to accomplish this.

What you would do is create a Rules Link that will attach your line item (exam) to a Job (that the user selects).

You would likely need to have an  field available for Rules to manipulate, but there would be no forms involved directly using an Entity Reference field (no forms involved).


display the multiple value in single field in drupal 7 view display the related multiple value in single field to avoid duplication in drupal 7 view

Guys help me to solve this issue.

Now it's like this.

Name -----------------------------Organization

sam --------------------------------Ministry of public Health

sam ---------------------------------It solution company

I want to display like below

Name------------------------------Organization

sam----------------------------------Ministry of public Health, It solution company

You can do this by "Rewrite results" follow the following steps.

1) Edit the first field and exclude it from display.

2) Edit the second field and click on the "Rewrite results"

3) check "Rewrite the output of this field" checkbox.

4) find your fields in the "replacement Patterns" and put it in the textarea like this [field1],[field2]


Remove query strings from static resources in template.php I've read several articles throughout the web about removing query strings from static resources, in the template.php file, after I saw a recommendation to do so in a forum, for better page-loading time in Drupal.

All of the articles I've seen lacked some didcatance in the following points:

Why should one remove Query strings for better loading times? I've never seen them in any URL of any my site's pages, and, I don't understand why would their appearance in a URL effect in any shape or form the loading time of a site's page (that deals more to image-optimization, bandwidth, etc).
What is a static resource in Drupal? Cache is something dynamic so I'm guessing it's not the cache itself. So what is it?
Where should I put the following code of this JavaScript function, at the start of the file, at the end, or between any special segments? It wasn't clear from none of the articles.

/**
 * Implements template_process_html().
 */
function MYTHEME_process_html(&$variables) {
  $variables['styles'] = preg_replace('/\.css\?.*"/','.css"', $variables['styles']);
}

The only reason you'd want do this is to remove any cache busting query parameter. These are query parameters that are appended to a URL (e.g. www.example.com/js/some_file.js?b= 1433781670 & www.example.com/css/some_file.css?b= 1433781671 ) to prevent browser caching.

As the tutorial probably explained, you'd only want to do this for static resources (i.e. any web resource like a CSS/JS/Image file that will never change) so that the browser will cache the static resource.

As for the template question you can place the MYTHEME_processs_html() function anywhere in template.php (if you don't have one, create it). On top of that, the only thing you'd need is to replace MYTHEME with the short name of your theme and flush your theme cache.

If you're new to Drupal I'd recommend avoiding this for now; unless you're sure there's only static CSS stylesheets that can safely have its cache-busting query string removed, you can end up with a scenario where modules/themes aren't displaying correctly because the cache busting query parameter was needed.


add AJAX to an existing node/page path? I'm trying to add 'new' or 'updated' to the links in a Menu, and one of the ways is with AJAX.
But to do that, I need to add AJAX to existing node/page path
following the documentation and various examples,
hook_menu()
successfully adds the scripts and call backs for paths that only exist in the module file

// The page that will run the command.
$items['my-custom-path/trigger-page'] = array(
  'title' => 'AJAX trigger page',
  'page callback' => 'my_ajax_trigger_page',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

[my_ajax_trigger_page calls add_ajax_js and works with and without clean URLs]

but when I add items for an existing node with a menu path, a page I created, and gave a URL path like 'my-toc-page' does not get registered for the AJAX calls.
nothing happens - the scripts to not load on to the page at all,
and the callbacks silently fail
I have also tried this with a View, with AJAX enabled, but still it does not register

// register script load
$items['test-toc-page'] = array(
  'title' => 'MyTable of Contents',
  'page callback' => 'add_ajax_js',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

How do you do this on a page that already exists and has content and blocks on it?
No forms, but the links on the page need to be processed.

Using a page template file , I can load the JavaScript files onto an existing page, but the AJAX call backs fail.

Thanks everyone, this is a continuation of my initial question about AJAX on page load.
Existing Page not getting registered by hook_menu to trigger Drupal AJAX on page load

There are many ways to add scripts to an existing page, one option is:

/**
 * Implements hook_init().
 */
mymodule_init() {
  if ($some_condition) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
  }
}

hook_menu() probably isn't going to help you here, because each menu router item can only have one page callback.


theme style.css is not loading for custom theme I am trying to learn Drupal 8 theme development. I am trying to create basic theme
My Folder structure

|-themes
  |  |-custom
  |  |  |-contra
  |  |  |  |-css
  |  |  |  |  |-style.css
  |  |  |  |-contra.info.yml
  |  |  |  |-contra.libraries.yml

My contra.info.yml is as follows:

name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
   -'contra/global-styling'

My contra.libraries.yml is as follows:

global-styling:
version: 1.0
css:
    theme:
        css/style.css: {}

I have cleared the cache in Admin->Configuration->Development and also refreshed my browser but I dont see the style.css loaded in view source.

Try adjusting your spacing. 2 spaces are required.

.info.yml:

name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
  - contra/global-styling

.libraries.yml:

global-styling:
  version: 1.0
  css:
    theme:
      css/style.css: {}

Also, take a look at https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Item pagination - fatal error: allowed memory exhausted I have an $items array that I was displaying with my template file. Now I want to add a pagination, therefore the code looks like this:

    $current_page = pager_default_initialize(count($items), 4);
    $chunks = array_chunk($items, 4, TRUE);

    return theme('activit_item_list_block', array('title' => $title, 'subtitle' => $subtitle, 'items' => $chunks[$current_page])).
           theme('pager', array('quantity', count($items)));

but now im getting error:

  Fatal error: Allowed memory size of 1342177280 bytes exhausted (tried to allocate 40961 bytes) in C:\xampp\htdocs\grantexpert\includes\theme.inc on line 1514

Can't find out what I'm doing wrong, the code is identical with few examples that i found on internet. There is only 5 items in $items array.

activit_item_list_block:

    <?php $countinrow = 0; $itemcount = count($items); $counter = 0; ?>

<?php echo rip_tags($subtitle); ?>

                <?php foreach($items as $item) { ?><?php $countinrow++; $counter++; if ($countinrow==1) { ?>
<?php } ?>

<?php echo $item['title']; ?>

                                    <?php echo $item['text']; ?>

                            <a class="button btn-small" href="/<?php echo $item['link']; ?>">Viac informácií

<?php if ($countinrow==4 || $counter==$itemcount) { $countinrow = 0; ?>
<?php } ?>

I'm not sure what theme_activit_item_list_block() is but I suspect you want this:

theme('pager', array('quantity' => count($items)));

instead of this:

theme('pager', array('quantity', count($items)));


How to insert a hashed password into table users? I'm using services module, but i've created my own resource 'login', I'm using $data to store username + password.

When i use postman, I put a text plain for password, and in my service code i've added the hash function (see my code please)

this is my resource declaration :

'user_connexion' => array(
  'actions'=> array(
    'login'=> array(
      'help'=> t('Permet de se connecter'),
      'file'=>array('type'=>'inc','module'=>'my_module','name'=>'my_module.resource'),
      'callback'=>'my_module_connexion_login',
      'access arguments' => array('connexion resource login'),
      'access arguments append' => FALSE,
      'args'=> array(
        array(
          'name' => 'username',
          'type' => 'string',
          'description' => 'username du client',
          'source' => array('data'=>'username'),
          'optional' => FALSE,
        ),
        array(
          'name' => 'password',
          'type' => 'string',
          'description' => 'password du client',
          'source' => array('data'=>'password'),
          'optional' => FALSE,
        ),

and this is the function callback :

function my_module_connexion_login($username, $password){
//hasher (pour le moment pour tester) password
module_load_include('inc', 'services', 'includes/password');
$password_h= user_hash_password(trim($password));
var_dump($password_h);
}

the var_dump result change every time i send a post request (example for the same password text plain i've got this) :

string(55) "$S$DV5cPYQpTqX94qlY9jiYSsCkMCE7AZldfHbXx7qm1ju1aA6AQxRv"
string(55) "$S$DMM2YDpjJ6R0q8.QxLTVjMrIw2dslnt.fBTRGUK6Q8RWEls.vEjy"..ect

this is the complete function :

function my_module_connexion_login($username, $password){
//hasher (pour le moment pour tester) password
module_load_include('inc', 'services', 'includes/password');
$password_h= user_hash_password(trim($password));
//var_dump($password_h);
$log = db_select('users','u');
$log->addfield('u','uid','id_user');
$log->addfield('u','name','username');
$log->condition('name',$username,'=');
$log->condition('pass',$password_h,'=');
$login = $log->execute();
$connexion = array();

foreach ($login as $co) {
    $connexion [] = array(
        'uid'=>$co->id_user,
        'username'=>$co->username
        );
}
if($connexion == null){
    $response = array(); // error, so no login
    return func_succes(3,$response);
}
else{

    $response = $connexion; //no error and login
    return func_succes(0,$response);
}
 }

If i create a valid user and i choose a password, there is no way to login with this password (using my custom resource) because my function that take text plain from postman as THE password and hash it with MY RESOURCE will not returns the same hashed password as the real drupal hashed password for the password i've created before

How to use my resource to login, with taking the username (works now) and a text password, hash it and have the same hashed password stored on users table, to be able to compare it ?

Thank you.

I solved it by using user_authenticate($name, $password) (see https://api.drupal.org/api/drupal/modules!user!user.module/function/user_authenticate/7)

Now my code is :

function my_module_connexion_login($username, $password){

$authentification = user_authenticate($username, $password); <======

$log = db_select('users','u');
$log->addfield('u','uid','id_user');
$log->addfield('u','name','username');
$log->condition('name',$username,'=');
$login = $log->execute();
$connexion = array();

foreach ($login as $co) {
    $connexion [] = array(
        'uid'=>$co->id_user,
        'username'=>$co->username
        );
}
if($authentification == false){ <==================
    $response = array();
    return func_succes(3,$response);
}
else{

    $response = $connexion;
    return func_succes(0,$response);
}
}

Thanks


How to add another filter to Scald search? I have added new field to the Scald Image atom admin/structure/scaldwhich is called description and it is text area multiple rows. Now I want to have this field in the search to be shown at the below screen shot.

I tried to edit the field by checking MEE Enabled but I could not get it in the search.

The search is provided by a View called Scald Atoms.  Add the filters you want to that view.


How to render user profile edit form in block? I want to render fields of user profile edit page  like "User Name ","current Password","email" in a customblock

I would suggest creating a view that displays user content. You should be able to add any fields you want from the user profile to the view. Then add a new display to the view with the 'block' type.


How to add the "user role field" in View showing users I created a view showing users. Then I have a list of users. I need to add a field to show the user role. I clicked add field but I don't see this field. Do I need to add a relationship to have this field available?

Update: I have Aggregation enabled.

So you need to add 2 field into your view User uid(exclude from display) and Custom text, next go to your template.php and do next

//implement hook_preprocess_views_view_fields
function YOURTHEME_preprocess_views_view_fields(&$vars) {
    $view = $vars['view'];
    $fields = $vars['fields'];

    if ($view->name == 'usr1') { // change on your view name
        $results = $view->result;
        $roles = array();
        foreach ($results as $row) {
            $user = user_load($row->uid);
            $roles = implode(', ',$user->roles ); //get all user roles
            //check if user name from field equal to current user in array
            if ($fields['name']->raw === $row->users_name) {
                $fields['nothing']->content = $roles;//put that roles to custom text field
            }
        }
    }
}

THIS CODE NEED IMPROVEMENTS, cuz it iteracts on every field of your view, so you can work on this :D.


How to retrieve Apache Solr's current search filters? I'm using Apache Solr Search, Search API and Facet API.

Is there a way to retrieve the current search filters being used when using Apache Solr on Drupal?

For example: I have a website using facets which reference a taxonomy called colours.  In this facet, there's a list of colours - if I select Green, this generates an Apache Solr search - using green as the filter.

www.example-website.com/?f[0]=field_colour%3A2712.......etc

When the Solr search is created - I guess, I could grab the term id 2712 from the URL using GET - but there must be a cleaner way.

Any ideas?

Sounds like you're writing a module to do this?

If so, if you're implementing something like the apachesolr_query_alter(&$query) hook or something like that, which gives you access to the search query, you can use

function [getFilters][1]($name = NULL)

Note that the name parameter is optional: Returns all filters matching $name, if set; otherwise, returns all filters.


Link product variations to its own pages (e.g. blue hat to blue hat variation, etc.) I have a product display of two t-shirts variations, one is blue color and one is black. I also use it in Views Slideshow, to show it in front page.

The problem is that both variations link to the default one only. If default product display t-shirt is black, but also has a variation of blue, when clicked on blue t-shirt in homepage, it redirects you to the black version. How do I make it link all variations to it's own versions/pages? Is this even possible? Because when filtering variations on product display node, the page path is same and doesn't change.

I solved it by using the following rewrite results: [path]?id=[product_id].


Create new page without using Views or Panels? I'm now in process of reducing the numbers of module used in the website. I will disable Panels and several other modules, but still using Views.

(The website is not too complicated, but because many modules involved, it become quite slow.)

Instead of using Panels, I'm customizing the appearance through dozens of template files.

But I just wonder, is it possible to create new page without using Views or Panels?

Yes, You can write a small custom module to create pages with out using heavy panels module.

Please see the hook_menu documentation.

function yourmodulename_menu() {
  $items['page_one'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_one_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page_two'] = array(
    'title' => 'Title of Page',
    'page callback' => 'page_two_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

 function page_one_callback() {
   $content = "";
   return $content;
 }

 function page_two_callback() {
   $content = "";
   return $content;
 }

To make your life much more easy without any coding, just go to "node/add/page" and create a new page !


Safe to remove core optional modules I'm running on a restricted machine space/memory where I have to remove all un-needed modules.

Is it considered safe to uninstall core optional unused modules?.

modules like: Book, Forum, etc.

Yes it's safe to remove them. But I would recommend you not doing so. These modules are just tiny modules and it won't give more than 1 MB of space to your system.

However, if you are no longer using a module, make sure you have uninstalled that module. If you had search module enabled and if you are no longer using it, disabling it and uninstalling it will clear existing search index and now you could get a lot of database space saved.

If saving every bit of the space is worth, look at your third party libraries. They often come with folders such as docs and examples in it that actually do not help in terms of the site functionality.

Other places that you might want to check include, log folders (Apache logs), SSH command logs, old backups from Backup and Migrate module (or other backups), obsolete caches (Admin > Configuration > Development > Performance > Clear All Caches  -- this will clear all caches, including in-use ones), watchdog (Administer > Reports > DB Log > Clear), spam comments (Admin > Content > Comments > Unapproved).

Make sure you keep a backup of the system for your own safety!


Profiles-2--user-edit-page I made my custom user-profile-edit.tpl.php using

function mytheme_theme($existing, $type, $theme, $path)
{

$hooks['user_profile_form'] = array(
                                // Forms always take the form argument.
                                'arguments' => array('form' => NULL),
                                'render element' => 'form',
                                'template' => 'templates/user-profile-edit',
                                );
return $hooks;
}

Now I want in user-profile-edit.tpl.php to render the account form (default Drupal form for users) and my profiles2 forms, from the forms i created without click the upper links.

Does anyone know how I can achieve this?

After creation template you need only implements form_alter and set this custom theme for whole form - $form['#theme'] = 'user_profile_form' and then you will be able to build form structure inside your template.

You can check diff module ( 'diff_node_revisions' theme ) as an example.


Order style-sheet list when adding custom one via template_preprocess_page() I'm using phptemplate_preprocess_page() to add a set of style-sheets which are only needed for a certain content type.

function phptemplate_preprocess_page(&$variables) {
  if ($variables['node']->type == 'example') {
    drupal_add_css(path_to_theme() . '/css/example.css');
    $variables['styles'] = drupal_get_css();
  }
}

The problem is that my added style-sheet is added to the top of the list, which results in undesired behavior. For example, let's say that in my main theme style-sheet I define the font-size of p to be 11px, but in my example.css for this specific content type I need it to be 15px. The main style-sheet is added via the .info file of the theme.

It seems I can only think of icky ways to add my specific style-sheet at the bottom of the list, or at least below the theme default ones.

Is there any proper way to order them?

OK, of course, a few moments after adding the question I saw what was wrong. Since I did not specify the type it added my style-sheets it added it to the end of the modules. I now added the theme type and it was added at the end of the list.


"Explanation or submission guidelines" missing In editing a content type on a Drupal 8 site, I added text to the Explanation or submission guidelines, but when I surf to the node create/edit form, the text is nowhere to be seen.

Is this a bug, or are there extra steps involved that aren't documented in the UI?

That information is displayed in the help block. Make sure the theme you are using on those pages has a help block.

The Seven theme does have that by default, but either you've configured the node add/edit pages to use the front page theme, or you removed the help block.


How to change an address field that says "There is data for this field in the database. The field settings can no longer be changed."? How to change an address field that says "There is data for this field in the database. The field settings can no longer be changed."?

I want to add a "Company" field as part of the address. I don't want to ditch all existing address data. I don't want to create a separate field.

The message you see is for the settings of an existing field name "Adresse".  It tells you that you can no longer change its field settings.

There is nothing that prevents you from adding a new field named "Company" to the content type. Just go to the "Manage fields" tab for the content type, fill in the "Label" (i.e. Company) and other settings for the new field, click "Add new field" and then "Save".


Is there any XML editor for textarea I want to insert XML editor for text area. Is it possible?

Currently Is there any XML data editors. If there is no XML editor for text area what is the possible way .

Try the XML Field module

  Defines an xml field type. Provides an XML widget using CodeMirror (beginning with version 7.x-1.6).Provides XML related API functions for working with XML code. Adds a theme_xml() theme function. Defines a form type called xmltext for use in the Forms API.

Image from project page


Testing an update hook that updates fields? I wrote an update hook for a site that moves data from one field to another. It looks a lot like this gist:

  foreach ($node_ids as $node_id) {
    try {
      $node_wrapper = entity_metadata_wrapper('node', $node_id);
      $node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
      $node_wrapper->save();
    }
    catch (Exception $e) {
      watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
    }
    $sandbox['progress']++;
  }

It's being tested on CI (Travis) which runs "drush updatedb -y" so what I was wondering is if there is a way to query a particular node and make sure the field is populated? Like for example make sure the data in field_new_field is the same as _field_old_field and printing that on the command line?

Yes, very quickly. You already have part of the code. Since you have already loaded the node via the entity_metadata_wrapper() you have all of the information at your finger tips.

An example is this in your hook_update_N()

foreach ($node_ids as $node_id) {
    try {
      $node_wrapper = entity_metadata_wrapper('node', $node_id);
      $node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
      $node_wrapper->save();
      if ($node_wrapper->field_new_field->value() == $node_wrapper->field_old_field->value()){
        print_r('Success. Old field data is in new field data');
      }
    }
    catch (Exception $e) {
      watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
    }
    $sandbox['progress']++;
  }

I added a comparison of the old field data and the new field data. If it is the same, it will print 'Success. Old field data is in new field data' in the console of Travis-CI. You can do this for any entity. You can use print_r() to output data that you can see in Travis-CI's console. I do this for troubleshooting my test scripts when I may be using a new test method I have never used before and I want to see what Drupal is giving me. Most of the modules I maintain on D.O are tested with Travis-CI.


How to list events filtered by date In Drupal 8, I have an 'event' content type with a date range that specifies when the event starts and when it ends. In my view, I need to set up a filter with the following behavior: i choose a specific day from a calendar (btw how to create a calendar and make it work like a view filter in D8?!?), and the view only lists events that start <= the specific day AND end >= the specific day.

Thanks in advance.

As jQuery UI is part of Drupal 8 core for the calendar functionality you can simply do this:

modulename.libraries.yml

modulename.id:
 version: VERSION
 js:
  js/custom.js: {}
 dependencies:
  - core/jquery
  - core/jquery.ui.datepicker

custom.js

function ($, Drupal) {
  "use strict";
  Drupal.behaviors.mymodule = {
    attach: function(context) {
      $('#views-exposed-form-id
       input:text').datepicker();
     }
   };
})(jQuery, Drupal);

To query for data between event starts & end date you can use hook_view_query_alter();

modulename.module

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

function modulename_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ( $view->id() !== "view_id" ) { return; }
 foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as $index => &$condition) {
   if (!empty($view->exposed_raw_input['start']['min']) && !empty($view->exposed_raw_input['start']['max'])) {
$query->addWhereExpression(0,'FROM_UNIXTIME(tablename.created, :format ) BETWEEN :min AND :max ',
array(':min' => $view->exposed_raw_input['start']['min'],':max' => $view->exposed_raw_input['start']['max'],':format' => '%m/%e/%Y'));
   }
  }
 }
}

Idea is to use BETWEEN :min AND :max in your query. Maybe there are other ways to solve this problem, but this is how I would approach this issue.


Access argument string for all administrators to access menu I have implemented a hook_menu method in a module i'm writing.

The problem i'm facing is, i'm not able to pass an access argument that grants access to all the administrators.

The only one able to access the page is the admin account that was made upon installation.

Any help would be appreciated. This is the code.

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

    $items['admin/config/people/raffle'] = array(
        'title' => 'Raffle',
        'access callback' => 'user_access',
        'access arguments' => array('administer site configuration'),
        'file' => 'raffle_admin.inc',
        'page callback' => 'raffle_abc_view',
    );
    return $items;
}

Defining your module in hook_menu is not enough. You need to define hook_permission() too. You can do something like this

function raffle_permission() {
   return array(
    'administer site configuration' => array(
      'title' => t('Administer Site Configuration'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}


How do I change the salt used for the user password when creating an account? I am working on Drupal 8 site where the client has asked us to use their own custom salt when storing the user password in the database.

Is it possible to set a custom salt for a Drupal site?

The client is thinking of the feature from a security perspective. What can be done?

In site/default/settings.php  there is a config for salt

$settings['hash_salt'],  passwords are hashed with this salt. you can change it to whatever the client has asked you.


Does 'aggregate and compress CSS files' actually use gzip? Under performance settings in my D7 site, I have "Aggregate and compress CSS files" enabled.

When I run YSlow, I get this:

  Grade F on Compress components with gzip. There are 4 plain text
  components that should be sent compressed:

  /files/css/css_CKoWqiBj9gVXhPuDSnNphuEB0b0J2To76x0pX0EGqn4.css
  /files/css/css_5lmdLBQE3741385dmh2zZ_gO_fPyq-62r9KkuUzfIH0.css
  /files/css/css_UIg6lj2uEi5H1zubqecd1x6N7_ejFWRiwKYJ_qrEmOQ.css
  /files/css/css_oYatxLY13v2flmA_6hUfSrbPmK_x8KS-tOsczLXYqqo.css

This suggests that the aggregated CSS files aren't being gzipped by Drupal?

There is a difference.  You are seeing aggregated (ie, concatenated) and minified CSS when you tick that option on the performance page.

That YSlow report is talking about the webserver sending the results compressed responses the wire.  I honestly can't remember if there is a Drupal option for output compression as I always use mod_deflate rules to do this.

Typically, I add the rules directly to the Apache config for my whole server (so I don't have to worry about core updates nuking my .htaccess file).  Lately, I have been using the rules from HTML5 Boilerplate:

<IfModule mod_deflate.c>
  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>
</IfModule>

Note that this works on MIME type, and not file extensions, so more respones from Drupal will get compressed.


Looking for best way to approach user profiles I'm looking for the best way to approach user profiles, I'll tell you what I want to achieve and maybe someone can give me some advice - There are a few things I'd like to do but not sure where to start, so here I go...

First I'd like 2 different user types, personal and business. When registering the user chooses which type of account they want and fills out the relevant form (personal and business will have different fields available to them, for example a business account will display a vat number where as a personal will not)

Then when a user creates a node I'd like fields from their profile to be displayed on their node, for example their name, location, picture and a link to their profile to name a few. (I would like this so people can search content based on users location for example)

I think these are the 2 main functions I'd like to get out of user profiles - what would be the best way to tackle this? I have seen a couple of modules - 1 being Profiles2 but I'm looking for an all in one solution if possible because I seem to be having trouble using multi modules for different tasks regarding this unless someone has a good guide on how to do this?

Thanks

EDIT:

Sorry to reply to my own post, but I have been looking more at Profiles2 and think this may be the best approach, I have created 2 'Rolls' "Personal" & "Business", Now I'm thinking I will create 2 'Profile' types, 1 for each, and a personal roll can only use personal profile fields and business roll for business profile. I think I can do this but its all in my head at the moment, but how could I go about giving the user which type of account they want on registration? (Without having 2 separate registration pages) I can see a way to create 1 page for each type of registration but is there a way that the user can check a radio button for which type of account they want during registration, they will then be displayed with the relevant profile and wont be able to see the other profile type - Do you know what I mean? So just to summarize the user clicks register -> they choose a username and password and then they check a box for which account type they want, (in my case business or personal) once they click submit they have to fill out the profile they chose after their account is activated. Is this possible? Thanks

Yes, Profile2 is probably the best approach there.

However, I don't think you'll be able to switch within a single registration form without custom coding.

To present alternative registration form pages for profile type, you can use the module:

profile2_regpath


Need advise to link a cck field with several values to another cck field I am going to try to explain what I need to do. I have a content type called Goals. This content type has a cck text field. This field can has several values in order to write a goal in each value of the field.

What I want is when a user write a new goal (each goal is a value in the same cck field), he has a list tex field to point if he completed the goal.

How can i do this? What is the best option I have?

After I would like to create I view to show the goals completed and incompleted, so the goal and completed-incompleted must be linked in certain way.

Thanks a lot!

As per your requirement I think you have need to create something like project & the task related to the project. I have done something like this.

For this you will have to create a main content type to hold the project, which will have TITLE & BODY without any other fields.

Create one another content type with reference to first content type. User can add as many task as needed below the first content if permission is given. Add a field named STATUS in 2nd content type, which will hold this COMPLETED or NOT-COMPLETED status of the task.

You can make views of it below the first content type by adding relation between first & second content type & adding the fields by help of the relation.

Let me know if it works in your scenario..


Calling a public function Over time, I have created some contributed module projects for D7. With D7 EOL not too distant in the future, I need to convert those to D8.

I've just started out doing this, and I've found the OO-style of D8 very different from the procedural style of D7.

For instance, I want to call the public function getTopics() that is part of the Advanced Help project. It can be found inside a file src/AdvancedHelpManager.php, and looks like this:

class AdvancedHelpManager extends DefaultPluginManager {
  …

  /**
   * Search the system for all available help topics.
   * @todo check visibility of the method.
   */
  public function getTopics() {
    $ini = $this->parseHelp();
    return $ini['topics'];
  }
  …
}

I want to call it from my module, in order to get hold of the list of topics I expect it to return.

So far, I've tried:

$foo = new AdvancedHelpManager();
$bar = $foo->getTopics();

but this returns the error "Error: Class 'AdvancedHelpManager' not found.

I guess I need to put some sort of "use"-statement on top of the file I try to use it, to make the class visible, but I am currently unable to figure out what that statement should be.

Your current code doesn't work because of namespaces, but even so, that's not the right way to approach your requirement.

AdvancedHelpManager is a plugin manager, which is a service, so you should get the instance of it like so:

$plugin_manager = \Drupal::service('plugin.manager.advanced_help');
$topics = $plugin_manager->getTopics();

(as always, if you're in a context where DI is available, inject the service instead of calling the static \Drupal method).

If any of this doesn't make sense it would be a very good idea to read the Services and dependency injection docs, which help to explain the architecture behind Drupal 8.


Global site variables to be used in node fields and menu item I'm looking for some way of having variable defined by admin which can be displayed in some fields or nodes.

Real use case:
I have that specific date that changes periodically. And I want it to appear in some places, ie. within text of some node body (with possibility of fixing the variable ie. putting some text instead of date, but it's not a matter of my question).

My guess: create some hook to preg_replace all occurences of some string, ie. ##VAR_VARNAME1## with certain fields of nodes or within field texts. But actually I know that it will occur mainly in 2 or 3 places within my website (which is for sure body of one specific node and text of 1 menu item).

Any ideas to make this efficient and quick?

edit: I believe it's easy to do with defining new block.. but how about way I mentioned above..

Try the Custom Tokens extension to the token module. Here is a quote about it (from the module's project page):

... gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.
Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.
The new 7.x-2.x relies on input filters. While still allowing for PHP tokens through the D7 core PHP filter module, administrators can permit only HTML or plain text custom tokens.


Fatal error: Call to undefined function wincache_ucache_get() After downloading fresh files and restoring fresh database from prod website, on my local server (IIS) I have a problem.

Fatal error: Call to undefined function wincache_ucache_get() in E:\XXX\sites\all\modules\wincachedrupal\drupal_win_cache.inc on line 145`

Permissions are good (for IUSR and IIS_IUSR)

settings.php passwords are OK

I updated the wincachedrupal module to newest version

I cannot do anything with Drush (same error as above)

I cannot rebuild the registry

if I delete or change the name of the wincachedrupal module, I get this error:

Fatal error: require_once(): Failed opening required 'E:\XXX/sites/all/modules/wincachedrupal/drupal_win_cache.inc' (include_path='C:\xampp\php\PEAR') in E:\terma\includes\bootstrap.inc on line 2413`

Have you any idea on what can be wrong?

I would assume that this is cache related. Try clearing your cache directly on the database by truncating the cache_* tables (since Drush is not working).

You cannot delete modules by removing them from in your modules folder. You have to disable/uninstall the module first, if you cannot disable the module through Drush or UI you can edit the system table by searching the column 'name' for your module and setting the column 'status' to 0. After that clear your cache again.


Why are variables & CSS loaded in the overlay? This seems really weird to me and makes no sense.

I'm using a custom theme, with Seven as the administration theme (inside the overlay).
Why on earth are variables such as $base_url loaded in the overlay (and produce errors) when I only called them in my page--front.tpl.php (in my custom theme)? The same goes for the CSS; it is messing up the admin theme.

I even renamed my style.css and used drupal_add_css() to call it, but the result is the same.
I don't get why the administrative theme is looking at my custom theme files.

Surely I don't need to add arguments to all the variables, and make my CSS calls more specific, or do I?

There is a misunderstanding on how the Overlay module works.
Suppose you are watching your front page, and you click on a link that opens the overlay. What Drupal will do in that case is:

render the front page using the theme you have set
render the overlay using the administrative theme you have set

The overlay is rendered as iframe using the Drupal.overlay.create() function defined in a JavaScript file used from the Overlay module.

/**
 * Create the underlying markup and behaviors for the overlay.
 */
Drupal.overlay.create = function () {
  this.$container = $(Drupal.theme('overlayContainer'))
    .appendTo(document.body);

  // Overlay uses transparent iframes that cover the full parent window.
  // When the overlay is open the scrollbar of the parent window is hidden.
  // Because some browsers show a white iframe background for a short moment
  // while loading a page into an iframe, overlay uses two iframes. By loading
  // the page in a hidden (inactive) iframe the user doesn't see the white
  // background. When the page is loaded the active and inactive iframes
  // are switched.
  this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement'))
    .appendTo(this.$container);

  this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
    .appendTo(this.$container);

  this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild'));
  this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild'));

  // …
}

/**
 * Theme function to create the overlay iframe element.
 */
Drupal.theme.prototype.overlayContainer = function () {
  return '

';
};

/**
 * Theme function to create an overlay iframe element.
 */
Drupal.theme.prototype.overlayElement = function (url) {
  return '';
};

About the error you are seeing, it is probably caused by the fact you are accessing the $base_url variable without defining it as global variable (using the global $base_url; line).
You should not need to use that variable to generating the URLs for your site, as Drupal has url() and l(); the first function is used to generate a URL, while the second one is used to generate an anchor link, such as Example link.


Cache form Drupal change expire time I made cache_form table work (see How to keep cache_form small). But cache_form, though expired cache is now cleared, is enormous anyway (nearly 2 Gb, and we have only 1000 unique users in a day).  How can I change expire time? Is this caching really needed?

BTW, can you recommend any module for caching handling in Drupal? Seems there are lot of them but mostly obsolete.

Look at the function that's used to save form "cache", form_set_cache:

function form_set_cache($form_build_id, $form, $form_state) {
  // 6 hours cache life time for forms should be plenty.
  $expire = 21600;

As you can see, it's hardcoded and you can't really change it without hacking core. Now the question is - should you?

{form_cache} as cache

Form data is kept as a cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

  In computer science, a cache (/ˈkæʃ/ KASH) is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what {form_cache} is not - it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them.

If you will shrink the time data is kept, you risk all kinds of errors. So keep in mind that your form cache bin should preserve data significantly longer than you expect anyone to need between first form display and the end of it's processing.


How to force Panels to render a node field even when field is empty I have a field that I want to display via the Views Hybrid formatter in a panel pane as a node element. It renders just fine when there is at least one user-selected item in the field, but when there is none, it is treated as an empty field and so none of the view results show either. The whole thing is not displayed just because the field is empty.

How can I force panels to render a node element even when the field contains zero values?

The reason i wanted to render an empty field in a panel was because the views hybrid formatter shows a view when the field is empty.  Instead,  i ended up showing the view via a views pane and making that pane conditional on the value of the field being empty.


Drupal 7 Trying to create a "Today in History" view I'm sure there's an easy way to do the following but I've not come up with a safe Drupal way to do so:

My current front page has a view which generates a list of the most recent three articles on my site using the date stored in  field_published attached to each article. The SQL which the view generates looks like this:

SELECT field_data_field_published.field_published_value AS field_data_field_published_field_published_value, node.nid AS nid FROM node node LEFT JOIN field_data_field_published field_data_field_published ON node.nid = field_data_field_published.entity_id AND (field_data_field_published.entity_type = 'node' AND field_data_field_published.deleted = '0') WHERE (( (node.status = '1') )) ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 OFFSET 0;

( You can see what this looks like live on my website )

Running the query on mysql CLI generates this:

+--------------------------------------------------+-----+
| field_data_field_published_field_published_value | nid |
+--------------------------------------------------+-----+
| 2017-01-23 00:00:00                              | 427 |
| 2017-01-01 00:00:00                              | 426 |
| 2016-08-07 00:00:00                              | 424 |
+--------------------------------------------------+-----+

I want to now create a similar view that searches only the month and day field of every article in the DB, matches the month and day against 'today', and generates a list of article nid. The SQL for this is:

SELECT field_data_field_published.field_published_value AS field_data_field_published_field_published_value, node.nid AS nid FROM node node LEFT JOIN field_data_field_published field_data_field_published ON node.nid = field_data_field_published.entity_id AND field_data_field_published.entity_type = 'node' WHERE (( (field_data_field_published.field_published_value LIKE (select date_format(curdate(),'____-%m-%d%'))) )) AND (( (node.status = '1') ))
ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 OFFSET 0;

This correctly generates a list of article nid on the CLI:

+--------------------------------------------------+-----+
| field_data_field_published_field_published_value | nid |
+--------------------------------------------------+-----+
| 2015-05-24 00:00:00                              | 369 |
| 1999-05-24 00:00:00                              | 222 |
| 1997-05-24 00:00:00                              | 150 |
+--------------------------------------------------+-----+

My question is, how do I get my functional SQL statement into a view?

I have tried using Views Contextual Filters and Granularity, but that does not allow me to omit the year when filtering dates.

I have tried to use hook views_pre_execute in a module but it barfs on my query: Something like

<?php
// TMG 3-21-09
// call to hook_views_pre_execute to override the query for the groups browser
function views_views_pre_execute(&$view) {
   if($view->name=="future_front_page2") {
       $kp_tih = date('____-m-d%');
       $view->build_info['query']="SELECT field_data_field_published.field_pub
lished_value AS field_data_field_published_field_published_value, node.nid AS ni
d FROM node node LEFT JOIN field_data_field_published field_data_field_published
 ON node.nid = field_data_field_published.entity_id AND field_data_field_publish
ed.entity_type = 'node' WHERE (( (field_data_field_published.field_published_val
ue LIKE (select date_format(curdate(),'____-%m-%d%'))) )) AND (( (node.status =
'1') )) ORDER BY field_data_field_published_field_published_value DESC LIMIT 3 O
FFSET 0";
       $query = db_select('node','n')->addTag('node_access');
       drupal_set_message(t($query));

Any suggestions?

Thanks in advance for any advice.

Try to use hook_views_query_alter.

Even though, I think you can do it using only views without altering the query.
Maybe using Date Views module would help.


Live content migration to a separate server for important content My clients are now spending a lot of money daily on creating content on my system. A few hours lost could be quite bad for them, and in turn, for me.

Most of the site is fine on daily backups, but there is a content type I'd like to offload onto a backup server when nodes are created or updated. Is this possible? Preferably sending a node object and related files.

I haven't had an issue in a long time but I'm feeling the stress with their investment.

With the Backup & Migrate module installed, navigate to: /admin/config/development/backup_migrate/schedule to create & manage database or site file backup schedules:

Note that there are options to backup the default Drupal database, all of the site files, or just specific Drupal file directories.

Under "Settings" there is an admin section to configure the destination address for the backups at: /admin/config/development/backup_migrate/settings/destination

Schedule a complete site backup daily with hourly database backups. The Backup & Migrate developers have the NodeSquirrel service available for offsite backups - but this service only works with the D7 module & is unavailable for D8 currently.

With cPanel, there are better options available now with cPanel Backups & Backup Tool:

If you need a more professional backup service, look into Veeam.


Feed Import (Twitter) via Cron I'm using the Feeds Module to import Twitter Tweets as Nodes. As long as I start the import manually via www.yourdrupal.com/import everything works fine. But I want the Feed importer to start automatically every hour. Cron is activated, but nothing gets imported. I get an error on the statuspage "Token and secret MUST be string values."

My Feed import settings:

Protokoll Log:

Feeds Log:

Debugging Info: "No channels ready to be executed, skipping cron."

I would recommend using this sandbox (Twitter Pull) for retrieving tweets instead. I've set it up before and it works quite well. You can see the relevant discussion below.

Errors occured while trying to retrieve tweets


How do I change date format in the submitted line using only template.php without node.tpl.php? Using Drupal 8, I can change the date format, and adapt it to the country.

How can I do the same in a Drupal 7 site, where I do not want to create a node.tpl.php file in my theme since I need fast work?

You can use template_preprocess_node to alter submitted variable. Here is the sample code.

function awesome_preprocess_node(&$variables) {
  $node = $variables['node'];
  $date = format_date($node->created, 'custom', 'm-d-Y - H:i');
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $date));
}

The most important line there is $date = format_date($node->created, 'custom', 'm-d-Y - H:i');. Change the format (m-d-Y - H:i) to any format you want.

See this page about PHP date format.


How can I theme "Error generating image." error 500's in Drupal 7? I wish to theme the error pages generated by the image module in drupal 7, I'm not sure it can be done as this is the code that runs when imagecache fails to generate a style:

else {
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
    drupal_add_http_header('Status', '500 Internal Server Error');
    print t('Error generating image.');
    drupal_exit();
}

I'm not intending on having a whole themed page, but something that isn't quite as ghastly as white screen with just "Error generating image." on it. Rather at least some way for a visiting to navigate away from it and remain on the site if they wish. It would be even better if I could return a 404 instead.

This is of course, without hacking core. So anyone have any ideas or have I missed something?

You can't.

This is hardcoded in http://api.drupal.org/api/drupal/modules--image--image.module/function/image_style_deliver/7.

You would need to completely override this page callback to change what it does. You could do this with hook_menu_alter() but that means that you would need to make sure that you also apply any upstream changes to that function to your own copy.

Can't you just leave the images there instead of deleting them? And if they are just a temporary resource, maybe exclude them from search with robots.txt?


How do I schedule a post in Drupal? I was just wondering how one should go about scheduling a post in Drupal so that it posts at a point in time later then when you are posting? Is it as simple as changing the post time on the author information to a future point in time or is it more difficult then that?

Yes as simple as changing the post time at the point time that you would like to released that post


How to implement a custom field available for Views? I'm making my first steps authoring simple modules. I would like to make my life easier by implementing a custom field for taxonomy views, a field named: "Taxonomy term: Arbitrary ascendant" so that it gets a term's ascendant at the given hierarchy level, as returned by taxonomy_get_parents_all.

Similarly, for content Views, I would like to provide a field configuration that would allow for ascendant tests for any term on an entity.

Could anyone point me to the Views API functions that must be taken into account to make this module properly authored?

Try views.api.php

  Describe hooks provided by the Views module.

& Views hooks

  Hooks that can be implemented by other modules in order to implement
  the Views API.


How can I have conditional content within page body that is dependent upon the domain? We are planning to use Domain Access to manage 5 different domains that will share content.  The majority of our pages will be shared across all 5 domains and will look identical on each domain. Domain Access makes it trivial to handle this use case. However, on some of the pages, 95% of the content will be identical and 5% of the content will be dependent upon the domain that is serving the page.

One possible solution is to create a unique page for each domain and publish it to the appropriate domain.  Although this works, it is difficult to maintain because we would need to maintain changes to the identical content across 5 unique pages.

Another option would be to embed PHP in the page, such as

shared content for all 5 sites here.

<?php if ($_SERVER['HTTP_HOST'] === 'domain1.example.com') { ?>

domain1 specific content here

<?php } else if ($_SERVER['HTTP_HOST'] === 'domain2.example.com') { ?>

domain2 specific content here

<?php } ?>

Again, this would work, but has several disadvantages.  I am looking for a way to share the identical content across the domains and yet have site specific content within a page in a way that makes it feasible to maintain and easy for content editors (non-technical users) to edit. Does anyone have any suggestions?

The sites module has support for multiple domains and managing content across those domains.

https://www.drupal.org/project/sites

If you are using the same template file for the page where you are displaying your content, then you can implement the 'hook_site_access()' from the sites module in the template file, and gather the content you desire to display based on the domain name.

In addition, depending on the type of content you are displaying, you might be able to get away with simply using the Views or Context integration from the Sites module, rather than editing your template file manually.

Another option is to use Drupal's taxonomies to classify your content. Then, you could use any of the solutions above (custom code in page template, Views, or Context) to filter only the content which is categorized to be displayed on the domain you are on.

In any case, if you want two different versions of the same page to display on different domains, you will need two different nodes, and they will need to be classified accordingly. I'm not sure if there is any way around maintaining multiple nodes if the content varies by domain.

However, when the same node is to be displayed on multiple domains, this kind of architecture will allow you to display it only on a specific subset of domains you choose.


How to put the menu above the content? I'm developing a website with drupal 7. I want to put the menu above the content. I use zen theme. How I does it?

#block-system-main-menu {
   float: left;
    top: 0;
    width: 100%;
}
#block-system-main-menu ul.menu
{
float: left; width: 100%;
}
#block-system-main-menu ul.menu li
{
float: left; width: 15%;
}

Use this css.it will help you

Simply put Your menu block above main page content block in same region and that menu will show above the rendered content or other option can be to change the order of the regions in the page.tpl.php file in your theme.


Users can spam votes and users will get userpoints I created the following rule:

Event: User votes on a Материал
Condition: Check the value of the vote, greater than 0
Action: Load points of a user, node:author
Action: Grant points to a user, node:author 1

When a user votes on a node, the node author will get 1 user point. The same user can vote more than once, and the node author would get 1 user point each time.

UPDATE. Solved my issue by myself. Will add link to solution soon.

One simple way to avoid this is to add a rule that removes points whenever a downvote happens. Same rule, different condition (if the value is -1) and different action: Decrease points.


How to create incremented view filters for numeric fields in Drupal? In my Drupal 7 I'm building a view of homes/properties with exposed filters of "Minimum Rent" and "Maximum Rent" - so that people can find homes according to their budget.

Rent (per month) is basically an integer number field and can be whichever number (£475 or £677 or whatever an end user enters when creating the node). But in my exposed filters for "Min Rent" and "Max Rent" I want it to be a dropdown list of £100, £200, £300, £400, £500 etc -in other words, automatically incremented. Exactly as we see on websites like www.rightmove.co.uk or www.zoopla.com or any other property listing website.

How can I achieve this?

If you create a field an select a type of text list using a list widget, you can create the any list you wish for the field.  Then when you expose the field in your view  the drop down list of values will be included in the exposed filter.