Image Style Clarification Can I get some clarification as to why images aren't being generated for a certain image style in a view?

Here's my setup; I have an Article content type which allows for a main image to be uploaded. An Article Images image style is applied which crops to the focal point (Module that's installed) and generates the image for the Article node.

I also have a view block that I use on my homepage that displays the 2 most recent articles. What this does is display the title of the article, date and tag over the main image.

In my view settings for this block, I have the Image Style set to Article Homepage - 1075x400 with the Formatter set to URL to image. With a custom template, the block is displayed and what it's supposed to do is set the main image as the background image. If I leave the Image Style set to Article Images in the view, this works perfectly, however, changing it to the above mentioned Article Homepage - 1075x400 ends up generating an error as it says the image doesn't exist.

In one way, this makes sense to me since when I uploaded that image to the article node, it was uploaded only in that certain style so it wouldn't make it available in any other style, would it? Or maybe I'm not seeing this the right way or something in my template is wrong.

Any clarification as to why changing the style for my homepage view ends up displaying nothing would be great.

Below is the template for that homepage block in case my issue is coming from this. Maybe there's something I need to put in here so that any style can take effect?

  {% set bg_url = fields.field_image.content|render|striptags|trim %}
  {% if bg_url %}

  {% else %}

  {% endif %}

{{ fields.title.content }}

{{ fields.created.content }}

      {% if fields.field_tags.content|render %}

{{ fields.field_tags.content}}

      {% endif %}

Update 1:

So, I think I might be onto what's happening here. I think it comes down to me using the twig filters in my theme file. If I remove |striptags|trim it generates the image style, however, it won't actually show up in my dev site, in which I'm developing all this, due to the fact that without those other two filters, this is what ends up printing out in the style class:

style="background-image: url(

/sites/default/files/styles/articles_homepage_1075x400/public/articles/2019-05/image.jpg?h=287a81f3&amp;itok=aMmcvNDO

)"

After removing those filters in the file, letting it generate the style, then putting the other two filters back, the image does show up. I'm assuming those filters are hindering the creation for some reason. It may end up not being a problem if I leave those filters out. Sure it won't show up properly on my dev site but I'm going to assume it'll work properly on dev.

Update 2:

Removing |render|striptags|trim from my field_image ended up making this work as intended on my production website. It still remains broken on my dev site though due to it spitting out that extra code.

Are you sure that image style still exists?  Views doesn't like when you delete/change image styles that it is already using.  A remedy might be to delete that field from your view, and reset it (with the confirmed good image style?)

Maybe your image style was formed improperly?

(Are your view blocks restricted to not show on the home page (block admin?)


Getting rid of module-specific control logic I'm writing a module that can have some additional functionality if other modules such as Block or Menu are enabled, but I don't want to declare them as a dependency.

Currently I'm using if(module_exists($module)) { ... } to provide module-specific functionality within my custom module (in this case, defining a particular view if the module in question is present).

However I've heard that this is not the right way to provide module-specific features, and that instead I should use hooks and plugins. The only problem is that I don't really know what that means or how to get started converting my module to using those instead of if()s.

How do I define a custom view that depends on another module without using an if()?

One of the things I am trying to do is to expose that module's SQL tables to Views if the module exists, and then define a custom view with those tables.

If you want to provide Views with your module, dependent on enabled modules, you can implement

hook_views_default_views

  This hook allows modules to provide their own views which can either
  be used as-is or as a "starter" for users to build from.

  This hook should be placed in MODULENAME.views_default.inc and it will
  be auto-loaded. MODULENAME.views_default.inc must be in the directory
  specified by the 'path' key returned by MODULENAME_views_api(), or the
  same directory as the .module file, if 'path' is unspecified.

  The $view->disabled boolean flag indicates whether the View should be
  enabled (FALSE) or disabled (TRUE) by default.

In that hook implementation, you can check if the relevant module is enabled with module_exists or function_exists when defining that View or component of the View and return the View definition(s) accordingly.


Autocreating new node based on non-existing node reference Are there pre-existing modules compatible with drupal 7 that let me autocreate a new node when I enter a value into an autocomplete node reference field that doesn't exist? Sort of like with taxonomy, but with node references instead. The new content is based on what's on the form only there's no need for a separate page to show up to fill in more details. I was wondering if there's something that does this, I'm aware that I could just create a simple module with a hook on node_insert to do this but I was wondering if I could leverage something that already exists.

You can use Node Reference Create module.

It will create the node automatically without having to fill in the node fields.


Is it bad practice to track all in the configuration module I am taking over a site that was built without configuration management, I installed the configuration module for the first time (I am used to using features). I am wondering if it is bad practice to just select all in all the categories and track all the available configurations instead of trying to cherry pick the applicable ones. What are the effects of performance, etc.

I have tried it in Drupal7 (not on Drupal8).

Logically it should be good practice to track all the configurations. However, not all the "configurations" are actually configurations. For example there are persistent variables or cached values that have nothing to do with the configuration. So, tracking all of them would undermine the aim of configuration tracking.

Besides this, the UI becomes infinitely slow and unresponsive when you select all the configurations. I guess it is because it tries to find out dependencies of each configuration and does it in an inefficient way. You can try to handle them from the command-line (with drush) but I doubt that it would be more efficient.

So, I think that the best option is to cherry pick the relevant configurations. But once you start cherry-picking them, you might as well use features, configuration management loses its meaning.

This is basically what I did on a project of mine: I started with configuration management, and ended up using features, which by the way was a tedious process.


How to send an email to the node author when a date is approaching? The user has created a node and has set a future date to be alerted of the approach of this date.

I want the user receive an email when the set date is approaching.

Making the user able to change the approaching time would be great.
Any sugestions?

Have you tested Rules, this is the module to do such actions based on events.
Here is a tutorial to help you with this: Publish content based on a CCK date field.

Also don't forget to enable the debugging feature of rules under admin/rules/settings.


Drupal Lightbox 2 not displaying image http://www.wmfs.net/blackcountrylevel3plan

I have the Isotope working with Lightbox2, however the Lightbox is just displaying a blank space and not the image.

I am trying different things to troubleshoot the problem, different configurations in Drupal, putting the JS in the header and footer, there are no significant JS errors in Web Inspector.

Any help is gratefully appreciated.

Ant

as i see in the console, you are using jquery.min.js?v=1.9.1

and lightbox.js is giving this error:

  TypeError: $.browser is undefined

because this function has been remove since 1.9

I'll suggest you to use default jquery version 1.4.2 where $.browser is deperecated but should work or use another ligtbox module like colorbox


Duplicated content on homepage I've found that my site is showing duplicated content, I think it was when I installed Pathauto. The nodes are not duplicated though but seems to be multiple aliases.

I've since tried using Global Redirect but it hasn't solved the issue. And even worse, some items are showing up three times now!

For example

http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening-1
http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening
http://biosphericproject.php5.demo.faelix.net/content/what-we-mean-forest-gardening-0

Confused,
Alex

You have to delete those duplicate alias by going to the alias list at admin/config/search/path (in Drupal 7). It's not an automatic task, I'm afraid.
Or you can delete all alias and bulk recreate them using the Bulk Update function. That would be an automatic process.

As a last step, you should check Alias Settings at admin/config/search/path/settings. I think you should change the "Update action" to "Create a new alias. Delete the old alias.".


How to show event calendar with active links and event details underneath I wanna show a page with calendar by month and all the upcoming events that fall within that month underneath.

So, on the page, I'd have this calendar that shows the current month:

Underneath I want the details of the events that fall in this month.

Any idea which module I should use and how can I achieve that in Drupal 7?

Thanks.

i have not tried this, but i think it will work, with calendar module enebled, go to month view, add a block view and build your underneath view, then add this block view as a footer (middle column in views ui) in your month view (Global: View area), then pass arguments in settings to be the same as your month view.


What is the relationship between hook menu() and menu_link_save()? I am trying to create a menu using code in D7 (see my related question) and have found that these two Drupal API functions have different arrays for the $item variable. My intent is to create a three level menu hierarchy but with all of the associated paths being the same format /name/%/something so that I can use views to refine the content.  In hook menu, the parents are defined using the Path name (eg. parent/child/something).  In menu_save_link, the hierarchy appears to be established using the pid array value in $item. Hook_menu is called when my custom module is read by drupal and the menu links are established.  What I am wondering is if menu_link_save, could be used to do the same thing but with the same path style for all links, rather than a parent-child pattern?

I have been trying to trace the logic between the two functions in the API, but have not found the link between them.  My thinking is that menu_link_saveis used by hook_menu after some preprocessing and that I might be able to define a uniform paths and establish the hierarchy through the pid.  Failing that, is there another way to alter the paths and preserve the hierarchy?

They're slightly different concepts to be honest; the items defined in hook_menu() are saved in the menu_router table, while menu_link_save() saves items to the menu_links table.

They come together in menu_rebuild():

hook_menu() is invoked through the menu_router_build() function to get a list of router items
The router items are saved to the database using _menu_router_save()
The menu links are generated/updated using _menu_navigation_links_rebuild(); the menu router items are passed to this function to build the links.
Finally the caches are cleared.

There doesn't seem to be any way to pass custom data from the router items to the links I'm afraid, and I don't think hook_menu() supports the sort of hierarchy you're trying to build natively.


How to convert text area data into select list in forms? I want to create a configurable select list in forms.To achieve this what I did is I have created a text area, in that I will enter values like:

HI|Hi
BYE|Bye

So, in form select options I have to use these values in a dropdown list. How can I achieve that. I am getting this text area data in form like below.Here I am getting data, but not displaying in the options.

$entityoptions = variable_get('entitydropdown');

I am getting the values as it is, but am not getting how can I assign these  values to #options. I did like below but its not displaying the values.

'#options' => $entityoptions,

Please help me to identify, where I am doing wrong. Thanks in advance.

As requested in the comments, in answer format:

Use the explode() function on your string
Loop through the results and split each entry
Add the result to the options array you feed to the select box

Eg.

$options = array();
$lines = explode(PHP_EOL, $entityoptions);
foreach($lines as $line) {
  $line = explode('|', $line);
  $options[$line[0]] = $line[1];
}


How to write paragraph template to add tags and css classes? I have a paragraph bundle (pr_bnd1), which has several fields as below:

field_txt
field_bg_clr (list field whose key values are mapped to a css class)
field_font_clr (list field whose key values are mapped to a css class)

The an example output

 field_txt value

Desired output

.
    field_txt value

How would i achieve the desired results? I am having trouble getting the template file to work. Any thought?

My paragraph bundle name is "pr_bg_font_clr".

So i imagine i would have to write a template file with the name of "paragraph-items--pr-bg-font-clr", but i am not sure what the structure should be and which fields i can utilize.

Have a look here for the naming

  The default paragraphs template is in paragraphs-item.tpl.php. It uses
  theme suggestions for other templates, the following suggestions are
  available:

  paragraphs__[view_mode] (e.g. paragraphs--default.tpl.php)
  paragraphs__[type] (e.g. paragraphs--image.tpl.php)
  paragraphs__[type]__[view_mode] (e.g. paragraphs--image--default.tpl.php)

As this seems to be wrong .. Try the suggestion:

paragraphs-items--pr_bg_font_clr.tpl.php
paragraphs-item--pr_bg_font_clr.tpl.php


How to add Callback function for delete operation? I want to add a custom callback function for my delete operation.

$form['table'][$entity->id()] = [
        'title' => [
          '#type' => 'textfield',
          '#default_value' => $title,
        ],
        'status' => [
          '#type' => 'checkbox',
          '#default_value' => 1,
          '#disabled' => ($delta == 0),
        ],
        'weight' => [
          '#type' => 'weight',
          '#default_value' => $delta,
          '#attributes' => array('class' => array('mytable-order-weight')),
        ],
        'operations' => [
          '#type' => 'operations',
          '#links' => [
            'view' => [
              'title' => $this->t('View'),
              'url' => $entity->toUrl(),
            ],
            'edit' => [
              'title' => $this->t('Edit'),
              'url' => $entity->toUrl('edit-form'),
            ],
            'delete' => [
              'title' => $this->t('Delete'),
              // add callback function.
            ],
          ],
        ],
      ];

How do I do this?

What I tried so far was

'delete' => [
              'title' => $this->t('Delete'),
              '#callback' => 'myDeleteFunction'
            ],

The operations are a list of links. If you want to delete a different entity see this example from the core workflows module how to build a delete link:

WorkflowStateEditForm::Form()

  $links['delete'] = [
    'title' => t('Delete'),
    'url' => Url::fromRoute('entity.workflow.delete_transition_form', [
      'workflow' => $workflow->id(),
      'workflow_transition' => $transition->id()
    ]),
  ];


Cron Run error for drush update script I have created a script drup.sh to update the site with security issues and placed it in the sites/default dir.

#!/bin/bash
drush up drupal --security-only -y

And on testing it by running bash drup.sh from the command line, as the user, in the sites/default dir. all works good

When I set up a cron to run it, as the user, I get the following errors

Command pm-update needs a higher bootstrap level to run - you will       [error]
need to invoke drush from a more functional Drupal environment to run
this command.
Command pm-update needs the following modules installed/enabled to       [error]
run: update.
The drush command 'up' could not be executed.                            [error]
A Drupal installation directory could not be found                       [error]

The command I use at the moment is

bash /home/user/public_html/sites/default/drup.sh

I have looked at the page you suggested, I had looked at it before but it did not make sense to me. I have tried various combinations, without success

The closest I can get to it not giving an error is

/usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin COLUMNS=72 --username=/home/username/public_html/sites/default/drup.sh

the output is

SHELL=/bin/sh
USER=middlesex
LD_LIBRARY_PATH=
REMOTE_ADDR_PROTOCOL=4
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
SERVER_REALROOT=/usr/libexec/webmin
PWD=/usr/libexec/webmin/cron/
PERLLIB=/usr/libexec/webmin
REMOTE_ADDR=x.x.x.x
SHLVL=1
HOME=/home/username
LOGNAME=username
_=/usr/bin/env
COLUMNS=72
--username=/home/username/public_html/sites/default/drup.sh

But drush does not run or do anything

Take a look what is said here about running drush with crontab and pay especially attention to "Setting the PATH". Also you should specify the path to your drupal installation with the --root option.


Programmatically added taxonomy terms not being indexed I'm assigning taxonomy terms to an entity (user) like this:

$drupalUser->taxonomy_vocabulary_6 = array('und' => array(0 => array('tid' => _findorcreate_tid($eecid, $arrUser[12]))));

_findorcreate_tid finds, or creates a new tid, within the supplied vocabulary.  This function is working correctly. $eecid is the vocabulary ID. $arrUser is some user data imported from a CSV.

When viewing the user object, the correct term name and ID is displayed, but viewing the term's "contents" (at a URL like http://localhost/taxonomy/term/1061), I'm told there is no content.

My very amateur poking around leads me to believe that the taxonomy_index table is not getting populated when I assign the terms in this manner.

I have tried to call
taxonomy_build_node_index($drupalUser);
after the user object is saved, but this has yielded no change (and I'm a bit unclear if that function only applies to nodes, or any entity).

Is there a better way of assigning taxonomy terms to a user entity that would fix this?

You're correct. The core taxonomy module doesn't index or display entities other than nodes. taxonomy_build_node_index() is only for nodes.

It sounds like the solution you're looking for is Taxonomy Entity Index.

  The Taxonomy Entity Index module maintains a normalized index of all
  terms associated with a specific entity and revision. The core
  {taxonomy_index} table only maintains its data for published nodes.
  This module maintains its data for all entity types (regardless of
  published or not) and also indexed by revision.

It also supports views integration so you should be able to create a view of users who have been tagged with your taxonomy.


Getting per-module memory stats? I'm hosting Drupal on Dreamhost shared hosting where I have a maximum of 90 MB RAM and a lot of enabled modules.
Is there a way to see how much memory each module is using?

No, unfortunately, this is not possible. The used memory of a module is scattered among many functions, caches, etc.

There are tools which allow you to display the memory usage per function, how much time a function used, and so on; for example, there are XHProf and Xdebug, but both are PHP extensions and you will not be able to install them on a shared host.

You could, however, create a local installation (if you haven't already) and then check these tools out. Devel integrates nicely with XHProf, so you only need to install the extension, and enable the corresponding checkbox in the configuration settings of Devel.


How to create file repository from which I can link files to other content types? I want to be able to "link" files to my content types. Two different nodes in two different content types can link to the same file, so I don't want use file upload field to avoid content duplication.

I also want to have publicly available "repository" where there is a list of all available files and for each file there is a list of articles / nodes to which this file is linked.

What is the simplest way to achieve this. Is there a reference field or something like that?

I would like to have little search field when linking files to content.

As said in the comments:

Media module is just the thing you are looking for. We are also using it in our project, it's pretty good and solves all the problems you listed.

It's maybe also important to mention that this is going to be part of the core very soon (8.4.x).


Token replacement for list keys I'm trying to define a Display Suite Code Field which would be responsible for converting a list item key (selected in a dropdown on admin side) into an image on the output side. The field simply assumes the list keys:

series1|Series 1 Name
series2|Series 2 Name

correspond to the images names and the tokenized field definition is as in:

<img class="product-series" src="/path/to/image/[node:field-product:field-series].png"/>

However what I got after replacement is the label ("Series 1 Name"), instead of the key. Is there a way to force the key replacement? (Yes I know I could drop the Label part, but this would not be admin friendly)

Enable the "Token" view mode and select "Key" as field formatter for the "Series" field.


Using Features with an existing content type? I'm trying to use features to deploy some changes from a local development site to a staging site on a seperate server, the problem is that I've got an existing content type on my dev and staging environment, let's call it hero_feature.

Here is an example breakdown of the fields that exist in this content type on both dev and staging:

Dev

Hero Type (Machine Name: field_hero_type)
Main Image
Main Title
Sub Title

Staging

Main Image
Main Title
Sub Title

So there's a field on my dev environment (Hero Type) that I want to transfer from Dev to Staging using features. I'm not sure if it's significant but it's a text select widget.

I've tried creating the feature in a number of ways (selecting the content type itself in one instance, and only the fields that need transferring in another) but every time I get the same error message, which is something like:

  DatabaseSchemaObjectExistsException: Table
  field_data_field_hero_type already exists. in
  DatabaseSchema->createTable() (line 657 of
  /sites/drupal/includes/database/schema.inc).

Which I understand is because the code is trying to create the content type for the field when it already exists.

This is really starting to drive me crazy.

Is it possible to do something like this with Drupal features? Or should I have featurised this before initially deploying to staging in the first place?

(I realise that in my example I could rather easily replicate the changes manually on the staging site, but in reality I have a number of fields and other changes that need porting over to the Staging site, and I'm not happy with manually making these changes everytime something like this needs deploying.)

If you want all your content type to be transferred to another site without any changes you can import all content type from your dev environment and export it in stg environment and remove the validation.


Removing the comma between Attribute Option and Attribute Price in Ubercart for Drupal 7 Discovering Product Attributes in Ubercart was quite a find. However, my client does not like the way the dropdown looks. Previously, all the prices had + in front of them, but I was able to remove them taking a clue from questions by other Drupal users (sites/modules/ubercart/uc_attribute/uc_attribute.module line 1361). But, finding where to get rid of the comma eludes me.

If you have any further clues, I would be most appreciative!

theme_uc_attribute_option($option, $price) is what you're looking for. Override that theme function in your theme and you can eliminate the "," & the price adjustment amount.


Drupal Commerce Mirgrate product displays I'm trying to create a migration class for my product displays. I already have one for the product variations which is seperate because it has a different CSV source.

So I'm just trying to create the drupal nodes of the product displays. When I check the database in the node table, the nodes are there with the correct type. However when I go to the product page, I don't see the new items there.

I think it has something to do with this line:

$this->destination = new MigrateDestinationNode('video_storage_recorder');

or

$this->map = new MigrateSQLMap($this->machineName,
      array(
        'Name' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'Recorder',
        ),
      ),
      //MigrateDestinationCommerceProduct::getKeySchema('commerce_product')
      //MigrateDestinationEntityAPI::getKeySchema('video_storage_recorder')
      MigrateDestinationNode::getKeySchema('video_storage_recorder')
    );

where video_storage_recorder is my content type.

Also I tried

$this->destination = new MigrateDestinationEntityAPI('video_storage_recorder');

But no different behaviour.

I think the nodes are created but not considered products for Drupal Commerce. But I don't know why.
Also Migrate does not give any (error) messages and just says 9 items were created.

When I added a product variation in code the product appeared in the list. It's required to have at least one variation to be linked for the product display to be considerd a product display.


Make errors also display in proper format and language I used webform and Internationalization. It works fine, but when error message are displayed, it shows in partial english and RTL and LTR is mixed up as shown in image.

how do i correct it.

Either import translation for Webform, or keep in synch with i10n.

If the string ('field is required') is not translated, you have to do it yourself in the translation interface admin/config/regional/translate.


how to setup entity access correctly? How to setup entity access correctly?

i have entity:

/**
 * @ContentEntityType(
 *   id = "test_entity",
 *   bla... let me know if you need detail of this
 *     "route_provider" = { "admin" = "Drupal\test_entity\Entity\TestEntityRouteProvider" },
 *   bla... let me know if you need detail of this
 */

and class TestEntityRouteProvider extends AdminHtmlRouteProvider implements EntityRouteProviderInterface with getRoutes as follow:

$parameters = ['target_type' => 'test_entity_type', 'target_id' => ['type' => 'entity:{test_entity}']];

$route = (new Route('/admin/testing/my-entity/{test_entity}'))
         ->addDefaults([
           '_controller' => '\Drupal\test_entity\Controller\TestEntityViewController::view',
           '_title_callback' => '\Drupal\test_entity\Controller\TestEntityViewController::title',
         ])
         ->setOption('parameters', $parameters)
         ->setRequirement('_entity_access', 'test_entity.view');

$route_collection->add('entity.test_entity.canonical', $route);

i read comments in: EntityAccessCheck:Access, it said:

  /**
   * ... dynamic entity type:
   * example.route:
   *   path: foo/{entity_type}/{example}
   *   requirements:
   *     _entity_access: example.delete
   *   options:
   *     parameters:
   *       example:
   *         type: entity:{entity_type}

question: is my $parameter in class TestEntityRouteProvider correct? i'm not sure if i follow the instruction in comment correctly.

and with my code above, $entity value in EntityAccessCheck:Access is "test_entity-15" as string

*for reference: "test_entity-15" is referring to my test entity ID the same as in my url: /admin/testing/my-entity/test_entity-15

if ($parameters->has($entity_type)) {
  $entity = $parameters->get($entity_type); // <-- value: "test_entity-15"
  if ($entity instanceof EntityInterface) { // will false in here
    return $entity->access($operation, $account, TRUE); // and didn't reach here
  }
}

and will giving me response:

  403: You are not authorized to access this page.

what am I missing here? let me know if you need my particular part of my code.

Thank You,

You say "i have entity and class TestEntityRouteProvider extends AdminHtmlRouteProvider implements EntityRouteProviderInterface. Normally you don't rewrite all of the route generating code when extending an entity route provider, you only modify some of the routes, rarely the whole set of routes in getRoutes(). But always execute the parent method first. See this example from a core entity type:

<?php

namespace Drupal\aggregator;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;

/**
 * Provides HTML routes for the feed entity type.
 */
class FeedHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
    $route = parent::getCanonicalRoute($entity_type);
    $route->setDefault('_title_controller', '\Drupal\aggregator\Controller\AggregatorController::feedTitle');

    return $route;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditFormRoute(EntityTypeInterface $entity_type) {
    $route = parent::getEditFormRoute($entity_type);

    $route->setDefault('_title', 'Configure');

    return $route;
  }

}

Or if you don't need to modify anything you simply use the standard class for the administration of entity types

  *     "route_provider" = {
  *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",

in the entity type annotations. Is it working then?


Where to start for implementing user roles/levels? I have three types of user roles in my site:

department heads.
department managers.
employees.

There are several department heads. Each Department Head manages multiple department managers. And each Department manager manages multiple employees.

What I want is:

Department managers should be able to see details of THEIR employees.
Department heads should be able see THEIR managers and the employees working under each of these managers.

There are lots of techniques/solutions on roles and permissions. Such as those provided by specific contributed modules (including Organic groups). But I am confused which one to start with.

Anybody can shed some light about this?

Have a look at the Group module (a new module as of D7). It should address most (if not all) of your requirements. And it offers a potential alternative to the Organic groups module. Here is a quote from its project page:

  Organic groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).

  Group instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Some major differences between these 2 modules are:

Group started in D7 only, taking full advantage of entities introduced in D7.
Organic Groups is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases.
A D8 version of Group is in the pipeline and actively being worked on these days (expectation is "only a few months from now").

Additional Group sub-modules

Extra features can be enabled via these sub-modules:

  Group Add: Add members to a group without their consent.
  Subgroup: Make group to belong to another group.
  Group Invite: Allow group members to invite people into their group.
  Group Node: Enables Group functionality for the Node module.
  Group member profiles: Create multiple fieldable member profiles, which can be attached to a member.

Have a look at my answer to "How to create basic Organic Groups functionality with flags and references?" for way more details about it, such as available integration with other (commonly used) modules.


How to put a custom message in the message module template? I am using the Message module with Drupal 8 to log information.

I was able to get the date and time in the messages produced by adding a token of the date and time , but I want to add a customized message that is different each time.  How can I do this? this is the code I am using:

 $message = Message::create(['template' => 'sfbu_progress']);
 $message->save();

How can I add a customized message to each message created?  For Example I want it to say "This file 444.pdf was successfully uploaded" or "this file 888.pdf was missing ".

Checkout the setArguments(), getText() and the processArguments() function in the Message Entity class:

$message = Message::create(['template' => 'sfbu_progress']);
$message->setArguments([
   '@my_argument' => 'my_argument_value',
]);
$message->save();

And in your Template which you create over the UI write the @my_argument to the textarea. It should be replaced with your text.

It is also possible to add an callback function as argument. Therefor checkout the declaration of the argument property in MessageTemplate Entity class.


git post-receive hook to trigger drush rsync without prompt or with predefined answer I have set up post-receive hook on my staging server, so whenever I push from dev server a master branch, it updates staging webroot and triggers drush rsync to update live site.

#!/bin/bash

    while read oldrev newrev ref
    do
      branch=`echo $ref | cut -d/ -f3`

      if [ "master" == "$branch" ]; then
    git --work-tree=/var/www/drupal/ checkout -f $branch
    drush rsync --delete --exclude='.htaccess' --exclude='io' --log-file=rsynclog.txt --exclude-files @stage @live

        echo 'Changes pushed live.'
      fi

      if [ "dev" == "$branch" ]; then
        git --work-tree=/var/www/drupal/ checkout -f $branch
        echo 'Changes pushed to staging.'
      fi
    done

Or i hoped to do so :) I have ssh keys in place and that is not the problem, what i can see is that it hangs on destroy yes no question. Output after git push origin from dev machine:

  Counting objects: 15, done.

  Delta compression using up to 4 threads. Compressing objects: 100%
  (8/8), done. Writing objects: 100% (8/8), 762 bytes, done. Total 8
  (delta 5), reused 0 (delta 0)

  remote: Already on 'master'

  remote: You will destroy data from mydomain.com:/var/www/drupal/ and
  replace with data from /var/www/drupal// remote: Do you really want
  to continue? (y/n): Aborting. [cancel]

  remote: Changes pushed live. To root@dev:/git/drupal 65abd19..7205946
  master -> master

So I would need somehow to tell script that answer is y, or I need a way to  avoid that question at all.

Also, I am not pro bash scripter ;) , are those commands being excecuted in line,  like in php, so one is not executed before other finishes ? (to make sure changes are propagated on staging webroot first, then rsynced all to live).

Add the --yes option to your Drush command.  This assuredly will work if you place it before the rsync directive.

For example:

drush --yes rsync @dev @live

Drush rsync is different than most Drush commands in that it uses strict option handling.  Commands that work with strict options pass all extra flags that appear after the Drush command name on to the tool that is being invoked.  Thus, drush rsync --yes @dev @live will fail, because the --yes will be ignored by Drush and passed on to rsync.

For more information, see:

drush topic docs-strict-options


Modal Popup for Vimeo when clicking on Vimeo Thumbnail Link I have a basic link field and in this link field I just have a vimeo/youtube link. What are some of the available modules that can give the functionality of:

Render the display of the video link with a thumbnail of the video on teaser/full display
When clicking on the video link, a modal popup overlay will show with the video.
The popup can also be responsive. (i guess this can be done manually via css)

You want to have a look at the video_embed_field module and the colorbox module.
They combine well to achieve what you want.

Create a contenttype with the new field provided by video_embed_field.
Then for the thumbs you could make a view and select the video_embed_field.
Go into settings of this video field and in the selectbox labeled Formatting tool, select thumbnails/w colorbox
This should give you a nice grid with thumbnails all linking to a colorbox overlay with player embedded.


Drupal insert query with uploaded CSV file array
  0 =>
    array
      'id' => float 1110
      'description' => string 'Culture de céréales (à l'exception du riz), de légumineuses et de graines oléagineuses' (length=86)
      'field2' => float 11
      'field3' => float 26.631
  1 =>
    array
      'id' => float 1120
      'description' => string 'Culture du riz' (length=14)
      'field2' => float 11
      'field3' => float 7.556

With this array what is the correct process for the string "description" to avoid SQL error when data is added with db_insert ?

I use this code for multiple insert :

$query = db_insert('table')->fields(array('id', 'description', 'field2', 'field3'));

foreach ($sql_query as $record) {
     $query->values($record);
}

$query->execute();

// $sql_query is the array described above.

The data come form a file where string were not convert to utf8 at the opening thus the Drupal 7 parsing function for database query couldn't convert string to avoid SQL error.

Sorry but I didn't think that the problem could be as much upstream...


Where shall I place "PHP SAML" library so that SAML Authentication module could find it? I have a multisite Drupal 7 installation (not using Composer), and I can't figure out where shall I place "PHP SAML" library so that the SAML Authentication module would find it.
The instructions within the module simply say to install OneLogin's SAML PHP module (and the only provided instructions set uses Composer). The Libraries API module is installed, but wherever sites/domainname/libraries I try to place the content of the cloned https://github.com/onelogin/php-saml.git, the SAML Authentication module still says the "PHP SAML" isn't installed.
How and where do I place the right files in absence of Composer?

I dabbled with this before. In order to get phpsimplesaml to work you need a module that autoloads composer libraries. I ultimately gave up trying it on d7 because it was a nightmare to get everything working, but I at least had the library recognized.


Devel admin interface unreachable; or I broke my Devel? Not sure what broke where, been using devel & love it. I enabled the Display $page array option, went, did stuff, came back to disable and when trying to load admin/config/development/devel either through button, url or asking nicely, I get a

  Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection
  without sending any data.

I uninstalled, reinstalled, no change. I uninstalled, deleted variables (shouldn't devel do this?) flushed caches, ran cron, deleted the devel folder, and reinstalled from a fresh download (7.x-1.2), no change. The strange part is devel still works (when module is installed), i'm still getting my $page array in the message area, but I can't admin devel anymore :'(

Unfortunately I'm ramping this site up for production & can't turn back now, might have to proceed w/o it.

Anybody know how to admin devel another way? Run into this before? Have something else I can try?

Update:
Just started testing the rest of devel & these functions elicit the same response (324):

Execute PHP
Devel settings (either the development menu link /devel/settings or the link in the admin toolbar admin/config/development/devel)
Menu item

Rebuild menus ! Thankfully this still works, because it fixed the problem! So try that if you start getting 324's in weird places!

Rebuild menus ! This fixed the problem!

One of the menu tables must have been corrupted somewhere in my Drupal shenanigans.

So try that if you start getting 324's (or other non 200 responses) in weird places!


Jquery and Drupal Autocomplete I have an autocomplete field in a custom form which works and returns a pipe-seperated value which I want to then split up and insert into the appropriate form fields.
For example, the autocomplete field returns 'Last|First|ID' such as 'Smith|John|123456789' and I want to assign these values to other form fields and replace the current value of the auto complete field with the last name.

I have successfully gotten the ID and the First Name to be populated using jquery, but the last name in the auto complete field WILL NOT CHANGE.

Some observations: if I first alert the value of the field, it changes. It's as if the script is running too fast and skips over the step to set the value of the autocomplete field. It also appears to work with other event firings instead of .change, such as .blur, or .keyup - but the thing is I need it to be .change or else it won't work for all cases.

Here's my jquery code:

$('#edit-emp-lname').change( function () {
    var empName = $(this).val();
    //alert($(this).val());
    var empArray = empName.split("|");

 //The following line is basically ignored. All other following lines work successfully.
    $(this).val(empArray[0]);
    $('input[name="emp_fname"]').val(empArray[1]);
    $('input[name="emp_uid"]').val(empArray[2]);
});

Update
In order to make this work properly and in IE to boot I had to do some extra code, shown below:

$('#edit-emp-lname').change(function() { doChange(); }).attr("onchange", function() { doChange(); }).blur( function() { doChange(); });
function doChange() {
    var empName = $('#edit-emp-lname').val();
    var empArray = empName.split("|");
    setTimeout( function () {
        $('#edit-emp-lname').val(empArray[0]);
        }, 10);
    $('#edit-emp-fname').val(empArray[1]);
    $('#edit-emp-uid').val(empArray[2]);
}

If I want to display in autocomplete all this field I will use hook_form_alter
I will change the value of autocomplete with another function
so this is what i will do

function hook_form_alter() {
  $form['field_selectedarticles']['und'][0]['nid']['#autocomplete_path'] = 'autocomplete/filteration';
}

function autocomplete_filteration($string) {
  //select * fields I want
  print drupal_json_output($items);
}


redirect whole site to HTTPS When I include the snippet found in answer to this question How to simply make the whole site HTTPS?  to redirect to https in my htaccess.php file, all urls resove to /index instead of going to the page originally requested (Ex: user tries to access example.com/about, and is redirected to https://example.com).

Here is the snippet I used:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I have also tried the slight variation found at https://www.drupal.org/https-information, which has the same unsatisfactory result:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www.domainname\.com*
RewriteRule ^(.*)$ https://domainname.com/$1 [L,R=301]

How can I make the site all https without breaking the ability to navigate to a specific page?

Edited to add: I've got the Secure Pages module, but haven't managed to get it to work. If you have advice on that point instead I'd happily take it.

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.


How does the UserData plugin get the correct value? The User module defines a UserData plugin for the Views module, which allows to access the user.data service from a view. Its render() method contains the following code.

$uid = $this->getValue($values);
$data = $this->userData->get($this->options['data_module'], $uid, $this->options['data_name']);

// Don't sanitize if no value was found.
if (isset($data)) {
  return $this->sanitizeValue($data);
}

}

How does the Views module know the plugin require a user ID? In other words, how does the Views module know that is a field plugin associated with the User entity and not another entity?

The annotation for the plugin is simply the following one.

@ViewsField("user_data")

Neither its create() nor its constructor method set something that would make clear to which entity the plugin is associated.

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static($configuration, $plugin_id, $plugin_definition, $container->get('user.data'), $container->get('module_handler'));
}

public function __construct(array $configuration, $plugin_id, $plugin_definition, UserDataInterface $user_data, ModuleHandlerInterface $module_handler) {
  parent::__construct($configuration, $plugin_id, $plugin_definition);

  $this->userData = $user_data;
  $this->moduleHandler = $module_handler;
}

The available fields for the user entity are defined in Drupal\user\UserViewsData::getViewsData():

$data['users']['data'] = [
  'title' => $this->t('Data'),
  'help' => $this->t('Provides access to the user data service.'),
  'real field' => 'uid',
  'field' => [
    'id' => 'user_data',
  ],
];

This attaches the field user_data to the user entity.


robots.txt encoding issue I'm in charge of a website for my company, which runs Drupal 7.66 (PHP 5.3.3), for a few years now. Since a few months, I discovered a strange behavior regarding the robots.txt file. In some case, the encoding is totally messed up.

Here is a brief description of the problem:

If I am connected to the website: no problem, the robots.txt file is well displayed in the browser
If I am NOT connected to the website (like all our users and the search engine robots): it randomly appears broken, and I identify that as an encoding issue. By “randomly”, I mean that sometimes when I check the robots.txt while not being connected, its ok, but sometimes it's broken. I can't find a pattern that will allow to reproduce the error.

The robots.txt is managed through admin/config/search/robotstxt thanks to the module RobotsTxt version 7.x-1.2

Here is a screenshot to illustrate the issue (I had to hide some parts of the images):

Of course, the webmarketing team noticed me that Google can't crawl the robots.txt file because of that issue:

I made quite a lot of searchs on drupal.org, Stackoverflow, Google... but couldn't find anything related.
I am not a developer, but I work with a guy which is specialized in Drupal and he can not figure it out either.

Any idea? Of course if you need any further information, please let me know.

Thank you.

Problem solved.

Thanks to @hansfn comment, I found a similar issue on drupal.org: Doesn't work for anonymous users

I told about it to the developer I work with and he updated the RobotsTxt module from the version 7.x-1.2 to the version 7.x-1.4, and it solved the problem.


Content type node not overwriting the default node.tpl.php even if I have cleared all cache's I have a content type with a machine name of 'empresas' after reading the documentation I should be able to just create a node--empresas.tpl.php to toy with the output of this in my theme.

it seems to be not overwriting it. I am trying to hack something together and I am using the twitter bootstrap Drupal theme.

I have seem a similiar problem into another post in this forum but it seems like taht is not may problem because he have solve it by clearen all the cache's but that was not my case.

Initially, i say like not to override the original theme folder,

Create a sub theme of the base theme, in your case create a sub-theme of twitter bootstrap.
Then make the necessary changes in the sub-theme.

Enable only the sub theme.

And about overriding node.tpl.php file,
your approach is correct node--empresas.tpl.php, should over-ride the display of this particular node content.

Cross check machine name, Enabled theme, path of the overriding tpl.php file.


Keeping the  part in the CKEditor and removing everything else I've naive customers who will need to copy the HTML part of email in Outlook. So I want them to copy and paste the HTML source of the email which includes <html> <body> </body> </html>.

Is there any filter which will remove all but keep only  the content within the <body> part?

Drupal's text format has an option for "Limit allowed HTML tags," in which you can specify which tags you would like to keep. You could always create a list of tags you use in your emails. If you exclude the html and body tags, that might work for you.

Another option is you can simply write your own text filter. You'll need to implement hook_filter_info.

Basiclly you would want something like:

function my_module_filter_info() {
  $filters['filter_name'] = array(
    'title' => t('Some Nice Filter Name'),
    'description' => t('Filter out stuff'),
    'process callback' => "your_filter_function",
    'cache' => FALSE,
   );
   return $filters;
  }

Then it's just a issue of writing your filter function.

function your_filter_function($body_text){
   //do stuff to your body_text to remove the tags you want to remove
   return $body_text
}


Delete entities in batches Is there a way to organized entity deletion by braking into different batches? I have 700.000 entities associated with pictures that I would like to delete and I would like to perform that into batches.
Any how to?

You can install Views Bulk Operations, create a View of those entities, and set up a delete operation. It should have configuration options to execute in batches. I have done this before to delete 100,000 records.

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


How can I import and export Drupal Commerce Products? I have a Drupal 7 site and installed the Drupal Commerce module.
In which I have added Commerce Product with Category like:

Software Products
Hardware Products
Electronics
Others

  I would like to Export those Commerce Products from My Development
  Server to Production Server.

So, for that we have any modules available in Drupal.org so, I can export the Commerce Products and Import to my server.

I found the Node_Export module, but it only applies to exporting the nodes. It does not apply to Commerce Products.

Anyone has an idea how I can Import/Export the Commerce Module Products?
I think it is general problem who are using the Commerce Module of Product (but not sure).

You can look at the Commerce Feeds module in Drupal

You can use this Views Data Export module to Export in CSV or Excel Format. Further read more details on that module for installation and configuration.

You can also watch View Tutorial


Is there a way to force some block caching despite system block caching option is disabled? In /admin/config/development/performance settings page, my "cache blocks" options is disabled due to "Block caching is inactive because you have enabled modules defining content access restrictions."

But I absolutely need to globally cache some blocks (in particular some superfish blocks because they recreates menu items on every page load if not cached).

I've already tried Block Cache Alter module, but without success, probably because this module can works only if system "cache block" option is enabled (see: https://drupal.org/node/1954224 )

Thank you for help

With latest Drupal 7.33 release there is a new setting variable now:

/**
 * Block caching:
 *
 * Block caching may not be compatible with node access modules depending on
 * how the original block cache policy is defined by the module that provides
 * the block. By default, Drupal therefore disables block caching when one or
 * more modules implement hook_node_grants(). If you consider block caching to
 * be safe on your site and want to bypass this restriction, uncomment the line
 * below.
 */

$conf['block_cache_bypass_node_grants'] = TRUE;

Setting the above to TRUE the "cache blocks" option becomes checkable.


When using hook_FORMID_form_alter(), how does one use validation to prevent form submission? Here is the code I have, and while the errors do print to screen, the form will submit anyway. How do I prevent the form from finishing submitting?

function my_module_my_form_form_alter(&$form, &$form_state) {
    // calls a function during validation
    $form['#validate'][] = 'my_module_validate_address_check';
}

function my_module_validate_address_check(&$form, &$form_state){
    if($form_state['values']['panes']['delivery']['delivery_postal_code'] != 91006){
         drupal_set_message(t('Wrong Zip'), 'error');
        $return = FALSE;
    }

}

Use form_error($form['delivery_postal_code'], $message) instead of calling drupal_set_message().

OR try

form_set_error('delivery_postal_code', $message);


Math Expression in Views: Date functions like now() Is there Date expressions or function? I'd like to calculate a duration between a date field and today ? Is there a now(), today() function?
i'd like this kind of math expression: now() - [field_arrival]

If you only want to display the duration between the given date and today in a view then you don't need any calculation.

Just use time ago display option and display your given date with this time ago option.

You will have the result something like this -- 1 year 3 months ago.

You can drop text ago if you don't need.


Modifying a Form submit button behavior Basically, there is a module I'm using and there is a submit button on the page.

When the user clicks submit, it validates and processes the user input before going to the next page.

What I want to happen is that when a user clicks submit, the form does the default behavior of validating and processing the user input. But then I want to add a popup depending on if the previous input is valid. There will also be a button on the popup to take you to the next page.

How can I do this, if at all?

In a custom module, implement hook_form_FORM_ID_alter(). In there, the $form['#submit'] element is an array of all the functions that will handle a valid form submission. You can add your function to that array to have it executed on (valid) submission. Submit handler functions are executed in the order of the array, so the best is probably to append yours at the end. If the array is empty, you need to create the array and it must contains default submit handler in addition to yours, otherwise your will loose the default behavior.

To open a popup, you will need some custom JavaScript to the page trough drupal_add_js() (which you would call from your submit handler). In your custom JavaScript, you can use jQuery UI Dialog library bundled with Drupal 7. To have the library available on the page use drupal_add_library('system', 'ui.dialog'). You can use drupal_add_js() to pass data from your validation handler to your JavaScript code using the setting type.


Get order value on completed checkout I'm using drupal 6 and ubercart 6.x-2.9

I've created my own template for the checkout complete page, this is so I can install conversion tracking code from adwords.

I'd like to pull the order value and insert it into the adwords snippet.

Does anyone know how to call this value?  Is there already a variable with the correct value that I can just echo/print into my template?

I was able to pull the order value using the following code

$order = uc_order_load(intval($_SESSION['cart_order']));

if ($order)
{
   $amt = round($order->order_total,2);
}


Data export view gives error if 0 records I have a data export option on a view.  however , if the filter has not chosen any records, the excel export gives an error.  Is there anyway to disable the data export icon if no records have been chosen, or other wise avoid this error?

thanks

This has been transitioned to https://www.drupal.org/node/2576429 per the request of Mołot.


Allow the node preprocess function to be called after setting the theme function in hook_node_view() In mymodule_node_view(), I set the theme function to be used with the following code.

$node->content['#theme'] = "my_custom_theme_function";

Now the node preprocess function (mymodule_preprocess_node()) is not called anymore.

How do I let Drupal run my node preprocess function, even if I set my theme function to be used?

With that line, you set the theme function for all the content shown for the node. Your code should be similar to the following one, taken from the documentation for hook_node_view().

function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['mymodule_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_custom',
  );
}

As to why your code is setting the theme function for all the node content, see the code executed by node_view(). (The comments are mine.)

  // This is the function that invokes hook_node_view().
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;

  // $node->content['#theme'], the value you set, becomes $build['#theme'].

  unset($node->content);

  // The following lines don't set anymore $build['#theme'], since you have already set it.
  // It is similar to executing the following code:
  //   $a = array('first' => "I am the first");
  //   $a += array('first' => "The array will never get this value");
  //
  // If you print the value of $a, you will see it is as it was first set.

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Now the code is going to use your theme function, which means that not even
  // the node preprocess function is executed.

Normally, what you want to do is adding a new content to the render array for the node. That is what the code I show in the first snippet does.

If you really wanted to change the theme function used for the node, then you should simply implement hook_theme_registry_alter(), and redefine the function associated with the node theme function.

Keep in mind that once you change the used theme function, also the preprocess function changes; in your case, if theme_my_custom_theme_function() is your theme function, then the preprocess function is mymodule_preprocess_my_custom_theme_function().


How to load a taxonomy term with case-sensitive? I used this

    $this->termStorage->loadByProperties(['name' => 'test']);

I got two terms: Test, test.
I want to get only one: test

This is working without case-sensitive:

    $this->termStorage->getQuery()->condition('name', 'test', '=')->execute();

    \Drupal::database()->select('taxonomy_term_field_data', 't')
      ->condition('t.name', 'test')
      ->fields('t', ['name'])
      ->execute()
      ->fetchAll();

    \Drupal::database()->query("SELECT name FROM taxonomy_term_field_data WHERE name='test'")->fetchAll();

To retrieve result with sensitive case, you can use binary in where clause:
Like this sql query.

SELECT name FROM taxonomy_term_field_data WHERE binary name='test'

For Drupal you can use \Drupal::database()->select with where conditions take a look here .

Try this:

 $result = \Drupal::database()->select('taxonomy_term_field_data', 't')
    ->where(
      'binary name = :term_name',
      ['term_name' => 'test']
    )
    ->fields('t', ['name'])
    ->execute()
    ->fetchAll();


How to set the language for the user while it is created? How to set the language for a user while it is created from admin/people/create?

Actually it was a simple thing, just that I didn't enabled the language. So the steps are:

install and activate i18n module
go to admin/config/regional/language and add the languages you want
then in admin/people/create you will have a language selector.


Create cookie on login What is the latest and best way to set a cookie upon login? What I mean is:
if a user succesfully logins, then a session cookie user-is-logged-in = 1 is set. When the user logs out, this is removed.

I see this https://www.drupal.org/project/logincookie but its very old and doesn't look supported..
I see this but https://www.drupal.org/node/2160739 but it starts with a requirement with Varnish which I don't have..

I am using Drupal version 7.43.

As you know session cookies set by Drupal don't do the trick, as anonymous users are also set a cookie and from a browser's perspective, they are not differentiable.

Thanks a lot for your help!

You could just write the code yourself in a custom module. What you want is pretty simple.

/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-is-logged-in', '1', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-is-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-is-logged-in']);
}


WSOD when trying to configure menu with many items I have a menu with many nested/multi-lingual menu items (I don’t know the exact number, probably something around 2000-3000).

Whenever I try to visit its configuration page in the backend (/admin/structure/menu/manage/menu-foobar), I get a WSOD after some loading time.

The site is hosted on a shared webhost (PHP memory limit is at 256M; max execution time at 120), so I assume it might work to move to a more powerful VPS, but I wonder:

Is there any way to access the menu configuration page without moving to a better server or changing the site architecture (i.e., using several menus instead of one)?

I tried the Menu Admin Splitter module, but it didn’t help.

A fiddly workaround:

On the "list links" menu page, you can visit, rearrange, enable/disable, edit, and delete all menu items. Except for visiting the node, all this is possible from a single menu item’s edit page.

But how to access the menu item edit page without being able to access the parent’s menu page listing all those items?

Visit the node whose corresponding menu item you want to edit.
Open its HTML source code.
Search (Ctrl+f) for active menu-mlid. You’ll find a class value like menu-mlid-218. 218 is the menu item ID.
Visit /admin/structure/menu/item/218/edit.


Can't edit Panels content When trying to change the Panel content design, there are no controls displayed as shown:

This is happening only when using Charts in my Panel page. I got this error chrome inspector console:

Uncaught SyntaxError: Unexpected token , in JSON at position 6
    at JSON.parse (<anonymous>)
    at Function.parseJSON (jquery.js?v=1.4.4:32)
    at HTMLDivElement.<anonymous> (charts_highcharts.js?v=1.0:11)
    at Function.each (jquery.js?v=1.4.4:34)
    at $.fn.init.each (jquery.js?v=1.4.4:27)
    at $.fn.init.$.fn.once (jquery.once.js?v=1.2:55)
    at Object.Drupal.behaviors.chartsHighcharts.attach (charts_highcharts.js?v=1.0:9)
    at Object.<anonymous> (drupal.js?pj2bso:112)
    at Function.each (jquery.js?v=1.4.4:33)
    at Object.Drupal.attachBehaviors (drupal.js?pj2bso:110)
parseJSON @ jquery.js?v=1.4.4:32
(anonymous) @ charts_highcharts.js?v=1.0:11
each @ jquery.js?v=1.4.4:34
each @ jquery.js?v=1.4.4:27
$.fn.once @ jquery.once.js?v=1.2:55
Drupal.behaviors.chartsHighcharts.attach @ charts_highcharts.js?v=1.0:9
(anonymous) @ drupal.js?pj2bso:112
each @ jquery.js?v=1.4.4:33
Drupal.attachBehaviors @ drupal.js?pj2bso:110
(anonymous) @ drupal.js?pj2bso:593
ready @ jquery.js?v=1.4.4:30
u @ jquery.js?v=1.4.4:38

Found the solution here: can't edit panels page with highcharts chart in quicktab (w/ workaround)


Do not send registration mail to fake users, who haven't specified their gender in registration form Since several years I run a Drupal 7 web site - as a frontend to a multi-player card game.

I have the following SPAM protection at my web site: the new users should specify their gender at the registration (it should be "Male" or "Female", but not the default "Robot") and then they have to play the card game:

Every night I run a cronjob, which deletes users who have wrong gender or who have registered 10 days ago and still haven't played:

delete from drupal_users
where uid <> 0 and
to_timestamp(created) < (now() - interval '10 day') and
uid not in (select distinct id from pref_money); /* haven't played the game */

This does work well, BUT recently the amount of registering fake users has increased to hundreds per hour and my site keeps sending lots of registering mails (which bounce then to my poor mailbox) every minute.

So my question is: how NOT to send the registration mail to users who have their gender set to "Robot"?

Here is what I have found sofar:

1) The gender (an additional field at my reg. form) can be found the following way:

        $result = db_query('select field_gender_value from {field_data_field_gender} where entity_id=:id', array(':id' => array($viewer_id)));
        $gender = $result->fetchField();
        if ('Robot' == $gender) {
           ....
        }

2) And I probably should provide a hook_mail_alter in my custom module:

function MY_CUSTOM_MODULE_mail_alter(&$message) {
  # XXX how to find gender here?
  if ('Robot' == $gender) {
      # XXX how to abort mailing for registration only?
      $message['send'] = FALSE;
      return;
  }
}

But in 2) I don't know 2 things - how to find the gender value there and how to cancel the registration mails only?

Any suggestions please?

Please do not suggest the Mollom module or any standard Drupal anti-spam measures, because my question is very specific.

I suggest you implement hook_form_id_alter to either add a new validation function to the registration form, or replace the submit callback.

In a validation function, you have access to the form values, and you can do whatever checks you want, and fail the submission. This will reject the form all together.

If you replace the submit callback instead, you could override only the sending of the e-mail. but otherwise let the form pass through, which seems closer to what is being asked for.


How create a file type field in custom entity programmatically? This is how i create my field in my Entity content :

  $fields['fid'] = BaseFieldDefinition::create('file')
      ->setLabel(t('Photo'))
      ->setRequired(false)
      ->setDescription(t('Product image'))
      ->setSettings(array(
          'upload_location' => 'public://produits/',
          'upload_validators' => array(
              'file_validate_extensions' => array('png jpg jpeg'),
          ),
      ))
      ->setDisplayOptions('view', array(
          'label' => 'above',
          'type' => 'file',
          'weight' => -3,
      ))
      ->setDisplayOptions('form', array(
          'type' => 'file',
          'settings' => array(
              'upload_location' => 'public://produits/',
              'upload_validators' => array(
                  'file_validate_extensions' => array('png jpg jpeg'),
              ),
          ),
          'weight' => -1,
      ))

      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

The field is create in my form but when i try to upload a file :

I got this error :

  Only '.txt' extension is authorized

Edit 1 :

In fact my settings are never read, after upload a .txt for test, the directory is wrong.

Any idea about this ?

The only way i have found is to move this param into the Entityform :

  $form['fid'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://produits/',
      '#default_value' => $entity->get('fid')->value,
      '#description' => t('png jpge jpg'),
      '#upload_validators' => array(
          'file_validate_extensions' => array('png jpg jpeg'),
      )
  );


How to find image style URL from within twig template? I'm implementing a node template that uses an image twice; once in a 'normal' way (i.e. using the image style defined in the field's display configuration for that view mode), and the other is as a css background-image property.

I need one of two things:

(ideally) a way to get the URL for a different image style of the same image.
a way to get the URL for the image field.

I'm struggling to use dump() and kint() to help myself to an answer. They both output far far too much (thanks to embedded links to "parent" etc.) and seem to not have the info I need. e.g. looking at dump(content.field_image) output the actual URL of the image is not there (so where does it come from such that it can be rendered with {{ content.field_image }}?!). kint() on the other hand dies completely if I pass an argument to it and the top-level version is again far too big to navigate. Debugging was soo much easier with phptemplate + xdebug. (Yes I know it's good that themers can't drop the database.)

There's an answer to (1) that implies you can't do it, but I don't understand why I can't get the existing URL in (2)?

The first part is already answered in the linked question, where there is the code how to do this. To answer the second part of the question, you can access the original image in the node object:

{{ file_url(node.field_image.entity.uri.value) }}

One remark about content:

In a node template the image field in content is not ready to be rendered. The field contains the configuration how it should be displayed and the field object which contains all raw data. Later this will be put together in the field, image-formatter and image templates. That is the reason you don't find the url you are looking for in content at this point.

In the node template you can use the fields on the top level of the content array, for example display the image field

{{ content.field_image }}

as configured in the view mode.

Edit:

There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url of the original image:

{{ node.field_image.entity.uri.value | image_style('thumbnail') }}


Trying to modify Main menu by testing $vars['heading']['text'] == 'Main menu', I'm trying to modify the code for the main menu only. below is my sorry code, which is not working.
it attempts to see if $variables['heading']['text'] equal 'Main menu'

function myTheme_link($variables) {
if($variables['heading']['text'] == 'Main menu') {
//put my mods here
} else {
  return '' . ($variables['options']['html'] ? $variables['text'] :     check_plain($variables['text'])) . '';
}
}

this must be close, no? i would greatly appreciate if someone could advise

You can do it by using this code in template.php file of your active theme.

function mytheme_links__system_main_menu($variables) {
  $html = "
";
  $html .= "
";
  foreach ($variables['links'] as $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "
";
  $html .= "
";

  return $html;
}

or you can add customization in $variables also if we have do minor customization to do.
Here replace mytheme with name of your theme.
Clear you cache after using this code.

Hope it will help you!


Programmatically create user and add complete address field values I have an address field on my User entities.  I want to programmatically create users and set their address field values, I currently have this:

 $values = [
  'mail' => 'chris+7asd7fadf7afdafasdf@example.com',
  'name' => 'chris+7asd7fadf7afdafasdf@example',
  'first_name' => 'First',
  'last_name' => 'Last',
  'roles' => [],
  'pass' => user_password(),
  'status' => 1,
];
$user = User::create($values);
$user->field_contact_information->country = 'US';
$user->field_contact_information->given_name = $values['first_name'];
$user->field_contact_information->family_name = $values['last_name'];
$user->save();

But it's not saving the values to field_contact_information.  Elsewhere in the app, I do access these values with $user->field_contact_information->given_name.

That was simple - it should be $user->field_contact_information->country_code = 'US';


replace css on certain pages by another css I use drupal 6. How do I remove global.css from certain path like cart* and replace it with another css? I can add for example stylesheets[all][] = custom.css inside my theme info file but how to load it only on path cart*  and how to disable global.css on the same path? Thank you

You would need to use your theme to watch for it. You'll need to hook into preprocess_page and look for the global.css file in the css array and unset it. Below is an example of how to remove the modules/system/system.css you'll need to see where in the array global.css is and do the same thing. You'll want to wrap that inside of an if for your paths. In this example I use arg() to get the first path value (ie cart) and turn it on for that case. You can do what ever you want.

function phptemplate_preprocess_page(&$vars)
{
    if(arg(0) == 'cart') {
        $css = $vars['css'];
        unset($css['all']['module']['modules/system/system.css']);
        $vars['styles'] = drupal_get_css($css);
    }
}


How do I add a  after every field element on the node edit form? There are two approaches that have failed:

In the theme, add a theme hook for the node edit form.  Then, create a template file for the node edit form.  This won't work for my case, because the form is rendered in the template file with drupal_render_children, and therefore the contents of the form are not reachable within the template file--I need to add the divs in between the form elements.
Use hook_form_alter.  This won't work for my case, because you have to target a specific form item.  The users may, for example, add a new node field after I hand it off to them, and my existing hook_form_alter wouldn't have a way to catch it.

What I want to do is simple; in between every element on the node edit form, insert a

 to separate them.

Or, I could add the "clearfix" class to the existing div containers around the form elements.

Do we have a solution for either method?

[EDIT] Here is the solution using hook_form_alter():

<?php
/**
 * Implements hook_form_alter()
 */
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if (preg_match('/node_form$/', $form_id)) {
    $language = $form['language']['#value'];
    foreach ($form_state['field'] as $field => $field_contents) {
      $form[$field][$language]['#suffix'] = '

';
    }
  }
}
?>

The easiest way is using hook_form_alter for each Field add #suffix => '

" to the existing FAPI array for the Field. I would just hard code it per field.

If you need to you could make a for loop and walk through the FIELDs so you dont hardcode the fields by hand ... If you were more crazy you could use an #after_build function too on the $form or set 1 per Field element as needed if you run into problems.


How to get searched item value in search form? How do I get the value of searched item value, if I searched for "cat" in a search box then it also displays on a search page?

You can catch your entity in the preprocess and put data into drupal_static. After that you can display it where you want.


how to create all dynamic ubercart product images for CDN module to sync I have enable CDN module to handle image/css and js requests from a static server.
As drupal creates product images for different styles dynamically there are many products whose images are not present at the time to CDN and my domains syncing of images.
How can i handle the request to new product images in this scenario >
Right now the missing images are coming blank

This worked with the following setting in default/settings.php file

$conf['image_allow_insecure_derivatives'] = TRUE;


Getting the inverse of drupal_realpath (Drupal 7) I know drupal_realpath is depreciated but as far as I can tell I cannot avoid using it.

I have a little module that will unzip a file and search the contents of the unzipped file and create content with the images it finds.  In order to search the unzipped directory tree I need to rely on standard php methods will not work with paths like 'public://..." so I need to use drupal_realpath to massage my paths into something drupal can handle.

When I actually create the image file I do not want to use the drupal realpath because this would obviously be problematic if I migrated to a different server.

Is there a way I can turn the realpath which will look something like this:

/Applications/MAMP/htdocs/drupal/sites/default/files/my_file.png

back into something like:

public://my_file.png

If not is there some way I can search a directory structure without using drupal_realpath?

EDIT:
So it seems that my problem may really only be with certain PHP lirbaries for example simpleXML.

$shape_xml = 'public://Arcade Projects/ender2012/AgentCubes/Open Arcade/Moonsweeper/version8/Moonsweeper/agents/Tutorial/shapes/Tutorial/shape.xml';

watchdog("file exists normal",file_exists($shape_xml));
watchdog("file exists real path",file_exists(drupal_realpath($shape_xml)));

In the above example, both watchdogs print 1, so it seems that file_exists works fine with the drupal path or the realpath.

But, if I call simplexml_load_file with the drupal_realpath like this:

$xml = simplexml_load_file(drupal_realpath($shape_xml));

everything works fine.

But If I call it like this:

$xml = simplexml_load_file($shape_xml);

I get the following error:

Notice: Trying to get property of non-object in harvest_icons() (line 775 of /Applications/MAMP/htdocs/drupal/sites/all/modules/custom/unzip/unzip.module).

It's not pretty but this will reverse engineer such a path quite reliably:

$old_path = '/Applications/MAMP/htdocs/drupal/sites/default/files/my_file.png';

$doc_root = $_SERVER['DOCUMENT_ROOT'] . '/';

$public_file_path = variable_get('file_public_path', 'sites/default/files') . '/';

$replace = array($doc_root, $public_file_path);

$new_path = 'public://' . str_replace($replace, '', $old_path);


Relationship to content in term view causes duplicate and missing results I have these terms, nodes and comments. So 'NodeA' and 'NodeB' are tagged with 'Term1'. Both 'NodeA' and 'NodeB' have new comments.

Term1
-NodeA (has new comments)
-NodeB (has new comments)
Term2
-NodeC (no new comments)
-NodeD (no new comments)
Term3
-NodeE (no new comments)
-NodeF (has new comments)
Term4

I need to make a view that looks like this:

Term1 – new comments!

Term2

Term3 – new comments!

Term4

If I make a term view is stars out ok:

Term1

Term2

Term3

Term4

However when I add a relationship 'Taxonomy term: Content with term' then add the field 'Content: New comments' using this relationship, then I get this:

Term1
New comments: 1

Term1
New comments: 1

Term2
New comments:

Term2
New comments:

Term3
New comments:

Term3
New comments: 1

I get a result for each node, not 1 result for each term. I also get no result at all for the term with no nodes. Is there a solution within views for this?

You can use aggregation ("Advanced" menu, "Other" section, "Aggregation" feature) to sum your results and have something like:
Term 1 (5) - New comments
Term 2 (3)

Or you can try having distinct enabled ("Advanced" menu, "Other" section, "Query settings" feature) to show just the distinct results.

Hope it helps


How do I create an "About us" page and make it appear in the main menu? I have created a custom page page--about.tpl.php.
And want that page to hook it in menu.
I have gone through hook_menu but didn't get my answer.
I also read page template suggestion.

Tell me how I can do that.

I think there are some confusions here.

First: Custom.tpl.php-files are not custom pages.  They are custom templates for pages, and unless you need to have a different style or layout on your "about" page, there is no need for it.

Second: The hook_menu function has nothing to do with this, it is (mostly) for setting up callback functions for forms and hooking those forms up to the menu router system.

To create an "about" page for your site and make it appear in your site's main menu is much simpler.  Do as follows.

First create your "About" page as a "Basic page" on your site.  To do so, navigate to Home » Add content » Create Basic page and just create the page.  When done, press "Save".
Make a note of the node path of this page.  Let's say it is node/69.
Navigate to Administration » Structure » Menus. To the right of "Main menu", click "add link".
In the field "Menu link title", fill in the desired title (e.g. "About us").
In the field "Path", fill in the node path (e.g.  node/69 if that was the path you made of note of in step 2).
Click "Save".
Clear all caches (you always do this after changing the appearance of a Drupal site).

After going through the steps above, a tab linking to the "About us" page shall appear in the main menu.

If you want a custom layout for this page, you can create this as a template file.  If the node path to the page is node/69, the file should be named page--node--69.tpl.php.


Titles not showing for tabs pages Below is the array in my hook_menu

The only issue that I have with it is that the titles are not displaying for tabs pages (the last three array collections).

They are showing the title for the parent: 'Affiliate Hoover Home page'.

I've tried title callback instead but that isn't working

$items['admin/config/affiliate_hoover'] = array(
    'title' => 'Affiliate Hoover Home page',
    'page callback' => 'drupal_get_form',
    'description' => 'This is the affiliate hoover homepage - add shit here',
    'access arguments' => array('access content'),
    'page arguments' => array('affiliate_hoover_first_form'),
    'file' => 'affiliate_hoover.home.inc',
    'menu_name' => 'Affiliate Hoover',
    'type' => MENU_NORMAL_ITEM,
    );

$items['admin/config/affiliate_hoover/uniquename/%'] = array(
    'page callback' => 'affiliate_hoover_unique_name',
    'access arguments' => array('access content'),
    'page arguments' => array(4),
    'file' => 'affiliate_hoover.uniquename.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'title callback' => 'affiliate_hoover_uniquename_title_callback',
    'title arguments' => array(4),
    );

$items['admin/config/affiliate_hoover/uniqueform/%'] = array(
    'page callback' => 'affiliate_hoover_unique_form',
    'access arguments' => array('access content'),
    'page arguments' => array(4),
    'file' => 'affiliate_hoover.uniqueform.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'title callback' => 'affiliate_hoover_unique_form_title_callback',
    'title arguments' => array(4),
    );

$items['admin/config/affiliate_hoover/ajax'] = array(
    'type' => MENU_CALLBACK,
    'file' => 'affiliate_hoover.ajax.inc',
    'page callback' => 'affiliate_hoover_ajax_callback',
    'access arguments' => array('access content'),
    );

$items['admin/config/affiliate_hoover/'] = array(
    'title' => 'Home',
    'type' => MENU_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => -10);

$items['admin/config/affiliate_hoover/delete'] = array(
    'title' => 'Delete',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.delete.inc',
    'page callback' => 'affiliate_hoover_delete_page',
    'access callback' => TRUE,
    );

$items['admin/config/affiliate_hoover/log'] = array(
    'title' => 'Log',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.log.inc',
    'page callback' => 'affiliate_hoover_log_page',
    'access callback' => TRUE,
    );

$items['admin/config/affiliate_hoover/tracking'] = array(
    'title' => 'Tracking',
    'type' => MENU_LOCAL_TASK,
    'file' => 'affiliate_hoover.tracking.inc',
    'page callback' => 'affiliate_hoover_tracking_page',
    'access callback' => TRUE,
    );

return $items;

If you have static titles of submenus I suggest you to return using 'title' value in array.

I guess: set static titles and 'title callback' to false.


how do I add check boxes in form created with the Registration module? I am getting a radio button in my form as default, but I want a checkbox.

I am using the Registration and the Entitiy Registration modules. How can I do that?

At the time of Field Creation.

Select FIELD TYPE : List (text)

Select WIDGET : Check boxes/Radio buttons & save

  Allowed values list :

  1|list1

  2|list2

  3|list3

& save field setting.

You see that radio buttons are shown.

Now in FIELD SETTINGS : Select Number of values : Unlimited & save.


How do I compile Mustache.php to use with the Template Field module? The Template Field module requires the Mastache Template Rendering Library.

  The Mustache Template Rendering Library can be found here. It must be
  installed at libraries/mustache/Mustache.php.

However, the Mustache.php file is not provided, and I'm not sure why. There is some discussion about using the composure.php library to compile it. What I'm supposed to do?

The Template Field module is looking for a file called Mustache.php which doesn't exist in the git repo.

  /**
   * Verify anything before rendering
   * @param Template
   * @param array $data the data to render in the template
   * @return boolean
   */
  public function valid(Template $template, $data) {
    // Does the mustache library exist?
    if (file_exists(self::mustache_path())) {
      return TRUE;
    }

    watchdog('template_api', t('Mustache Library was not found'));
    return FALSE;
  }

  public static function mustache_path() {
    return libraries_get_path('mustache') . '/Mustache.php';
  }

There is a mention for using Composer but I'm not sure what that does. I have tried adding the Drush Composer extension to build a file but I don't understand how the Composer extension works.

Open command line.
cd to your basedir/sites/all/libraries
mkdir mustache && cd mustache
git clone https://github.com/bobthecow/mustache.php.git

You now have /sites/all/libraries/mustache/mustache.php .

Mustache.php is actually the name of the folder, not an individual php file.

To get an earlier version, such as 1.0, try

Open command line.
cd to your basedir/sites/all/libraries
mkdir mustache && cd mustache
wget https://github.com/bobthecow/mustache.php/archive/v1.0.0.tar.gz
tar -zxvf v1.0.0.tar.gz
mv mustache.php-1.0.0 mustache.php


Admin Access for Webform Entries The following problem has occurred:
A client fills in a reservation form, but the time requested is already fully booked. The clerk and the client negotiate a different time, and the clerk wants to change the requested time (f.e. 18:00) to the negotiated time (f.e. 20:00) -- but as the same form has a date restriction (one cannot reserve on the same day) the clerk can't save the form at the day of the appearance.

Is there any way to give a role the permission to change every webform, without any restrictions? I.e. any changes made by role "Trusted User" will not be checked in any way.

Webform for Drupal 8 allows you to give a role (or specific user) access to view and update submissions of a SPECIFIC webform to accomplish what you need

Goto Settings > Access of the webform in question and assign VIEW ANY SUBMISSIONS and  UPDATE ANY SUBMISSIONS to your Trusted user role

Than you have to give this user the URL to view and edit/update all the submissions.  For example for the contact form they should visit /admin/structure/webform/manage/CONTACT/results/submissions and they would be able to see all submissions and edit them.


Increase search field maxlength? Currently the search field has a maxlength of 128, I am wondering if there is any way to increase it too maybe 255?

Yes but it's not pretty. Drupal really doesn't want you to change field definitions after they've been created.

The correct way would be to create a new field definition and migrate values from the old field into the new one.

The quick and dirty way would be to manually change the field definition in the database directly.

The quick and dirty way that is deployable via code is to do a two-step process:

Export the field (such as with Features) and alter the #maxlength setting in the code.
TEMPORARILY hack core by commenting out the code in hook_field_update_forbid() in field.api.php.
Deploy a tag containing 1 and 2. Run updates.
UNCOMMENT hook_field_update_forbid and deploy that tag so further changes are not allowed and core is put back in its natural state.

This is terrible but I have done it and it works.


Page not found without record about page Is there a way to find the source of an error that I have on my production site during the last few days? In reports/dblog I see an error "Page not found" but there is no any information about what page, source, time of this error.

EDIT I looked in phpmyadmin and saw the source of the problem. The error appears when user reposts node in livejournal. I don't know is it a big problem for website or not (I mean problems with perfomance or search engines). Does anyone know the answer on this last question?

Is it something you're experiencing personally or are you just looking at the logs?

If you're just looking at the logs, it's usually a spammer/bot/crawler that's triggering the response. There are some security modules you can install that gives you a little more insight into those kinds of things (such as the IP address that triggered it), but I can only think of the D6 ones right now.


Is there a module that would allow me to reorganize the way fields are displayed for a content type form? When I create a particular content type, Drupal generates a form for me with all the appropriate data entry fields.

However, the form is not particularly attractive: all the fields are displayed one below the other, but in some cases I would like to be able to display fields side by side, for example.

Does anyone know of a module which would allow me to take control of the way fields for data entry are displayed? I am thinking of something like Display Suite, but for forms.

The best way to do that is using Display Suite module.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.


Transfer field from Organic Group to group content I have a field on an Organic Group and I want to transfer the field to a piece of content related to the group and have it stored in the database rather than being referenced. I've been able to do that with the Field Reference module, and the referenced field shows up when the view is rendered on the content node; however, I can't seem to pull that field into a "schedule evaluation date" in Rules Scheduler because I think it is not a hard-coded value.

So, is there any module that just takes a field from one entity/node and stores it in another entity/node when you save a new piece of content?

Or would the Computed Field module let me do this? I know I don't see a "date" type to store in the database there.

Thanks in advance!

I actually just ended up doing a hook_form_alter and adding a submit handler that saved the referenced field value from the form state into the field that I wanted to save it in on the non referenced node.

This worked nicely, but you had to save the node before it updates and you have to make sure to tell the web admins that the date field won't update until after they save the node. This provided a little confusion at the beginning.

So, this is a great solution for any node where you want to save form state data from one node/entity to another and have a unique identifier like nid/gid to do database lookup and save. Code sample below. I realize that node_load might be expensive to do, but since it's only happens when an admin user saves a form, I thought it was alright.

/**
 * Implements hook_form_alter().
 */
function custom_add_survey_date_form_webform_node_form_alter(&$form, &$form_state, $form_id) {

  //Add submit handler to grab and change date values
  $form['#submit'][] = 'custom_add_survey_date_submit_handler';
}

 /**
 * Adds a submit handler to webform_node_form
 */
function custom_add_survey_date_submit_handler($form, &$form_state) {

  //grab reference to event date
  $og_reference = $form_state['values']['og_group_ref']['und'][0]['target_id'];

  //load date from event plan node
  $og_node = node_load($og_reference);
  $event_date = $og_node->field_date_of_event['und'][0]['value'];

  //Store date on survey node
  $form_state['values']['field_date_of_event02']['und'][0]['value'] = $event_date;
}


Option for User to edit their own Profile Is it possible for the user to be able to edit their own profile without going through the Drupal administration panel?  I have a /user page with views that output the needed fields.  Ideally I would like an 'edit profile' button that loads up the same editable fields.

Could someone point me to how this can be achieved?

Thanks in advance,

P.S.: I'm on Drupal 7. Might be worth noting that I'm using Profile 2 as well.

I've managed to find the solution to this problem.  I have to call the 'edit user' link directly from Views as a field.  Thank you.


unable to edit content created by user 1 In drupal 6 I have created an admin user with the permissions to add, edit and delte all kind of nodes. The problem is that I am unable to edit nodes through this newly created admin user which are created by user1. any idea ??

I think, you did not assign "edit any [contenttype] content" permission to newly created admin user, so this user does not have access to edit content created by other user.

You can follow below step for configurations.

Go to Administer ->  User management -> Permission
Assign "edit any [contenttype] content" permission to newly created admin role and save the permissions.

Kindly see that [contenttype] is content type in your website. If you want to allow newly created admin user to edit all content created by other user, you need to give permission for all content type.


Charge user after status of order is changed with eCommerce I am using the Drupal 7 eCommerce kickstart distribution.

I want to sell service (like cleaning, gardening...), and I want user to be able to create order, but I want to give them ability to do payment after service is done.

Is there any way to do this, to make user able to make payment after they create order.

You can use a payment gateway that allows for Authorization Only transactions. This will authorize a certain amount, but will not actually charge the credit card.  This is what gas stations, hotels, etc. do. They charge a preset amount, and then finalize the actual amount later.

commerce_authnet offers this capability. In the settings for the payment gateway you just set Authorize Only.

Once the administrator is ready to finalize the payment, they would go to the Orders page, and choose Payment on the Order.  You then 'capture' the amount to finalize the payment.

You can fine tune who has access to the Payments page on the Permissions page.


How to deploy a module locally for testing? I'm currently developing my first custom module for Drupal 7 and am having a hard time finding documentation about the available local deployment strategies.

I have a custom module project, consisting of my modules sources, a gulp file and some other things of less interest (README, .editorconfig, ...). When I make a change on my source code, my gulp builder automatically deploy the changes to my local Drupal installation (the document root), in the folder where my custom module is installed.

Now, I would like to test my changes, and that's where I'm stuck: changes that are part of the install hooks of the module (adding fields, custom nodes, and so on) don't appear on the website. I have to disable my module, uninstall it, resinstall it and enable it to see those changes. This is a very long and painful process.

Even using drush commands to achieve this, the disable, uninstall, install and enable process is very long, meaning I'm losing a lot of time waiting for Drupal to manage my module, even for the tiniest source code change.

And of course, in any case, I have to recreate every content I had previsouly created to test my module.

Is there a strategy to allow near-realtime deploy and testing when developing a custom module ? How are you guys dealing with this ? Is there at least a drush command to replay the install hooks of my module ?

Thanks by advance.

I do not think there will be a way to reduce time of reverting the database changes. However you can get a shortcut command to re-install a module.

Checkout answer by @MPD Quick Uninstall/Reinstall of a Custom Module, so you will need devel module to bind all those commands in one, also devel is good for development purpose.


Change AJAX processing icon and progress bar in Drupal7 using CSS Can I change the throbber/ajax loading icon and progress bar in Drupal 7 by adding new pictures and overriding CSS system files?

You can do it by overriding the CSS in your theme CSS file. Here is the rule that you've to override

.ajax-progress .throbber {
  background: transparent url(../../misc/throbber.gif) no-repeat 0px -18px;
  float: left; /* LTR */
  height: 15px;
  margin: 2px;
  width: 15px;
}

You can just change the background and you will be able to change the processing icon.

Here is the another one that you should override

html.js input.form-autocomplete {
  background-image: url(../../misc/throbber.gif);
  background-position: 100% 2px; /* LTR */
  background-repeat: no-repeat;
}


How do I implement drag and drop node re-ordering in a view? I am creating a simple content admin view, and I need to implement drag and drop re-ordering (instead of weights in drop down menus). Is that possible, and how?

I think you're looking for the Draggable Views module:

  DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.