"Rendered" View style for a Taxonomy Term? When creating a View for content Nodes, the "Format > Show" options includes "teasers" and "full posts" in addition to "fields". But for Taxonomy Terms, the only option appears to be "fields". I have Taxonomy Terms that have additional fields attached, and have the Display Preferences set to show/hide various fields for a teaser/full display of that term. Since different Taxonomy Terms have different fields, I want to use the Term's configuration rather than hard-code it into the View.

Is there a way to add a rendered View of a Term itself? Or do I need to create a separate View for each Term I want to summarize and define the "teaser" display again in the View?

At "Format > Show" there is an option "Rendered entity".

Apply it and then you can choose term's "View mode" in the select dropdown.

Also you can install Display Suite and notice new option "Display suite" at "Format > Show".


Disable Clean Url in database I am migrating a site from Apache to IIS.

When I backed up the database Clean Urls was active, now my links do not work and I have to add ?q= to them!  Some links work well but the Admin pages are not shown and they display a white screen!

How can I disable Clean Urls?

Also, my images that are customized with ImageCache are not showing!  They return a link to a broken image.

Edit settings.php and add:

$conf = array(
  'clean_url' => 0,
);

Use drush:

drush vset clean_url 0

You can also edit the database as well.


How to add jquery lower version for a particular drupal page? I have installed the jQuery Update module and set jQuery 1.10 as default jQuery version, but one of my previous functionality stop working.

I just want to use jQuery 1.8 for a specific page. How can I achieve this?

Add your condition to remove jquery 1.10 :

function THEME_js_alter(&$javascript) {
if ($your_condition) {
    $path = drupal_get_path('module', 'jquery_update') . '/replace/jquery/1.10/jquery.min.js';
    unset($javascript[$path]);
    drupal_add_js('path/to/jquery1.8');
}


Use views attachment as a block Is there a way to use the views attachment as its own block? I would like to take the attachment from the "Glossary" view and output it elsewhere on my site.

You could try creating a block in a custom module using hook_block_info and hook_block_view. Then use views_embed_view to load the view and display it in your block.

This may look a little like this:

function my_module_block_info() {
  $blocks['glossary_attachment'] = array(
    'info' => t('Glossary Attachment'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function my_module_block_view($delta = '') {
  $block = array();
  if ($delta == 'glossary_attachment') {
    $block['subject'] = t('Glossary Attachment');
    // Load the view.
    $view = views_embed_view('glossary', 'attachment');
    if ($view) {
      $block['content'] = $view;
    }
    else {
      $block['content'] = t('The view is empty');
    }
  }
  return $block;
}


When using custom twig expressions to rewrite view title, the breadcrumb shows the twig expression without replacing it In some of the views, I needed to customize the title using twig. For example {{ title }} which would read the title of the first row in the view result and place it in the page title. This works fine.

The problem is with the breadcrumb. It shows as Some Parent page > {{ title }} without replacing the {{ title }} with its actual value.

I guess a solution could be something along the lines of placing some code in THEME_preprocess_breadcrumb, but I am not sure what to write there exactly. But shouldn't this functionality be something out of the box?

P.S. Not all my views are using {{ title }}, actually some of them are a little more complex, and some views are parents of other views path-wise. So solutions like in this Q doesn't help.

I had a similar issue where I needed my view title to be {{ field_first_name }} {{ field_last_name }}. The head title tag and page title were correct, but the twig variable's value wasn't being rendered for the breadcrumb.

I ended up writing a tiny module in which I get the title then set the title to the title. Somehow, doing this in post_render makes the twig get rendered correctly in the breadcrumb. Hopefully someone will come along and tell us why this works or why it was needed.

?php
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_render().
 */
function peopleview_views_post_render(ViewExecutable $view) {
 if ($view->id() == 'people') {
  $title = $view->getTitle();
  // Set the view title.
  $view->setTitle($title);
  // Set the route title.
  $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
  $route->setDefault('_title', $title);
 }
}


Smart_IP homepage redirect I have a multilingual site. I am browsing from Holland and with the Smart_IP module i am redirecting to the correct language:

http://landberg.at/nl/ or http://landberg.at/de/

My default language is English. But now as user from Holland for example (dutch browser), you are NOT able to switch to the English homepage. This is because the homepage URL in English is http://landberg.at/ >> Then you are automatically redirect to http://landberg.at/nl/

Is there a solution for this?

I don't know the Smart_IP module's mechanism, but I think you should simply solve your problem outside of Drupal: adding an Apache redirection like Redirect "landberg.at" "landberg.at/en". Somewhat brutal but should work...


Drush pm-updatestatus No JSON output on success My sites are running Drupal 7, Drush 8.0.3.

I'm creating a dashboard to check what core and module versions my Drupal sites are running (they're all on the same server). I use a shell script to get Drush to check available updates, write them to a JSON file then my dashboard script reads the JSON file.

/usr/local/bin/drush --root=/home/www/html/www.mysite.com rf
/usr/local/bin/drush --root=/home/www/html/www.mysite.com ups --security-only --format=json > /home/www/html-private/mysite.json

This works fine but the problem I have is that when there are no updates available I get an empty JSON file. How can I tell the difference between this and a failure to write the JSON properly? Can I get it to output 'No updates available' or something so I can tell it ran correctly?

Did you check to see if $? is correctly set? It should be 0 for success, and 1 if there was an error. Please open an issue in the Drush queue if this is not the case.


"Experimental modules found: Place blocks" but I am using core 8.6 I am using Drupal 8.6.2. When I open the status report I see the following warning:

  Experimental modules found: Place Blocks. Experimental modules are provided for testing purposes only. Use at your own risk.

I researched this issue and found that place blocks has been part of Drupal Core since 8.2.

When I check the list of installed modules then I see no reference to a module named place blocks or block-place. I also ran drush pm-list and grepped for place and block. Is it possible that my database contains some outdated dangling reference to this module? How can I clean up my Drupal installation and get rid of this warning?

The module is present since Drupal 8.2, but since Drupal 8.4 it has been marked hidden. That explains why you get the error, but you don't find the module: The module was enabled before updating to Drupal 8.4 or later, and it is still installed; once Drupal was updated to any version after 8.4, the module has been just marked as hidden (without changing its status of installed module).

If you look at the content of the block_place.info.yml file (core/modules/block_place/block_place.info.yaml), you will notice the following lines.

package: Core (Experimental)
version: VERSION
core: 8.x
hidden: true

If you remove the hidden: true line, and visit admin/modules to install a module that you then uninstall, you will see that module listed in /admin/modules/uninstall, and you will be able to uninstall it.
Installing and uninstalling a module is done just to force Drupal to clear the cache it uses to keep the list of found modules. In this case, Drupal will notice the module is not marked anymore as hidden, and it will show it again.


Is it proper to perform a db_update on an entity table? I have a custom entity. During a save operation, under certain circumstances, I need to change the value of a specific field (not field API) of some other entities (of the same type).

If I perform a db_update on the entity's table, is it safe for caches or for any other reason yet unknown to me?

Alternatively, I suppose I could use a rather complicated select query to retrieve the ID's under concern. Then update each entity separately in a loop or batch.

Which causes my second similar question, is it safe to perform a select query in the middle of this operation? Are there any circumstances where entities have different content in memory or DB cache comparing to the DB values?

The thing to look out for is invalidating the correct caches and making sure the correct hooks are called if needed.

When updating entities directly you will need to flush the appropriate caches so the next time the entity is loaded it does not grab the old data from the cache.
entity_load()
 -> DrupalDefaultEntityController::load() {uses a static cache by default}
 --> DrupalDefaultEntityController::attachLoad()
 ---> field_attach_load() {uses the cache_field cache bin}.

Once you have that taken care of you will then need to address any 3rd party modules that use hook_entity_load() or hook_TYPE_load() (hook_node_load()). Odds are you won't have to do anything in here but it is best to double check.

Once loading has been addressed you will need to address the hooks that get ran on insert/update to make sure nothing else is done in a different place that you may not know about. hook_entity_update(), hook_entity_insert(), field_attach_presave(), hook_entity_presave(), hook_TYPE_presave() (hook_node_presave()), etc... You can follow the trail of hooks in node_save() as an example. Once again odds are nothing crazy is going to happen in here, but it is best to double check.

In regards to getting ID's entity_load_unchanged() might be what you are looking for.

Most people will tell you it is not "proper" to update fields in the database directly via SQL queries. This is because 3rd party modules might do something with that data or react to it in different ways; also be aware of modules added after you've done this workaround. In reality you can directly update the database as long as you know the risks and how the code works; most people do not and thus using the API is the best answer.

Now for the interesting part. My guess is you're looking to work around the entity api due to speed issues. There are some ways to fix this. Using a background worker to do the updates is my recommendation. register_shutdown_function() when used in combindation with HTTPRL's threading can help. I don't have a good how-to yet but here is a really quick explanation:

httprl_qcinp - Queue Callback to run In a New Process. This takes arguments similar to call_user_func_array(). I'll use a node as a example.

<?php
hook_node_save($node) {
  // Preform update at the end of this request.
  register_shutdown_function('my_shutdown_function', $node);
}

my_shutdown_function($node) {
  // Load other entity that needs to be updated.
  $alt_node = entity_load_unchanged('node', $node->some_field_reference_nid);
  // Update object
  $alt_node->my_field = 'updated info';

  // Queue background node_save.
  // node_save($alt_node);
  httprl_qcinp('node_save', array($alt_node), FALSE);
  // Run it.
  httprl_send_request();
}
?>

At this point you might not even need HTTPRL; register_shutdown_function might do what you need.

EDIT: Also noted that this is a handy guide for just updating a single field http://timonweb.com/how-insert-and-update-only-specific-fields-your-entity-drupal-7


How to get variables of field from a view in twig? I'm trying to style the title field from a view. So I create this template

views-view-field--frontpage--title.html.twig

And when I was trying to see what variables are avaiable in this template level. I decide to add

{{ kint() }}

And for some reason it showing me this huge error.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: CREATE TABLE {cache_render} ( `cid` VARCHAR(255) BINARY CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.', `data` LONGBLOB NULL DEFAULT NULL COMMENT 'A collection of data to cache.', `expire` INT NOT NULL DEFAULT 0 COMMENT 'A Unix timestamp indicating when the cache entry should expire, or -1 for never.', `created` DECIMAL(14, 3) NOT NULL DEFAULT 0 COMMENT 'A timestamp with millisecond precision indicating when the cache entry was created.', `serialized` SMALLINT NOT NULL DEFAULT 0 COMMENT 'A flag to indicate whether content is serialized (1) or not (0).', `tags` LONGTEXT NULL DEFAULT NULL COMMENT 'Space-separated list of cache tags for this entry.', `checksum` VARCHAR(255) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL COMMENT 'The tag invalidation checksum when this entry was saved.', PRIMARY KEY (`cid`), INDEX `expire` (`expire`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT 'Storage for the cache API.'; Array ( ) in Drupal\Core\Render\RenderCache->set() (line 275 of core/lib/Drupal/Core/Render/RenderCache.php).The website encountered an unexpected error. Please try again later.

I think this might be a Drupal 8 bug, but I'm not sure.

So my question are..

How can I get the variables ? Or at least the field value so I can added wrapper around it.
In Drupal 8, do you think I went to deep on this template ? I notice that using the theme_debug functionality I could not see this template suggestion.

If you do kint(), then it will try to output the raw data from the sql query and that is obviously to much for kint.

In this template there is not much going on and so there is not really much you can inspect with kint:

function template_preprocess_views_view_field(&$variables) {
  $variables['output'] = $variables['field']->advancedRender($variables['row']);
}

You can check the output with

{{ kint('output') }}

But this will only be the field content.

If you want to put a wrapper around the field, that is no problem, that is, what this twig is used for in most cases:

{{ output -}}

If you want to debug the variables, see what variables are available in the view templates, look in core/modules/views/views.theme.inc and inspect them one by one with kint.


Get node author's real name in views or convert username I currently have a content view that displays a list of nodes for a blog. I would like to display the node authors real name (John Smith) at the top, but currently I am only able to display their username (john_smith) by creating a relationship to Content: Author and then adding User: Name.

How can I grab some fields from the node authors user profile?

The fields I need are $field_first_name, $field_last_name, $field_position.

FYI: I realize that there are modules that might be able to fix this problem such as Real Name, but I am hoping to do this without it.

If you don't use any special modules and you have simply added fields to the user acount (on /admin/config/people/accounts/fields then you should be able to add those fields in the Views UI. Just like you do it with all other fields, except that you use the author relationship that you have already created.


How do I pass local settings? The documentation on Drupal.behaviours suggests that local settings can be passed to Drupal's JavaScript behaviors.

Rather than hard coding my series data into my function:

series: [{
    name: 'Jane',
    data: [1, 5, 4]
}, {
    name: 'John',
    data: [3, 1, 2]
}]

how can I pass this series data to my function as settings, directly after the context?

JS code (my_highcharts.js)

(function ($) {

Drupal.behaviors.my_highcharts = {
  attach: function (context, settings) {
    $('#drupal_behaviours').highcharts({
      chart: {
          type: 'bar'
      },
      title: {
          text: 'Drupal.behaviors'
      },
      colors: ['#50b432', '#ed561b'],
      xAxis: {
          categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
          title: {
              text: 'Fruit eaten'
          }
      },
      series: [{
          name: 'Jane',
          data: [1, 5, 4]
      }, {
          name: 'John',
          data: [3, 1, 2]
      }]
    });
  }
};

})(jQuery);

Module code

drupal_add_js(drupal_get_path('module', 'my_highcharts') . '/highcharts.js');
return array('#markup' => '

');

For one thing I would suggest no using #drupal_behaviours as a HTML element ID because it doesn't describe that element in any way.

It would more logically be called #chart or #highchart or something like that.

To add settings you can use drupal_add_js() (there are examples on that docs page) like this (in your custom module in PHP):

// add the series' to a javascript setting.
$series = array(
  array(
    'name' => 'Jane',
    'data' => array(1, 5, 4),
  ),
  array(
    'name' => 'John',
    'data' => array(3, 1, 2),
  ),
);
drupal_add_js(array(
  'moduleName' => array(
    'series' => $series
  )
), 'setting');

Then in the js you can access it like this:

(function ($) {

Drupal.behaviors.my_highcharts = {
  attach: function (context, settings) {
    $('#drupal_behaviours').highcharts({
      chart: {
          type: 'bar'
      },
      title: {
          text: 'Drupal.behaviors'
      },
      colors: ['#50b432', '#ed561b'],
      xAxis: {
          categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
          title: {
              text: 'Fruit eaten'
          }
      },
      series: settings.moduleName.series
    });
  }
};

})(jQuery);

Note how the settings object in the javascript mimics what you passed into drupal_add_js().


Create content in chinese language in drupal 7? I want to create content in Chinese language manually in drupal 7 just by inserting translated text into body, without using any module like internationalization. Kindly suggest any solution ? Do I need to add language support for chines by using 'locale' module ?

See how to install a language on Drupal.org.  After installing and enabling Chinese as a language, you will be able to specify that a node is a Chinese language node when creating/editing it.

There is no risk of data corruption, but in order to avoid problems, never change the default language (as quoted from the documentation).


Pathauto and dynamic branch depth I downloaded the Pathauto module to have the taxonomy aliases generated dynamically. The problem is that the pattern apparently expects a fixed depth, while my taxonomy is not that stiff - some items have one, and some up to 3 branches underway. Can such a scenario be addressed by pathauto?

Well, I'm really surprised such important functionality hasn't been implemented in D7.
Here we go: too much talk, not so much work.
In short: currently there's no token for dynamic taxonomy depth like termpath in D6.


Is referential integrity supported? Does Drupal 8 support referential integrity? Can I tell Drupal what it should do if a parent row in a content type is deleted? For example:

I could tell Drupal not to allow the deletion of a parent row if it has child rows
I could tell Drupal to delete all child rows that belong to a parent row when that parent row is deleted

By row I mean an item of a content type. For example, if the content type is Book, a row is the data about one book.

No, there's no such feature out of the box.

For D7, there is a module for that, but I haven't see a Drupal 8 version: https://www.drupal.org/project/erri.

We did build something like that ourself based on the entity_usage module, we alter the node delete form and display a warning that shows where the node is used.


cron.php failing with errors I have a site running Drupal 6.30 which has started giving errors when it run the hourly call to cron.php.

The cronjob in question is and run as root:

0 * * * * wget -O - -q -t 1 http://example.org/cron.php

I get the following rather cryptic / truncated message when it runs

could not

I have looked in system logs and apache logs but do not see anything that would indicate reason for the problem.

Would anyone be able to suggest anywhere else I could look on the system to troubleshoot.

edit
additional logs from administer -> reports -> dblog around the time the cron fails.

1

mysql_connect() [function.mysql-connect]: Access denied for user 'mann'@'localhost' (using password: YES) in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 7.

2

in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 7.

3

mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /var/www/example.org.org/includes/common.inc(1743) : eval()'d code on line 8.

4

Cron run exceeded the time limit and was aborted.

View watchdog logs at Administer >> Logs >> Recent log entries. (admin/logs/watchdog)

More details in this post Drupal.org: Watchdog: monitor your site


Is there a module? Or: How to alter the Drupal pager to get this? I want to add to alter the output of theme_pager(), and add a <li> tag, as the following:

<li class="pager_go_input last">to <input type="text" id="pager_go_input_1" class="form_text pager_form_go_input" alt="1" value="1">
  page
</li>

How is possible to do this?

Update of the question:

I want to change the Drupal pager to this style: http://www.dedecms.com/knowledge/servers/windows/list_66_1.html. Is there a module? Or: How to alter the theme_pager to get that?
the pager is located at the bottom of the pager. as this displays(首页 1 2 3 4 下一页 末页 the selected downlist 共 4页33条). Compare this to the Drupal default pager. It adds a selected downlist, when selects a page from the downlist, the site then auto redirect to the specific page. The whole count  pager (how many the pager have pages?)  and the count of all the records in the pager.

You need to look at the code above and understand what it is doing. Where does li.pager-last come from? Notice that the last line uses theme('item_list') to build the result and it passes in $items. Just above that you'll see the code which adds an item to the $items array with 'class' => 'pager-last':

if ($li_last) {
  $items[] = array(
    'class' => 'pager-last',
    'data' => $li_last,
  );
}

If you want to add another item after li.pager-last, you might try duplicating these 5 lines and modifying them to do what you want.


Drupal sending SPAM, can't log in anymore My unupdated drupal website has been sending large amounts of spam. I have now blocked the website with HTTP Basic authentication, but I can't seem to get in my admin account of the website. I've tried setting a new hash, but logging does not seem to work, as I don't get any error message when trying to.

Also the password reset function and create new account function do not work, I've tried showing error messages in my template.php file, etc.

Do any of you have any experience with this kind of hack? My Drupal was unupdated and is currently on version 7.15. How do I get back in? Or is it best to set up a new site and transfer the content.

[UPDATE] I have currently updated my drupal system to the most recent version, 7.30. But still no success. I can still not login, even though all the files are renewed. I have also reverted back to the garland theme, but also this theme is not giving me any error messages.

Thanks in advance.

I've managed to log in programmatically using a theme function, explained in this post.

How do I programmatically log in a user?


How do I handle an incoming POST request in a module? I am really new to Drupal but I have to do a project using it and I was just wondering how to handle an incoming POST request in a module:

I am creating a module that will get incoming data from a Webform, process the data by running an R script on it, and then return the result of the R function on the data to the url path specified in the module, but I am not sure at all how to begin handling POST requests - can someone give me some insight? In Webform settings you can specify a URL to send a POST request with the form data upon submission, but if I can figure out how to handle that data I will be golden!

If posting to external URLs is allowed, and given that you are not familiar with Drupal, you can post that data to an external URL where you can write a script using the language / framework you are familiar with and process the data. Especially since you are only looking to process the data with R.

If you want to manage your processing within Drupal itself that is also doable. You will have to write a custom controller in your module, add the route in the module.routing.yml file and then handle the POST data in your controller.

Here are couple of places you can start

https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

How to get $_POST and $_GET parameters


getting error while showing a user online or offline While setting a user online or offline status with the Views module, I get this error message:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) < 30, 1, 0) AS users_node_is_online, 1 AS expression FROM node node LEFT JOI' at line 1

How do I fix it?

I believe the field meh is referring to is provided by the user_stats module. Indeed, once installed it is possible to add that field in a views. There is also a patch for this error on the user_stats issue queue.


How can I edit the search form? I have an OpenAtrium distribution installed on Drupal 6. As you may already know OpenAtrium already implements a search feature. What I'd like to do is change the following form:

by adding another button alongside the Search one (there are other modifications that I'd like to do but it doesn't matter this is just the final goal).

The problem is that I don't know what is the PHP page that builds that form. All I know is that page.header.inc prints the content of that form:

 ...

<?php print $space_tools ?>

 ...

As you can imagine $space_tools contains the entire menu and also the form. But who's the one who builds the $space_tools variable? Is there an OpenAtrium API that I can read somewhere?

This is the result HTML which I'd like to change:

<form action="/openatrium/XXXXXX/" accept-charset="UTF-8" method="post" id="atrium-search-form">

        Search XXXXXXX: *
        <input type="text" maxlength="128" name="search" id="edit-search" value="" class="form-text required fluid">

    <input type="submit" name="op" id="edit-submit" value="Search" class="form-submit">
    <input type="hidden" name="form_build_id" id="form-31ea0a19166f0619050f7ac923ebf331" value="form-31ea0a19166f0619050f7ac923ebf331">
    <input type="hidden" name="form_token" id="edit-atrium-search-form-form-token" value="aaf2e5374720acee5769fcafb6421e35">
    <input type="hidden" name="form_id" id="edit-atrium-search-form" value="atrium_search_form">

</form>

Thank you. Almost forgot, here where I work imgur is blocked by the proxy so I can't tell if the image has been uploaded or not.

EDIT: This is driving me crazy I looked up over the entire OpenAtrium folder for the word "atrium-search-form" and no result at all inside files. How can this even be possible lol? Unless the ID is built upon different variables, in that case I don't know what to do...

It's displayed using the Context module.  I found it like this:

Go to admin/build/context and select the global context

Click the Blocks reaction
Under the Space tools region, Atrium: Search form block is being shown

I then searched for the name Atrium: Search form, and found that the block is defined in the atrium_features module, in functions atrium_block and atrium_search_form of file atrium/atrium.module.

You could modify the search form using a hook_form_FORM_ID_alter hook, such as hook_form_atrium_search_form_alter.


File Field description field default using tokens? Using Drupal 8 File Field and enabling the optional description field works normal.

I want to have a default value populated for the field using tokens from other fields in the content type (to create a standard formatted description).  Is there a way to enable this or must I disable this field and override the twig for the content type to display the desired description for the file link?

Note that this question pertains the optional description field (not the filename - that works perfectly well with the tokens using File (Field) Paths module.)

Good news - it's not that hard!  Here's what you need to do:

Install Drupal Console (if you haven't already): https://drupalconsole.com/
Install the devel module: https://www.drupal.org/project/devel
Enable the webprofiler module (part of devel) drush en webprofiler
Webprofiler adds a toolbar to the bottom of your browser window.  Use this to get the form ID of the form you want to modify.
Use Drupal Console to generate a hook_form_FORM_ID_alter() function.  You'll need either a custom theme or a custom module for this.

Warning: If you're modifying the node edit form, it probably uses the admin theme.  You probably don't have a custom admin theme, so you may want to put this in a custom module.

Customize your function to prepopulate the field the way you want.  Here's what I did:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() on behalf of coit_customizations.module.
 *
 * Provides a default for file description on meeting edit form
 */
function coit_customizations_form_node_meeting_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Check to see if there's already a file description
  $existing_description = $form['field_supporting_documents']['widget'][0]['#default_value']['description'];

  // If there isn't, add the default
  $new_description = $existing_description ? $existing_description : 'Download Supporting Documents';
  $form['field_supporting_documents']['widget'][0]['#default_value']['description'] = $new_description;
}

Don't forget to enable your module!

For further reading:

http://enzolutions.com/articles/2016/02/01/form-altering-will-not-be-the-same-in-drupal-8-after-using-webprofiler/
How to change a field's description using hook_form_alter in Drupal 8?
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.4.x
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_FORM_ID_alter/8.4.x

One last tip: xdebug is very useful for inspecting your form array so you know what to customize.  If you're trying to do this kind of thing and aren't using xdebug, I recommend you check it out.

As an easier alternative, just add this to your function: drupal_set_message($form);


"Route "ctf.content" does not exist" when installing custom module I tried writing my own copy of the skeleton module from https://github.com/sidharrell/D8HWexample.git modules/custom/hello_world, but I thought I'd start by changing the module name and using "ctf" instead of "hello" in the routes. I tried to install the module but I got an exception.

  Route "ctf.content" does not exist

I deleted my module folder from beneath the custom folder and reloaded the page, but I still get this error. The site is now unusable.

Do I need to reinstall or is there an easy way to flush the cache or uninstall the module? I don't have drush installed (yet).

You do need to clear the caches any time you edit routes. The simplest way is from the performance settings page: /admin/config/development/performance.

To change the module's name you'll need to replace every instance of the original name throughout every file in the module.


How do I install Drupal Console to my project with Composer? I am running my Drupal 8 project under Acquia Dev Desktop 2 and just got Composer installed. How can I add the Drupal Console to my project?

You should follow the docs on the official Drupal Console repo on how to install it with Composer. Note that the global launcher is not recommended, it is recommended to add it to your project through Composer.

https://github.com/hechoendrupal/drupal-console/blob/master/README.md

# Change directory to Drupal site
cd /path/to/drupal8.dev

# Download DrupalConsole
composer require drupal/console:~1.0 \
  --prefer-dist \
  --optimize-autoloader \
  --sort-packages

Note that the second command is all one command, not four. The \ tells terminal the command is continuing to the next line.


how to restore the calendar view created by the calendar module? When you install the calendar module a calendar view is automatically created. For some reason it seems that I deleted this view. Now I need to use the calendar module and I need this view.

The version of the module is: 7.x-3.4

I can't find a way to make that the calendar module recreate that view. This is what I did:

1) I disabled the calendar module

2) I uninstall the calendar module

3) I enabled the calendar module again

But the view is not created at all.

How can I have this view restored.

it is very simple.
Go to Home » Administration » Structure » Views and add new view from template.
Yo could see in this section different calendar views.
Regards


What is the correct way to iterate over multivalue items of a form element in D7? I'm sure there is a function to help with this by I can't find it in the API docs. What I want to do is: in a hook_form_alter, iterate over all of an element's items and and manipulate them.

The example form below is from a bean form which has a multivalue field collection called field_listing_articles. I want to iterate over all the instances of that element. They are located in the form under field_listing_articles -> und -> 0, 1, 2 etc

If I do a foreach and iterate over $form['field_listing_articles'][LANGUAGE_NONE] I will pick up all the other (non-numeric) parts of the form at that level. I realise I could put an if is_numeric condition in there but I'm sure there is a more 'Drupal' way of doing this.

Any advice appreciated.

$form
--label
--title
--view_mode
--bean
--actions
--#validate
--#submit
--#parents
--#entity
--field_listing_articles
----#type
----#attributes
----#weight
----#tree
----#language
----und
------0
------1
------2
------3
------4
------5
------6
------#theme
------#field_name
------#cardinality
...etc

element_children() returns any array's key that doesn't start with #, used for properties in form API arrays, and in rendering arrays. It doesn't return numeric keys, as the function would pass to your code an array key such as "item", for example.

Instead of using the constant LANGUAGE_NONE, I would use field_get_items(), which returns the values for the language currently set for the field, which could not be for the LANGUAGE_NONE language.


How to configure a different main menu for each language on a multilingual site? I have set up multilingual options on my site, and have a lot of pages in two languages.

I can't work out how to have a different main menu for the two languages. Under Structure->Menu->Settings, it says "Source for the Main links", and I'm adding all menu links to the "Main menu" there. However, this means I just get one big menu with all the items in both languages.

What I want is when the page is in English, the main menu is in English, and when in Chinese, the main menu is in Chinese. How to set that up?

Make sure the i18n Menu Translation sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there it should be possible to select the translation mode you want, e.g. Translate and Localize.

After doing so, when editing a menu link, there should be a new link Translate to actually translate the menu entry. Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

translations of blocks, which requires the Block Languages (i18n_block) submodule to be enabled.
translations of taxonomies, which requires the Taxonomy Translation (i18n_taxonomy) submodule to be enabled.


Ajax'ed file field doesn't find the form constructor function on rebuild I'm manually printing the user profile form in a block using:

module_load_include('inc', 'user', 'user.pages');
$form = drupal_get_form('user_profile_form', $user);

That works great for displaying and submitting the form.

The form has an image field to add a picture. When I try to upload the picture through Ajax, I get a PHP notice that drupal_retrieve_form() is missing the form constructor function (user_profile_form()), and the image field isn't being shown anymore.

I'm guessing the image field's Ajax doesn't know about the user.pages file that I included, and can't find the form.

Any idea how to fix this?

You will need to include file by using the $form_state['build_info']['files'] array.

For example:

$form_state['build_info']['files'][] = drupal_get_path('module', 'user') . '/user.pages.inc';


Custom field validation condition not working I have created a custom form validation.

I am using webform module to build the form.

in _achva_tz_validate function there are two fields that have the same validation.

The second field, zug_id, is shown only if the user selects family_state  value to 1. if family_state is not 1 the zug_id field is hidden.

The issue is that the zug_id validation is not fired.

I am looking for a way to fire it only if
$form_state->getValue('family_state') === 1

this is the module_name.module code:

// DEFINE TZ RETURN VALUES
define(TZ_ELEGAL_INPUT, -1);
define(TZ_NOT_VALID, -2);
define(TZ_VALID, 1);

function ValidateID($str)
{

    //Convert to string, in case numeric input
    $IDnum = strval($str);

    //validate correct input
    if(! ctype_digit($IDnum)) // is it all digits
        return TZ_ELEGAL_INPUT;
    if((strlen($IDnum)>9) || (strlen($IDnum)<5))
        return TZ_ELEGAL_INPUT;

    //If the input length less then 9 and bigger then 5 add leading 0
    while(strlen($IDnum<9))
    {
    $IDnum = '0'. $IDnum;
}

    $mone = 0;
    //Validate the ID number
    for($i=0; $i<9; $i++)
    {
        $char = mb_substr($IDnum, $i, 1);
        $incNum = intval($char);
        $incNum*=($i%2)+1;
        if($incNum > 9)
            $incNum-=9;
        $mone+= $incNum;
    }

    if($mone%10==0)
        return TZ_VALID;
    else
        return TZ_NOT_VALID;

}

function achva_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    switch($form_id){
    case 'webform_submission_qyt_qlyth_mwrwt_mmnwt_wqdmyh_kyt_add_form':
        $form['#validate'][] = '_achva_tz_validate';
        break;
    default:
        $form['#validate'][] = '_achva_tz_test_validate';
        break;
    }
}

function _achva_tz_test_validate(&$form, $form_state) {

    if(ValidateID($form_state->getValue('idno')) !== 1) {
        $form_state->setErrorByName('title', t('Please enter a valid ids number'));
    }
}

function _achva_tz_validate(&$form, $form_state) {

if(ValidateID($form_state->getValue('idno')) !== 1) {
    $form_state->setErrorByName('idtitle', t('Please enter a valid id number'));
}

if(ValidateID($form_state->getValue('zug_id')) !== 1 && $form_state->getValue('family_state') === 1) {
    $form_state->setErrorByName('zugidtitle', t('Please enter a valid zug id number'));
     }
  }

You anyway have a problem here:

//If the input length less then 9 and bigger then 5 add leading 0
while(strlen($IDnum<9))
{
$IDnum = '0'. $IDnum;

}

it should be:

while(strlen($IDnum)<9)
{
$IDnum = '0'. $IDnum;

}


Migrate existing content types to MongoDB I have a "Company" content type that has about 30 fields that I'd like to migrate over to MongoDB (field_sql_storage to mongodb_field_storage).

Would anyone know of a great way to do this?

I have about 150,000 nodes and it's starting to get slow in MySQL.

Thanks!

Sure - you want to use the Migrate module to map your fields from a datasource (ex. CSV file) into your new MongoDB. Moshe has a post on this, more related to performance of his method for Amazon RDS but there is an example module that extends the Migrate API to pull the data from a CSV file into his MongoDB database. The relevant include file is here (maybe a little to long to include on stackoverflow?).

To get your data out of the content-type into a csv dump, I would recommend using Views Data Export.


Organic Groups module  messes up node editing Updated header to reflect real cause of problem

I've created some content types using node references for "belongs to" or "owned by" relationships.

When I add a new node, selecting the node references seems to work fine, and the default "list view" showing the newly created nodes also shows that the relationsship is correct. However, when I try to view or edit a single node, the form displayed includes only the "Title" field, and nothing else. I've also verified through "Manage fields" and "Manage display" that my node reference field is supposed to be displayed, but it still does not seem to work.

Do you have any ideas?

Just figured out that the problem was not caused by the references module, but by the "Organic Groups" (og) module. It seems to be a known bug in the organic groups module that basically hides/disables all fields for custom content types that are not marked as group or something like that. There's a report about this in http://drupal.org/node/1029230.

Disabling the organic module make the fields come back again, and even relationships seems to be editable again. I can live without organic groups for now, and considering the severity of the bug I will definitively not try to use that module again until it has been fixed.


How can I suggest a template file specific for a content type? In Drupal 8, is there a way to get html.html.twig to only show on a content type like html--blog.html.twig? The suggestions in the debug don't seem to give me that option.

<!-- FILE NAME SUGGESTIONS:
   * html--node--1222.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

You can do this with a theme suggestions alter hook:

/**
 * Implements THEME_theme_suggestions_html_alter().
 */
function MYTHEME_theme_suggestions_html_alter(&$suggestions, $vars, $hook) {

  // Check to see if you are on a node.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Get the node type.
    $type = $node->getType();

    // Create the theme hook suggestions.
    $suggestions[] = 'html__' . $type;
    $suggestions[] = 'html__node_' . $type;
  }
}

Of course, change "MYTHEME to your theme name. I tested this on a blog content type for example and the new template suggestions printed out after creating this hook and clearing cache.

<!-- THEME HOOK: 'html' -->
<!-- FILE NAME SUGGESTIONS:
   * html--node-blog.html.twig
   * html--blog.html.twig
   * html--node--15.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

The new theme hooks here are:

  * html--node-blog.html.twig
  * html--blog.html.twig

The content type name will change accordingly in the naming suggestion.

To test, I copied html.html.twig and named as html--node-blog.html.twig and it worked great.


How do I add administrator approval on webform submitted data? I have the functionality that when any anonymous user submits a webform, then I display the submitted webform data in my new page, but I need admin approval before that submitted data displays on another basic page in Drupal 7.

Does anyone know about admin approval for webform submitted data?

Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Content Approval module.

  a module that enable the approval of a content (node) by an
  administrator prior its publication (like the existing feature for
  comments).


Cann't delete the CSV file after imported by Feeds module We uninstalled the "Feeds" and "Job Scheduler" modules, after a successful imported csv data by Feeds. However, the csv file is still maintained in "media" list. When we try to delete that file, it say "The file xxx.csv is in use and cannot be deleted". Is there a way to delete that, or do we have to delete from FTP?

The "file still in use and cannot be deleted" means Drupal's still managing the file, so don't remove it via FTP because that basically bypasses Drupal and could cause other issues related to Drupal expecting a file to be somewhere and it's suddenly not there. So I'd recommend finding a solution that involves working via the UI and not directly on the file system.

Is the file attached as a field to an item of content somewhere? That would result in "file still in use". If so, delete the item of content, clear cache a few times and check again.


How to list blogs by anonymous in blog module I am able to list blogs by a specific user, e.g. /blog/123 - where 123 is the uid, but when I use /blog/0 I get access denied.

Can someone advise on a config setting to enable /blog/0 to list blogs by anonymous user (i.e. uid = 0), please?

I could implement a hook or override the View or something, just wanted to check if there isn't a config setting somewhere. I couldn't see one, looking so far.

The blog route blog/%user_uid_optional route provided by the blog module performs a few checks in blog_page_user_access():

  // The visitor must be able to access the site's content.
  // For a blog to 'exist' the user must either be able to
  // create new blog entries, or it must have existing posts.
  return $account->uid &&
         user_access('access content') &&
         (user_access('create blog content', $account) ||
          _blog_post_exists($account));

The $account->uid part of the conditional check will preclude access to blog/0 even if anonymous users can create blogs posts.

A module evoking hook_menu_alter() you can override this route behavior by providing your own access callback that excludes the $account->uid check:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog/%user_uid_optional'])) {
    $items['blog/%user_uid_optional']['access callback'] = 'MYMODULE_blog_page_user_access';
  }
}

function MYMODULE_blog_page_user_access($account) {
  return user_access('access content') && (user_access('create blog content', $account) || _blog_post_exists($account));
}


Generate only parent taxonomy terms in a block I need to generate a menu for parent taxonomy terms.

How would I go about doing this? I'm also looking to generate these terms in a block.

I have a views set up right now that displays just all taxonomy terms. I can't figure out how to filter out child terms. Is there a filter for this, or do I just have to manually create each category item?

In Drupal 7 to only show parent terms you add a “Contextual Filter” and add “Taxonomy term: Parent term,” then set “Provide default value” to a “fixed value” of 0.

That will filter out the child terms.


Is it possible to make summary mandatory? For a given content type is it possible to make creating a summary mandatory?

Short Answer

Yes, you can require the summary field be populated before it can be sumbitted.

Details

Implement hook_form_FORM_ID_alter() in a custom module.

hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['body'][LANGUAGE_NONE][0]['summary']['#required'] = TRUE;
}

This assumes that you are taking the standard "body" field and requiring that it's summary be entered before submission.


Create Custom Date Formatter for Date Posted Field I followed a very helpful article by Antonio Benitez that gave some example code showing how to create a custom date formatter for date fields (How To Create a Custom Format for a Date Field). The code adds an additional format option in the manage display settings page. This works great for date fields I have created (such as an event date for an event content type) but it is not applying to the existing date fields such as the node posted date. How can I make this custom formatter apply to system date fields such as the posted date, so that it appears as an option on the manage display page as well?

I am reproducing the code Antonio posted in his article here:

/**
 * Implements hook_field_formatter_info().
 */
function custom_module_field_formatter_info() {
  return array(
    'custom_date_format' => array(
      'label' => t('Custom date format'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function custom_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $element = array(
      'element' => $item,
      'field' => $instance,
      'display' => $display
    );
    $elements[$delta] = array(
      '#theme' => 'custom_module_formatter_' . $display['type'],
      '#element' => $element,
      '#field' => $field,
    );
  }

  return $elements;
}

/**
 * Implements hook_theme().
 */
function custom_module_theme() {
  $themes = array(
    'custom_module_formatter_custom_date_format' => array(
      'variables' => array(
        'element' => NULL,
        'field' => NULL,
      ),
    ),
  );
  return $themes;
}

/**
 * Implements theme function
 */
function theme_custom_module_formatter_custom_date_format($vars) {
  $element = $vars['element'];
  $field = $vars['field'];

  // Configure custom date
  $format_date = 'd M';
  $timezone_bd = date_get_timezone_db($field['settings']['tz_handling']);
  $publish_date = DateTime::createFromFormat('Y-m-d H:i:s', $element['element']['value'], new DateTimeZone($timezone_bd));
  $date = format_date($publish_date->getTimestamp(), 'custom', $format_date);
  $date = explode(' ', $date);

  // Declare array for render content with custom format and tags
  $render_array = array(
    'date' => array(
      'date-day' => array(
        '#prefix' =>'',
        '#markup' => $date[0],
        '#suffix' => ''
      ),
      'date-month' => array(
        '#prefix' =>'',
        '#markup' => $date[1],
        '#suffix' => ''
      ),
    ),
    '#theme_wrapper' => array('container'),
  );

  return render($render_array['date']);
}

In Drupal 7, the created and updated "fields" on nodes (and other entities) are properties and not proper fields.  The display values for these are created in the default template_preprocess_node() provided by core, which some theme and modules may override.

Note these lines:

$variables['date'] = format_date($node->created);
...
// Display post information only on certain node types.
if (variable_get('node_submitted_' . $node->type, TRUE)) {
  $variables['display_submitted'] = TRUE;
  $variables['submitted'] = t('Submitted by !username on !datetime', array(
    '!username' => $variables['name'],
    '!datetime' => $variables['date'],
  ));
  ...
}

So, if you want to change how this is displayed, you need to implement your own template_preprocess_node() (you can do this in a theme or module), and provide your own logic.  You can either update the existing variables, which will allow the existing templates to be used, or you can add new variables and also provide your own node templates.  Typically, I do the later.


How to write a partial "setRebuild"? I created a custom module which contains a Class Form. When I submit my form, I redirect the user to the form page. During the submission, I need to save a form_state variable to re-use it after the user is redirected to the form.

So, from my submit method, I save my variable (with "$form_state->set(...)" ) and I add "$form_state->setRebuild()".

All works perfectly. Now, I want preserve my variable AND empty some field's form. I don't want to preserve values of all fields of my form after the user has been redirected.

I tried this :

// From my buildForm
// ...
$form['test'] = [
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

But I have this error when I use the setValueForElement method :

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to
  Drupal\Component\Utility\NestedArray::keyExists() must be of the type
  array, string given, called in
  /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in
  Drupal\Component\Utility\NestedArray::keyExists() (line 259 of
  core/lib/Drupal/Component/Utility/NestedArray.php).

I don't understand where my mistake is, use the setValueForElement maybe not the better way?

Edit (after Ismail Cherri's answer)

This is my new code : ("$form['#parents'] = array();" added)

// From my buildForm
// ...
$form['test'] = [
  '#parents' => [],
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

I keep the same error when I submit my form...

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to
  Drupal\Component\Utility\NestedArray::keyExists() must be of the type
  array, string given, called in
  /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in
  Drupal\Component\Utility\NestedArray::keyExists() (line 259 of
  core/lib/Drupal/Component/Utility/NestedArray.php).

Can you please try adding this to your buildForm() method:

$form['#parents'] = array();

According to documentation: FormStateInterface::setValueForElement
You need to pass an array() and set the parents array for the form element.
Hope this helps.

UPDATE
After revisiting the documentation, can you try this code:

$form_state->setValueForElement($form_state->getValue('test'),"0");


Content profile fields on registration form by role I have two main users roles: authenticated and agent.

First role uses content profile fields on registration form.

Users with the agent role can only be created by admins but agent doesn't need content profile fields.

In user_add_form the content profile fields is added as well so the admin must fill them.

How can I disable those fields when an admin want to create user with the agent role?

You can use hook_form_alter to alter the form. This is how the profile fields is added and they can be removed this way as well.

You have to make sure that your custom module is run after the profile module, which may require that you alter the weight of the module. This is merely a value in the system table.


Drupal 6 Core Update Not Updating I am running Drupal 6 and have attempted to update the Core about 5 times recently, and it continues to tell me I haven't updated it. I AM running update.php, and doing it the way it's always worked before. But Drupal is not perceiving that I've done it.

No problems with individual modules updates. Drupal and following a procedure I've followed numerous times before, successfully. Not using Drush, but am using command line.

Its better to use drush.

Goto your project source folder from terminal.

Use the following command to upgrade.

drush pm-update projects

Ex: root@karthik$ drush pm-update projects drupal-6.34

This will update your drupal core to 6.4 version.


Views 3: display "block" doesn't show full node I would like to show full node including comments in views. Everything is ok if I choose display "page" but in case of "block" all comments disappear from the view only content and link "add comment". What is wrong in my case and how to correct it? I need a block with full node content including comments.

My parameters in views:

Format:
Format: Slideshow
Show: Content; All (I also cheked "show comments" and "show links")

Thanks in advance

When you select teaser view instead of full content you can see comments in your block.

If you see implementation of comment_node_view() comments are displayed only in node lading pages.

if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

If you enable the same block in node landing pages you can see the comments in your view.

If you enable the block other than node landing pages, then you cannot see the comments because of node_is_page($node) condition i think.


Automatic creation of Product Display for Drupal commerce? Is there any way to automatically create a Product Display when I create a Product with the commerce module. The product display should references the product.

I'm thinking of using rules to accomplish this but not sure.

My client finds it complicated to create a product and then a product display.

Should I go with Ubercart module to accomplish this?

If your products and products display has a 1 to 1 relationship, you could use views to display your products instead. You also could do it with rules or custom code. Rules allow to create entities so it's all a matter of filling out data on the product display node with the product date.

The idea behind product displays is that you want to display multiple variants or related products. An example would be to display the variations in size, color, material etc and from the same node be able to select the product I want.

IMO you should go for Commerce and not ubercart. It's far more flexible and powerful. It's also better integrated with Drupal 7 features and the main modules in Drupal like, Views, entity, rules, and is doesn't have the history of legacy code that needs to be supported like Ubercart does.


Block displaying in 'content' region of admin theme? The below implementation of hook_block_info renders a block in the 'content' region of my theme. Unfortunately, it also appears in the content region of the administrative theme. The documentation states:

  properties: (optional) Array of additional metadata to add to the
  block. Common properties include: administrative:

  Boolean that
  categorizes this block as usable in an administrative context. This
  might include blocks that help an administrator approve/deny comments,
  or view recently created user accounts.

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['diary'] = array(
    'info' => t('Diary'),
    'properties' => array('administrative' => FALSE),
    'weight' => 1,
    'status' => TRUE,
    'region' => 'content',
  );
  return $blocks;
}

However, my block is still appearing in the 'content' region of the administrative theme?

According to this comment, you can also specify the theme. I haven't tried it -- let us know if it works!

  There's also a theme key-value pair:

'exposed_order' => array(
'info' => t('Exposed commerce order filter'),
'theme' => $admin_theme,
'region' => 'content',
'pages' => ORDER_MENU_LINK,
'status' => 1,
'visibility' => 1,
),


Enabling Clean URLs on website-in-progress I host my site and a few others through Hostgator. When I build a new Drupal site as a replacement for an existing site at a different host, I build it on the IP address (192.xxx.xxx.xxx/~username) or on the corrado (Hostgator) url (corrado.websitewelcome.com/username). In both cases, I cannot activate Drupal's "Clean URLs" feature. Once the site is built and we are ready to point the domain name to the new site (and we do so), Clean URLs works fine. It is an issue, though, while I am still building the site, because I have to use absolute URLs in the CSS and the various content blocks for the links and images to work correctly, and that creates extra work during the website activation process where I have to go back in and remove all of those absolute URLs. I have tried modifying my hosts file so that the site's existing URL will resolve to the Hostgator IP address for that new site-in-progress, but this isn't enough to "fool" the Clean URLs function.

I already reached out to Hostgator support, and they did not have a solution for me. Any ideas on how I can work around this issue and get Clean URLs to work in this environment?

You can use relative css as long as you are pointing to files within your theme. That will work like this. url('img/image.jpg'); So no need for full url's here.

More explanation here: http://css-tricks.com/quick-reminder-about-file-paths/

At template level you might want to use drupal_get_path to point to the various modules and or themes.


How do I enable the "print PDF" link on only a specific page? I have enabled the print module and configured the basic page content type to show a PDF print link under the basic page settings.

On the print module's Links settings page at admin/config/user-interface/print/ui, under the  Advanced Link Options heading, I can specify the paths where I want to show a PDF print link.

But it is still showing a "print PDF" link on all basic pages.

I also tried by disabling the print setting under basic page settings, and only entering the path under print links settings, but then it disable the pdf print link from all basic pages -- even from the one I want it to show up on.

Check the Link options section at admin/config/user-interface/print/ui, making sure you don't have 'content corner' selected.


Organic Groups admin has can't edit roles and permissions in groups I have a user who is an "administrator member" of a group called "Fancy group".

"Administrator members" of this group have permission to administer roles and permissions within the group.

but my user, an administrator of Fancy group, can only view the roles and permissions, not administer them:

Is this a bug in OG or am I doing something wrong?

The problem is probably that the group doesn't have it's own role/permission settings. It's using the global og roles/permissions, and so the settings within the group are all read-only.

One of the fields you can add to group entities via the OG Fields settings is a "Group Roles and Permissions" field. Once that field is added, you can edit the group entity and set the field to "Override default roles and permissions".

Once that's done, the group will have it's own permissions, and users within the group who have permission to edit the groups permissions will be able to.


CAPTCHA on custom form I have a client where they have an integrated form from another website.  For some reason the Drupal 7 captcha module will not work on this form when entering it into captcha settings.  The form id="contact-form" and then in the captcha setting I put contact_form.  This works on any other form that is either created with webform or and drupal module but will not work when the custom form is put into the content section of the page.

Any ideas?

You must create form with FormAPI, then the form is avalable for Captcha as you say "contact-form" -> "contact_form". If the form is embeded whatever other method like iframe, then the form must already contain integrated own captcha. This also applies when form is build without FormAPI - using  in client's site.


How to create flagged nodes views that show up to colorbox using custom link I Have flagged nodes, but because there are many flagged list with user, I want to show flagged list if user click on the text link as I describe on the picture. How to figure out this stuff?

Check the "Enable Colorbox load" option in Colorbox settings.
Create a page view that lists the flagged content with path of /flagged/%
Add Contextual filter of Flags: User UID

Now in your table view:
Add User ID field, and checkmark hide from display.
Add Custom text field to view
Click here to show.


Create a menu item with subitems How can I create a menu link for main-menu which has related subitems?

For example in main-menu I have Home  About  Products and for the Products menu item I want it to put all categories as subitems: Products -> Shoes -> Shirts ...

Is there a hook or an example so you can achieve this?

You can create a menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module. You can also set up new menu items and strcutre through Drupal's admin menus management (admin/structure/menus)


How to access the request in REST API I'm trying to follow the example of a custom rest api in https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources.

I don't understand how I can access the request for get or post. In the example there is only a default response, but I would of course like to make it depending on the request headers and body.

The only classes that extend ResourceBase implemented by Drupal core don't check/use what passed in the request. So I could not use Drupal core code as example.

If you really need to access any request value, and the argument passed to the get() or post() methods is not enough/adequate for your purpose, you can inject the request object in the create() static method.

  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Request $request) {
    parent:: __construct($configuration, $plugin_id, $plugin_definition,  $serializer_formats, $logger);
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('request_stack')->getCurrentRequest()
    );
  }

In the class methods you then use $this->request to access the request object.


Hierarchy in entity reference view display I have a hierarchical taxonomy vocabulary of page categories:

Category A
  - Category A1
  - Category A2
Category B
  - Category B1

I would like to list some of them (conditionally) as options on my Page content type. For that, I am using an Entity Reference field, with the "Views" reference method.

I created a Taxonomy view with the Entity Reference display for that, but this way, the categories display as options without hierarchy:

Is there any way to selectively display taxonomy terms as field options on a content type, maintaining the hierarchy?

I just came across this question, because I had the same issue. The solution I've found is to use a Relationship; no extra modules required.

Add a Relationship and choose "Parent Term". Check on "Require this Relationship" in the dialog box.
In the "Filter Criteria" section of the view, add the "Term" field (NOT the "Parent" field*). If you want, you can choose to show the hierarchy in a dropdown, in prep for choosing the term in step 4.
Choose the created Relationship in the "Relationship" field of the filter dialog box.
Choose the Parent term in that same filter dialog box (to use your example, say "Category A").

Now your view should output only the children of that parent term. (Again, using your example, if you chose Category A, your view would output:

Category A1
Category A2

*there is a "Parent" field in the Filter field options, and it seems intuitive to use that, but using that only outputs the top-level hierarchy of the Taxonomy, even when combined with an AND with the Taxonomy field. Maybe a bug?


Changing colors of drupal tables I noticed that drupal always use grey as background and line color with tables.

I prefer to avoir modifying the code of my template. Is there any way to modify the ugly grey drupal tables ?

There are a couple of ways to do it. Here are two of them:

 Through your theme

write your own mainstyle.css file.
place it in your active theme directory (directly or in a folder that you create there)
go to that theme directory and open the file: [themename].info (e.g. bartik.info or myAwesomeTheme.info)
add stylesheets[all][] = mainstyle.css after the existing stylesheets. (or stylesheets[all][] = css/mainstyle.css if your stylesheet is placed in a folder called 'css').
flush your cache

This way drupal will include your stylesheet.

 A simpler way to do it , with the help of a module, so that you don't touch any of your files, is

download the module  css injector
enable the module
go to configuration -> development -> css injector (admin/config/development/css-injector)
create a new rule and give a name to the rule: e.g. table styling
Finally in this rule write your CSS  e.g. td {background-color: red;} etc

Tip: If you want to target your elements (e.g. tables) correctly, then you may need firebug, which is an extension for Firefox.


Views Contextual filter using two terms, one assigned to node and one not I have a view which uses TID from a single vocabulary as a contextual filter to create a dynamic slideshow.

This slideshow is displayed on nodes of a specific content type ("Landing Page"). The images for the slideshow are loaded from another content type ("Slideshow"). Both are tagged with terms from a common vocabulary with only one level.

The slideshow then displays all images tagged with the same term as the current landing page. This bit is working as intended.

However, I also want all slideshows to include images tagged with another term from the same vocabulary. This term has not been assigned to the landing page.

So, I'm looking for a way to achieve something like this:

Show all images tagged with the TID from the current node AND all images tagged with term 58.

Term 58 is static and will not change.

I've tried all manner of configurations with no luck. I figure I could use some PHP code in the contextual filter but haven't been able to find anything similar that would help. Worse case scenario is I create a separate display in the view for each term but that just seems inefficient.

Thanks

David

You can use relationship settings to add in the taxonomy, and then add field to also add items tagged with that Term into the slideshow.

Something like this:

Edit your view and add a relationship (3rd column on right) for
Content: Taxonomy terms on node

Then under your filters add:

"Taxonomy term: Term" and Select the term that is 58

I just did a test with a sample view and results were as expected, it showed me all the items for that node plus the specific term.


Node template.tpl.php for custom view mode? I tried this http://www.fredparke.com/blog/using-custom-template-files-different-display-modes-drupal-7, but doesn't work, gives errors and tried this How to provide template for particular view mode? kind of works, but gives errors.

My content type is product_display and view mode is Product List, created with display suite. I need this, so I could delete h2 title from it, because views forces title output via rendered entity format no matter what.

Errors I get are either Notice: Undefined index: product_display in mytheme_preprocess_node() (line 170 of /template.php).

or this http://i.imgur.com/a26bQeX.jpg

You need theme_hook_suggestions.

    /**
     * Implements hook_preprocess_node().
    */
    function MYMODULE_preprocess_node(&$vars) {

      if ($vars['type'] != 'product_display'){
         return;
      }

      if($vars['view_mode'] == 'product_list'){

        $vars['theme_hook_suggestions'][] =  'node__' . $vars['type'] . '__' . $vars['view_mode'];
      }

  }

Now you will be able to use: node--product_display--product_list.tpl.php

Make sure you have to change MYMODULE.

If you want to use it from template php then use following code. I also assume you use zen theme:

function template_preprocess_node(&$variables) {
 if ($variables['type'] == 'product_display' && $variables['view_mode'] == 'product_list'){
// looks for node--node_type--view_mode.tpl.php in your theme directory
   $variables['theme_hook_suggestions'][] =  'node__' . $variables['type'] . '__' . $variables['view_mode'];
 }
}


display newly added field value of account settings I added a new field(First name) in Account settings under Configuration & its machine name is 'field_first_name'
I am trying to load this value in home page like this

<?php print $user->field_first_name ?>

But the above code is not working. Please help. I debug $user and found that this value isn't there. What should I do to show the value of the newly added field in home page.

I've added screenshot.

You should use field_get_items:

global $user;

$user_contaning_field = user_load($user->uid);

// Check if we're dealing with an authenticated user
if ($user->uid) {

  // Get field value from $user
  $field_first_name = field_get_items('user', $user_contaning_field, 'field_first_name');

  foreach ($field_first_name as $key => $value) {
    print field_view_value('user', $user_containing_field, 'field_first_name', $field_first_name[$key]);
  }
}


How to show one field in more than one regions? I'm using Drupal 7. I have used two column stacked layout to display Node Fields. I created one Rating Field and I showed it in top region. I want to show the same field in bottom region also. How can I show the same field in bottom region?

You can achieve this using Dynamic fields in Display Suite Module. Check this ans.

Please find the detailed steps below to achieve this:

Navigate to Manage Display page of Content Type and click on "Add a Dynamic Field".

Add Unique Label (e.g. "Duplicate Field") to Field and Select valid Entities (e.g. "Node") based on your requirement.
Click on Save.

This will create a Dynamic Field and Display on Managed Display page of Entities you've selected.
Re-position newly created field (i.e. Duplicate Field) into another region, say as Footer and click on Settings icon as shown in screenshot.

This will open a display settings for this field. Click on Select Content, to select the field you want to display the content of.

From left menu, select Node and then click on Node field (e.g. "Field: Body (body)").

On next screen, change settings based on your requirement for displaying label, display formatter and click on Continue.

Click on Finish

Now you need to tell Display Suite that I've selected field and attached it to Dynamic Field by clicking on Update Button.

This will show a preview of Field Name, you've attached to Dynamic field.

Click on Save of Manage Display Page.


Migrating from Drupal 7: source database does not contain a recognizable Drupal version After looking at this issue, it appears to be my schema_version. How and what do I need to change about the table to get it recognizable as a Drupal version?

I was able to solve this after putting in the correct prefix.  This issue on drupal.org was very helpful: https://www.drupal.org/node/2637870

The correct prefix for anyone with a similar problem is shown here: http://i.imgur.com/MKf6CuG.png


Menu add item or edit item not available for users with admin rights I'm working on a Drupal core 6.26 website and I'm unable to debug or find an answer for this problem.

I have a group of users, let's call it GroupTest that has permissions enabled for administer menu.

When trying to edit a menu item or add a menu item with a user from GroupTest group, the add item / edit item form (actually just the fieldset Menu settings) is hidden by an inline "display: none;" style. The only thing visible is the save button.

However, this doesn't happen when I'm using the admin (1) user. The form is displayed just fine.

I've tried different approaches to debug this, looking for hook_form_alter in custom modules/themes that might be modifying this, even for javascript code that would hide the form.

Any help or hint would be greatly appreciated.

Do you have any custom/forked modules installed on the site? Themes?

Try changing the theme; if it works with another theme (let's say Bartik) then the problem is somewhere in your theme.

If the above doesn't work, clone the site and start disabling the modules one by one; eventually you will find the one which is causing the problem.


Attaching Google PHP Library to custom module How do I use an external PHP package in my own module?

This is the one I want to use: https://github.com/googleads/googleads-php-lib

I have some questions

Where should i put the library?
Where should i declare the library?
Should i include something like use

Thanks in advance

I advise using composer to do this.

First, you need to pull in the library:

composer require googleads/googleads-php-lib:dev-experimental

The reason you want the experimental branch is it has added PSR-4 support and namespaces to its various classes. The master branch does not have these changes.

Then, to use any of the classes in your own class files, you need to use use statements.

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201605\cm\OrderBy;
use Google\AdsApi\AdWords\v201605\cm\Paging;
use Google\AdsApi\AdWords\v201605\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

class MyController extends ControllerBase {

  // code...

  public function foo($args...) {
    $adWordsServices = new AdWordsServices();
    // code...
  }

}

Check the README in that branch (not the master) for more examples.

https://github.com/googleads/googleads-php-lib/tree/experimental

composer require (run it from the root of the application) will add this package to the list of dependencies.

If you are shaping this module to someday be a contributed module on drupal.org, you can add your own composer.json file to the custom module folder, and add this Google package as a dependency of the module. When users run composer require drupal/drupal_rollers_module - it will automatically fetch the Google library as well for them.

One last thing, the example above is kinda not so great (instantiating a new object in a method) and what you really want to do is have dependency injection provide that for you. I haven't taken a deeper look at the Google library you want, but you would need to define some services that pull in those classes in order to get to that point. Feel free to open another question later or peruse the ones already discussing DI.


How do I overwrite a lazy service? I'm trying to have my D8 site use Memcache for the lock service backend instead of using MySQL which is the default.

In core.services.yml we have the lock defintions:

  lock:
    class: Drupal\Core\Lock\DatabaseLockBackend
    arguments: ['@database']
    tags:
      - { name: backend_overridable }
    lazy: true
  lock.persistent:
    class: Drupal\Core\Lock\PersistentDatabaseLockBackend
    arguments: ['@database']
    tags:
      - { name: backend_overridable }
    lazy: true

In my site's default.services.yml I have this:

services:
  # Replaces the default lock backend with a memcache implementation.
  lock:
    class: Drupal\Core\Lock\LockBackendInterface
    factory: ['@memcache.lock.factory', get]

But when I obtain the lock service via \Drupal::service('lock');, I get a class Drupal\Core\ProxyClass\Lock\DatabaseLockBackend returned instead of an instance of Drupal\memcache\Lock\MemcacheLockBackend. So my override did not work.

Unfortunately there's no documentation in the D8 memcache module for doing this, I'm just kind of winging it.

Perhaps it has something to do with the fact that the original service is lazy loaded?

default.services.yml is just basically just documentation/ an example, it's not actually loaded, at least not by default.

To load a services.yml file, it either needs to be named services.yml, or you need to explicitly added to the settings.php file, see example.settings.local.php and how it loads development services.

The redis module also provides implementations for those services, and it does so by providing a separate example.services.yml file that you can either include directly or copy and customize. That definitely works, I wrote and tested it.


How to cache a node_load_multiple I'm loading 5 media gallery nodes into a single page via node_load_multiple().  Unfortunately the load time is very slow, several seconds.  I read up on Drupal's caching mechanism, and Jeff Eaton's tutorial and got the idea that I could cache each gallery node via the #cache array on the node's renderable array.  I think I've set everything up correctly, but I'm not seeing any increase in performance.  Any idea what I've done wrong or neglected to include?  Here's what I've done on a page.tpl.php for the page that contains the galleries:

$nodes = node_load_multiple($nids = array(1653,1654,1656,1657,1658), NULL, FALSE);
$i = 0;
$cid = "gallery_cache";
foreach ($nodes as $gallery) {
  $renderable = node_view($gallery);
  $cid .= $i;
  $renderable['#cache']['cid'] = $cid;
  $renderable['#cache']['bin'] = 'cache_page';
  $renderable['#cache']['expire'] = '1392001200';
  print drupal_render($renderable);
  $i++;
}

The results from node_load_multiple() are already cached within a single page load - the only time they're not is if you pass the $reset parameter as TRUE (which you're explicitly not doing). Looking at the code calls to node_view() don't seem to be cached, but I might be wrong there.

At a guess your performance hit might be coming from those individual calls to node_view(), which you might be able to mitigate a bit by using node_view_multiple() instead.

$nodes = node_load_multiple(array(1653,1654,1656,1657,1658));
$views = node_view_multiple($nodes);

foreach ($views as $view) {
  // ...
}

I'm pretty sure the reason your code isn't working as you expect is that the return from node_view() isn't a reference to anything, so the changes you're making to the array aren't actually getting saved anywhere, only to the local copy of the array.

One last piece of advice...it would be a good idea to take this code out of the template file and put it in a preprocess function at the the theme or module level. Running database queries directly in the template file isn't the best idea for a number of reasons.


Form hook not found through module_hook_info in module subdirectory Context:
In my Drupal 7 project, I have a module with several submodules. Because the module's root directory got crowded, I moved the submodule files to their own directories within the root.

My module's structure is like this:

mymodule
├── mymodule.info
├── mymodule.module
├── mymodule1
│   ├── mymodule1.block.inc
│   ├── mymodule1.form.inc
│   ├── mymodule1.info
│   ├── mymodule1.module
│   ├── mymodule1.page.inc
│   └── pages
│       └── foo.tpl.php
└── mymodule2
    ├── classes
    │   └── foo
    │       └── Bar.php
    ├── mymodule2.form.inc
    ├── mymodule2.info
    ├── mymodule2.install
    ├── mymodule2.module
    ├── mymodule2.page.inc
    └── pages
        ├── foo.tpl.php
        └── bar.tpl.php

Before "the big move", files that are now in the subdirectories mymodule1 and mymodule2, were located in their parent directory (the module's root directory).

The problem:
Ever since moving the files, my custom forms are not loading anymore. I have a form in mymodule1.form.inc, which used to load and render perfectly before. Now, when I use drupal_get_form() to load the form, I only get an empty form with a hidden build ID input.

Keep in the mind that the only thing that has changed here, is that the .inc files have been moved to the subdirectory, along with the module file. Also, drupal_get_path('module', 'mymodule1') returns the correct path to the module in the subdirectory.

Strangely, there are also block hooks, located in mymodule1.block.inc, which work perfectly fine, even after clearing all caches.

This is the first time I'm working with separate directories per submodule within a module. I got the inspiration from the module i18n, which uses the same construction. I searched in the Drupal documentation and the code of i18n, but could not find where I'm going wrong.

Does anyone know where I could possibly have gone wrong, or if I need to add data to mymodule1.module or mymodule1.info to make this work? Thank you.

Some details:
Caches were cleared through <path to project>/admin_menu/flush-cache multiple times.

I use module1_hook_info() to direct the hooks for blocks and forms to separate files. This is the return value:

array (size=9)
  'block_info' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_configure' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_save' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_view' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'forms' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_validate' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_submit' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_alter' =>
    array (size=1)
      'group' => string 'form' (length=4)

My form functions are called:

mymodule1_foobar_form
mymodule1_foobar_form_validate
mymodule1_foobar_form_submit

Thanks to Clive I found module_load_include(), which is used to load files when working with a form. I moved hook_forms() back to my main module's file and now load the mymodule1.form.inc through there, like so:

/**
 * Implements hook_forms().
 */
function mymodule1_forms($form_id, $args)
{
    module_load_include('inc', 'mymodule1', 'mymodule1.form');
    $forms = array();

    $forms['mymodule1_foo_form'] = array(
        'callback' => 'mymodule1_foo_form',
    );

    return $forms;
}

Now all my forms are loading correctly (again), over both mymodule1 and mymodule2.

The one thing I'm not sure about, that whether this could have been achieved without redundantly declaring the form callbacks to their same-named form IDs.


How to apply .diff and .patch file by SSH? I use Drupal 7 and I read every article about applying patches, but I don't understand how to apply patches to Drupal files using SSH. I am administrator of a Linux server that hosts a Drupal site.

Can anybody help me?

After logging in to your site with SSH, in order to apply patches, you should have or install a program on your server. patch is the most widespread one, but you can also use git for it.

You can find more documentation on applying patches in the Drupal site: https://www.drupal.org/patch/apply


Custom image style is not honored on new content On drupal 7 I created two new image styles. Now when I save new contents, I expect the new images to be saved in the new image styles as well but this does not happen. Images are only saved in the ordinary thumbnail, medium, large and square-thumbnail sizes.

How can I make the new image styles be honored?

Edit: So Mołot and Bala made it clear that a certain image style has to be called to generate an image of that style. Yet, I would like to call for a smaller image in the code, and then load a larger version for wider screens.

Is this possible?
Note: I am using ZEN as the theme.

Edit 2:

What I want to do is to load an initial small image like:

<img class="resp-image" src="very-small.jpg" />

Then, according to the screen size, I will replace the image with a larger version. This version of the image is provided by an image style:

if($(window).width() > 768) {
    $('.resp-image').attr('src', 'large.jpg');
});

The problem is, since I do not refer to large.jpg in the content type's display settings, it is not rendered to the given style and thus does not exist yet.

I was going to put this up as a new question but I found out that it is already discussed here and here.

Mołot's answer best described the situation referred to in the inital question. So I accepted it.

Images are only rendered to a given style when something actually tries to use that style. If you want to force generation, you need to use image_style_url to obtain URL for the image, and then download it via regular HTTP request. It becomes more complicated if you don't want to download (aka show) it. In that case, use image_style_deliver.


How can I get the current user role in my web app? I'm working on web app with a Drupal 8 back-end which is accessed by the D8 REST API.  I need to get the current user role so I can manage some options by role. Is there an existing REST route for getting the role and/or ID of the currently authenticated user.  I've had success with other REST routes like http://example.com/drupal/user/1?_format=hal_json, but this returns the user with id=1. What i'd like is http://example.com/cms/user/me?_format=hal_json
Any suggestions?

I have just used views to get this working.

Duplicate the default people view and rename it current_user.
Add a rest export route eg. rest/users/current_user.
Add a filter for current user. (User: Current = yes)
Save all.
Retrieve the current user via http get request on example.com/rest/user/current_user?_format=hal_json

Thanks to QueenVictoria for the advice.


Remove the image style from node--type.tpl.php Is there a way from a node--'type'.tpl.php template to remove the image style of an image field?

I found it, in field.tpl.php.

$items[n]['#display_settings']['colorbox_node_style'] = "";


Adding html to t() in Drupal 6 template.php? Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ????
I am in a Drupal 6 template.php file.

This is the code I am trying to add as html -

 Newer Posts
 Older Posts

I need to replace the above in these spots located in the full function below ?

 t('Older Posts')
 t('Newer Posts')

I want to create something like this

 t('Older Posts')
 t('Newer Posts')

Full Function

 function theme_views_mini_pager($tags = array(), $limit = 10,
 $element = 0,  $parameters = array(), $quantity = 9) {
 global $pager_page_array, $pager_total;

 // Calculate various markers within this pager piece:
 // Middle is used to "center" pages around the current page.
 $pager_middle = ceil($quantity / 2);
 // current is the page we are currently paged to
 $pager_current = $pager_page_array[$element] + 1;
 // max is the maximum page number
 $pager_max = $pager_total[$element];
 // End of marker calculations.

$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
 if (empty($li_previous)) {
$li_previous = "&nbsp;";
}

$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = "&nbsp;";
}

if ($pager_total[$element] > 5) {
$items[] = array(
  'class' => 'action back pager-previous',
  'data' => $li_previous,
);

$items[] = array(
  'class' => 'action pager-next',
  'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}

I am trying to figure out if this is possible I have tried many things and nothing has worked yet.

You should probably look into overriding the pager theme functions instead.

theme_pager_previous
theme_pager_next


How update user info using its UID in a custom module? We have a webform and when submitting this form we would like to update user info in the database regarding values of submitted Webform.

I already managed to get the submitted values from the webform in my custom module. But I don't know how to update the user info in the database because all user info are in separated tables.

I can run a few update queries for each value but it's not a logical way for me!

Any other suggestions?

You can equally use either user_save() or field_attach_update().

// Load the user's account.
global $user;
$account = user_load($user->uid);
$edit = $account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
user_save($account, $edit);
// field_attach_update
$account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
field_attach_update('user', $account);

The difference between using one function or the other is that user_save() will update all the user fields whereas field_attach_update() will update only the specified field.


node information and messages I created a user login page, and used the login destination module to redirect my user to a new "front page" I created using views.

On this "front page" I call all the nodes created by the logged in user, so a user can see newly created nodes.

My question is, how do I call a message or view which tells my user when a node has been deleted or edited?  This "front page" acts as a 'notification wall', which the user can see everything that is added or edited.  It will become more complex later where admins will be able to edit user nodes.  So I need to let the user know when he/admin has edited or deleted a node.

You can used Rules, and/or Views Rules.

Here is the rule that you need to created:

Event: When a node from a content have been delete or updated.
Condition: based on role.
Action: message display if a node from an specific content type have been remove or updated


Appending Multiple Fields In Twig I'm attempting to append two fields with some text in the middle. Using the changed date and a plain, core, text field, I can do something like this, and it works:

{{ node.changed.value|date('m.d.y') ~ ' | By, '}}{{ content.field_author_name.0 }}

However, if I attempt to do that in a single tag, the changed date, and the 'By' text is output, but I don't get the author name field.

{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ content.field_author_name.0 }}

Is that not valid twig syntax, or is there something else needed to get that to work in a single statement?

When using {{ content.field_author_name.0 }} it works because field is rendered with the twig.
The ~ operator converts all operands into strings and concatenates them. Given that content.field_author_name.0 is a render array you need point to the string value of this field. To do this you can inspect it with the devel or twig_vardumper module using dump(content.field_author_name.0). More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables

Assuming that field_author_name is simple text field with the Plain text formatter, this should work:

{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ content.field_author_name.0['#context'].value }}

To display node creator name you can use this:

{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ node.uid.entity.name.value }}


Online payemnts with commerce: what charges should I expect I am currently trying to setup a website with a simple online shop. Now for the online payments I'm struggling a bit to gather the information of all the things I'd like to know before making a decision. There are different banks, "externalizers", modules etc. and it seems to me that everywhere they want some money and I am not quite sure what for! So to get things straight - where should I expect charges? And if possible, what is the most economic or even free solution? I do not know if this little web-shop is going to work out. I see this list for example (https://drupalcommerce.org/faq/payment-methods) and do not understand how these things work except that every entity says that they are really awesome :-/. I do not find out how I will get the money transferred (and what countries).

I do not really get how online payment works: I need a bank account and something that transfers the money - so 2 things right?

Should I expect to pay for a module?
What should I expect to pay to the bank or entity that is transferring the money?
What are free/economic solutions?
Are there any traps/problems what kind of credit cards will be accepted?
Is there any resource that gives an organized overview of the segment?

Thanks for your help

you shouldn't pay for the module itself, most gateways have free modules, see https://drupalcommerce.org/extensions/module/payment. When you click on each module the CommerceGuys have been so nice to list transaction fees
I recommend not using a gateway charging more than PayPal. See their fees here: https://www.paypal.com/dk/webapps/mpp/merchant
Laws on online payments differ from country to country, so there isn't one answer to this. To my knowledge PayPal is the closest thing to free. No-one handles payments for free but some don't take setup fees, only transaction fees.
Accepting cards directly on your site requires a lot from you, both in terms of subscription to an organization offering merchant accounts (NETS in my case charges around 300€ for this in Denmark - and have a monopoly on the market). Proper gateways like ePay etc. furthermore charges a subscription plus transaction fees (on top of whoever has given you the merchant status). Finally you need to meet certain criteria about how you handle payments. For Example:

It's illegal to accept payment for something yet to be delivered in DK, so our gateway has to be able to only reserve the money. We're also obliged to offer our terms and conditions on both english & danish. And the list goes on - and varies locally.

I recommend you to keep it simple and easy by using PayPal until your sales are high and your knowledge on these matters have increased significantly.
For your last question I again recommend the drupal commerce module list in my first bullet