Manipulate texts before rendering to frontend I'd like to have two text fields in back end and programmatically manipulate the texts in these two fields before displaying the result in the front end. The text fields need to be WYSIWYG/CKeditor - preferably the standard editor.

How would I go around this? Should I create my own custom field or use hooks? Can you provide a not too complex example?

Since version 5, Drupal provides filters, a mechanism to manipulate the value of a text filter before rendering. In Drupal 8, filters are implemented as plugins.

So, in order to have two (text) fields which can can manipulate the value before display, you would need to

Create a custom filter (in a custom module)
Define a text format specific for your two fields, configured to use your custom filter (and any other filter you still want to apply)
On your content type, configure the two fields to use that text format
?
Profit

You filter code would look like

namespace Drupal\celebrate\Plugin\Filter;

use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * @Filter(
 *   id = "filter_ninjafart",
 *   title = @Translation("NinjaFart Filter"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class NinjaFartFilter extends FilterBase {
  public function process($text, $langcode) {
    $text = doSomethingWith($text);
    return new FilterProcessResult($text);
  }
}


Field API field_schema for text field error I've built a custom field using the Field API. I've defined the following element:
  $element['tabcontent'] = array(
    '#title' => t('Tab content'),
    '#type' => 'text_format',
    '#required' => $required,
    // use #default_value to prepopulate the element
    // with the current saved value
    '#default_value' => isset($item['tabcontent']) ? $item['tabcontent'] : '',
    '#tree' => true,
    '#rows' => 10,
    '#format' => 'full_html',
    '#base_type' => 'textarea',
  );

I've got the following code in the install file:
function tabfield_field_schema($field)
{

  $columns = array(
    'tabtitle' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
    'tabcontent' => array('type' => 'text','not null' => TRUE,'size' => 'normal','description' => 'Question prompt','length' => '1000'  ),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(),
  );
}

However, I get the following error when saving a new node:

Warning: preg_match_all() expects parameter 2 to be string, array
given in _media_generate_tagMap() (line 186 of
C:\Workspace\RnD\drupal1\sites\all\modules\media\includes\media.filter.inc).
Warning: Invalid argument supplied for foreach() in
_media_generate_tagMap() (line 187 of C:\Workspace\RnD\drupal1\sites\all\modules\media\includes\media.filter.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, array
given in check_plain() (line 1572 of
C:\Workspace\RnD\drupal1\includes\bootstrap.inc).
PDOException:
SQLSTATE[21S01]: Insert value list does not match column list: 1136
Column count doesn't match value count at row 1: INSERT INTO
{field_data_field_tab} (entity_type, entity_id, revision_id, bundle,
delta, language, field_tab_tabtitle, field_tab_tabcontent) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1,
:db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7_value,
:db_insert_placeholder_7_format); Array ( [:db_insert_placeholder_0]
=> node [:db_insert_placeholder_1] => 17 [:db_insert_placeholder_2] => 17 [:db_insert_placeholder_3] => tabbed_page
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] => ss [:db_insert_placeholder_7_value] =>
ss [:db_insert_placeholder_7_format] => full_html ) in
field_sql_storage_field_storage_write() (line 448 of
C:\Workspace\RnD\drupal1\modules\field\modules\field_sql_storage\field_sql_storage.module).

This is because your value suppose to be string, however you given array as per these errors:

Warning: preg_match_all() expects parameter 2 to be string, array given in _media_generate_tagMap()
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain()

Since you're sending array, the column count doesn't match in your SQL query.
This is what you're sending:
INSERT INTO {field_data_field_tab} (entity_type, entity_id, revision_id, bundle, delta, language, field_tab_tabtitle, field_tab_tabcontent)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7_value, :db_insert_placeholder_7_format);
Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 17 [:db_insert_placeholder_2] => 17 [:db_insert_placeholder_3] => tabbed_page [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => ss [:db_insert_placeholder_7_value] => ss [:db_insert_placeholder_7_format] => full_html )

which can be broke down into:

Fields: entity_type, entity_id, revision_id, bundle, delta, language, field_tab_tabtitle, field_tab_tabcontent
Placeholders: :db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7_value, :db_insert_placeholder_7_format

So you've 8 fields, but 9 placeholders.
Fix
To fix it, you've to check passed value of $item['tabcontent'] and make it a string. For example:
'#default_value' => !empty($item['tabcontent']['value']) ? $item['tabcontent']['value'] : '',

See also:

Errors when using a field of '#type' => 'text_format'


How can I omit downloading default themes in drupal core in make file Is it possible to not download the default themes- e.g. bartik, garland etc, in my make file when I download the drupal core?

No, I do not believe a makefile (assuming you mean Drush Make) can do this.  Deleting the actual theme files is not the best approach, since each time core is updated they will be re-downloaded.

If you want to remove core themes from the Appearance admin section, you can hide them with hook_system_info_alter().

function example_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme' && $info['name'] == 'Bartik') {
    $info['hidden'] = TRUE;
  }
}


Get field content from tid I am wondering how to retrieve the actual data of a field instead of the tid on a node.
Googling around I found a solution to a similar problem, by constructing a query on my own. However, it is usually the case that a function already exists for this. Do you know how I can achieve this?

What I get is something like this

field_category (Array, 1 element)
  -> und (Array, 1 element)
    -> 0 (Array, 1 element)
      -> tid (String, 2 characters ) 18

Specifically for taxonomy terms you have taxonomy_term_load(), e.g.

if ($field_items = field_get_items('node', $node, 'field_category')) {
  $tid = $field_items[0]['tid'];
  $term = taxonomy_term_load($tid);
}


How to list all the commands in Drush 9 (aka: drush help)? I'm trying to list all the available commands by drush help, however I've the error:

$ drush help
  [Symfony\Component\Console\Exception\CommandNotFoundException]
  Command  was not found. Pass --root or a @siteAlias in order to run Drupal-specific commands.

It was working in Drush 8, what's the equivalent command in Drush 9?

It is clearly a bug that drush help is printing a meaningless error message. Instead, it should tell you how to get the list of available commands.

drush list is the way to do that.


Add a block to a region How can I add a block to a region using Drush?

I'm using Drupal 7.0 and Drush 4.3.

The Drush extras project has commands for administering blocks.

Short instructions (following their README.txt):

Install this Drush add-on:

drush dl drush_extras

Determine desired module name and delta of block, and the desired region name and weight for adding the block:

drush block-show

Add the block to the region:

drush block-configure --module=block_module --delta=block_delta \
  --region=region_name --weight=-12

More instructions via:

drush help block-show
drush help block-configure
drush help block-disable


Can kint be used to debug templates? Normally, I can use kint() in the place of dump() to debug my twig templates.  The theming manual agrees.

However, this doesn't work for me in Commerce 2.

In commerce-product.html.twig, I added

{{ kint(product) }}

And rebuilt the cache.

This caused me to be redirected to the "install" url, with the message "Drupal is already installed".

If I use {{ dump(product) }}, I get the expected output, but this array is enormous and hard to read so I want to use kint.  Is there something different about variables in Commerce?

If I use {{ kint(links) }} and the like in a template copied from core I see the kint output correctly.

The object/array is too big for your server resources to handle the default kint settings.
Edit modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.


Pass view contextual filter arguments programmatically I want to pass contextual filter arguments programmatically to a view. I know it can be done through views_get_view and views_embed_view, but I want to pass it to a view's page display. Also I want to pass multiple arguments to the view, so it won't be good to pass all the arguments in the url.
I tried to pass the arguments using $view->args = implode('+', $args); in hook_views_pre_render, but it didn't work.
Does anyone know how to pass contextual filter arguments using any of view hooks?

I got the solution. It can be done using hook_views_pre_view(). Since hook_views_pre_view() allows altering a view at the very beginning of views processing, before anything is done, I am able to feed the arguments to the view.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $tids = custom_function();
    $args[] = implode('+', $tids);
  }
}

Hope this is useful to someone :)


Cannot uninstall modules due to missing table br_schedule When I hit the Uninstall tab in the UI or try to uninstall a module with Drush I get the following errors:

Drush:

SQLSTATE[42S02]: Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist

Drupal Log:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]:
Base table or view not found:
1146 Table 'DATABASENAME.br_schedule' doesn't exist:
SELECT base_table.vid AS vid,
base_table.id AS id FROM {br_schedule}
base_table LIMIT 1 OFFSET 0; Array ( ) in
Drupal\Core\Entity\EntityStorageBase->hasData()
(line 552 of MYSITEPATH/core/lib/Drupal/Core/Entity/EntityStorageBase.php).

I have no idea what br_schedule is so I don't know how to rebuild that table. I have Businesses Rules installed but I see no br_schedule module.

Found the issue. My database updates are not happening. Ran updatedb:status with drush and I get:

file_entity                           8004        hook_update_n   Fix entity field mismatches on the file type field.
business_rules_schedule entity type               entity-update   The Schedule entity type needs to be installed.
file entity type                                  entity-update   The File type field needs to be updated.
node entity type                                  entity-update   The node.field_zipcode field needs to be updated.

"Fix entity field mismatches on the file type field." is failing so the "business_rules_schedule" update isn't happening.


Values don't get saved to the database when fields are wrapped in a container When I wrap a field in a container, the field value doesn't get saved to the database. But if it lives in root, it works properly.

public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

    $item =& $items[$delta];
    $element += array(
      #type' => 'fieldset',
    );

    /** a bunch of fields **/

    $element['concelhocontainer'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'concelhocontainer']
    ];

    /** works properly **/
    $element['concelho'] = [
      '#type' => 'select',
      '#title' => t('County'),
      '#default_value' => isset($item->concelho) ? $item->concelho : '',
      '#options' => $this->getConcelhoList()
    ];

  /** does not work
  $element['concelhocontainer']['concelho'] = [
    '#type' => 'select',
    '#title' => t('County'),
    '#default_value' => isset($item->concelho) ? $item->concelho : '',
    '#options' => $this->getConcelhoList()
  ];
  */
  return $element;
}

The problem is that the value of the second input is not saved to the database (I've confirmed it in the database).

It seems Drupal adds a #tree = true property to the field parent so you need to process the data output by the form youserlf or the form nested elements will be ignored. As @IvanJaros poited out, WidgetBase::massageFormValues let's you alter the data.

public function massageFormValues(array $values, array $form, FormStateInterface $form_state)
{
  for ($i=0; $i < count($values); ++$i) {
    if (isset($values[$i]['concelhocontainer']['concelho'])) {
      $values[$i]['concelho'] = $values[$i]['concelhocontainer']['concelho'];
    }
  }
  return $values;
}


Display images instead of nodes titles in Drupal 7 Normaly in Drupal 7 we have (node.tpl.php):

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

It is taking node_url and putting it on a Title in every Node.

I do have 5 nodes (pages) displayed:

First
Second
Third
etc

I have created images First.gif, Second.gif and I want to load that images instead of Title.

I did check various implementation, but didn't find any resolution for me.

[Update] I did try to edit template.php file and to add functions for replacing title with image-if images exists.
I need this in Drupal 7 - please see here - http://drupal.org/node/221854

Is there any help? Thanks

For non-coders: the views slideshow module (or something similar) could easily solve this problem without requiring custom code to maintain.
From http://drupal.org/project/views_slideshow:

Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Potential uses
News item slideshow (such as the title, image and teaser of the last 5 news articles submitted)
The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
Rotate any image, based on any filters you can apply in views.
Hottest new products for any ecommerce drupal site.
Rotate contact links, share links, etc.
Heck, you could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
Its also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.
The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.


How to display selectable variations without attributes? With Drupal Commerce 2, each of my products have multiple variations which are unique and can be adequately described by their variation title.

I can not figure out how to display a dropdown for the add to cart form based the variation title alone. All that is shown is the title of first variation, the price and the add to cart button. No dropdown with the other variations.

The only way I can get it to work is by first creating a series of matching attributes which is both a repetitive exercise and seems like it should not be necessary.

What am I missing?

Similar question: What's the best the approach to add an extra attribute field in Drupal Commerce?

if i understand you question correctly, you accomplish this by going to your order item type, choose manager form display then you have the field available called Purchased entity ... you want to change the default widget from product variation attributes to Product variation title.


Override default php settings I am having difficulties in overriding the default PHP settings within my Drupal installation. I do not want Drupal to display E_NOTICE messages. So I wanted to override the default PHP error_reporting setting from E_ALL to E_ALL & ~E_NOTICE or from 2047 to 2039 (the corresponding error reporting values).

I added the line ini_set('error_reporting',  2039); in both sites/default/settings.php and sites/default/default.settings.php, but still when I go the status report page and view the PHP info file, I see the error reporting setting of PHP is still set to 2047. What am I doing wrong here? How to override the php setting?

PS: I even tried adding the line php_value error_reporting 2039 to Drupal's .htaccess file, but there is no effect.

You will have to add

error_reporting(E_ALL ^ E_NOTICE);

to the settings.php file. Here's more.


How to know from variables tu use them in a custom code I know it's a newbie question, but it's take me a lot of time to find a a small code for a small fonctionality.

for example I wanted to make the address phone field required, I didn't know how to know the arrays keys.

        <?php
/**
 * Implements hook_field_widget_form_alter().
 */
function organize_address_field_widget_form_alter(&$element, $form_state, $context) {
  if(!empty($element['#addressfield'])) {
    $element['country']['#weight'] = 100;
    $element['phone_block']['phone_number']['phone_number']['#required'] = TRUE;

  }
}

I tried devel to find it but without result.

So my question,after finding the good hook, how I can know the variables to use.

Is a general question to help me to learn module development.

May be I'm missing something: I don't understand why you want to programatically make the field required.

Required is not a feature of a field by itself, it is an option you can set on its instance once it's attached to a node, through the admin/structure/types/manage/yourContentType/fields/yourFieldName.


Is it mandatory to clear cache for each and every change made? It takes more time to clear caches and it also needs to be done more frequently for the each CSS or functionality wise changes.

Are there any alternatives available?

Disable Drupal 8 caching during development

  When you are developing a module or a theme you have to clear Drupal's
  cache (render cache, dynamic page cache, Twig cache) very often to see
  the changes being applied. You can disable caching for development.

Steps

Copy and rename the file sites/example.settings.local.php to sites/default/settings.local.php:

$ cp sites/example.settings.local.php sites/default/settings.local.php

Uncomment these lines in sites/default/settings.php:

if (file_exists(__DIR__ . '/settings.local.php')) {
    include __DIR__ . '/settings.local.php';
}

If you want to keep CSS and JS aggregation and preprocessing, change these lines in sites/default/settings.local.php to TRUE:

$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;

Uncomment these line in sites/default/settings.local.php:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = cache.backend.null';

Add the following lines to sites/development.services.yml:

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

(source: drupal.org)


Proper approach for showing menu based on node I'm setting up a new Drupal site and created a content type, taxonomy, and two menus. The taxonomy just has 2 items, which correspond to the menus. What I'd like to do is render the corresponding menu in a sidebar when the user is viewing a node from the content type, ideally highlighting the current item in the menu.

My current thinking is to write a custom module and use the hook_page_build. Then in that hook, see if arg(0) is 'node' and arg(1) is numeric and then node_load arg(1) and then if that node's type matches my content type, then field_get_items to get the node's taxonomy and pull the corresponding menu and then add it to $page['sidebar_first'].

Is this the right approach or is there a better way?

Thanks in advance!

I'd say the best way would be to use Menu Block.  This would allow you to use blocks built in visibility rules.

All you would need to do is create a new menu block, select which menu to display and select which content type it should be displayed on.  The menus get all the functionality of standard menus.

You could also just use the standard block that is created with every menu, check the disabled blocks section for those.  Menu Block however has a few more features.


Load fields from a node which reference an entity I have a node with a entity reference field (more precisely a product reference). How do I access the fields of the referenced entity from the node?

(I’m trying to do it through a code field in the Display Suite, so I have access to the $entity object, not sure if that helps)

To explain better I would like to be able to do something like these tokens:

[node:field-products:0:field-flow-rate]
[node:field-products:1:field-flow-rate]
[node:field-products:2:field-flow-rate]

but with PHP, so I can cycle through the index.

You can use entity_metadata_wrapper() to easily get referenced entities, their field and much more.

$node_wrapper = entity_metadata_wrapper('node', $entity);

foreach ($node_wrapper->field_products as $product_wrapper) {
  // You can print or do whatever you like with the value of the fields
  // of the referenced entity like below:
  print $product_wrapper->field_flow_rate->value();
}


Sending mail to detailed groups? Ok, I need a bit of help with this one.

I have a website where I created a newsletter using Simplenews - works just fine, I'm sending some welcoming text + attached views of new things on site. But now I need to make something more with it.

I want to create new type of newsletter, that would be sent irregularly - or manualy as some would say. That is not a problem. Question appears here: I want admin to be able to create groups of users (manually again adding mails to the group etc.) for example, let's say I want to have two new groups for start:

group a
group b

And from time to time, admin needs to send a mail to all the email addresses in the selected group. How can I achieve that? Is even Simplenews a good idea in this situation? Or maybe there's some better tool?

Thanks in advance

I guess Simplenews Roles modules can help you for creating the groups.

You can assign users to a specific role and then based on this roles you can send Simplenews.

For Eg.

User 1 and User 2 can be assigned to role A

And

User 3 and User 4 can be assigned to role B

Now you can use role A and B for sending Simplenews.

I guess this helps.


What does rc stand for? when to use alpha, beta and dev instead? how to name your projects

project_name-7.25-1.0-alpha
project_name-7.25-1.0-beta1
project_name-7.25-1.0-dev2
project_name-7.25-1.0-rc3
project_name-7.25-1.0-stable4
project_name-7.25-1.0-unstable5

following best practices?

See Drupal.org for release naming conventions and
further explantion.

Summary:

rc = Release Candidate, deemed suitable by the author for production sites.

rc: A release candidate should only be created when the all critical bug type issues are reported fixed in the project's issue queue. This tag should only be used when the developer believes that the project is ready for use on a production site. There is no official best practice for how long a project should be a release candidate before creating a official .0 release, but it is suggested that it should be out for at least a month with status set to "needs review".  If something (e.g. a new critical bug is reported) makes it necessary to create a new release during this period, a new release candidate should be created and this should remain for at least a month with status set to "needs review".

It is OK to tag a module "rc" with feature requests issues outstanding.  Module authors are not required to fulfill every feature request users of the module post to the issue queue.

Here is a description of the other allowed release tags:

unstable: The project is not in a stable state.  There are probably numerous unfixed bugs, including security issues. The API may change without notice.  The database schema may change without hook_update_N beeing implemented. Usage and API may not be documented. Installing a new unstable release entails uninstalling the project, thereby losing all data.  Only for those who want a early preview of the project.  Not yet suitable for shared development.

alpha: Most reported errors are resolved, but there may still be serious outstanding known issues, including security issues. Project is not thoroughly tested, so there may also be many unknown bugs. There is a README.txt/README.md that documents the project and its API (if any). The API and DB schema may be ustable, but all changes to these are reported in the release notes, and hook_update_N is implemented to preserve data through schema changes, but no other upgrade/update path. Not suitable for production sites. Target audience is developers who wants to participate in testing, debugging and development of the project.

beta: All critical data loss and security bugs are resolved.  If the module offers an API, it should be considered frozen, so that those using the the API can start upgrading their projects.  If it is an upgrade or update of a project, an upgrade/update path should be offered, and it should be possible for existing users to upgrade/update to the new version without loss of data.  All documentation should be up to date. Target audience is developers who wants to participate in testing, debugging and development of the project, and developers of other projects that interfaces the project. Not generally suitable for production sites, but may be used on some production sites if the site administrator knows the project well, and knows to handle any remaining issues.

The strings "dev" and "stable" are not valid as part of a release tag, but untagged development releases are assumed to be "dev" and are given descriptions such as "7.x-1.x-dev" by the Drupal.org release packing system to indicate that they are untagged development releases.

All release tags must end with a number.  The numbers are just to distinguish releases of the same class.  The first is numbered "1" (as in "alpha1"), the next "2", and so on.

PS. The strings denoting releases (such as "7.x-1.0-alpha4") are known a "release tags" in git parlance, not "names".  And you never use the drupal minor version as part of a tag, you use "x" instead.


get user profile picture at registration I am using Drupal 7.

I follow this link to enable profile picture of user.

Now i want to get profile picture from user at the time of registration.

How can i get this?

Any help will be appreciated.

There is a development version of the Register with Picture module.


Class not dynamically loaded in custom module I have a very simple Drupal 7 module in which I want to load a custom class. I'm not able to load the class and I get the following error when I enable the module:

Fatal error: Class 'Drupal\testmodule\TestClass' not found in www/sites/all/modules/testmodule/testmodule.module on line 4

Here are the contents of my module files:

testmodule.info

name = "Test Module"
core = 7.x
files[] = src/TestClass.php

testmodule.module

<?php

function testmodule_init() {
  Drupal\testmodule\TestClass::go();
}

src/TestClass.php

<?php

namespace Drupal\testmodule;

class TestClass {
  function go() {
    print 'Foo!';
  }
}

Please could anyone help me understand why Drupal 7's dynamic-loading code registry is not working as documented here: https://www.drupal.org/docs/7/creating-custom-modules/writing-module-info-files-drupal-7x#files ?

To use namespaced classes in Drupal 7, you can use one of these modules:

https://drupal.org/project/xautoload
https://drupal.org/project/registry_autoload

One reason for choosing one or the other may be if you have other modules that also depend on one of those modules.

Otherwise I guess it is largely a matter of taste.

One difference is that xautoload is more convenient during development, because newly created PSR-4 classes are immediately available without rebuilding the class registry.

On the other hand, it does a lot of things which you probably don't need right now, and the code looks complex.

Of course you could do some profiling to find out which is faster, but as always you would need to be careful what you measure and what you compare. I currently cannot tell you which one is faster, or better for memory.

There is also the alternatives module that can help to have only one of those enabled, instead of both.

Disclaimer: I am the author of one of these modules, and I am subscribed to the autoload tag on drupal.stackexchange.com.


Why `GROUP BY` in hook_views_query_alter() doesn't work? I'm using Views 7.x-3.6 and I tried altering the GROUP BY clause with hook_views_query_alter() as below:

function mymodule_views_query_alter(&$view, &$query) {
    if ($view->name == "view_name"){
      $query->add_groupby('field_name');
      dpm($query);
    }
}

When I look in $query, the groupby clause is correctly enabled but the SQL query is not affected: the GROUP BY clause doesn't appear:

What I eventually did is using a Drupal core hook (hook_query_alter()) and it worked fine: the SQL is now affected.

function mymodule_query_alter(QueryAlterableInterface $query) {
  $view_name = 'view_name';
  if ($query->hasTag('views_' . $view_name)) {
    $query->groupBy('field_name');
  }
}

Any reason why my hook_views_query_alter() doesn't work? I'm wondering if there's a cleaner way to do it and.

Use add_field() with array('function' => 'groupby') parameter.

$query->add_field('node', 'nid', 'node_nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

Aditional information:

After using add_groupby you might see the next code after GROUP BY:

GROUP BY node.nid, nid

See the next issue: https://drupal.org/node/1578808

To avoid unnecessary GROUP BY conditions add:

$query->distinct = TRUE;


How do I configure Apache and Varnish with both HTTP and HTTPS access and prevent mixed content error? I have Drupal 7 installed on Ubuntu server with apache2 and varnish. I was asked to provide both http and https access to the site.

To utilize Varnish I setup apache reverse proxy to redirect all https traffic to varnish(http). Now I can access my site via http/https protocols fine.

However, when I load any https page with images in it, all images are served via http, thus making browsers issue a warning about mixed content. I would like to suppress that.

To suppress that, I changed $base_url to https:// in site/default/settings.conf and that worked fine for all https pages.

However, I experienced the same mixed content error while loading normal http pages (images were served via https this time.) Then, I created an if statement trying to differentiate between http and https and assigning different $base_url values accordingly.

I have tried using $_SERVER['']  array variables as well as $is_https, and nothing seems to be working.

I also used $GLOBALS[''] variable to make sure variables are defined. I would clear the Drupal cache as well as browsers before each testing. However, when I access https version of a site, all is rendered ok and everuthing is fine. But when I access http, all images are served with https. I would clear cache again, and try accessing http first, and everything would be fine. But when I access https after that, images would be served with http. So, the logic within settings.conf is fine, but possibly caching makes browsers/Drupal to serve images with the protocol they were first accessed (be it http OR https).

My question: is there a way to assign $base_url dynamically based on the protocol used?

Some of the settings I have tried:

-----------------------------------
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $_SERVER['HTTPS']='on';
        $base_url = 'https://';
        }
else {
         $_SERVER['HTTPS']='';
         $base_url = 'http://';
}
-------------------------------------
#if (isset($GLOBALS['$is_https'])) {
#       $_SERVER['HTTPS']='on';
#       $base_url = 'https://example';
#       }
#else {
#        $_SERVER['HTTPS']='';
#        $base_url = 'http://example';
#}
---------------------------------------
$base_url = '//example'
---------------------------------------
$base_url = '';
---------------------------------------

Drupal 8

Apply the following settings in site's settings.php file:

$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']]

It should work for CDN where IP addresses are dynamic.

This is explained in the following comment:

 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken

Drupal 7

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = [@$_SERVER['REMOTE_ADDR']];

See also:

Setting reverse_proxy and reverse_proxy_addresses behind AWS ELBs.
Using a load balancer or reverse proxy


Which hook do I need to use to pull external content in pages? I want some of my pages to pull content from another application. Someone suggest I should write a module to do that.
As I'm a complete beginner in Drupal I was wondering which hook do I need to implement (a snippet would be greatly appreciated) :

hook_page_alter
hook_page_delivery_callback_alter
something else ?

hook_page_alter() is used to alter the page returned from another module, and hook_page_delivery_callback_alter() is used to change the page delivery callback for a page output from another module. All the hooks with a name ending with _alter are hooks that alter the output of another module, what another module returns, or the data stored by another module.

The hook you should use is hook_menu() to define a page callback, and drupal_http_request() to get the external content.
The minimal code you should use is similar to the following one.

  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_external_content_view',
      'access arguments' => array('access content'),
    );

    return $items;
  }

function mymodule_external_content_view() {
  $response = drupal_http_request($url);
  if (!isset($response->error)) {
    $data = $response->data;

    return array(
      '#markup' => filter_xss($response->data, $allowed_tags)
    );
  }
}

Replace abc/def with the path of the page you want to output, $url with the URL of the external application, and $allowed_tags with an array of strings for the tags that you want to allow as output. By default, filter_xss() uses array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd').


How do you refer to the field in views-view--field-fieldname.tpl.php? I'm using the views-view-field--field-fieldname.tpl.php to rewrite the output of a specific field in a view. However in this template I'm having trouble referring to the actual field.

I can produce the normal input with

print $output;

However this contains the classes and divs it is wrapped in. Including the default icon that is used to represent it. I'm having trouble producing the specific data of the field. Specifically the url to the file. (It is a file field). Is this possible? I made quite a number of attempts. Below are the attempts I've made that were unsuccessful.

print $fields['fields_field_fieldname']->content;

print $row['fieldname'];

print $view->results->{view->field['field_fieldname']->field_alias};

I understand that I could use string replace and regex to extract the data I need $output. If that's the only way to do it, I'll stick to that.

File field has formatter "URL to file", please see this screenshot:

So finally, in $output will be only url to file.

Also, if you don't want any views default wrappers, you can unselect checkbox in "STYLES" fieldset (see screenshot abowe).


Are there any module options or techniques to authenticate through OpenAM on Drupal 8? I see that there is an OpenAM module for Drupal 7, but I do not see one for 8. Is there an option for this?

Yes. Port OpenAM to Drupal 8 yourself.

Alternatively, create a new issue and wait until maybe someone else ported it.


Limit drush sync paths? I have 3 drush-aliased sites: @DEV, @STAGE & @PROD

rsync & sql-sync all work between them.  At the moment, that's both directions, between any two sites.

I want to limit the sync paths to only allow sync in the following cases:

(1) @DEV -> @STAGE, files & db
(2) @STAGE -> @PROD, files & db
(3) @PROD -> @DEV, db ONLY

How do I limit drush sync to allow only those three cases of sync, preventing all others?

You can do this with a policy file.  See examples/policy.drush.inc.

In the example policy file, specific named destinations are rejected.  To increase the stability of the system, you could reverse this test to reject any destination except for known good targets, or perhaps some combination -- for example, you could reject sql-sync to any remote destination except @stage.

You probably should not allow sql-sync to @prod, but of course it's up to your policy to decide that.  For moving configuration stored in the database, see ctools_export_bonus.


Expose some administrative functions on the front-end I'm developing a web-app for managing non-profit organizations by extending the functionality of the Drupal CMS. What I want is to have only one administrator account (call it super-admin if you prefer), which should be used only by the developer, next there will be a set of roles (coordinator, director, employee).

The idea is that non of those should be able to perform administrative tasks that may broke the site functionality (like managing blocks or menus), but not just that, to provide a cleaner and more compact interface I would like to expose some functions of the admin side to the front-end (accessible only for determined roles), for example, the coordinator should be able to change the role of an employee in order to upgrade him to director.

Is that possible?

Your question is a little broad -- anything is possible given time, effort and perseverance!

I find the Role Delegation module and similar modules help to give out permissions to trusted users.

I also have been creating an Administrative Panel page using the Panels module with embedded Views and Blocks for centralized site admin options for users. I usually call this page the staff dashboard for my admin-type users.

Without specific problems you're having, these general tips are all I can provide. Happy coding!


Query in URL not affecting view filters I currently have a view that has a page display and a block display. The page is disabled, but I have exposed the form in a block, which is then displayed on the homepage of the site.

When the user selects the filters and submits, it then goes to another page with the results in the block view (filters included).

The problem I'm facing is that when the user submits the form from the homepage, the results aren't showing on the subsequent page. The query shows in the URL but it doesn't change the results.

This was working before, but has suddenly stopped working. Any ideas why this may be?

Sounds like a common mistake with views.

On you filter's settings, under More make sure you have the Filter identifier set with the same name, in both your page and your block.


programmatically add line item of commerce_discount type to order I want to programmatically add line item of commerce_doscount type to my order, I test below code,it is correctly add a record to line items array but not show in  order list even I refresh the order I dont see anything in order table .

$amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
if ($amount) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
     $line_item = entity_create('commerce_line_item', array(
    'type' => 'commerce_discount',
    'line_item_label' => 'my test',
    'quantity' => 1,
));
    // Wrap the line item and product to easily set field information.
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
// Set the unit price on the line item object.
$basePrice = commerce_price_field_data_auto_creation();
$basePrice['amount'] = $amount;
  $line_item_wrapper->commerce_unit_price = $basePrice;
// Save the line item now so we get its ID.
  commerce_line_item_save($line_item);

      //  $line_item = commerce_line_item_save($line_item);
        // Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;
     //commerce_order_save($wrapper);
      commerce_order_save($order);
$order = commerce_order_load($order->order_id);

        // Recalculate discounts.
      //  ym($order);
        commerce_cart_order_refresh($order);

also I look at discount module and try below code

 module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');
   $amount = trim($amount);
  $basePrice = commerce_price_field_data_auto_creation();
  $basePrice['amount'] = $amount;
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  commerce_discount_add_line_item($order_wrapper,'commerce_discount',$basePrice);

but return me EntityMetadataWrapperException: Unable to get the data property commerce_total as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue()

Don't reinvent the wheel, here. Discounts provides functions for apply discounts to orders:

// Pass in an $order or $product that has been entity_metadata_wrapper()ed.
// And pass in a discount name.
commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, $discount_name);

// Same thing, but a percentage.
commerce_discount_percentage(EntityDrupalWrapper $wrapper, $discount_name);

If you must reinvent the wheel, use these functions as examples to guide what you are doing.


Rules- How can I make a variable/token with the site URL minus the language path? I have created a rule set to handle login redirects for users on my site.  If a user logs in from a page that is set to a different language from that user's language (example: English user logs in on a Japanese page), the user will be redirected to a page with the same language as the page upon which they logged in (in the example, a Japanese page).

To fix this, I want to force my redirects to be the appropriate language path based on the user language.

However, the [site:url] replacement pattern which is provided by Rules includes the language path (because it is the front page).

My front page is https://mysite.com/en.

I want to create a new variable which is the URL of my site minus the language path:
https://mysite.com/

I tried creating a variable of type text with a value of

<?php substr("[site:url]", 0, -2); ?>

but for some reason this just gives me the value of [site:url]; it appears that the substr() function has no effect.  I don't understand PHP very well so I could be missing something obvious-- I just want to remove the last two characters of the [site:url].  How can I do this within Rules?

Use Drupal global variable $base_root for that.


Integrating dropdown menu of different views options on a page I have one content type called 'images' - at the moment they are just displayed as a list. However I want the users to have some options on how to view those images.

What I have done:
I have created 3 different Views that have different slideshow settings

What I need help with:
I need to have these 3 options appear automatically when any node from that content type is viewed as a dropdown with label: "View images as:"

Most importantly the different views need to be generated programmatically using the images on that node and not by creating 3 slideshow for each image page!!!

there is no option in views to expose any changer for 3 different blocks, one thing you can do is make a drop-down and show/hide views using javascript/jQuery or make single unformatted view and change format using js/css on dropdown change.(you need to make some custom codes.)


Weird usernames on my Drupal site I help run quite a Drupal site (up to date) with around a few thousand registered users. More and more frequently I am finding users who have registered with usernames like the following (found 13 so far but I am going back through the history to see if there are anymore):

briantuffddwwjbsao
heiditsfacjsheiffg
vickikqskaiwlfnxcg

I am 99% certain these are not legit users and I have blocked their accounts for the time being.  Oh and they have been authorised (clicking link in email).

When looking at the profile, in every case the first and last names are populated by the same text (the same as the first four or five characters of the username).  The last part of the username is seemingly random characters (no numbers/special characters).  I also note the address does usually exist (at least on gmaps) but I cant comment on the zip code/telephone being accurate (it doesn't seem so).

We do have a CAPTCHA implemented.

Has anyone else had experience with users registering on Drupal with this type of username?  Are they legitimate or is it some sort of "bot"? Am I just being paranoid?

Yes those are most likely bots; you can never be 100% sure but if you're seeing a pattern, and these users aren't contributing to the site in the same way regular users do, it's likely.

I think anyone who's ever administered a medium-large Drupal site has experienced this at one time or another. Standard tools for the arsenal include:

Botcha

  BOTCHA is a highly configurable non-CAPTCHA spam protection framework.

Spambot

  Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

Both are very effective in my experience, though Spambot can get fairly intense on outgoing http requests if you get a lot of registration attempts. There are some others listed on the Spam control modules page too.


How do I create a sub-theme from CLI? How do I create a sub-theme using Drupal Console or Drush 9?

I looked at Creating a Drupal 8 sub-theme, or sub-theme of sub-theme and the documentation of drupal generate:theme, but I didn't find anything about creating a sub-theme from CLI.

My aim is to automatize the process with a CLI. Is it possible now?

The option exists in Drupal Console's drupal generate:theme; it's done by specifying the --base-theme option in the command. The option's value adds the base theme key with option's value into the generated theme's .info.yml file (which make the new theme a sub theme).


Developing a mobile website I am using mobile tools module. It asks for path of mobile website. Does it mean that i need to develop mobile based pages again? i.e one for mobile and another for desktop ?

Mobile tools will let you differentiate between what you consider to be your 'desktop' version and your 'mobile' version via the theme you choose.  For example, www.example.org as your desktop and m.example.org as your mobile.

Mobile tools will try to redirect based on device detection, if you configure it that way.  If you want the desktop version to show on all devices, computer and mobile, you can configure it that way as well, or include the desktop version for 'desktop and mobile.'

But, if you do want a separate mobile theme, there are several existing mobile themes out for drupal.  To make that work you would have to install and enable the mobile theme, and then mobile tools will automatically select that theme when it detects the mobile based site.

Whatever version of the site you want to display on any device is very possible. It's just according to your goals for each device.


How can I log(watchdog)? In D7 is used to log using Watchdog function. In D8, I see its gone and I should use something called the logging API.

What I a trying to do:

I have created a menu/route, mysite.com/logmessage
When user opens that url in browser, I want to log "hello" to the dblog.

Where should I register the service that D8 documentation says to do? Is it in the services.yml file in sites/default folder?

Can I just load the said class in my controller/module file and call the function for logging? Or should I explicitly extend the class first in my module before using the function?

There are many different types of logging, all called the same way as per the documentation:

\Drupal::logger('my_module')->alert($message);

\Drupal::logger('my_module')->info($message);

\Drupal::logger('my_module')->debug($message);

Just call this code anywhere in your module, if you want to register logmessage as a path you'll need to create my_module.routing.yml, etc.


Displaying current date on views Is there a way to display the current date on views? I just realized that I couldn't use global tokens nor could I get custom date created on Display Suite on views.

Install Token Filter.
Got to Configuration > Text Formats and enable Token Filter ("Replace Tokens") for a text format.
In your view add Header/Footer "Global: Text Area" and choose the text format from step 2.
In the text area write [current-date:short] and optionally check [x] Display even if view has no result.

Source: https://ffwagency.com/digital-strategies-blog/how-add-current-date-view-drupal-7

To do this in the fields section use Advanced Text Formatter, which allows you to choose a text format for "Global: Custom text" fields.

Source: https://www.drupal.org/project/views/issues/1417266#comment-12245061


"You need to be logged in to view that page" alert for authenticated user I have created a page using hook_menu for "employee" role using the code below:

 $items['admin/employee'] = array(
    'title' => 'Dashboard - Employee',
    'page callback' => 'employee_page',
    'access arguments' => array('Access administration theme'),
    'type' => MENU_NORMAL_ITEM,
);

When this page is viewed by an employee this alert appears: "You need to be logged in to view that page".

I tried to rebuild cache etc.

PS. I don't have an issue to access this page as an admin. Maybe I should use different access arguments?

First off, checking access as user 1 or Administrator is not a test because no permission checks are done for user 1, and in most cases Administrators have all permissions.

Two, your permission is mixed case, change it to all lower case and clear the cache.

Three, in order to access anything under /admin, user will also need access administration pages permission as well - or whatever permission is assigned on that menu item (I think that’s the one).


504 Gateway Time-out error in batch process I have submit the custom form using batch process in which process I have upload big xml file(min 200MB) and read xml file and inserted xml data in database

but after 30~35 minits batch process display the

  504 Gateway Time-out error.

Also I have increased memory size, excution time, max upload size and so on.

Please help me..

I have find the answer...

Please increase memory limit, excution time and max input time.

1. File php.ini

memory_limit = 768M
max_execution_time = 3600
max_input_time = 3600

OR

Define in settings.php

<?php
    ini_set('memory_limit ', '768M');
    ini_set('max_execution_time', 3600);
    ini_set('max_input_time', 3600);
?>

My problem is solve. :)


Show various nodes in different ways on home page in drupal7? I want to show nodes in different ways. For example, i want to show featured nodes, recent nodes. My question is that how we can show nodes in different ways on my home page.

See this demo site, i want my home page in drupal as like it.the problem is that how to manage nodes different ways as posts in WordPress.

thanks for the help

Welcome to Drupal StackExchange !

You can build various views of same content using Views module in Drupal. You can follow this link to know more about the views module and also Views Documentation in the project page.


Multiple path aliases based on taxonomy term I have taxonomy terms from A-Z and each article can belong to multiple terms.

for an example, when I create a new article, I have a multi select list for terms. Therefore a particular node should work for multiple URLs.

example.com/categories/a/planning
example.com/categories/g/planning
example.com/categories/s/planning

Please let me know if this can be achieved using a contributed module or can it be built with a custom module?

You can use pathauto module.
After installing the pathauto module, please configure the path of article content type from here admin/config/search/path/patterns.

Note:
To use pattern require token module. Then use like following pattern:

categories/[node:field-token-of-term-reference-field]/[node:title]


How to access Drupal variables in a PHP included file? I have a snippet of HTML that I've saved in my theme as mysnippet.inc. I'm using this code in template files (eg. node.tpl.php) to include it:

<?php include($directory."/includes/mysnippet.inc"); ?>

This is working fine, but the snippet also needs to access Drupal variable $node_url. So I tried to global it into my snippet:

<?php global $node_url ; ?>
<?php print $node_url; ?>

This doesn't work.

What would be the best way to achieve this? Should I be using template.php to create a variable containing my code snippet instead?

You can access the $variables array in your included file like this:

 // assuming you are viewing a node
 $node = $variables['node'];
 // the node is an object, so to display the url do
 echo drupal_get_path_alias('node/'.$node->nid);

To see what kind of data the $variables array contains do something like:

 echo '<pre>';
 print_r($variables);
 echo '</pre>';


PDO - Duplicate entry on file upload I'm developing a module that uploads CSV file.

/**
 * Implements hook_menu().
 */
function geo_points_menu(){
    $items['geo-points-upload'] = array(
        'title' => 'Geo points',
        'description' => 'Upload users',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('geo_points_form'),
        'access arguments' => array('access content'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
    );

    return $items;
}

function geo_points_form($form, &$form_state) {
    $form = array();

    // Use the #managed_file FAPI element to upload a file.
    $form['file_fid'] = array(
        '#title' => t('File'),
        '#type' => 'managed_file',
        '#description' => t('The uploaded file will be processed.'),
        '#default_value' => variable_get('file_fid', ''),
        '#upload_validators' => array(
            'file_validate_extensions' => array('csv'),
        ),
        '#upload_location' => 'public://csv_uploads',
        '#process' => array('geo_points_my_file_element_process')
    );

    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Import'),
    );

    return $form;
}

/* It disables the default upload button that comes with this #managed_file form */
function geo_points_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#access'] = FALSE;

    return $element;
}

function geo_points_form_submit(&$form, &$form_state) {
    // Load the file.
    $file = file_load($form_state['values']['file_fid']);
    dpm(csv_to_array($file->uri));
    file_usage_delete($file, 'geo_points');
//    // Change status to permanent.
//    $file->status = FILE_STATUS_PERMANENT;
//    // Save.
//    $uploaded = file_save($file);
//    if ($uploaded == TRUE) {
//        dpm(csv_to_array($file->uri));
//    }
//    else {
//        drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
//    }

    //$file_path = $file->uri;

    //Function call to process file contents.
    //csv_import_create_node($file_path);

}

/**
 * @param string $filename
 * @param string $delimiter
 * @return array|bool
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

When I upload the same file more than one time I'm getting the following exception:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://csv_uploads/points2014-01-16T14-22-48.csv' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => points2014-01-16T14-22-48.csv [:db_insert_placeholder_2] => public://csv_uploads/points2014-01-16T14-22-48.csv [:db_insert_placeholder_3] => text/csv [:db_insert_placeholder_4] => 84 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1390315536 ) in drupal_write_record() (line 7170 of C:\wamp\www\drupal7_poc2\includes\common.inc).

I have 2 questions:
1. How avoid this exception.
2. After I upload the file and read it's content I don't the file anymore, can I read the stream only without saving the file?

Use a try...catch block and recover in whatever way makes most sense to your application.
The file is already on the disk by the time you get access to it (in the /tmp folder), so no. If you don't explicitly choose to keep it, it will be deleted either by a system job or the system module's cron run.


Attach user created content (in this case a gallery view) to a Profile 2, per user I have created Galleries by following the tutorial here:

http://www.dailymotion.com/video/xnqe4c_creating-a-drupal-7-image-gallery-using-content-types-nodes_tech?start=0#.UOS4IRwujTN

I managed to do it fine and have the galleries working.

Now what I would like to do, is to be able to attach that view to the Profile2 for each user.

I tried different ways, but I probably don't have the concept right and time is pressing. I would really appreciate if anyone could give me a pointer.

Just by changing the EVA parameters from Content: Album to Profile: Name of Profile. I assumed the view was going to get attached to Profile. Well it does!

But How do I filter the content in order to just get the attached images uploaded by the profile owner?

Also, I have the following issue, the profile author is always the administrator, since users cannot create profiles. They are able to edit them after the profile is created by the admin.

I thank anyone who can give me a tip on how to solve this issue.

Further info: Using Drupal7, Profile2, Views3, Eva

FOUND OUT YET ANOTHER ISSUE : The "Add more images" link as per the reference node is public. If you set this field as private, it only affects the display of the Title(link) in the image node, but the "Add more images" link shows and can be used by anyone. How can this be solved?

I am going to answer the first part of my own question:

If you need a gallery per user and you need to attach it to a profile2 type. Follow the tutorial linked to in above question, to create each gallery.

Clone the gallery view (EVA Field), and change in Entity Content Settings.
For Entity Type use Profile.
For Bundles, the profile types you want the view to be attached to.
For Arguments, choose token, and select profile2:user:uid.
Go to Advanced and add a Content: Author relationship and Contextual Filters: (author) User: Uid. In the settings of the Contextual filter choose author for Relationship (that's what appear between brackets) and also for WHEN THE FILTER IS NOT AVAILABLE select Provide Default Value -> User ID from URL. And below, Specify Validation Criteria > Choose "User" as the Validator from the pull down, and "Allow both numeric UID's and string username (I don't know if that's strictly necessary but broadens the possibilities).
You may want to (I did) restrict the selected roles to those that have that kind of profile2 type. Done.

Now I need to figure out how to restrict the "Add more images" link. If anyone can answer that, I appreciate.

I have created a URL alias pattern for the images content type that includes the USER ID in the URL when an image is uploaded.


Call python from module and receive output I am creating a Drupal 7 custom module and would like to call a python script from the PHP and receive back some output from the script.  I am running on a Linux OS and have the following so far:

    $command =  "/usr/bin/python " .  drupal_get_path("module", "mycustmod") . "/pycriptdir/pyscript.py ../../../../default/files/shapefiles/CherokeeCounty.shp";
    $output = shell_exec($command);

Within the python script I am using echo to pipe the output.  However, I do not get anything back into the output variable as I would expect.

Any advice on how to get this to work would be greatly appreciated.

Thanks,
Derek

Thanks for the responses.  The basic take-home for me here is to try a simple python script shell_exec first.  Once I did this I was able to quickly see that shell_exec was working as expected.  This in turn led me to my issue which ended up being not really related where I had some minor path issue that were throwing me off.  Perhaps drupalist advice to "try a simple command to make sure shell_exec works, then check the python" will help others with the same issue.

Derek


Create a Redirect for a page if its unpublished / deleted We have an issue when a page is deleted/ unpublished someone forgets to add a redirect.

Now what i am looking for is when someone is about to unpublished a page or delete it, we pop something up that will offer a user a list of pages and they can select which one it should go to.

Any ideas where I should start with this and what hooks I could use.

There is a module that does much of what you describe: Save Redirect on Delete.  It will push the user to a predefined page and you could put popular items on that destination page.

If you want the recommended content to be customized for the page they tried to reach you'll almost certainly want to build something custom. This module would probably give you a starting point, but in addition to what it provides you'd also need to preserve some kind of taxonomy reference (or similar) information to be able to provide something sensible.


Generate meta in controller I'm creating a custom module. This module displays public custom content without node and views . For this content custom page , I would like to add dynamic meta keyword and meta description .

I have read this excellent answer
How do I add a meta tag in <head>...</head> section?
and it said we can use

mymodulename_page_attachments(&$page)

and update variable

$page

But the meta contents are getting in a controller's method. For this raison, I would like to
pass the meta contents to mymodulename_page_attachments hook.

How can I call and update $page in my controller module to do this ? Or how can I generate meta in my controller ?

hook_page_attachments() is only needed so you can attach it to any possible route/url. You should be to just add it directly to the response that you re returning, and it should bubble up and be added.


How can I list all the terms of a given vocabulary using Views? I just need to list all the terms of the "Colors" vocabulary using the Drupal 7 version of Views. I thought it was simple to do it, but I can't find a way to get it.

I can't use contextual filters.

You need to build the view from a taxonomy base as shown in this screenshot (I'm showing Tags; you would need to show Colors):


Can I attach a javascript function to a Drupal.behaviors javascript function? I want to trigger another function any time Drupal.behaviors.MultiPage (found in field_group/multipage) changes page.

It's part of this code:

Drupal.behaviors.MultiPage = {
  attach: function (context) {
    $('.multipage-panes', context).once('multipage', function () {

      var focusID = $(':hidden.multipage-active-control', this).val();
      var paneWithFocus;

      // Check if there are some wrappers that can be converted to multipages.
      var $panes = $('> div.field-group-multipage', this);
      var $form = $panes.parents('form');
      if ($panes.length == 0) {
        return;
      }

      // Create the next/previous controls.
      var $controls;

      // Transform each div.multipage-pane into a multipage with controls.
      $panes.each(function () {

        $controls = $('

');
        $(this).append($controls);

        // Check if the submit button needs to move to the latest pane.
        if (Drupal.settings.field_group.multipage_move_submit && $('.form-actions').length) {
          $('.form-actions', $form).remove().appendTo($($controls, $panes.last()));
        }

        var multipageControl = new Drupal.multipageControl({
          title: $('> .multipage-pane-title', this).text(),
          wrapper: $(this),
          has_next: $(this).next().length,
          has_previous: $(this).prev().length
        });

        $controls.append(multipageControl.item);
        $(this)
          .addClass('multipage-pane')
          .data('multipageControl', multipageControl);

        if (this.id == focusID) {
          paneWithFocus = $(this);
        }

      });

      if (paneWithFocus === undefined) {
        // If the current URL has a fragment and one of the tabs contains an
        // element that matches the URL fragment, activate that tab.
        var hash = window.location.hash.replace(/[=%;,\/]/g, "");
        if (hash !== '#' && $(hash, this).length) {
          paneWithFocus = $(window.location.hash, this).closest('.multipage-pane');
        }
        else {
          paneWithFocus = $('multipage-open', this).length ? $('multipage-open', this) : $('> .multipage-pane:first', this);
        }
}
      if (paneWithFocus !== undefined) {
        paneWithFocus.data('multipageControl').focus();
      }
    });
  }
};

/**
 * The multipagePane object represents a single div as a page.
 *
 * @param settings
 *   An object with the following keys:
 *   - title: The name of the tab.
 *   - wrapper: The jQuery object of the
 that is the tab pane.
 */
Drupal.multipageControl = function (settings) {
  var self = this;
  var controls = Drupal.theme('multipage', settings);
  $.extend(self, settings, controls);

  this.nextLink.click(function () {
    self.nextPage();
    return false;
  });

  this.previousLink.click(function () {
    self.previousPage();
    return false;
  });

What I want to do is track anytime the user clicks the "Next" or "Previous" buttons - the code that triggers this is at the bottom of the snippet.

Is there a way for me to bind an event handler to this function?

Yes you can. You can attach as many event handlers to any DOM element as you want.

So you have to write your own module that alters the output (is a form? some form_alter function. Is a page? some ouptut alter function or theme function) adding your custom JavaScript.

In your custom JavaScript add the code using behaviors that attachs your event handlers for the click event.

The tricky part is how you locate the next and prev buttons. You can start from the code snippet you posted. It seems that prev and next buttons are located here:

 var multipageControl = new Drupal.multipageControl({
      title: $('> .multipage-pane-title', this).text(),
      wrapper: $(this),
      has_next: $(this).next().length,
      has_previous: $(this).prev().length
    });

See the has_next and has_previous entries.

Looking at the previous lines you can see:

// Transform each div.multipage-pane into a multipage with controls.

It seems that the $(this) code referes to a div.multipage-pane, so the buttons seem to be:

$prev_buttons = jQuery('div.multipage-pane').prev();
$next_buttons = jQuery('div.multipage-pane').next();

Disclaimer: I don't know that module so I am shooting blindly but I think this approach will work.


Show "create new node" form with "my" and "user I followed" content in a single block I have a content type. Let us say "articles". When a user wants to create an article, the user will go to /node/add/article and it will show a form like it shows on stack exchange when go to /questions/ask.

What I want?

I want to create a block which will show the "create new node" form + my articles + articles of the user I am following with follow(user) flag. "My" and "user followed" articles should be shown below the form. The form and articles should always be visible in the block. When user saves a new article, it should show in the list below without page refresh.

The user should not be allowed to select text format. The admin should choose which text format to enable on this particular content type.

Note: When user visits node/add/articles directly, user must not see the articles. User should only see the form to create a new node.

I am sure I have explained it quite well. Let me know in case you have any questions.

I have a content type. Let us say "articles". When a user wants to
  create an article, he will go to /node/add/article and it will show a
  form like it shows on stack exchange when go to /questions/ask.

Give whichever user you want to create the node, permission to do so /admin/people/permissions

What I want?

  I want to create a block which will show the "create new node" form
  as above

  my articles

You mean the articles of admin or of the user creating the form? If admin, create a view with articles and filter by user admin, or filter by currently logged in user.

  articles of the user I am following with follow(user) flag.

as above. I presume you are giving the user the ability to flag other users to follow somehow? So you could filter by a list of users that are being followed.

  "My" and "user followed" articles should be shown below the form. The
  form and articles should always be visible in the block.

  When user saves a new article, it should show in the list below
  without page refresh.

You would use ajax to achieve this. Check out 'exposed filters' in views and look for the option to 'use ajax'.

  The user should not be allowed to select text format. The admin should
  choose which text format to enable on this particular content type.

This is built in. There are permissions for, example, "Use the Filtered HTML text format" and in the settings for the content type, which text formats are available.

  Note: When user visits node/add/articles directly, he must not see the
  articles. He should only see the form to create a new node.

  I am sure I have explained it quite well. Let me know in case you have
  any questions.

There are multiple questions here, and ideally you would post some code and show what you have already done.


How do I redirect the unsubscribe link in a newsletter to a particular node? I am using the Simplenews module for sending newsletters, and the Mandrill service for sending emails. When I send a test newsletter to the test user, the unsubscribe link should be redirected to particular node, for example to node/2.

How can I achieve this?

Use the Rules module and use the Rules (System) Event "Drupal is initializing" (= init). And add an extra condition related to the URL of your unsubscribe link. Add to that a Rules Action to perform a redirect to your node/2.

Here is a rule that should be close to what you'd need (assuming the path of your unsubscribe link is Some/Unsubscribe/Path):

{ "rules_redirect_unsubscribe_link" : {
    "LABEL" : "Redirect unsubscribe link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "Some\/Unsubscribe\/Path",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirecting URL [site:current-page:url] ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "node\/2" } }
    ]
  }
}

The above rule does not (yet) take into account to only apply the Rules Action for your "test user" (as in your question) only. But for anybody a bit familiar with the Rules module, that is a straight forward Rules Condition to add ...

And the above rule also uses a Regular Expression in its Rules Condition that could be simplified to a simplified version of it (not using such expression). However, if you have various unsubscribe links that all have a similar pattern, you only have to massage that expression in the above Rules Condition to have all such links fit in the same expression.

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if the Rules UI submodule is enabled). Then further edit/refine to make it fit in your own environment (e.g the "Redirecting URL ..." message to be shown).


Views field that links to fragment URL of comment on /node/ instead of /comment/ With Views, I want to output a list that links to each comment of the current node. But instead of linking to

/comment/42#comment-42

I want to link to

/node/23#comment-42

I tried these fields, but they all link to the URL in the /comment/ space:

Comment: Title (Formatter: Plain text)

/comment/42

Comment: Title (Formatter: Comment Permalink)

/comment/42#comment-42

Comment: Link to Comment

/comment/42

Is there a way to output anchors in the /node/ space? The solution doesn’t need to support comment pagination (a node will never reach the limit).

An ugly workaround (which will not work for paginated comments):

Add the field "Content: Link to Content"

Use the relationship "Content" (should be default when creating a comments view)
Enable "Exclude from display"
Enable "Output the URL as text"

Add the field "Comment: Comment ID"

Set "Formatter" to "Unformatted"
Enable "Exclude from display"

Add the field "Comment: Title"

Set "Formatter" to "Plain text"
Disable "Link to the Comment"
Enable "Output this field as a custom link" (under "Rewrite results")
Link path: {{ view_node }}#comment-{{ cid }}
(field names might differ, use what’s listed under "Replacement patterns")


Error in User Edit form Have searched a lot for this issue. I am not sure if it is a php issue or Drupal issue but the error message is pointing towards Drupal. Whenever i go to the user edit form in Drupal 7 i get the following error:

Notice: Undefined index: #title in user_account_form() (line 1070 of /opt/lampp/htdocs/modules/user/user.module)

I have searched a lot. This seemed relevant http://drupal.org/node/1088964 but it did not work out for me. Any suggestions would be appreciated.

Thanks

Edit 1: I am using 7.18 and yes i have done some changes in user registration form...i have commented the lines in bold and added a placeholder. Now when i uncomment them then no error occurs but then in my user registration form those fields show up...let me clear this through 2 images...1st image shows the case when i commented the lines(in bold) and added a placeholder (this is what i want it to look like):

However this gives me the error in user edit form. Now when i uncomment, it looks like

I do not want the labels Username and password to show up there. How can i achieve this without that error bugging me. The line number 1070 is inside user_account_form as well. I have realized the error is because i have commented out and it is looking for a title field or password field but then my registration form looses its appearance as i want. Is there a way round to do this.

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

      $account = $form['#user'];
      $register = ($form['#user']->uid > 0 ? FALSE : TRUE);

      $admin = user_access('administer users');

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

      // Account information.
      $form['account'] = array(
        '#type'   => 'container',
        '#weight' => -10,
      );
      // Only show name field on registration form or user can change own username.
      $form['account']['name'] = array(
        '#type' => 'textfield',
        **//'#title' => t('Username'),**
        '#maxlength' => USERNAME_MAX_LENGTH,
        //'#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
        '#required' => TRUE,
        **'#attributes' => array('class' => array('username'), 'placeholder'=>t('Username')),**
        '#default_value' => (!$register ? $account->name : ''),
        '#access' => ($register || ($user->uid == $account->uid && user_access('change own username')) || $admin),
        '#weight' => -10,
      );

      $form['account']['mail'] = array(
        '#type' => 'textfield',
       **'#title' => t(' Email Id'),**
        '#maxlength' => EMAIL_MAX_LENGTH,
       // '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
        '#required' => TRUE,
        '#default_value' => (!$register ? $account->mail : ''),
        **'#attributes' => array('placeholder' => t ('E-mail')),**
      );

The lines where the error points to :

if (!$pass_reset) {
      $protected_values['mail'] = $form['account']['mail']['#title'];
      $protected_values['pass'] = t('Password');

You shouldn't be modifying any core files. Removing a declaration for a value that needs to be used elsewhere is causing your problem, and the solution is to make your changes using hooks and templates in custom modules and themes, which are Drupal's way of allowing users to modify behavior and output.

This thread contains discussion of theming the user edit page, and has links to helpful information.


What's difference between node_revision__field_X and node__field_X tables in Drupal 8? I'm in the process of migrating a complex D6 site up to D8 using the Migration tool. An old table content_field_gallery seems to have been migrated to a node_revision__field_gallery table, but there is also a node__field_gallery table with about half as many rows.

I'm guessing that the node__field_X version has only the latest revision and the node_revision__field_X has ALL revisions. Is that correct? Isn't that redundant? And a good index should make a single table pretty efficient? Where can I read more about this?

Yes, that is correct. This is the same data structure as in Drupal 7.

It would be possible to write a different backend that only uses one table, there was a project for that for Drupal 7 but I think it never really took off.

See https://www.drupal.org/node/2083451 for a discussion if that's still necessary or not.


How can I transfer votes to nodes selected from an entity reference list? I create a form where users can submit their opinion and votes about nodes that they select from an entity referenced list.
How can I assign the votes to the entities that apoear on this list?

eg.
"Review" content type are completed by auth users.
In "review" form there are 2 fields "class" and "teacher" where the user can select from an list of nodes "class" and "teacher" content types. After the user select the "class" and "teacher" then must vote (voteapi & rate) and complete an opinion (textarea) about the nodes he selects.

Use the Inline Entity form, which allows you to set a view with the list of nodes and modify them directly (you would set the voting in the voted node e.g., the class or teacher, in your example).

The plan is for you to set up the Review content type with a Entity Reference field. This will allow you reference a View where you can set up your Class and Teacher Nodes.

You need the following Modules: Five Star and Voting Api (Which you already have) Views, Entity API, Inline Entity Form.

The way I understand your process is as follows:

You have a set of classes and a teachers
You intend to make available a set of these classes and teachers to a different content type (this is review), to generate votes for that class and/or teacher
The number of classes/teachers available for that review to emit a vote from is unspecified (may be all or a subset of them)

To go about this you need to have the following:

Voting fields in class and teacher content types
Create a Entity Reference View which displays the list of nodes you need (one for each, selecting their respective content types).
Add a Entity Reference field in the review content type with the Inline entity form - multiple values widget.
While setting the field:

Check Allow users to add existing nodes, so that they can select the class/teacher from your current list.
Select in Entity Selection: Views: Filter by an entity reference view
Select in View used to select the entities the view you would prefer for that field (teacher or class)

You should be able to add the classes/teachers you want to vote for. Also, you can control the entities shown by the view (so you could add context filters). Be mindful of setting the votes so you can vote while editing.


PHP error with Computed field here is my code:

$nid = $entity->field_empf_number['und']['0']['nid'];
$result = db_query("SELECT MAX(entity_id) FROM field_data_field_empf_number WHERE field_empf_number_nid = $nid")->fetchField();
if (isset($result)){
  $n = $result ;
  $node = node_load($n);
  $node->field_empf_stat['und']['0']['value'] = 'off';  //list field
  node_save($node);
}
$entity_field[0]['value'] = $result;`

when add new node (if there is previous node i mean the if statement return true ) this error message show up:

  Fatal error: Maximum function nesting level of '100' reached,
  aborting! in C:\wamp\www\finance\includes\database\database.inc on
  line 429

I googled but i did not found any answers.

Try to change the node_save($node) to drupal_register_shutdown_function('node_save', $node). It will remove the old node saving process from the actual node saving.
But I don't think, that type of code should have place within a computed field. The computed field good to modify the same field. It isn't designed for modifying other data of your system.
These code should be in a custom module in hook_node_presave().


Can you set the Media module to only show specific images? I'm looking to use the media module on a site. Very impressed so far with it but there is one thing I need of it for it to be perfect.

I need it to only show certain images in the library, not every single image that has been uploaded. Is there any way of doing this that any one knows?

Thanks

Media module 2.x uses views in its media browser.  You can edit the standard view, or create new ones, and use relationships and (exposed) filters.


Date Field Type - Text Field Widget is Gone? I am noticing that the Date field type only has the availability of three widgets:

Select list
Date and time
Select list, no time

Can someone tell me why the "Text Field" widget is gone?  Or am I missing something?
I have a use case where the user needs to be able to copy the date from another source and paste that value into the date field.  It would be too time-consuming to have to pick the date from a "date picker" widget.  It would be ok if it were a one-off situation but this user needs to be able to enter several at a time.

I have a use case where the user needs to be able to copy the date
from another source and paste that value into the date field.

Bootstrap Datepicker
This will allow you to type/paste in and change the date format.

Note: composer won't install the library for you, you have to manually get the /dist folder from github and put in in the /libraries folder. So it has the /libraries/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js structure.

Similar but don't quite do it
Datetime Flatpickr Allows you to change date format, but doesn't allow you to type/paste in.
Bootstrap DateTime Picker Allows you to type/paste in, but doesn't allow changing the date format.
Single Date Time Picker doesn't allow you to type/paste in nor change the time format.


How to add currency (TMT) to Commerce? Turkmenistan Manat is missing from Drupal Commerce list - how to add it to 7.x?

Per the commerce.api.php file, there is a document hook which allows you to add currencies.

function hook_commerce_currency_info() {
  return array (
    'CHF' => array(
      'code' => 'CHF',
      'numeric_code' => '756',
      'symbol' => 'Fr.',
      'name' => t('Swiss Franc'),
      'symbol_placement' => 'before',
      'code_placement' => 'before',
      'minor_unit' => t('Rappen'),
      'major_unit' => t('Franc'),
      'rounding_step' => '0.05',
    ),
  );
}

http://cgit.drupalcode.org/commerce/tree/commerce.api.php


Can I use ajax to target multiple form elements from one input? I'm trying to use ajax to update two different parts of a drupal form from just one form input blur.

I have the standard ajax stuff on my input:

$my_form['my_input']['#ajax'] = array(
  'callback' => 'my_callback',
  'wrapper' => 'my_target_div',
  'event' => 'blur',
);

This is working well, swapping out my div when the input is updated ... however I also want to update another form input elsewhere in the form with different code as a result of the blur on my original input.

Is this possible, any ideas?

Edit: For clarity, here's my real world example:

Content type 'movie'
Added field 'primary_title'
When 'primary_title' is updated my ajax callback checks for similar strings and returns html.
The html from the callback is inserted into an empty div.

That part is working great!

I'm trying to also modify the standard node 'title' input, giving it the value of 'primary_title' after I have done some regex to tidy up the string (removing "The" or "A" from the start etc) The result will be two title fields, one with the complete title 'primary_title' and one trimmed 'title' that will be useful for sorting and displaying records.

It appears that you can target different parts of a form using ajax commands, however you must choose to return only one of either:

HTML or
A renderable array or
An array of AJAX commands

In the situation I originally wrote about, I was trying to return both an array of AJAX commands and a renderable array, which doesn't seem possible.

Code in the examples module demonstrates targeting different parts of a form using an array of AJAX commands:

function ajax_example_advanced_commands_html_callback($form, $form_state) {
  $text = $form_state['values']['html_command_example'];

  $commands = array();
  $commands[] = ajax_command_html('#html_div', $text);
  $commands[] = ajax_command_replace("#html_status", "
Updated html_command_example with text=$text;  " . date('r') . "
");
  return array('#type' => 'ajax', '#commands' => $commands);
}

In this code sample, #html_div is getting $text, and separately #html_status is getting "Updated html_command_example with text=$text;  " . date('r') . ""

Two different locations on a form with two different pieces of information from the one ajax callback!

Looking again at what I was working on, I realized that I didn't need to return the node title field at all. It will only be a utility field, used for sorting data in lists.

I have hidden the field on the node form and it is populated the second time my form is built when my original ajax callback is triggered.


How to limit the number of privatemsg? To avoid bulk private messaging by spammers in busy Drupal 6 community site, I'd like to limit the messages an authenticated user can send out in certain time span.
I saw Private Message Limits but it is still in dev since 2011 hence it may  not be ready for production. So I'm wondering what is the best way to apply the limit? Thanks

Privatemsg 6.x-2.x has a Limits submodule built in, either use that version or use try out the separate project for 6.x-1.x, you will have to find out yourself it is working well enough for you.


Create block programmatically based on node content In Views we can create a block that the content depends on the content of a node using contextual filters. So we can pass variables and check the visibility of the Views-Block.

Let’s say in our content type we have a field that has a text-field. In Views->Contextual->Our field->Provide default value-> content ID from URL can grab this.

But creating a block programmatically

hook_block_view($delta = '') {
…
$block['content'] = theme('item_list', array(
         'items' => ???,
          'type' => 'ul',
        ));
…
}

How we can grab these values form the node-field?

And if there are no values how we will hide the block?

Found a few modules depending on your need:

Node field block

  An easy way to create blocks with a collection of node fields. Focused on letting customers manage most of the content on a page in just one node. You can create multiple blocks for a node with one or a combination of fields and move them in different regions.

Field as block

  Field as Block provides an easy way to display one or more fields of the current node in a block.

There's a custom way also if you want. You can use below function for this purpose.

render(field_view_field('node', $node, 'field_myfield'));


how to create tabbed blocks for recent comment and recent content? i want to create a tabbed block with two tabs . One for showing recent content and one for showing recent comments .. how can it be done in drupal 7 using only the modules ??

Use the quicktabs module:

http://drupal.org/project/quicktabs

Install it normally, and then 'add quicktabs instance'. In the interface, select the two views you have that you want to display and add them to each of the tabs. Your new block will show up in the block menu to be placed using the blocks menu or other layout solution.


commerce_customer_address I am using Commerce Kirckstart installation.

I would like to  change a field in commerce_customer_address.
I only want a new field, like telephone and I would like to remove State.
Some one knows how to do without code.
thanks

Commerce customer profile uses an address field, whose columns are defined by the addressfield module.

It's not possible to alter those columns without writing code, so you're out of luck.

Also, I'd imagine that removing the state field would incur quite a bit of extra work, as existing validation/submission functionality would need to be overridden.

The easiest thing you can do is add the telephone number field to the profile type entity itself, and use a form alter or CSS to remove/hide the state field.


Count Search Results I am trying to create a block to put on the search results page that has a list of the content types in the search results and the number of results for that content type.

Does anyone know how this can be achieved, if it can be?

So far I've tried hooking into _preprocess_search_results but that only works with the current page of the results.

Thanks for any help with this.

Why aren't you using facets?

That's how blocks which list search results grouped according to a certain criteria are called and it's a built-in feature of Search API.

All you need to do is get Facet API, enable the integration module search_api_facetapi, enable the type field, set it up as a facet and enable the block.

That block then doesn't just list the content types, you can also click on it and the results are automatically limited to that type.


How should the view data be defined when adding a custom filter to a field? How to add a custom views filter handler for a specific field? answers on how to add a filter to a base field.

I'm looking to add a filter to a non base field. (The field name is contact).

Here's what I have so far:

/**
 * Implements hook_views_data_alter().
 */
function custom_contact_views_data_alter(array &$data) {
  $data['node__contact']['active_contact'] = [
    'title' => t('Active contact filter'),
    'filter' => [
      'title' => t('Active contact filter'),
      'help' => 'Filters node on active contact',
      'field' => 'contact_target_id',
      'id' => 'active_contact',
    ],
  ];
}

It is added, but it complains about group missing in the Views UI Error: missing group

How should the views data be defined when adding a custom filter to a non-base field?

You get the error Error: missing group.

You should be able to fix it by adding the group property, like this:

$data['node__contact']['active_contact'] = [
  'title' => t('Active contact filter'),
  'group' => t('Contact'), // Add this line.
  'filter' => [
    // ...
  ],
];


Nested Image/Video Galleries in Drupal 7 Alright so after looking around for awhile and not finding exactly what I am looking for hopefully someone can help me out with this.

On my website I plan on having both image galleries and video galleries.
I can configure a views gallery or using Media Gallery which works wonders except for what I want to do(media gallery that is).

My videos (or even images if this is possible) section I would like to have nested galleries potentially up to 3 tiers at a time. I am assuming I can do this taxonomy but I don't want to add a new term every time a new 'series' comes out, as I don't necessarily know the name of said series before it comes out.

I would like my gallery to flow as such:

Galleries Overview

Gallery A

Gallery A1

Nested Gallery A11
Nested Gallery A12
Nested Gallery A13

Gallery A2

Nested Gallery A21
Nested Gallery A22
Nested Gallery A23

Gallery A3

Gallery A31
Gallery A32
Gallery A33

Gallery B

Gallery B1
Gallery B2
Gallery B3

Gallery C

Gallery C1
Gallery C2
Gallery C3

I am probably over thinking this and there must be an easier way to do this because I have read posts of sites with nested galleries I just cant seem to figure it out.

Final option would be to downgrade to Drupal 6. If it is truly easier this way, it is not that big of a deal, (no real content on my site yet). I know nested galleries are done on D6, and a few years back I had a D6 website with Nested Galleries which is why I am surprised this is an issue now.

The trick is information architecture. I suggest you use the book module to define the hierarchy. This is an underestimated core module, which works amazingly well and has good integration with Drupal. In a recent site I've architected, all the site navigation was built dynamically using views, book-related contextual filters, and the viewfield module (which allows to put a view inside view). Play with the setup below and enjoy!

Detailed instructions:

Enable the book module.
Define top galleries as toplevel books, without a parent:

Go to the node editing screen.
Click on the new 'Outline' toplevel tab created by the book module.
Click on the 'Add to book outline' button. This will create a new book.

For each child gallery, select it's parent gallery

The parent gallery may be one of the toplevel galleries created on the previous steps, or one of the previous child galleries created on this step.
The child gallery may either be selected on the on the 'Outline' tab (when editing existing nodes) or on the 'Book Outline' vertical tab  displayed below (when creating new nodes).

Create a new view, which will show your toplevel galleies. let's call it "top galleries"

Open a 'block' display
Make the view field-based.
Add the title field to show the gallery title.
Add a viewfield to show the sub-galleries of this book.
The viewfield will refer to a new view we will create in the next step.
And, most imprtantly, use a filter criteria of Book: Depth (=1)

Create a "gallery-inner" view.

Open the 'Advanced' setting
Create a relationship from the node to Book: Parent - the parent book node.
Set a contextual filter to "Content: Nid" taken from the parent book node.
Now the view show all children of it's parent book.
I haven't tried it but you may also try to add another viewfield here to show the children of those child views recursively, until there is a level with no more children (if it doesn't work, then create anorhter  "gallery-grandchildren" view for the 3rd level. Please report back here and write which way succeeds.

Notes:
- The screenshots were taken from a similar solution, where I've implemented all of the site navigation menus using the book hierarchy defined by the user. So please add an image field to each view where appropriate.


How can I output log messages to stdout/stderr? I can create log messages really easily in Drupal 9.x like this;
\Drupal::logger('mymodule')->error("something went wrong");

I see these messages appear in /admin/reports/dblog, but it would be convenient if I had the option to print them to stdout, or perhaps a file that I could tail. Is this possible?
Note that this question looks similar but I think it's for an older version of drupal using watchdog, so I don't think it applies: how to show admin/reports/dblog in terminal ( cli )

I’ve been using the log_stdout module for stdout logging. It works well with Docker containers.

This module provides a hook for Drupal Watchdog that directs log messages to php://stdout or php://stderr for better log handling with Docker.