How to group views rows by year using date field? I have a content type with a date field.
I need to output them grouping by year, i.e.

2011

- nodeA 2011-09-01
- nodeB 2011-01-29

2010

- nodeC 2010-12-08

How can I do that?

Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.


Why is Rules reacting on Commerce Events multiple times and out of order? I am having lots of problems with my site because Rules is evaluating Events multiple times, and out of order.

For example, the debug log shows that when I add a product to cart, Rules reacts as follows:

Calculating the sell price of a product <- for internal processing, ok.
Calculating the sell price of a product <- why twice?
Before saving a commerce line item
Apply a fee to a given order <- why now?
After updating an existing commerce order <- but it didn't update; no fee added?
After adding a product to the cart
Calculating the sell price of a product <- for display, ok.
Apply a fee to a given order <- why now? and why again?
Select available payment methods for an order <- why now?

Would like to know if there is a way to debug deeper than the log; i.e. find out exactly when each rule evaluation was called ...

Somebody please help, this is making it impossible to work!

thank you.

Solved!

I had upgraded to PayPal WPP, but also left PayPal Express Checkout enabled.

This caused EC to not display where it normally does, i.e. on every page starting with the cart, but to only display on the Review page where other payment methods can be selected. However, the Rules events for EC were evaluated in their normal place in the process.

Thus the Events were being evaluated even though they had apparently not occurred.

The multiple evaluations of the Event "Calculating the price of a product" is normal.


How to add custom slider for textfield I read:

Best way for including javascript/jQuery OnLoad in EVERY page on my site
How to get jquery working on Drupal 7 - for Newbies
How to include jQuery UI on a page without PHP?

I'm using jQuery Update module. Tried different versions of jQuery.

I have theme tao_test (that is subtheme of Tao). In tao_test.info I added:

scripts[] = scripts/ranger.js

And inside of this js file is this code:

(function($){

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

          $("input#edit-field-range-test").before("

");

          $(".range-slider").slider({
              range: "min",
              value: 1,
              step: 1000,
              min: 0,
              max: 5000000,
              slide: function( event, ui ) {
                  $( "input#edit-field-range-test" ).val( ui.value );
              }
          });

      }
    };
}(jQuery));

Now problems:

When logged in as admin, slider kinda works, but looks strange:

There is no knob and overall it looks graphically broken. Also it only works if I set "CDN jQuery and jQuery UI" in jquery_update settings to some value.

When watching as anonymous user, I'm getting in firebugs console:

  TypeError: $(...).slider is not a function

What I'm doing wrong?

Added: Oh, I realized that this slider is supposed to be unusable without theming. However the problem with anonymous user is still current.

It appears that:

function THEME_preprocess_html(&$variables) {
    drupal_add_library('system', 'ui.slider');
}

is needed for query_ui to be available for anonymous users on every page.


Overriding views-view-fields.tpl.php Is it possible to override views-view-fields.tpl.php file for a specific view?  I've tried creating a views-view-fields--view-name.tpl.php file and have re-scanned template files and cleared the cache with no effect.  Similar issue as reported here: http://drupal.org/node/1137942

Though if I name the file views-view-fields.tpl.php in my theme folder, the new file is applied when template files are re-scanned. But this would mean that it applies to all views.

I noticed that views-view-fields.tpl.php is NOT one of the files listed in the Theme Information screen which Views presents.

Can someone definitively tell me that overriding of this file by creating a views-view-fields--view-name.tpl.php (or following similar naming conventions) is not possible/is not supported?

For views 3 - make sure that under "Format->show" field is selected "Fields" (NOT content)

Than go to views and find "Theme: Information" there you can see list of all template currently used (BOLD) and candidate template files. Find witch tpl.php file you want to use.

Go to views module directory and under "theme" folder you should be able to find base tpl.php for your chosen file. Copy that file in your theme folder. Rename it on naming convention given in Theme:Information.

Rescan template files.
If everything is OK views-view-fields.tpl.php should not be bolded anymore. Bolded should be your newly created tpl.php then you can style new tpl.php file as you like.


Trying to update node using node_save() produces integrity constraint exception This is the first time I've tried to do this so I may be missing something really obvious. I'm developing a module which uses hook_node_insert() to catch the creation of a node, and puts the node into Drupal Queue for later treatment by a cron process.

At the end of the process, I want to update a field in the node and save it. I've tried using entity_metadata_wrapper as well as node_save, but in both cases I get an error "PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3011' for key 'PRIMARY': INSERT INTO {node}....". Apparently, Drupal is unaware that the node exists already despite the fact that $node->nid is set (which is why we get a duplicate entry integrity constraint).

Looking at the node_save() code, it certainly seems to be supposed to check and load the node first if the nid is set (which it is - I've followed this step by step in debug). I must be doing something wrong, but what?

Here is the code from hook_node_insert which queues the node for treatment:

if ($node->type == "sms_message") {
  $queue = DrupalQueue::get('sms_message');
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $node_wrapper->field_queued->set(1);
  drupal_set_message($node_wrapper->label() . ' has been queued');
  $queue->createItem($node);
}

And here is the relevant code from the callback module for hook_cron_queue_info

function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  node_save($node);

I've also tried:

$node_wrapper->save();

instead of node_save, but with the same result.

please see the documentation of the hook
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7

Notice that it says that the hook is invoked (i.e. triggered) by node_save and that means that the data is NOT yet written in the database! so you essentially create an infinite loop.

Try to do something like $node->yourfield['und'][0]['value']= 'yourvalue_here' and DO NOT call node_save again. Also do not use a wrapper because in this case only adds complexity. Notice that if you dont use the wrapper you must provide the langauage (['und']  in my example) the number of the item ([0] ie the first one in my example) and the key of the table that stores the value (['value'] in my example). This is done automatically when you re using an entity wrapper but since your node is not ready yet it is not the best option because you clone the object by value and not by reference and then even if you change it the changes are not reflected in the original one that will be fed into the database.


How to change a node's term reference value, dependant on date I have a content type "Page" and one of its fields is a term reference to the taxonomy term "Page Type"

Another field is "Expiry Date"

The page type starts off as "Open Consultation", but I need it to automatically change the term reference to "Closed Consultation" if the "Expiry Date" has passed.

I've been a developer for years, but I'm still quite new to Drupal (7)... I know the GUI, but not php or which files to override (if that is the answer)

So, I need a basic explanation of how to achieve this.  Thanks !

Take a look at the Computed Field Module, I'm not sure if can handle the date field type or not. on the other hand if Computed Field didn't do what you want you could do a hook_form_alter hook in your custom module. and code your logic there.


How to create several -lists in one display with Views? I display a list of news which have a category. I wish to have over my news list , a list of all categories. Is this possible in one single view , and therefore with one single SQL query ?

What I want :

<ul> Cat1; Cat2; Cat3; .....</ul> //1st list

<ul> //2nd list
Title 1
Cat 1
Body 1

Title 2
Cat 2
Body 2

Title 3
Cat 3
Body 3
</ul>

All of that with one display of a view with Views module.

I get to see the first list. But not the list of categories above. I don't want several block and combine them in a template, wich means several query.

My view :

As far as I know you need two views, one for the first list and another for the second. You can "embed" the first view in the Header of the second view using the Views Field View module.
Views Field View:

This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
It's highly recommended to use this module in conjunction with views caching.
Views Content cache and Cache Actions are good ways of caching views.


Drush php-script | Drupal functions such as node_load() are not being found I successfully installed Drush on Ubuntu 12.04, and I created a script containing the following line.

print_r(node_load(10));

I am calling the script with drush php-script --uri=http://localhost myscript.php

Drush returns the following error.

  PHP Fatal error: Call to undefined function node_load()

I also tried with drush --uri=http://localhost cache-get, but I get the following error.

  Command cache-get needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
  The drush command 'cache-get' could not be executed.
  Drush was not able to start (bootstrap) the Drupal database.
  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See drush topic docs-aliases for details.
  connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.
  Drush was attempting to connect to:
  Drupal version:  7.26
  Site URI:  http://localhost
  Database driver:  mysql
  Database hostname: 127.0.0.1
  Database username: username // This is shown correctly
  Database name: database_name  // This is shown correctly
  PHP executable: /usr/bin/php
  PHP configuration:  /etc/php5/cli/php.ini
  PHP OS:  Linux
  Drush version:  7.0-dev
  Drush temp directory:  /tmp
  Drush configuration:
  Drush alias files:
  Drupal root:  /opt/lampp/htdocs
  Site path:  sites/default

I finally figured out what was missing.

In my case I had to install the mysql-client-core-5.5 package with sudo apt-get install mysql-client-core-5.5.


Webform/YAML Form component email mapping In Drupal 7, Webform module have the ability to map different emails against webform component's options so that the webform notification could be sent to different emails depending on a user selection.

In Drupal 8, Webform was ported and its email submission settings pretty basic so I decided to use YAML Form. However, YAML Form email handler have the ability to either have a custom emails separated by comma or a value from the component.

Is there a way to have component email mapping functionality?

The feature has been added to the latest dev release of Webform-8.x-5.x.

@see Issue #2854021 by jrockowitz: Send email based on element options selection


Get node ID or URL in Twig on field level I have a field value, which I would like to link to the content (to the node itself, using it in a teaser).

How can I get the URL or at least the ID on field level, to create that link?

The node in a field template is the parent entity you find in element['#object'], which you can use to build the path:

{{ path('entity.node.canonical', {'node':  element['#object'].id}) }}


How to send email to submitter in a webform? I have a webform and i want to send by mail this webform to submitter.
For the moment, i created an hidden field with token [current-user:mail] and i chose this field in adress.
I think it isn't very well. Can I do it in hook_form_alter ? if yes, how to do it?

You can set a e-mail field in the webform, whether it is hidden or not is up to you. You should then set the current users e-mail address as the default value. For this, you will need hook_form_alter()

function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
  //drupal_set_message($form_id); (uncomment this to get form id)
  if ($form_id == 'your_webform_id') {
    global user;
    if ( $user->uid ) { //check user is logged in
    $form['field_email']['und'][0]['value']['#default_value'] = $user->mail;
    }
  }
}


What variable will let me access user profile info? I'm using prepopulate to prepopulate a feild of a node/add/content. I'm trying to generate a URL using some PHP code that willl generate a URL like:

http://mysite.com/node/add/content_type?edit[title]={$some_var}

Each of my user profiles will have this link at the top of the page and I would like $some_var to hold the username of the user whos profile we are currently viewing. I was wonder how to populate $some_var with the username of the user profile being viewed.

Something like:

$some_var = $username;
print("Content Type");

If this link is to be on the user profile page then you can grab the related user ID from the internal URL (using the arg() function), and then use user_load() to load a user object that contains the username:

// Get user ID from internal router path (this isn't necessarily the URL shown in the address bar, it's the internal path that Drupal is using to serve the page).
$uid = arg(1);

// Load the user account and extract the username
$account = user_load($uid);
$username = $account->name;


Remote entities versus local entities for third party integration While integrating any third party tool with its own data storage capabilities, I usually end up with a question

So far I could figure out following Pros and Cons in both the cases.

PROS for storing on Drupal(local entities):

Easy reporting with views.
Being local entites to Drupal, we can leverage drupal out of the box functionalities like add/edit/delete forms.

CONS for storing on Drupal(local entites):

It creates dependency on Drupal, while the third party tool has all possible capabilities to run as standalone application.

Another possible option could be storing at both places Drupal and third party tool

But that would cause data syncronisation problem, and will require development at both ends to push data changes.

An example of such integration I recently came across is Camunda(BPM tool).

What will be a suitable place for data storage? Should we keep it on Drupal, or should we leverage third party storage capabilities?

Personally, I go usually with a caching system within Drupal. How this is implemented really depends on the external system, and how it works, but essentially I'll pull the data from the external source when first requested, and save it within Drupal somehow, whether that be into a node, or a custom entity, or some other data entity unrelated to Drupal entities.

The reasoning behind this is that pulling data from a 3rd party application into Drupal, then delivering it to the user, adds a lot of overhead and processing time. Essentially the browser makes a request, Drupal then starts to build it, makes it's own request (same as a browser) to the 3rd party app, gets the data back, finishes the Drupal page build, and sends it to the browser. This can make for some particularly long page builds. Whereas, if you pull it the first time from the 3rd party app and cache it, it takes longer for that first request, but subsequent requests will already find the data within Drupal, making for faster page loads.

Some things to consider however:

Will the data change every request? If so, then it should not be cached within Drupal.
Will the data never change on any request? If so, then it should be created as either a Drupal entity, or a non-Drupal entity, within Drupal, permanently
Will the data ever be deleted? If so, then it should be cached within Drupal, and periodically checked to see if it's been deleted. If however it must definitely not be accessed after it's been deleted, then it should not be cached within Drupal, else you risk showing the data to the user after it's been deleted.
Can you cache the data safely for a period of time? For example, maybe you can make the Drupal cache expire periodically.
Will you need the data to be accessible as fast as possible, when it's cached? You may want to create a cron mechanism that makes requests to the 3rd party for any new items, caching them immediately so they are ready right away when necessary.

Each 3rd party app is different, so there is not a one-size-fits-all solution to this. The various limitations and requirements need to be researched, with a solution created accordingly.


date field missing when use date popup with date & time in my custom module, I have used the following code:

$form['event_date'] = array(
    '#type' => 'date_popup',
    '#title' => 'Set Date & Time :',
    '#date_format' => 'd-m-y H:i',
    '#default_value' => date('d-m-y H:i'),
    '#date_year_range' => '-3:+3',
    );

but after submitting it only show time field value. also work fine when only use date('d-m-y').

Yep, I found it in $form_state['input'].

I am actually using this with Ajax. so In callback function you can get the form values from $form_state array. All form values are present in $form_state['values'] and input type values are also can be found in $form_state['input'].


How can I disable theme update notifications? How can I disable Drupal update notifications for certain themes?

I am using the Drupal Bootstrap 7.x-3.0 Theme which is not the latest version. That is why Drupal sends out a email Update notifications and shows a update warning. I don’t want to miss any module updates, thus I would  like to keep update notification enabled. However I don’t want receive theme update message all time.I didn’t know that this is such difficult approach.

I was looking for a easy solution e.g. theme .info settings or on/off option in Drupals settings.php.

The Update Status Advanced Settings enables you to disable any project, including themes, that you don't want to be alerted about updates for.

  Extends the administrative interface for Drupal core's "Update status" module (added to core in 6.x).

  Users of the 5.x Update status contrib module will probably want to use this once they upgrade to 6.x, since some of the functionality in the contrib version was deemed too complicated to include in core. In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.


Workbench: How can I reorder display of Workbench Tabs? I'm running Workbench, workbench access, workbench moderation and workbench media on Drupal 7.
I added a new state "Needs publish" for "Waiting to be published", which is under "Configuration > Workbench > Workbench Moderation > States tab". Also, I cloned the "Needs review page" view for "Needs publish page"(just changing the filter "Workbench Moderation: State" to "Needs Pulish"). However, the new tab I have for "Needs publish" is in between "My Drafts" and "Needs Review".

Question: How can I move the new tab "Needs Publish" after "Needs review"?

--- Added screenshot on July 23, 2014 at 1:49pm

under the view Table Display Settings. You should be able to assign placement of the columns there.

See the Format > Table > Settings at the left:

Then assign fields to certain columns here. The ordering of these columns by default is the ordering of the Fields defined in the View.


Fatal error when restoring PostGreSQL DB from dump: undefined function system_run_automated_cron I'm trying to simply install Drupal 7.8 on PostGreSQL 9.1, backup the DB, and then restore from it ... nothing else, just to test out backing up my sites, but the site will not come back up!

Here are my steps:

install Drupal & get through configuration to the "you're done" screen
dump the DB (pg_dump > file.sql)
drop the DB (dropdb)
create a new DB with the same info (createdb)
restore the DB (psql < file.sql)

No steps in between (except when I've tried to avoid the error by putting the site into maintenance mode and/or clear the cache). No adding content, no nuthin'!

But when I access my site, I get the following error message:

[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 1009 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Fatal error:  Call to undefined function system_run_automated_cron() in /Applications/MAMP/htdocs/drupal-postgres/includes/common.inc on line 2573

Anyone have any thoughts? This CAN'T be this hard!

Thanks a million!

After looking into this a bunch, I just decided to move the DB to MySQL. I hated to have to do it, but support for sql-dump in drush is limited to MySQL, and Backup and Migrate is as well. Kills me to have to run two DB servers (all my other applications use PostGres), but desperate times call for desperate measures.

I would hope some day that these modules would support PostGres. As Drupal supports both, so should the modules.

Some notes to others when using Backup and Migrate and Backup and Migrate Files

File ownership travels with the files, so I've had to "chown apache" files that get moved
It looks like the Temporary Directory setting is stored as a machine-specific folder, so be sure to update this on the destination machine
Clear the cache on the destination machine. I had a case where a tpl.php file wasn't being used until I did this.


Why cannot I choose MySQL as database type in the installation page? I downloaded the Drupal archive and extracted it on the dedicated server. In cPanel, I created a MySQL database, but when I try to install Drupal, in the Database configuration page, I can only choose between PostgreSQL and SQLite as database type; I cannot choose MySQL.

Why did it happen? How do I fix it?

Create a info.php file and upload it to your server :

 php_info()

upload the file to your server is docroot then visit the URL http://youdomain.com/info.php
search for pdo_mysql and it should be enabled if it does not exist  contact the server admin and tell him to enable the pdo_mysql (https://serverfault.com/questions/471282/how-enable-pdo-mysql) :

  in your case I think you have just the pgsql and SQLite PDO enabled


Display Suite View Only Showing Default Display Custom displays are no longer showing up on the Front-End; instead only the default view is showing. The following message displays next to the template section on the display page (structure/types/manage/contenttype/display/display_name) "This layout is defined in code: disable layout." When I click "Disable Layout" link it takes me to a new page and displays: "This operation is not possible."
What does this error mean? What is the cause? How can it be corrected?

It is not clear whether this error is the reason the display is not showing on the frontend. I have tried accessing the display several different ways include through a view, shows the default (view-mode-full) content display, not the one it is set to. Though the default view is picking up my assigned custom classes.

It is as if Display Suite will not display more than one display on front-end. I can customize and edit "full content" display but this displays on front-end regardless.

It was caused by a conflict with View Role Per Node Module
Even though I did not have any node views assigned based on role, it still seemed to be interfering with the Display Suite behavior.


Ask services "Which user am I?", as defined by session id? Scenario: An external service wakes up. This could be a remote Drupal site running a cron , a mobile application being started or something completely different.

The service has a session id from it's last interaction with a Drupal site running Services.

How does this service go about asking the Drupal site: "Based on this session ID, who am I?"?

For a regular user on the Drupal site, /user will tell you who you are. However, when accessing [endpoints]/user through Services, you get an index of all users, instead of a specific user object.

If possible, please include json as the content type for any code examples.

This service resource simply return an object representing the currently authenticated user:

/**
 * Implements hook_services_resources().
 */
function MYMODULE_services_resources() {
  $resources['MYMODULE'] = array(
    'actions' => array(
      'whoami' => array(
        'help' => 'Get an object referring to the currently authenticated user.',
        'callback' => '_MYMODULE_whoami_service_resource',
        'access callback' => 'services_access_menu'
      )
    )
  );

  return $resources;
}

/**
 * Resource callback
 */
function _MYMODULE_whoami_service_resource() {
  return $GLOBALS['user'];
}

Once enabled you should be able to access the resource at http://site.com/[endpoint]/MYMODULE/whoami.json.


Optimal Settings.php for Pressflow + Varnish + memcache I am using pressflow having varnish + boost + memcache and also using cloudflare caching, I have seen some variable forms of settings.php file on forums and I am confused whether mine is optimal for best usage of all these caching mechanism :

# Varnish reverse proxy on localhost
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('127.0.0.1');

# Memcached configuration
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
         '127.0.0.1:11211' => 'default',
         );
### END Mercury settings written on 2011-11-01T07:12:49-04:00

Unless you are doing something quite unique, using boost & varnish is usually overkill. If you have varnish setup exactly how you want it, I would just use varnish.

Here is an example settings.php. It is a multisite safe memcache configuration thanks to the memcache_key_prefix setting.

<?php
// Skip db query that checks for blocked IP's.
$conf['blocked_ips'] = array();

// Reverse proxy settings.
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array(
  '127.0.0.1',    // Localhost
);

// Use memcache for caches, locks, and sessions.
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = './sites/all/modules/memcache/memcache-lock.inc';
$conf['session_inc'] = './sites/all/modules/memcache/memcache-session.inc';

// Memcache Settings.
// Set memcache server.
$conf['memcache_servers'] = array(
  '127.0.0.1:11211' => 'default',
);
// Set memcache bins.
$conf['memcache_bins'] = array(
  'cache' => 'default',
  'cache_form' => 'database',
);
// Set memcache prefix to be the location of the settings.php file.
$conf['memcache_key_prefix'] = basename(realpath(conf_path()));
// Try to use a persistent connection.
$conf['memcache_persistent'] = TRUE;
?>


Drupal language icon problem I just started a new project where I aim to provide country Icons. I use two languages in my project. My default language is English, and my problem is that in some pages it works fine, but in some other pages the English language does not work. Also I have a problem as shown below in image:

So what am I to do and how can I remove the English cross text form here. I am new in Drupal.

The strikethrough effect (what you describe as 'cross text') over the language is because the specific content which you are viewing does not have content for that language in the language switch block.

The particular effect comes from the rule .locale-untranslated in modules/locale/locale.css line 2 (D7.36).

If you wish to remove it, either add content for the particular language, or add a rule as the following to your custom theme:

.locale-untranslated { text-decoration: none; }

Also for the record (I suppose you already use it) there is a module for displaying language icons.


Can I add a "edit node" link as field in a node? I need to have the "edit node" link as a field so that I can manage its display.

Can I do this?

Update:
I created the field but the token code is printed instead of its value.
The code you see in the capture is printed: http://misite.com/node/%5Bnode%3Anid%5D/edit

Capture:

You could also check to see if the user has access before printing the edit link.
<?php
  if (node_access('update', $entity)) {
    print l(t('Edit'), 'node/' . $entity->nid . '/edit');
  }
?>


Programatically get the webform submission "sid" on submitForm I am trying to programatically get the webform submission sid on submitting a webform but failed to get it !

On my customwebformhandler.php file i have the below:

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get the Webform submission "Sid".
    $sid = $webform_submission->id();

// Show a success message.
    \Drupal::messenger()->addMessage(t("$sid"));

}

but i am not getting any sid value.

any help please ?

So it turns out i will have to save the webform before i can get its sid since i am using the public function submitForm which is fire in submitting the webform but before saving it.

Final code will be:

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
// Get an array of the values from the submission.
    $values = $webform_submission->getData();
    // ...
    $webform_submission->save();

    // Get the Webform submission "Sid" after saving the webform submission.
    $sid = $webform_submission->id();

// Show a success message.
    \Drupal::messenger()->addMessage(t("$sid"));

}


Does storing my database as a .sql file in my site git repository cause problems? I have been saving a series of database export files each time I do a git commit of my Drupal site.  I have a nice git repository for my site files and a messy folder for my database backups.  Because the database file is related to a commit, should the database file be included with the Drupal site files (in a temporary folder of some kind?)  It seems helpful to bind these files together in a single commit.  However, this practice does not seem commonplace, so there may be a problem with it.  Have I overlooked a major issue?

If so, would it be better to create another repository for my database backups?

It should be the right way  so that both site & database are in sync.

I'd suggest you better backup the (zipped) mysql dump from backup-migrate module. If you can use lzma compression then you can save another 20% space on mysql backups using this way.


Views: display entity reference fields as view fields I have a content type (1) with an entity reference field that point to another content type (2).

I'm trying to create a view where I want to display fields of content type 1 mixed with the FIELDS of the content type 2.

When I go to add fields in my view I can see the fields of content type 2 but the output is empty, the only thing I can do is display the rendered content type 2 with all of its fields.

Is there a way to output single fields of content type 2 as view fields?

Yes you can do it. The Entity view Attachment  module is built for such task. Using this module, fields of another content types becomes a filed of another one. this link is a good tutorial of this module.


entity getPropertyInfo() not working I am working with the entity_metadata_wrapper, and I found online this function to display all of the wrapper's properties.

$billing_profile = commerce_customer_profile_load($order->commerce_customer_billing['und'][0]['profile_id']);
$billingWrapper = entity_metadata_wrapper('commerce_customer', $billing_profile);
dpm($billingWrapper->getPropertyInfo());

However, it gives me an error.

  PHP Fatal error:  Call to undefined method EntityValueWrapper::getPropertyInfo()

When I googled the function, it came up as EntityStructureWrapper::getPropertyInfo(),  where I see that its not a function of EntityValueWrapper, but rather EntityStructureWrapper.

How do I create that class instead of using the code I found?

Commerce customer only defines a commerce_customer_profile entity type (not commerce_customer), so changing the second line to this should fix it:

$billingWrapper = entity_metadata_wrapper('commerce_customer_profile', $billing_profile);


How to autocomplete taxo term (inside a paragraph) when using a filter in a view Here is a node structure which is storing cooking recipes

recipe (node)

-title (string)

-field_ingredient_quantity (paragraph) => see below the definition

-... (other fields)

field_ingredient_quantity (paragraph)

-field_ingredient (taxonomy term)

-field_quantity (float)

Let say that I woul like to filter in a view all recipes containing mustard with the autocomplete filter on field_ingredient (inside the paragraph type field_ingredient_quantity)

Is it possible?

Why not try to define a relationship towards the field_ingredient_quantity and then add the field_ingredient in the fields of the view(should be available after defining the paragraph relationship). Afterwards just add the exposed filter with the autocomplete functionality.


My Aquia Dev Desktop is insanely slow. What could be the problem? I'm running Drupal 7 with the latest version of Aquia Dev Desktop and the site is REALLY slow on local host. I mean something like one minute to load a node  to edit it, and three minutes to load the modules page.

I tried the Boost module, and I have all the performance settings maxed out.   What could the problem be (a port, the PHP version, too many installs)? I have about seven sites in there.

The site on the live server (in the USA) is faster and I'm connecting from Thailand; that is twice as fast as localhost.

I experienced the same thing when I tried using the Acquia Dev Desktop.

I now use c9.io (clould 9) and do all my development in the cloud :)

Here is a nice overview video of the IDE.


SEO for possible duplicate content Website is about bands and musicians.

Musician can create the profile and add his bio.
Band can create profile and add band members and their bio.
Many musicians are members of several bands, so i will have bio of XY repeated on several pages of my website.

Any idea how to control this since site will be made and controlled more or less by users ?

I think the answer relies on the way you organize your content. I imagine bands could be a content type, with fields like bio, discography, pictures, videos and whatever, and a field with multiple values to add users, beeing the band musicians.

The users get their own fields from which bio. Then you can display a list of teasers of musicians in the band node, with a link to complete profile and bio.

EDIT : (for lazy or busy musicians :) I guess NY Big Band staff i.e knows all members's emails, names...

Create a role "band manager" with the rights to create user accounts
When an account is created by this role, set up a rule to send an automatic email to notify the musician,  that an account has been created for him and he's welcome to check if his information is correct.

This way you 'll have a unique "musician content", without SEO duplicate problems, and you 'll also improve the involvement of musicians in your website.


How to parse PHP variables in drupal_add_js in template.php I'm using drupal_add_js for some inline jQuery - I need to parse some php variables in the inline jQuery, what is the correct way to do it?

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

I've tried this, and it DOES print the variable, but breaks the JS code in the process (splits the jquery code up and doesnt function) :

drupal_add_js('jQuery(document).ready(function () { alert(" '. print $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

Just remove the print function from your code:

drupal_add_js('jQuery(document).ready(function () { alert(" '. $site_name .' "); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

Looking at the javascript Window alert() Method it has this syntax:

  alert(message)

And the message parameter has the type string

PHP's print function prints to the output buffer and returns an int. It has this definition:

  int print ( string $arg )

So your code prints the variable $site_name to the output buffer and returns an int, and your string for the alert is then an integer and you have printed to the output buffer which you did not want to do.


Create AJAX multi step form which changes based on user input I am trying to create a form where initially, the user is presented with just one field, which is their email address. When they click submit, I would like it to be an AJAX submit where I then lookup their email in a custom table in the database and then present them with additional form fields that will either be blank if we do not have their email address in the sytem, or will be pre-populated and ready for them to edit, if we already have them in the system. I was thinking a multi step AJAX form might do the trick, but I don't know if it even needs to be "multi step". Can I accomplish this with just a standard AJAX submit? I just can't figure out how to show/populate those additional fields after they submit the form. This is what I have so far, I just can't figure out how to only show the additional fields AFTER the submit and verification process:

/**
 * Implements hook_form().
 */
function _vista_form($form, &$form_state) {

  $form = array();

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => 'Email',
    '#required' => TRUE,
  );

  $form['wrapper'] = array(
    '#markup' => '',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // all of the fields below this are the ones that I would like to show ONLY after I look them up and then I can prefill them in or not
  $form['id'] = array(
    '#type' => 'hidden',
    '#value' => 0,
  );

  $specialties = db_query("SELECT specialty_code, specialty_name FROM {specialties_vista}")->fetchAll();
  $default_specialties = explode('^', '');

  $specialty_options = array();
  foreach ($specialties as $specialty) {
    $specialty_options[$specialty->specialty_code] = $specialty->specialty_name;
  }

  $form['specialty'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#size' => 10,
    '#title' => 'Specialty',
    '#description' => 'Hold Control or Shift while clicking to select multiple specialties',
    '#options' => $specialty_options,
    '#empty_option' => '-All-',
    '#empty_value' => 'all',
    '#default_value' => $default_specialties,
  );

  $type_options = array(
    'VISTA-HealthCare-Partners-Government' => 'Vista Healthcare Partners',
    'International' => 'International Locum Tenens',
    'Permanent' => 'Permanent Physician',
    'US-Locum-Tenens' => 'US Locum Tenens',
  );

  $form['job_type'] = array(
    '#type' => 'checkboxes',
    '#multiple' => TRUE,
    '#title' => 'Type of Job',
    '#options' => $type_options,
    '#empty_option' => 'Choose a placement type',
    '#empty_value' => 'all',
    //'#default_value' => $type_selected,
  );

  $form['active'] = array(
    '#type' => 'checkbox',
    '#title' => 'Subscribe/Unsubscribe',
    '#default_value' => 1,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array('class' => array('submit')),
    '#ajax' => array(
      'callback' => '_display_form',
      'wrapper' => 'ajax_wrapper',
      'effect' => 'fade',
    ),
  );

  return $form;
}

function _display_form($form, $form_state) {
  //do database lookup here and set some variables? Not sure.
  return $form['wrapper'];
}

You need to keep track of the step you're in. The first time a user hit's the form you would initialize a variable, say $stepand give it the value 1. On submit you augment that value to be in step 2 on the form rebuild. In the form builder itself (_vista_form()) you add form items depending on the current step. The same goes for validation and submit handlers. Usually you would use switch statements.

Have a look at this very complete tutorial: http://www.jaypan.com/tutorial/drupal-7-ajax-driven-multi-step-forms-non-javascript-fallback


Media module is bring contextual links with it into the middle of WYSIWYG content - how to remove? Is there anyway to remove these links from the output of the media module? I suspect that they're responsible for breaking the link tag I have wrapped around the Media image in the WYSIWYG editor.

On the rendered template of the page this looks like

How can I prevent these links from being embedded by the media module? They even appear to show when I am not logged into the Drupal administration too.

You'll have to change the sort order of filtering within your text format, admin/config/content/formats/full_html (for Full HTML text format).
Just place the "Convert media tags into markup" before the "CKeditor Link filter".


What is the simplest, most drupalish, way to restrict access to some content to authenticated users or a certain role? I am creating a publications database that is used by staff to input their publications.  Some of these publications are available to the public, and some are not.  Additionally, the publications have files associated with them, some being public and some not.  I have a number of content types for different types of publications with a boolean public field, and two seperate file fields, one for public and one for internal files.  I currently have one user role (Staff member) though the number of roles is likely to increase slightly to allow for administrators and a content approval workflow.

Content Type a

Public?
Public Files
Internal Files

Content Type b

Public?
Public Files
Internal Files

The idea is that all the publications lists should show a list of public documents to non-authenticated users, and a list of all documents to authenticated users of the right role.

My initial thought is to create two different views for each page with different access settings on each.  The first being a page that doesn't check the public field and includes the non-public files field, and a second, available to anyone, that filters to publications where the public field is set to true, and does not include the internal files field, and a few other fields only of interest to staff.

node list view

view a

access: staff only
filter: Published nodes

node list view

view b

access: no restriction
filter: Published nodes AND public is true

node view

view a

access: staff only
filter: Published Nodes
fields: All Fields, including internal files

view b

access: no restriction
filter: Published Node AND marked public
fields: don't display internal files, some other fields

Is this the simplest, most drupalish approach?  Would it make more sense to control the fields used through the view or via view mode (Full Content, Teaser, etc.)  I'm still somewhat new to working with Drupal, and find that I'm fighting it at every turn, that makes me think, I must be thinking the wrong way for working with a drupal site.

Further Information: I'm actually reimplementing this from an existing system, and am using the Migrate module to bring in thousands of entries, so I have to be able to specify as part of the migration in some way, what the permissions should be.

Content Access

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial
Field Permissions

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Your views approach is fine, assuming everything you need is in the view.
But if you want to restrict access to nodes, then you're better off using Content Access.
For example: If your view was listing links that you don't anonymous to access (eg: premium content) you would want to use the Content Access module because if anonymous users somehow get a hold of the direct link then they could see the premium nodes.


Run validation callback before ajax The submit element on my form uses an ajax callback which sends out an email.

I have a validation callback which I've added to this form, but it gets run after the ajax callback and so the email will be sent out even if the form doesn't validate.

I can't add the validation to the ajax callback itself because it gets used on lots of other forms on my site.

Is there any way to run my validation callback before ajax is run?

Actually, you will pass through your validateForm() method, whether you are using Ajax or not.

In the validateForm(), you have to set the appropriate errors on your fields which do not validate.
Then, as Charles Bamford stated, you need to handle the error management in your submit callback.

So basically, you would end up with some kind of the following structure:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#prefix'] = '

  $form['my_field'] = [
    '#type' => 'textfield',
    '#title' => $this->t('My field title'),
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#ajax' => [
      'callback' => '::myAjaxCallback',
      'wrapper' => 'my-ajax-target-element',
      'method' => 'replace',
    ],
 ];

 return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  // I set error on my field here, but due to Ajax, the display
  // of error messages will be handled in the Ajax callback
  if($values['my_field'] != 'my expected value') {
    $form_state->setErrorByName('my_field', $this->t('This is my error message'));
  }
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  // If $form_state contains errors, populate the ajaxResponse content with the error messages
  if($form_state->hasAnyErrors()) {
    $errors = $form_state->getErrors();
    $command_content = $errors['my_field'];
  }
  else {
    // Happily proceed to the submission of your form
  }

  $response->addCommand(new HtmlCommand('#my-ajax-target-element', $command_content));
  return $response;
}


Absolute URLs instead of relative I have a problem with entity URLs in D8. All of them are absolute instead of relative, which causes various problems. For example,link URLs to edit content on /admin/content look like this:

http://example.local/node/693/edit?destination=http%3A//example.local/admin/content

instead of

/node/693/edit?destination=/admin/content

It's not theme-related issue
I checked various custom classes implementing OutboundRouteProcessorInterface and it seems, that none of them should affect this

What could be the cause, then?

EDIT: It's the same with all Drupal-generated links.

BTW. The issue can be seen by executing

use Drupal\Core\Link;
$link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1])->toString();
print_r($link);

It should result in relative URL, in my case it's absolute one.

Sorry, it was caused by

$host = $_SERVER['HTTP_HOST'];
$config['language.negotiation']['url']['domains']['cs'] = $host;

in my settings.php file. Thanks all!


Adding fields to content type edit form (not to the node itself) In Drupal 8, how do you add fields to the content type edit form, i.e. where you define the content type?  I know how to add fields to the content type that wind up on the node edit form, but I'm looking to add a field to the content type itself.  Essentially, what I'm trying to do is add some data to content types that would allow me to group them together.  To do this, I need to add some additional metadata to the content type beyond name and description.

It sounds like you need to create custom entities.
Try reading Creating a content entity type in Drupal 8 and maybe this module can help: Entity API


how to use token in "Execute custom PHP code" in a rule I used "Execute custom PHP code" in my pricing rule.

However I got Notice when I checkout:

  Notice: Use of undefined constant testsku - assumed 'testsku' in eval() (line 7 of /var/www/jmu/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).
  Notice: Undefined variable: line_item in eval() (line 7 of /var/www/jmu/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).

I know there must be something wrong with my token replace code:

$line_item_label = token_replace([commerce-line-item:line-item-label],array('commerce_line_item' =>$line_item));

I used "line-item-label" as product sku's machine name

Anyone have any idea about this?

At the very beginning, I just saw "$commerce_line_item" can be used in php code, but I wanted to use [commerce-line-item:line-item-label] value which showed in the token place. So I tried to use token_replace to get this value.

Finally, I figure out how to get that value and use it in PHP Code.

Although it isn't showed in the variable name place, we can still use $commerce_line_item -> line_item_label in the PHP Code. This works for me.


How to create dynamic link in views? I am using views and I want to put a dynamic link in the header. The link is http://www.example.com/node/add/album/31
The number 31 varies depending which node it is viewing so I want it to change to whatever node id it is viewing. I'm not a coder so can anyone give me code?

you can add a "global text area" field to the "header" of the view. Then add the link HTML in there:

add

The %1 will take the the first argument from the URL


How do I associate multiple nodes to a user? I have some users, and I have a "product" content type, which has the following fields: "name," "type," and "description."

I want to associate specific nodes of this content type to a user. How do you suggest I should do this?

Shall I create a new table and store the user and the product ID?

There is a module for handling relationships between entities for Drupal 7 which shows great promise called relation. At the current time it's still in alpha and I haven't tested it out for a while, so I am not sure where it is at. When I last tried it out, it wasn't quite suitable.

A more stable version which could be made obsolete by the relation module is the references module, which is a port of the Drupal 6 CCK node reference field. I've used that with great success.


Importing nodes with different field names from Drupal 6 to 7 I need to import certain nodes from a Drupal 6 site to a Drupal 7 one. I have a particular situation:

I need to import only nodes of a certain type
Node types have different names in the sites ("Question&Answer" in the drupal 6 site, "Answers" in the drupal 7 one)
The 2 types have the same fields, but some fields have different names (The drupal 7 nodes have additional fields, but they are not required)
I need to put the id of the drupal 6 nodes in a field called "orig_id", the drupal 7 nodes need to have different IDs
Nodes have 4 taxonomy relations: 2 use Hierarchical select, 1 (tags) can have new terms added when creating a new content (and the 2 sites have a different set of tags at the moment).
Taxonomy vocabularies have different names, but (except for tags) contain the same terms.
Node Authors are the same in both sites, but they have different IDs. Importing authors references is not a must, so it can be skipped

I am fairly new to Drupal, i have tried searching for some import modules and/or articles about importing, but i can't find a guide that suits all my needs.

I have solved by checking which fields i needed, i made a table with those fields then made a custom boostrappable script to import them as new nodes


Create a primary link for the user edit page What is the proper way to create a link under "Primary Links" that will take the logged in user to their own user edit page?

I use the me aliases module to do this: it provides an alias, user/me, that you can add to menus and elsewhere. It also provides mappings for things like user/me/edit.


how to create domain specific domain admin I am using domain access module to create different sites using subdomain. I want to create domain specifc admins so that they can view only listing of their own domain and want to able to install modules,themes etc all action on their specific domains.

Only Super admin should able to see all listings without any restricitons .

How can I achieve this ?

Thanks

I have used Access Domain module.

What you have to do is:

A- Create a user role. Example: [domain A admin]

B- Give that [domain A admin] user permission to access the admin menu system as well as other permission you want.

C- Go to domain module settings - admin/structure/domain/roles Now restrict the [domain A admin] to the domain you want.


how can I change the admin url? Is it possible to have the administration pages on a different place than /admin?

so something like: www.mysite.com/someotheradminlocation

I don't want the admin location to be guessable by hackers.

There is a module to do what monymirza suggested - http://drupal.org/project/rename_admin_paths

  The purpose of this module is to secure drupal backend by overriding
  admin path.


how to hide the main menu which is not listed in a block I downloaded a theme which automatically puts my main menu in the header region.  However, when I look at my blocks you can't edit that region.

I would like to BLOCK ALL unauthenticated users from seeing the main menu.  How would i do this?  thanks!

It seems that you want to lock down specific areas of the site with permissions that are not readily available on the Permissions page. I would address that issue in the following way.

I would update the theme to make the region editable and make it so that the menu was not part of the theme by default.

Next I would install the Context module so that I could display specific blocks, in specific regions, when specific conditions are met.

Finally I would create a Context with the settings:

Conditions

"Sitewide: Always active"
"User Roles": "Authenticated User"

Actions

"Block": Main Menu


Get cron to process QueueWorker items at a specific time I have a Plugin\QueueWorker that creates a queue of emails to send from nodes that are created/updated throughout the day. I've defined a processItem() method, as well as an arbitrary function (let's call it mymodule_add_to_queue()) that runs $queue->createItem() to add the node to the queue. When cron runs, all the items in the queue get run, which is fine and dandy.

The only problem is that cron is running every hour, and it seems the QueueWorker class will run the process every time, when I only want it to run once, say between 2am and 3am.

I have the code that checks the REQUEST_TIME and the state of the last time it ran and all that, however I don't know where to put it. Even if it goes into hook_cron(), it doesn't appear to make any difference to the default behaviour.

Pseudocode for what kind of thing I'd be expecting to happen is:

<?php

// @file src/Plugin/QueueWorker/MyModuleCronQueueWorkerEmailSend.php
class MyModuleCronQueueWorkerEmailSend extends QueueWorkerBase {
  public function __construct () {
    this.auto_cron = FALSE;
  }
  public function processItem() {
    doSomething();
  }
}

// @file mymodule.module
function mymodule_add_to_queue() {
  $queue = \Drupal::queue('mymodule_queue_worker_email_send');
  $queue->createItem(['foo' => 'bar']);
}

function mymodule_cron() {
  if (some_cron_conditionals()) {
    $queue = \Drupal::queue('mymodule_queue_worker_email_send');
    $queue->process();
  }
}

... this may be completely out of scope though, or there may be a really obvious other method I'm missing. Any thoughts? As always, thanks in advance :)

Copied from \Drupal\Core\Annotation\QueueWorker, the annotation and placd where the @QueueWorker annotation is documented.

 * Worker plugins are used by some queues for processing the individual items
 * in the queue. In that case, the ID of the worker plugin needs to match the
 * machine name of a queue, so that you can retrieve the queue back end by
 * calling \Drupal\Core\Queue\QueueFactory::get($plugin_id).
 *
 * \Drupal\Core\Cron::processQueues() processes queues that use workers; they
 * can also be processed outside of the cron process.
 *
 * Some queues do not use worker plugins: you can create queues, add items to
 * them, claim them, etc. without using a QueueWorker plugin. However, you will
 * need to take care of processing the items in the queue in that case. You can
 * look at \Drupal\Core\Cron::processQueues() for an example of how to process
 * a queue that uses workers, and adapt it to your queue.

See the last paragraph, the solution is simply to just fill an arbitrary queue and then implement similar logic as Cron::processQueues() for your queue to process the items when you want. Nothing will happen automatically with items of a queue that doesn't have a worker plugin.

Instead of a plugin, you can implement your login in a service instead and call that from your own cron implementation.


Webform two dependent select lists I have a content type "course" and a taxonomy vocabulary "Course categories" and a Webform
"Register" the user will register by choosing the course category in select list then use the course related to this term .

Now i have a list for terms and a list for courses
The problem is i don't know how to link between the two lists so the courses list show only
the correct course

Install conditional fields module and it creates relationship between fields.


I cannot create a directory when installing a module I have a clean install of Drupal 8 on a new Centos 7 server. This is the first module I have attempted to install. I'm using the built in update manager. I get the following error.

  File Transfer failed, reason: Cannot create directory /var/www/html/modules/somemodule

This seems like a common enough permissions problem but no answers I've found on similar questions have worked. The webserver user is apache (not www-data) and it owns the modules directory. I have confirmed this with ps aux | grep -i 'www\|apache\|nginx'.

These are the current permissions.

drwxr-xr-x.  2 apache apache    24 Jan  3 13:27 modules

I have chowned and chmodded until I'm blue in face, but it hasn't changed anything since the apache user already owns the directory and should be able to write it.

/admin/reports/status shows all green including FILE SYSTEM Writable (public download method).

What could be wrong? How can I further troubleshoot?

I am using PHP 7.1.14, Apache httpd-2.4.6-67.el7.centos.6.x86_64, and Drupal 8.4.4.

Update:

I have tried chmod -R 777 as a test and receive the same error. I have also tried creating the directory for the module manually but the update manager is still unable to copy files to it.

Update 2:

I have downgraded to php 7.1 to be fully compliant with Drupal 8 requirements but this has not solved the issue or changed the behavior.

This turned out to be an SELinux issue. SELinux is enabled and running in enforcing (strictest) mode by default in Centos 7 and this will prevent the web user from being able to write to /modules or /files (or anywhere) regardless of the file permissions set.

To see if you may be having the same problem:

more /etc/selinux/config

This will display the SELinux config file and let you know if it is enabled and what mode it is in.

The issue can be corrected with the following commands:

sudo chcon -Rt httpd_sys_content_t /var/www/html
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/sites/default/files
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/modules
sudo chcon -Rt httpd_sys_rw_content_t /var/www/html/vendor

This will correct the context of the directories you want to grant write permissions on so that Drupal will work without disabling SELinux. For more information see the man pages for selinux and chcon.


Check in php if a view display exists? I've created a display called 'stats' for some views I've created - its cached and its generic and its quick and I use it for things like this

$result = views_get_view_result($view_name,'stats');
$count = count($result);
if ($count) $variables['title'] .= ' ('.$count.')';

However, not all views have this display.
How can I check, in php, if a given view has a display called 'stats' ?

Off the cuff, this should work:

$view = views_get_view($view_name);
if ($view && $view->access('stats')) {
  // it has a 'stats' display
  $view->set_display('stats');
  $view->pre_execute();
  $view->execute();
  return $view->result; // or do whatever with it...
}

but realize at this point you're halfway through the 'heavy lifting' views does, so you should probably use $view inside that if instead of then calling views_get_view_result()

ADDITION:  I added what I think the correct $view incantations should be for getting just the results above :)


How to Sum up 2 fields of integer, and present as "Time period"? I am building a drupal site.
I have 2 fields: "prep time"  and "cook time".
Both fields are:
FIELD TYPE = Integer
WIDGET = Time Period

I need to sum up the two fields to one field (total time), and present it with widget of Time period, Or at least present it in time format ("2 hours 35 min").

Question Update (3/12/2013):
In addition, I need to present the date with ISO format in the HTML code (datetime="PT3H45M"). After I am using the Computed Field module, I don't know how to present the computed number as time format ("2 hours 35 min") and add the ISO format in the HTML code. as you will see below, I created a "field--field_preptime.tpl.php" that works great for the "prep time" and the "cook time", but when I am passing the computed value, the out put is wrong - as I don't see the the time format correctly, and the iso foramt in the html code is also wrong.

can someone help me fix it?

here is how I created the prep time and cook time:
I created the following field override template file called: "field--field_preptime.tpl.php"

<?php
function time_to_iso8601_duration($time) {
    $units = array(
        "Y" => 365*24*3600,
        "D" =>     24*3600,
        "H" =>        3600,
        "M" =>          60,
        "S" =>           1,
    );

    $str = "P";
    $istime = false;

    foreach ($units as $unitName => &$unit) {
        $quot  = intval($time / $unit);
        $time -= $quot * $unit;
        $unit  = $quot;
        if ($unit > 0) {
            if (!$istime && in_array($unitName, array("H", "M", "S"))) { // There may be a better way to do this
                $str .= "T";
                $istime = true;
            }
            $str .= strval($unit) . $unitName;
        }
    }

    return $str;
}
 ?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <?php $time = strtotime(render($item), 0); ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

          <time datetime=<?php print time_to_iso8601_duration($time); ?> itemprop="prepTime"><?php print render($item); ?></time>
    <?php endforeach; ?>

The Output of "prep time", when I am viewing in the "view source" on the relevant page (I don't know how to do the same for the calculated value of "total time"):

          <time datetime="PT3H45M" itemprop="prepTime">3 hours 45 min</time>

Thanks.

UPDATE 1/10/2014:
I couldn't do it without using computed fields. when I tried, I got an error: "Notice: Undefined variable: field_cooktime in include() (line 54 of D:\XXX\field--field_totaltime.tpl.php). I got the same error for preptime.
I guess that is the reason the output is always 0 sec for total time, even though I put the totaltime field after the preptime and the cooktime fields.

How can I get the value of two fields in my override template, and then Sum up?

Thanks.

One way to do this is the Computed Field module, which will allow you to use PHP to perform calculations.

To use this, you could add a field, Total time, of type Computed Field.  Then you could write some PHP code to calculate the value for Total time based on the other two fields.  This way, every time the node is updated, the correct calculation value will be saved in the Total Time field.

If you need to customize the display output, the Computed Field module allows you to optionally add PHP code to output the field for display with custom formatting as well.

But

Please note the warning on the module's page:

  This module is intended to be used by PHP developers to insert &
  execute PHP code on a Drupal website. It does not provide a macro
  interface, a code builder or anything other than insert your working
  code here into this text area. You need to have a good working
  knowledge of PHP and the Drupal API to use this module. To get the
  best results with this module, pre-test your PHP code in the Body
  field of a Page in Drupal.


Obfuscating email addresses displayed by Views? I'm working on a View that displays a user's email field as a mailto. Given this is a recipe for spam, I'm wanting some way of obfuscating it.

I thought I'd go with Invisimail, but it (and seemingly ever other similar project) relies on a text filter. Given that the User email field doesn't use input formats, this makes it useless for my particular application.

I suppose I could create a separate email field, but I'd really like to not have to.

In short -- How do I obfuscate a user email field displayed via Views?

Thanks!

Spamspan module will help you. It can obfuscate email addresses from email fields along with emails provided inline in text.

For email field - chooses Spamspan formatter in display settings.


Get argument from current URL in twig to generate a link with that argument I'm trying to get an argument from search page URL so that I can pass that argument to a link.
For example I have this URL for a search results page:
http://domain.com/site-search?search_api_fulltext=foo
And on that page I want to have a link that goes to:
http://domain.com/other-search?search_api_fulltext=foo

I've tried {{ url('<current>') }} but that only returns the domain and path, but not the arguments. I've been trying stuff like {{ app.request.requestUri }} but that returns nothing.

FWIW, I'm trying to include these links in a custom block that appears on the search results page.

well if you are making a custom block then you are probably doing something like this ....

 $build = [];
 $build['#theme'] = 'your_template',
 return $build;

and then in you hook_theme().

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
    ],
  ];
 }

you don't need to pre prossess the block at all just make sure the block is not being cached aka add this to your block plugin.

see How to prevent a block from being cached?

public function getCacheMaxAge() {
  return 0;
}

then in your block function :

 $search_query = \Drupal::request()->get('search_api_fulltext');
 $build = [];
 $build['#theme'] = 'your_template',
 $build['#search_query'] =  $search_query,
 return $build;
....

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
     'variables' => [
       'search_query' => NULL,
     ],
    ],
  ];
 }

then in your twig template

{% if search_query %}
  do what you want here {{search_query}}
{% endif%}


How can I download a distribution? Am I right in thinking that the Drupal distributions that I can download from http://drupal.org/project/distributions are a standard Drupal core download with a load of other stuff added at /profiles?

Anyone know if there are any plans to create a dev branch of distributions that would automatically update the core version that the distribution is running on? Currently it seems that the distribution runs on whatever core version its developer has chosen.

And how can I use distributions with Drush? Is there an equivalent to drush dl drupal that will download a specific distribution?

And, finally, is there any difference between an install profile and a distribution?

A distribution is a collection of Drupal modules configured to perform a certain function.  An installation profile is a script that will configure Drupal at install time.  A distribution always has an installation profile in it, but not every installation profile will be a distribution.  An installation profile can be distributed without the modules it uses; in that instance, you can use drush make to download them, as installation profiles include a make file.

Drush dl will download distributions as well as Drupal core and contrib modules (e.g. drush dl commerce_kickstart).  Distributions are updated whenever the developer chooses to update them; of course, you can always run drush pm-update on your copy of your distribution, but there are testing concerns -- occasionally, updates will break things.  This is no different with distributions than your own Drupal install, but in the case of a distribution, presumably the dev will test and fix problems before rolling out an updated release.


Restrict administrator users from seeing blocks I am using Drupal 6. I placed a JavaScript snippet in a block required by a third-party chat service I have on site.
Now, this block is by default displayed on my administrative pages, which is annoying. Is it possible to restrict the admin role from seeing this block?

I tried this kind of snippet but it doesn't work.

global $user;
if (($user->role) == 'anonymous') {
  return TRUE;
}
else {
  return FALSE;
}

?>

If you don't want the block displayed on admin PAGES, eg, www.yourhost.com/admin/HERE, you can go into the block admin pages and restrict the block to be displayed on all pages EXCEPT admin/*.

However, if you don't want your "root" or "superuser" to see the blocks on any page, you can do what @BetaRide has suggested above in the PHP area of the admin page.

In the same vein, if you don't want anyone with an admin role to see the block, you can do something like this:

global $user;
if ($user->uid==1 || in_array('admin users', array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

Of course, here you have to make sure you have a role called admin users so that might be different on your system.

If you don't want to add a role, you could use permissions and do it like this:

if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

which would display the block only to those users who could NOT access the admin pages.


Query on custom drupal 7 field I'm facing problem in Drupal query for order by custom field
Here is my query

$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype', array(':ntype' => 'portfolio'));

this work fine but when I change that to this

$result = db_query('SELECT n.nid FROM {node} n WHERE n.type = :ntype order by n.field_weight DESC', array(':ntype' => 'portfolio'));

That query not working. It saying field not found?

Try something like (supposing "weight" module is used and weights are stored in the "weight_weights" table - to be adapted for another module ) :

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'type'));
$query->join('weight_weights', 'w', 'n.nid = w.entity_id');//join can not be chained
$query->condition('n.type', 'portfolio', '=');
$query ->orderBy('w.weight', 'ASC');


Deploying Drupal 7 with read-only DocumentRoot, especially concerning image handling I'm deploying a Drupal 7 application in an environment where the web server's DocumentRoot is mounted read-only (so Drupals root directories and all directories below are not writable). For storing files a separate directory outside of DocumentRoot is provided which is mounted read/write. This directory is accessible from a separate web server instance (which only serves static files without executing PHP code, e.g. static.example.com).

What I did:

setting file_public_path to said writabke directory
implementing hook_file_url_alter to modify URIs in the public scheme to point to the separate web server instance

Everything seems to work fine (CSS, ...), except for delivering images. Drupal's concept for delivering images is whenever a requested image resolution isn't found on disk, the thumbnailing mechanism is invoked instead. The thumbnailer creates a new image, which is delivered to the requesting browser and stored below sites/default/files. Subsequent requests deliver the image directly from the disk (using Apache's rewrite rules, so PHP isn't involved any more).

Since we are using varnish in front of the web server, I'd prefer a different way of handling images:

images are served from a different virtual host (e.g. image.example.com)
thumbnailed images are never written to disk
instead a Cache-Control header is sent using a reasonable long max-age value, so varnish's LRU expiration mechanism can keep the often used images in memory and discard unused images

Any ideas how to accomplish this?

When an generated image is not available, the page callback is image_style_deliver(). This callback first generate the image (after some access and concurrency checks) and then stream the file as response (through the file_transfer() function).

Using hook_menu_alter(), you can override the image generation callback to redirect to the static domain once the image has been generated. Ensuring the generated files are always served from the static domain. On the static server, you can add a rewrite rule to redirect request for a not yet generated image to the non-static domain. Ensuring the files are generated, even when requested from the static domain. Because of the redirections, Varnish should be able to cache the files as soon as they have been generated.

Edit: Not creating the image derivatives as files on disk does not seems to be an option. Drupal uses its Image Toolkits wrapper API (GD and ImageMagik are usually used a backend) to generate the image and this API does not seems to offer a way to generate images in memory. If you really want/need to remove the generated files, you can do it in a cron job using image_style_flush() via hook_cron().


On a multilingual website using i18n, should I set the built-in Drupal English or my custom English as the default source language for strings? I have a multilingual website with five languages.  Because I wanted to extensively customize Drupal's built-in English, I also created a custom language, "U.S. English."  I then disabled the built-in Drupal English; the site now uses my custom U.S. English as the default language.

However, I'm confused about which language I should select to be the "Source language" for string translations on the i18n module's admin/config/regional/i18n/strings page.  Should I select my custom "U.S. English" or the built-in Drupal English?  How does the default language affect string translations?

EDIT: Please note that I am asking about the i18n module's "Source language" for string translations, not the site's default language.  Clearly, I need to set the default language of the site on admin/config/regional/language to my custom U.S. English; if I do not, users of the site will not see it.  The "Source language" for string translations (at admin/config/regional/i18n/strings) is separate from the default language, and I don't understand whether I should set it to my custom language or the Drupal default.

I18N is a beast of a module. I will try to answer this but have no I18N setup on hand, so this is from memory.

As you have probably realised, depending on how things are configured the default language is normally used as fallback when translations are not available. So, keeping this in mind, you would use your U.S English to translate/modify the entries you want, and set it as default. Source language would be set to the original English.

It used to be one would need to export and re-import translations but that is not the case anymore.

There is a warning to heed, ripped from http://drupal.org/node/1279668 (good reference on your topic btw):

  In contrast to Drupal's standard localization system, which always
  translates from English, strings will be translated from the source
  language. By default the source language is the site's default
  language, so changing the default language could break these
  translations. You can set which language is used as the source
  language via Administration > Configuration > Regional and language >
  Multilingual settings > Strings.

As this message states clearly things may break along the way, backing up your data is very important while you are tweaking this.

Another great link for I18N information that has cleared many things up for my multilingual projects: http://hojtsy.hu/multilingual-drupal7

PS:  Much better and simplified I18N support is upcoming in D8, *YEAH! *

Good-luck!


Complex sorting Views Our Drupal 7 site has a feed of events which are parsed into nodes. Not every event is equally relevant, and they would like a way to selecrt the top five events, sorted chronologically, to appear on a block on the frontpage. They would also like the events to no longer display in the block once the event has passed. They are comfortable using Nodequeues and have requested one be created for this functionality. So far, this is pretty basic stuff and I have created a View which accomplishes this. The tricky part happens when there are less than five upcoming events in the queue. In this case, they would like unselected events to fill out any vacancies in the block of five.

Typically when I create a Nodequeue:

I create a relationship to the queue
I sort by position in the queue
I filter that the event is in the queue.

By removing the sort and filter, and instead sort first by if event is in queue and then by event date, I get the content I desire; when more than five events are selected, it works fine. When no events are selected, it works fine, however when there is a mix; naturally the in queue events are listed first. I would like all five events to be sorted chronologically.

An aside, I'm not certain Nodequeue is even the best way to do this; as the position in the queue implies a hierarchy. A flag could mark selected nodes, or a boolean field on the content type, or a taxonomy term might each be better solutions. I'm open to suggestions.

But first, how can I best properly sort this list?

I suggest you to make use of the following hook:

function YOURCUSTOMMODULENAME_views_post_execute(&$view){

    switch ($view->name){

 case "YOURVIEWMACHINENAME";

    // Get the result of the view in a array
    $data = $view->result;

    // your custom code to add / remove instances after the view was executed

    // Set the result of the custom code back into the view
    $view->result = $data;
    break;

  }
}

Your custom code would be something like
If there are less then 5 elements and more then 1 elements in the data array add new elements to the data array coming from another view.

To execute a view in code u can use something like this:

  $reflang = views_get_view("NAMOFYOURMACHINENAMEVIEW");
  $reflang->set_display("NAMEOFYOURDISPLAY");
  $reflang->set_arguments(ARGUMENTSFORTHEVIEW);
  $reflang->pre_execute();
  $reflang->execute();

  foreach ($reflang->result as $row => $rowinfo) {
    // add this to the data array
  }

Hopefully this helps you to solve the problem.


Grouped gallery content with Views I have an gallery content type with a title-, image-, and text select list field. This content type is used for a gallery where the select list values works as a kind of category for the gallery(a bit like a taxonomy). Using Views I have gotten all the published values printed out group according to there select list values. However I would like to print out an headline above each of the grouped images. Like this:

headline1

item1, item2, item3...

headline2

item4, item5, item6...

The headline is one of the values from the select list field and the grouped items below is the content where this specific value is chosen from the select list field(during upload). Its easy to get stuff printed out and sorted using Views but it seems to be more difficult to get and headline in there.

Anyone know if this is possible, maybe using preprocess for views or views-view.tpl.php files? I have gotten this to work with the grouping feature for table layout, but would like to have it printed out in unformatted html instead.

This should already be happening. Which version of Views?

If, as you said, the headlines ARE the values of the select list, then they should be showing up above each group automatically.

In Views 3:
Under Fields, add the select_list_field and check "Exclude from display"
Under Style settings (unformatted), choose Grouping Field: select_list_field

It will group by the select list item, and display that select list item's name (ie, the headline) above the group.


Different front page for anonymous users and authenticated users I have an app in Drupalgap. I would like to display a different frontpage for anonymous users and authenticated users, for example /dashboard for the first and /user_listing for the last.

I have read "Display Different Text for Anonymous and Authenticated Users", but it is not the same scenario. (/user_listing has ['access user profiles'] as access_arguments.)

I also have tried with drupalgap_goto() without succeed.

How can it be done?

You can achieve this using Context Reaction: Front page module, which extends the great Context module.

Create a new context and:

Add a condition for User role
Add a reaction Front page putting the path for the roles you want to affect.

Save the context and all should be done.


Create custom meta tag with the metatag module Just this. I need to create some metatag using the metatag module: https://www.drupal.org/project/metatag

Something like:

<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />

I can't see how to get this in its setting.

Then after I will need to use these metatags in nodes and views.

You can either use Custom Meta module or roll your own module:

From Custom Meta project page:

  The module allows you to define and manage custom meta tags. Simply
  select the Meta attribute (property, name, http-equiv) and set the
  value and content value in the format and the module will add your
  meta tags to all non-admin content for your site.

An example of writing your own module:

my_metatag.info

name = My Metatags
description = Provides my custom Metatags.
core = 7.x
version = 7.x-1.x
dependencies[] = metatag
files[] = my_metatags.metatag.inc

my_metatag.module

<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_metatags_ctools_plugin_api($owner, $api) {
  if ($owner == 'metatag' && $api == 'metatag') {
    return array('version' => 1);
  }
}

my_metatag.metatag.inc

<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

//
// Implements hook_metatag_config_default_alter().
//
function my_metatags_metatag_config_default_alter(array &$configs) {
  foreach ($configs as &$config) {
    switch ($config->instance) {
      case 'global':
        $config->config += array();
        break;

      case 'global:frontpage':
        $config->config += array();
        break;

      case 'node':
        $config->config += array(
          'my_custom_metatag' => array('value' => 'This is a default value.'),
        );
        break;

      case 'taxonomy_term':
        $config->config += array();
        break;

      case 'user':
        $config->config += array( );
        break;
    }
  }
}

Hope that helps.


drupal contextual filter (URL argument) OR operator So, I have a view which filters content from 3 different content types: Books, photos and articles and outputs in the same view.

All three content types have an independent "issue number" field. The view basically filters content based on the issue number. Now in order to create views for each issue, I was individually creating views for each issue. In order to pull content from multiple content types, the OR operator in the filter menu came in handy. The OR relationship is as follows (Let's take Issue 5.1 as an example) in the second group:

Content published = yes
AND
2.Content type is one of Article,books,photos

AND

field_books_issue_number = 5.1
OR
field_photos_issue_number = 5.1
OR
field_articles_issue_number = 5.1

Now, this works perfectly fine, with the only downside that I had to create a view for each issue.

Now, I want to pass the issue number as a URL argument, so that I don't have to create a view for each issue. It would rather be a wildcard path such as: /issue/% and the wildcard value would take the value from the URL (using contextual filter). To do this, I changed the filters to:

Content published = yes
AND
2.Content type is one of Article,books,photos

AND

field_books_issue_number = Not empty
OR
field_photos_issue_number = Not empty
OR
field_articles_issue_number = Not empty

and added the following contextual filter:

field_books_issue_number = Value from URL
field_photos_issue_number = Value from URL
field_articles_issue_number = Value from URL

But as we know, contextual filters have a default AND relationship, which means that only the first condition will satisfy, since the other 2 fields in the contextual filter are from different content types and the other two conditions will automatically fail for every content being filtered.

Now, my question is this:
1. Can different content types share a common field?
2. If not, can the normal filter take values from the URL?
3. If not, can we add an OR operator to the contextual filters?
4. If not, is there an easier way to do what I'm trying to do without having to create an individual view for each issue?

Hope the question is clear. Thanks in advance.

Kaushik

Can different content types share a common field?

In drupal 7 (maybe also in drupal 6) yes you can.
When you add a new field to your content type, you've the possibility to add a field that already exist: "Add existing field".

Then filtering on the field should work for any content type using it.

Basically, I would add to the three content types Books, Photos and Article the same field "field_issue_number".

I think that will make your life easier :)


Commerce 1 or Commerce 2? I am not a developer although I have been using Drupal since it came out 19 years ago.

I have an existing D7 Ubercart site that works well, but I want to move to Drupal Commerce.

I have installed Drupal 8 Commerce 1 at one site, and Drupal 8 Commerce 2 (commerce 8.x-2.16) at a second site.

I know that Commerce 2 requires composer, but at the moment I have set up the Commerce 2 site with the above module (commerce 8.x-2.16) with Ludwig and it seems to function just fine.

Here is my question:

Would it be advisable to start my new site with Commerce 1 or Commerce 2?

Commerce 1 is stable, and I am thinking that perhaps I should start there and eventually migrate to a stable version of Commerce 2.

Thank you for any insights or advice.

As @No Sssweat points out in a comment on your original post, there is no Commerce 1 for Drupal 8, so if you're upgrading your site to Drupal 8, Commerce 2 is your only option.

But even if that weren't the case, Commerce 2 is stable and it's where all the current improvements in Commerce are happening. While Commerce 1 may have a larger contrib ecosystem at present, I find that once developer energy has moved on to the latest version of Drupal, it's frustrating to try and solve contrib problems on the old version. So my advice is always to go with the more recent version, once contrib has progressed enough that they key functionality you need has been developed and is reasonably stable. I believe Commerce 2 is there.

Finally, the migration process is kind of a bear (especially if you're migrating historical order data), so personally I'd only want to do that once, D7 Ubercart directly to D8 Commerce 2, rather than the two step process of D7 UC -> D7 Commerce 1 -> D8 Commerce 2. I think you'd be creating a lot of extra work for yourself without much benefit.


Drupal 7 AJAX disables my callback I have JavaScript attached to an element in a form that sends it's new value to a PHP callback function. The callback function queries the database and then returns a value that JavaScript then puts in a text box as its value.

I have experimented, and found that callbacks do not work on node edit forms. I assume it has something to do with the new AJAX functionality built into forms.

How to get around this problem?

According to the code example that you posted, you are using a relative path in your AJAX request. Maybe you should try anchoring your request to the base path by using /objnum_callback instead of just objnum_callback. This will ensure that your request is pointing to the same place regardless of the current page.


Create a faceted search like eRecruiter without solr? I am in need to create a search results page & filter like the eRecruiter demo page: http://drupaljobs.epiqo.com/search/job

The filter on the right hand side shows the amount of results for specific tags or taxonomy terms, clicking enables that filter, updates the number of results for each filter etc ..

I am using D7 and views3

I do not have apache solr on my server and I wonder if it is possible to create the filters (in my case by taxonomy terms attached to the nodes of a specific type) like they are in this example using mysql and search api?

So far I have used exposed filters in views, but I really need the amount of results for each term behind it.

I have tried something along these lines:

Add new view
Show -> taxonomy terms
Continue
Relationships -> Taxonomy term: Content with term
Use aggregation:Yes
Taxonomy term: Name -> Group results together
Add field -> Content: Nid
Aggregation -> Count DISTINCT
Make your own style for Content: Nid field (Set prefix to "(" and suffix to ")" to get
the count between brackets)

but without getting the right results.

Is this possible at all?

Thank you all in advance!

You can also use the Facet API module. It allows site builders to easily create and manage faceted search interfaces. Facet API works with the core Search and Search API.


Rewrite markup of a field in twig template I want to calculate dynamical a value and give it back in the markup without saving the newValue. I try this with:

 {% set content.field_my_field[0]['#markup'] = newValue %}

This doesn`t work!
The "newValue" is given from preprocess_node in the .theme file.
Should I rewrite this directly in the preprocess function? How?

Found a solution in preprocess_node. I tried to manipulate $variables['node'] instead of $variables['content']

function mytheme_preprocess_node(&$variables) {
    $variables['content']['field_my_field'][0]['#markup'] = $newValue;
}

Sorry I couldn't be more verbose earlier, I was typing from a phone.

One way to solve this would be to just create a new template variable. Also, its easier to use the field value instead of parsing the render array - the contents of that array could change without warning. Not saying it happens a lot, but is possible. Just access the field value directly in one of two ways:

$field_value = $node->get('field_name')->value;

or

$field_value = $node->get('field_name')->getValue();

Note that not all fields will work that way, but most basic ones like text or textlong do. Reference fields for example will work a little differently.

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mytype') {
    if (!$node->get('field_my_field')->isEmpty()) {
      $variables['new_variable'] = $node->get('field_my_field')->value;
    }
  }
}

Then, in your node--node-type.html.twig template of your theme, where you want the field output, do:

{{ new_variable }}

Note that if you use ->getValue() above, you need to dig into that value array to get the actual value as opposed to ->value.

Always isolate the effort to the node type(s) and templates it should affect. In your question, you say you have this:

function mytheme_preprocess_node(&$variables) {
    $variables['content']['field_my_field'][0]['#markup'] = $newValue;
}

This code will fire for every node in the system any time it is loaded on that active theme. Unless that field exists on every single node type, it will cause a lot of warnings/notices in your logs. If you moved the field from visible to hidden from the admin UI, this code will fail as well, since the field will be removed from the content render array and not exist. I tend to also enforce checking both the node type and the view mode of that node being rendered too, but that is all up to what your design requirements are.


Add "Post as anonymous" checkbox to forum topic creation is it possible to add a post as anonymous checkbox to the topic creation in drupal forum?

I can also provide a user if not a string via which the content should be submitted. Basically I don't want users to need to logout but directly from their account create a disguise username or anything that would resemble this functionality.

Thanks! Jan

https://www.drupal.org/project/forum_cloakpost
This module allows registered users to post to a forum as an anonymous user, via a checkbox on the add node/comment page.


Drush db connection issues after upgrading to MAMP 4? Upgraded to MAMP 4 yesterday and cannot get Drush to connect for the life of me. I believe I had a similar problem with MAMP 3, but the following fixed the issue. No luck this time.

sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Any ideas? I have Drush installed globally with Composer. Here's the error:

    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.
The drush command 'pm-update' could not be executed.                 [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.50
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  ba_dev
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/5.5/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/ja/.composer/vendor/drush/drush
                           /drush.php
 Drush version          :  8.1.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/ja/Sites/ba/public_html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

Figured this out by adding the following to my .bash_profile file and modifying the PHP versions to match what's in MAMP. Working just fine again.

export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.4.45/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.5.38/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.6.25/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php7.0.10/bin:$PATH"

After this run:

source ~/.bash_profile