Contextual filters in taxonomy term ID (with depth) I need to make a view that will show me the nodes of a content type inside a node of another content type filtered by a taxonomy term.

I have three content types. The first one is Projects, in which I've added some projects (title, body and images-shadowbox). The second one is Projects Categories, in which I have some categories like:

houses.
offices.
etc.

The third one is Services, in which I've added the following categories:

architecture.
engineering.

I have added a "Projects" vocabulary with two items:

Project 1.
Project 2.

In each node of the "Projects" content type, I assign term of the Projects vocabulary. Each node of the "Project Categories" & "Services" can have more than one terms of the Projects vocabulary.

What I need is to preview under each "Project Categories" & "Services" node the relevant node "Project", filtered by the taxonomy term of the "Projects" vocabulary.

How can I achieve this?

This is similar to another request: Contextual filter in taxonomy- Drupal 7

I've customized my answer to your specific requirements:

First thing you need to do is install the References module

When setting up your project content type, create a category node reference field and a services node reference field. This will tie each project to one or more categories and one or more services.

When configuring your view, you will need to create relationships between the project and service/category.


How to install a module which includes a different version of Symfony? I am a developer and maintainer for the CiviCRM project. We've been trying to make a Drupal 8 version CiviCRM, and have a come a long way. We're beating our heads against our collective keyboards trying to figure a major blocker for the project.

CiviCRM has used Symfony for a while, and the version that is included is different than what ships with Drupal.

We can get CiviCRM installed with Drupal 8, but after you install it, we cannot install any other Drupal module.

I believe it boils down to a situation where somehow the CiviCRM version of Symfony loads before the Drupal version, and this causes problems.

Does anyone know of a Drupal 8 module that includes a different version of Symfony than the one that ships with Drupal?

Recently I ran across the Ludwig project. This module allows the registering of namespaces in a class that extends ServiceProviderBase.

Would it be possible for the Drupal 8 version of the CiviCRM module to include a CivicrmServiceProvider.php file, which defines a CivicrmServiceProvider class,  and a register() method that adds a container namespace to allow this to work?

Many CiviCRM files have use statements like Drupal starting with Symfony, like here.

We actually put CiviCRM Core into Drupal doc_root/libraries folder, and use the libraries module.

This is the repo for the CiviCRM Drupal module 8.x version, if somebody wants to look at what we got so far. If somebody has the magic elixir for this, I can tell you there would be many happy folks in our community. So if you know how to help us, please do.

CiviCRM does install, and the CiviCRM pages do work. What doesn't work is that after CiviCRM is installed, we can't install other modules via the admin/modules page. As far as I know that's the only thing that is broken. Also installing modules with Drush, after installing CiviCRM, does work.

Trying to install another module after CiviCRM is installed causes the following error:

  PHP Fatal error: Call to undefined method Symfony\Component\DependencyInjection\Definition::setFactory() in /var/www/html/civi-for-d8/core/lib/Drupal/Core/DependencyInjection/YamlFileLoader.php on line 206

That's in Drupal 8.3.5. Trying to install CiviCRM for Drupal 8 into a clean Drupal 8.4-dev instance causes the following error:

  Drupal\Component\Serialization\Exception\InvalidDataTypeException: The reserved indicator "@" cannot start a plain scalar; you need to quote the scalar at line 8 (near "arguments: [@string_translation, @civicrm.page_state]"). in Drupal\Component\Serialization\YamlSymfony::decode() (line 40 of /var/www/html/drupal84/core/lib/Drupal/Component/Serialization/YamlSymfony.php).

So, I think if CiviCRM were installed into Drupal 8 via composer (ie. composer require civicrm/civicrm-core in the Drupal root) and CiviCRM's use of Symfony was compatible with Symfony 2.8 or 3.x (ie. not using deprecated functionality), this could work.

This would get everything installed in Drupal's vendor directory, rather than having two, and it'd mean that CiviCRM would use the Symfony version in Drupal 8. But if CiviCRM was compatible with later Symfony versions (even if it bundled an older version for Drupal 6 & 7 and other CMS's) it should be fine.

I think?

UPDATED: Yes, it works - I tried it. :-) I originally posted the below in the CiviCRM issue queue (CRM-17652), but re-posting here for completeness.

The big idea:

Since composer is pretty new to a lot of people, I'm going to attempt to go step by step, from some high-level composer stuff all the way to one way it could be done in CiviCRM:

Composer allows applications to require the libraries it needs (and libraries, of course, can require other libraries).
Libraries have a composer.json file which says what other libraries it needs and what versions it's compatible with (but not necessarily a specific single version - usually a range of versions, like ^2.4.3 which says a minimum of 2.4.3 and up to (but not including) 3.0.0)
Applications have a composer.json which similarly describes needed libraries and compatibility with a range of versions, but the range is really to help with updating. An application will also have a composer.lock which is a specific set of individual versions
Libraries can also have a composer.lock for their own testing or distribution (like building the release tarball with the dependencies bundled), but this is ignored when an application requires the given library (see https://getcomposer.org/doc/02-libraries.md#lock-file)
When an application wants to require a new library, composer finds an intersection of version compatibility between all the things the application requires (including all the libraries already installed and their dependencies) and the new library, possibly doing some updates to make everything line up (or erroring out if it can't find a compatible mix of versions)
In this case, CiviCRM is a library, and a particular Drupal 8 site is the application (Drupal core itself is a library)
CiviCRM could say it "requires" Symfony ^2.5 in its composer.json which means it is compatible with versions 2.5.0 up to (but not including) 3.0.0
When a Drupal 8 site wants to use CiviCRM, the site admin uses composer require civicrm/civicrm-core to require the CiviCRM library and all it's dependencies. If CiviCRM is compatible with Symfony 2.8 (like used in Drupal 8.3.x) everything will install and work fine, using the single Symfony 2.8 from Drupal. All the dependencies end up in Drupal's vendor directory.
However, CiviCRM could keep Symfony 2.5 in its composer.lock, which means the tests would use that, and the tarballs for Drupal 6 & 7 and other CMS's would bundle Symfony 2.5

The proposal:

Update the composer.json of CiviCRM so it can be used as a library by composer-based CMS's like Drupal 8 (but probably others could move that way in the future - composer is getting quite popular)
Make sure CiviCRM core is compatible with Symfony 2.8 and 3.0 (used by Drupal 8.3.x and 8.4.x respectively) but keep the "officially supported" version (currently Symfony 2.5) in the composer.lock for testing and the tarball for distribution. Being compatible with multiple Symfony versions may not be as hard as it sounds - there's a number of libraries out there compatible with both Symfony 2.8 and 3.0. It may just be a matter of avoiding deprecated methods/classes/features! The composer.json will need to be updated to reflect this
Use composer to install the CiviCRM library on Drupal 8 rather than copying into the libraries directory. This is becoming the normal way of installing 3rd party PHP libraries in Drupal 8 (this is used extensively by Drupal Commerce, for example)

For composer-based CMS's, I really think this is The Right Way. While this issue is currently affecting Symfony and Drupal, as the PHP community starts using more and more 3rd party libraries via composer, this could very well affect other CMS's with other version conflicts.

Some working code to test:

So, as promised, I actually got this to work to a limited degree :-) I'm totally coming at this from a Drupal/Composer/Symfony perspective -- I don't have a ton of CiviCRM experience, so there's probably some better ways to do my process below. I welcome any advice!

Download and install Drupal 8.3.5 (or the latest dev of Drupal 8.4.x!)
Go into the root directory in the shell and run these commands to install CiviCRM via composer: https://gist.github.com/dsnopek/56311dbea347874e75180883efabb620
If you use Apache, remove the vendor/.htacess file. This is a security measure from Drupal, which prevents resources like CSS/JS being loaded. This will need some collaboration with the Drupal project to figure out a proper solution because removing this file altogether is a bad idea on production. See: vendor/.htaccess blocking CSS/JS assets from composer libraries.
Go into the /modules directory and do git clone https://github.com/dsnopek/civicrm-drupal.git --branch composer-library
Go to the "Extend" page (/admin/modules) and install the CiviCRM module
Clear drupal cache via Drush (drush cr)
Log out and log back in again per CRM-19878
CiviCRM works! :-)

After all of this, CiviCRM is using Symfony 2.8 from Drupal and the dependencies in Drupal's vendor directory, and isn't loading anything from it's own vendor directory. Huzzah!

I tested enabling the "Telephone" module which failed before these changes (see my steps to reproduce), but works fine with them. :-)


creating nodes with many to many relationship type with some fields? This is in line with How to structure a "many-to-many" relationship between nodes.

To keep things in line with the example from the linked thread, what if i was a book warehouse and i had a list of all my books but i want to allow each seller to name his own price and show that book in the seller's store view with only the price that he set?

How would I allow him to edit the info of his entry without having access to anyone else's entry? I am trying to avoid associating nodes from different content types like creating a node type seller's price and reference a book inside of it.

I thought about a combination of field collection, content access, and TAC to try to make each seller capable of entering and editing their own price field collection. While I thought that field collection would create a new collection for every user, this doesn't seem to work: All sellers end up editing the same collection.

Do you have any idea?

You are looking for the capabilities in the Relation module. With it you can relate a seller to a book, and attach a price field to the relationship.

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes
  Relation the most flexible and powerful relation model out there.
  (Still, using Relation with anything but the default SQL storage will
  not work in most cases.)


Theming multi-value fields in Views I added the field_tags to my view.

Now I want to add a the tag name as a class name, so I can colour each tag differently.

ex:

tag1

tag2

tag3

Unfortunately, unchecking display all values in same row is not an option for me since I need to limit the view to 4 results.

Therefore, somehow I need to be able to loop through them and attach each of them the tag name as a class name.

How can I achieve this?

The only work-around solution that I can think of would be to:

Create a separate view for the tags.

Then there I will be able to uncheck display all values in same row.

Re-write field to <div class="{{ field_tags }}"> {{ field_tags }} </div>

Then use View Fields View to insert the Tags view as a field in my other view and pass the nid as contextual filter.

Probably not the best solution, so if anyone has a better one I'd love to hear it.


Reverse node reference I have 2 content types:

vehicles
engines

Several engine nodes are referenced to the single vehicle.
Is there any way I can load all engines referenced to the single vehicle node if I have that vehicle node object (thus the nid as well)?

I use Node reference module.

If you need any more info, please ask.
Thanks in advance!

I found a solution to this issue by performing a query on 'field_data_field_vehicle_reference' table.

For my case, the solution can be something like this:

function engines_of_vehicle($vehicle) {
  $nid = $vehicle->nid;

  // get all engine nids referenced to this vehicle
  $engine_nids = db_query('SELECT ref.entity_id FROM {field_data_field_vehicle_reference} ref WHERE ref.field_vehicle_reference_nid  =:nid AND ref.bundle =:bundle', array(':nid' => $nid, ':bundle' => 'engine'))->fetchCol();

  //load all engines referenced to this nid
  $engines = node_load_multiple($engine_nids);

  return $engines;
}


pass argument from url to view I have a view with 5 results limit and a more link to show all nodes. The more link goes to xxx/yyy/123. Number 123 is the nid of node, that listed nodes are referencing to. On a current page, lets say- xxx/yyy/123 I would like to use another view that can print the name of node with 123 nid. I tried to set a view using default argument - node id from url and use a field with title but it seems that the number from such url it is not picked up as an argument. Can anybody give some advice? Thank you

Views generally gets node id from url when url format seems to be node/nid

For your case, select 'Raw value from URL' in Provide default value section and select path component as 3 as nid lies in 3rd url arg. Your views should be getting the desired nid now.

Hope this helps you. :)


How to limit access to vocabulary term by role? We have two roles: Reviewer and Editor along with two content types: Basic and Article. We have a couple vocabulary terms and taxonomy fields on each content type. Currently only users with Administer vocabularies and terms and Use the administration pages and help can edit those vocabulary terms, but they have access to add/edit/delete all Vocabulary terms (something we don't want).

How can we selectively allow only users with Editor role to be able to add/edit/delete any values in just the Tag vocabulary term?

Basic Content Type:

Fields:

Category (field_category) -> Taxonomy term field -> linked to Category vocabulary
Title
Description

Article Content Type:

Fields:

Article Tags (field_article_tags) -> Taxonomy term field -> linked to Tags vocabulary
Title
Description

Desired outcome:

Users with Reviewer role cannot access anything other than the nodes. (this is already done)
Users with Editor role should be able to access only the admin/structure/taxonomy/manage/tags/overview page (Tags overview page)
While on the Tags Overview page, users with Editor role should only be able to access that link and no other admin pages.
While on the Tags Overview page, users with Editor role should only be able to add/edit/delete any terms in the Tags vocabulary.

Have you tried taxonomy_access_fix? It allows you to manage permission for each vocabulary for each role.


Subtract UserPoints from all taxonomy terms upon purchase? OK So i was wondering if someone could point me in the right direction. Currently I'm running User Points Module with UberCart in order to purchase items with currency or use points for purchases. Now i've managed to get the transaction to work as needed except for one small thing. The Ubercart API only allows me to subtract the purchase points from a single category like "General". Id like to subtract the points used to buy the product from ALL the categories the use has points in. Does anybody know a way this can be done?

You have few options that depend on the number of userpoints categories and the way you want to do it (w or w/o code):

Option 1: Create separate actions for each userpoint category within Ubercart.

Option 2: Enter custom PHP code and do the following:

Load userpoints dictionary - userpoints_get_vid()
Loop through all terms in it and subtract the points.

Sample code:

$userpoints_vid = userpoints_get_vid();
$userpoints_terms = taxonomy_get_tree($userpoints_vid);
foreach ($userpoints_terms as $term) {
  // Build the params for this transaction.
  $params = array(
    'points' => -100,
    'moderate' => FALSE,
    'term_id' => $term->tid,
    'entity_id' => $order->order_id,
    'entity_type' => 'order',
  );
  // Subtract the points. This will call automatically all UP hooks.
  userpoints_userpointsapi($params);
}

Option 3: You could also create a Rules action from the code above that will accept $order as an argument. This will take slightly more time, but is the right way to do things.


Optimizing of DB resources I'm pretty excited about Drupal capabilities in general and consider it as probably the most solid free CMF with a really powerful API. One of the things I'm concerned about is the resources it takes. A basic installation with localization generates about 90 database tables (WordPress generates  11). Can this be optimized or, if it cannot be, does it really matter, does it affect performance?

Table count is not an indicator of optimization. It is actually opposite of what someone might think. Good database design breaks data up into multiple related tables that are kept small in field count. Drupal core has a very efficient relational database design compared to WordPress. I have experience with both platforms and your statement highlights what you must realize about Drupal. Drupal really is a content management framework, WordPress is a content management system. They are vastly different in their capabilities.

So to answer your question plainly, no optimization is required. It already is optimized for a relational database.

As always, choose the right tool for the project. Even though I am a Drupal developer I have recommended Wordpress to several clients. Because their needs and requirements could be satisfied with a simple Wordpress site.


How to display a block only for Admin I want a block to be visible only for Admin in Drupal 6.

To do it I've selected the third option(Show if the following PHP code returns TRUE (PHP-mode, experts only).) and entered the php code:

<?php
global $user;return $user->uid == 1;
?>

But the problem is that now this block shows only when I'm on some specific urls while logged in admin and not always when logged in admin.
What's wrong?

I don't want to use the second option (Show on only the listed pages).

One more way to check for admin rights, sure it works in Drupal 6.

if (user_access('access administration pages')) {
    // do something
}


Redirect if nothing is select in the View's jump menu In D7, I have a view that produces a jump menu. As a default label for the jump menu I display "Please select category".

At the moment if I click submit while  "Please select category" is selected, it just reloads the page. I want to be able to redirect to another page instead (only if nothing has been select in the drop down). How do I do it?

Thank you

Using hook_form_alter you override the default $options value used in ctools_jump_menu for the array key _none to whatever site url you want to redirect to.


How to print the relative url or node id for each referenced node in twig? I am using paragraphs to render a number of nodes on a page. The nodes are obtained through an entity reference field called 'field_nodeslist' in my cards paragraph type. The cards are then rendered using a custom view layout.

Here is a snippet of my view layout:

{{ content.top_region|striptags}}

{{ content.middle_region }}

The problem I am having is printing the relative path for each referenced node. I have tried the following twig commands but have not had any success so far:

The following allows me to manually specify the node id in twig however that's not what I am looking for:

Any ideas?

Notes/Thoughts: In my first code snippet, the fields in 'top_region' just contains the nodes title. There was an option to link the field to content however I had to add the '|striptag' filter in twig due to additional markup messing up the style. Is it possible to grab the url path from the node title?

You probably need to work more in UI to configure what is in {{ content }} and then render the fields as they are.

If still necessary you can use {{ node }} respectively {{ paragraph }} to access all field values, see How to retrieve value of hidden field in twig?, but you can't access the url directly. You have to build this with the help of the raw database value target id, see How to print the URL path of a referenced node using paragraphs?.

BTW the result is the same as the entity method toUrl() would provide, only that this method is blocked by the twig sandbox policies. As a third (least favourable) option you can change this, too, see https://stackoverflow.com/questions/40091324/allow-new-methods-in-sandbox-policy-in-twig-drupal-8


Drupal 7 - Giving correct path to callback function in #autocomplete_path I have this below code for autocomplete implementation but I just get AJAX error

As you can see there is not anymore details for tracking down the issue. I also checked the logs but seems like this particular error is not logged anywhere which is making me hard to debug. However I suspect (almost confirmed) there is a strong relation between menu path (tdyards/tdyards_searchbox), autocomplete_path (tdyards/tdyards_searchbox/autocomplete_callback)and callback function name (tdyards_searchbox_autocomplete_callback)

Please help me to understand and correct this

Below is the complete code of my module which is sub-module of tdyards

function tdyards_searchbox_menu(){

  $items['tdyards/tdyards_searchbox'] = array(
    'title' => 'Autocomplete (simple)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('autocomplete_form'),
    'access arguments' => array('access user profiles'),
    );

  return $items;

}
function autocomplete_form($form, &$form_state) {

  //dpm(cities_autocomplete_callback("A"));
  $form['info'] = array(
    '#markup' => '<div>' . t("This example does a simplest possible autocomplete by username. You'll need a few users on your system for it to make sense.") . '</div>',
  );

  $form['user'] = array(
    '#type' => 'textfield',
    '#title' => t('Choose a user (or a people, depending on your usage preference)'),
    '#autocomplete_path' => 'tdyards/tdyards_searchbox/autocomplete_callback',
  );

  return $form;
}

function tdyards_searchbox_autocomplete_callback($string = "") {

  return drupal_json_output(drupal_map_assoc(array('Data','Theta','Quota','Meta')));

}

You've just forgotten to define the path for the autocomplete itself:

function tdyards_searchbox_menu(){

  $items['tdyards/tdyards_searchbox'] = array(
    'title' => 'Autocomplete (simple)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('autocomplete_form'),
    'access arguments' => array('access user profiles'),
    );

  $items['tdyards/tdyards_searchbox/autocomplete'] = array(
    'title' => 'Autocomplete',
    'page callback' => 'tdyards_searchbox_autocomplete_callback',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

Add that, clear the caches, and it should work.


How to create a map like the one used on the drupal.org homepage? I want to know how to create an interactive map like the one used on the home page of drupal.org.
Thank you very much

Perhaps this is useful: How the Drupal.org home page map works

This is the actual module: HTML5 user geolocation


Independent search box for views taxonomy page I'm using the "taxonomy term" view.

I would like to have a search form box independent of this page, which I will place for example in my navbar, allowing me to search among the terms of taxonomy, with autocompletion, and thus leading to the page of the corresponding term.

For example:

I have as taxonomy terms: tag1, tag2, tag3.

I'm on my home page, I type in the search form "tag2", I arrive on the page "tag2" with all the nodes having the tag "tag2", sort according to the criteria of the view.

I tried to create a separate block with views, but I do not get results.

I also tried to add a block to the "taxonomy term" view, but that does not work either.

Do you know how to do it ?

You can achieve this in Drupal 7 and 8 using a mixture of modules such as:

Search API

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc. Also,
  with the Apache Solr integration, a high-performance search engine is
  available for this module.

Then you can use: Search API Autocomplete to accomplish the auto complete functionality you require

  The Search API Autocomplete module in action. This module provides
  autocomplete functionality for Search API searches.

And all of this is managed and is customizable via Views module and having a Search API Server that indexes what you want (Here are taxonomy terms for your case)

If you want to make it easier setting things up you can try Search API Pages

  This module is for creating simple search pages for the Search
  API project, not using Views or any other modules. They can be used
  when a view would be unnecessarily slow or complex, or for quickly
  testing out functionality. They also provide search blocks for
  starting a search from anywhere on the site.


Instructive message when a module is disabled accidentally Site breaks without a warning when code of a non-enabled module is called.
(In my project I disabled accidentally a module, while the code is executed by another module.)

The correct way is to add dependencies, but sometimes that is forgotten (and rather old-fashioned). PHP Storm does not check whether a module is active or not; it just validates the call.

Is there a way to get a message when code of a non-enabled module is called?

Absolutely. In the module that calls the function, use one of the following

Drupal 7:

if (module_exists('foo')) {
  // Use a function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

Drupal 8:

$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('foo')){
  // Use function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

If your code runs in a context that can use DI, inject the module handler service rather than getting it from \Drupal.

You're right, though, dependencies should be used and then this extra wrapping code isn't necessary.

Dependency management is definitely not "old fashioned", by any stretch of the imagination; not in Drupal, and not in the greater world of programming/frameworks. It's a thriving, constantly-improving area of work.

I'm not sure where you got that idea from, but if that's what's stopping you using the proper methods to solve your problem, you should probably think about reevaluating your opinion, as (and no offence meant by this), it's quite frankly just wrong at the moment.


Where to input hook_element_info_alter() to remove format description in date_popup form field? I want to remove format description in date_popup form field (code posted here). The solution requires me to implement hook_element_info_alter() to add a process function to the element.

I found the code I was looking for, but being a novice, I don't know where to input it?

Could someone please guide me?

I have Drupal 7.53 with Date Module Version: 7.x-2.9 installed

Thanks

You need to create a custom module.

You can follow this guide to creating your first module.

However you won't need any form code... just your element info alter, and process function. After enabling and clearing cache, you should see the desired behavior you are after.


How to print fields manually I am using print module. I am also using devel module. In print.tpl.php file, I see a php code that prints the content as print $content. I don't want to print the entire content. I think content is an array. How can I print manually some fields from the content variable using the devel module or in php?

Thanks.
D

1.

  print render($content['field_machine_name']);

Get this error:
 Fatal error: Only variables can be passed by reference in /..sites/all/modules/print/print.tpl.php on line 100

  php  print $content['field_machine_name'];

I get left error only (<)

3.

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

I get completely blank

I am using bartik 7.22.

themes > bartik > template.php

Added the below function.

function bartik_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['test'] = field_view_value('node', $node, 'field_price', $node->field_price[$node->language][0]);

}

themes > bartik > template > print.tpl.php

I added:
print render($test);

I went to my page
http://bettylist.com/ac/node/12 > clicked printer friendly link >
I did not see the value of variable.

In print.tpl.php, what works:

print $content; //I GET CONTENT IN PRINT PAGE
print dsm($title); // I GET VALUE OF TITLE IN PRINT PAGE

Please advise.
Thanks,
D

It worked. I have added one more variable as below:

function bartik_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['price'] = field_view_value('node', $node, 'field_price', $node->field_price[$node->language][0]);

// Create a var and render using field_view_value
$vars['vehicleOption1'] = field_view_value('node', $node, 'field_vehicle_option_1', $node->field_vehicle_option_1[$node->language][0]);

}

In print.tpl.php, I added

print render($test);
print render($vehicleOption1);

But I am only getting the value of the last variable $vars'vehicleOption1'.

Please advise.

Try with this:

<?php print render($content['your_field_name']); ?>

This should print the field you want.

Change 'your_field_name' with machine name of the desired field.

You can install and enable Devel module and add this:

<?php dsm($node); ?>
<?php dsm($content); ?>

in your print.tpl.php file. You will see all $node and content fields.

UPDATE

Also, you can add this function in your template.php file:

/**
  * Renders the content of the print page using the theme api.
  */
function THEME_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['any_variable'] = field_view_value('node', $node, 'your_field_name', $node->your_field_name[$node->language][0]);

}

Replace THEME with your theme name, any_variable with any name you want for this variable and your_field_name with machine name of your field.

After this you can render your field in print.tpl.php file like this:

<?php print render($any_variable); ?>

Again, change any_variable with the name you choose for this variable in function from template.php file.


Headers already sent I found this error repeated several times for two of the pages on my website.
    Warning: Cannot modify header information - headers already sent by (output started at
/home/customer/www/mydomain.com/public_html/includes/common.inc:2800) in user_cookie_save() (line 4041 of
/home/customer/www/mydomain.com/public_html/modules/user/user.module).

I checked a bit around and found other similar errors with "Headers already sent" but none of them on the user_cookie_save function.
How can I debug fix it?
I'm running on Drupal 7.78, PHP 7.3.2.7 and as modules that could influence the cookies, I'm running just the EU Cookie compliance module.
What I find strange, is that I do not recall having seen this error before. There is a small chance that the error was there ad I did not see it because the logs are filled with page not found, and access denied errors by nice persons from the internet :) I would say though that that is a small chance as I've checked many times the logs in the past and did not see this error.
I have no idea what changed, and also no idea of what is the impact of this error, it's a warning, but I can't reproduce it.
Many thanks

HTML requests return headers, that tell what the response will be, and the body, that is the response. The headers are required by browsers to understand how to interpret the data that is in the body, therefore no output must be sent before the headers. This error is outputted when headers are sent after some body output has been sent. When working on a Drupal system, there are three common causes to this error that you can debug:

An echo statement in a module/theme (and not in a template). Sometimes developers will echo out a value for debugging purposes, and forget to remove that line.

Blank space before the opening <?php tag in a document on the system. This is usually in a custom module or theme, or can be in settings.php, or settings.local.php.

A closing `?>' tag, with whitespace after it. Drupal coding standards are to not use the closing php tag, so if you find this anywhere outside of a template, you can probably remove the closing tag. At the very least, you should ensure there is NO whitespace after the tag.


How to get price to update when changing attrubutes within a View I have a view and have a relationship so I can display the product price. When I change an attribute option, the price field doesnt dynamically change.

I think I will have to do something with the style settings and change to DIV, check create a CSS class and add a tokenized CSS class so it will change when the product id changes? but i cant get it to work.

What I've done so far:

Add relationship Content: Referenced products
I have 3 fields: 1.
content nid (excluded from display) 2. product add to cart form. 3.
commerce product price field.

At this point i can display the price but it doesnt update when i select various attribute options

Style Settings, Customize field HTML --> DIV --> Create a CSS class

I think under the create a CSS class i need to print a CSS class with a product id token or something like that, but cant find the correct token or CSS valule.

Found it:

you must add a content: NID field and exclude from display to get the token of [nid] available
Then under style settings of the price field, select 'customize field HTML'
HTML element = DIV
Select Create a CSS class
the CSS class for Price is: node-[nid]-product-commerce-price

The NID token will update when a certain attribute changes. This can also be applied to other fields as well finding the CSS with firebug and then adding in the [nid] token


Toolbar broken, permission errors after permission changes After performing the most recent core update, which required me to temporarily disable layout builder, my admin toolbar somehow became grey and unformatted as shown below. I've tried changing the admin theme, rebuilding the cache, disabling CSS, etc. but to no avail.

After updating, I ran the security check, which gave some apparently very bad advice about changing permissions of hundreds of files to 744. I followed the advice, which totally broke the site. After reading the various guidance on permissions, I restored permissions to the best recommended ones I could, find but there are still permission errors occurring in the logs, which may or may not be related to this issue.

13498   11/Jun 17:49   file   Error      The specified file 'temporary://fileiFPN8R' could not be copied because the destination directory is not properly configured. This may be caused by a problem with file or directory permiss
13497   11/Jun 17:49   file   Error      The file permissions could not be set on public://css.
13496   11/Jun 17:49   php    Warning    User warning: mkdir(): Permission Denied in Drupal\Component\PhpStorage\FileStorage->createDirectory() (line 145 of /home/public/core/lib/Drupal/Component/PhpStorage/FileStorage.php) #0 /h

What other troubleshooting steps can I perform short of attempting to restore a backup pre-update?

Issue was from the instructions at the top of the page of this top-ranked search result for Drupal permissions.

I did chmod -R 664 files for the files directory, which apparently wasn't sufficient to change all file permissions. Issue persisted until changing permissions it via find files -type f -exec chmod 664 {} \; as described here.


Separate permissions for form access and form submit I have a module on a website, called members, and 2 roles: "low admin" and "manager". They have permissions: 'low admin tasks' and 'manager tasks'. Every low admin has access to both permissions.

There is an edit member form. Manager must be able to view the data, but not be able to update. Low admin can do both operation. Here is the code:

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

       //members_edit calls members_edit_form
       $items['members/edit'] = array(
           'page callback'    => 'members_edit',
           'access arguments' => array('manager task'),
           'type' => MENU_CALLBACK,
           );

       return $items;
}

function members_edit_form($form, &$form_state, $data_array = NULL)
{
    //here I prepare the fields
    ...

    //submit button is shown only for the low admin
    if (user_access('low admin tasks'))
    {
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            );
    }

}

function members_edit_form_submit($form, &$form_state)
{
    if (user_access('low admin tasks'))
    {
        //save to the database
    }
}

Is it possible to remove the condition from members_edit_form_submit and set somewhere (maybe in members_menu), that only users with 'low admin tasks' privilege can call members_edit_form_submit?

It's an odd use-case where certain roles can view the form itself, but not submit it. Perhaps better to allow non-privileged users to view the rendered form output instead of the input form.

That way, you can put the access check on the menu callback for the form itself.

Anyway, have you considered putting the access check into the form validate function?

e.g

function members_edit_form_validate($form, &$form_state)
{
  if (!user_access('low admin tasks'))
  {
    form_set_error('submit', t('Sorry, you do not have access to update this form'));
  }
}


Customising Search Box in Search Results Adding OnBlur and OnFocus Attributes I am trying to add custom #attributes to the search_form in the search results page. I get the $form_id from devel which is $form_id = "search_form".

Here is my hook_form_alter() implementation:

function nm_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'search_form' ){
    $form['search-form']['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['search-form']['#value']."';}";
    $form['search-form']['#attributes']['onfocus'] = "if (this.value == '".$form['search-form']['#value']."') {this.value = '';}";
  }
}

I checked if the condition is right inside the if statement with the following code, but nothing happened.

dpm($form['search-form'])

So, I am suspecting that the if condition is right.

If you want to add attributes to the form itself you need to do it on the $form array:

$form['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['search-form']['#value']."';}";

I'm just guessing but I think you're expecting there to be a search-form element because that's the CSS ID of the form? That's not quite how it works with the FAPI, the elements are in a hierarchy that will eventually be rendered down to HTML. Until that rendering happens the elements have no concept of an ID/class etc., so you won't find them in the array under the ID/class.


how to add one form element into another form? I have a webform. And I want to add some fields of user registration form to the webform because I also want to add the facility of registration on webform submission. So I want to add those fields of user registration form which are required to the webform.

Any help?

Probably you should do it programatically.

Use hook_form_alter to modify form A, load data of form B by drupal_retrieve_form inside this function and get fields from form B data which you want to add them to form A


Email Attachment File Path I am using Drupal 7 with the WebForm and MIME Mail modules.

I've got webform attachments being sent in the email working fine. However the email also contains a path to view the email in a directory on the server. Currently, it's set to /sites/default/files/webform/sites/default/files/webform/ /.

How can I change the directory where WebForm submissions are stored?

As far as I know they've got to stay within /sites/default/files/webform/ folder as /sites/default/files is the only folder that should be both writable and publically accessible

If you edit the file component you added to your webform you can then specify a folder within /sites/default/files/webform/ that you'd like them to be stored specifically for that form. Look for the "upload directory" field.


Is it possible to hide menu items based on path? I am looking to hide a menu item based on the path of a couples pages. It would be similar to how blocks can be shown on or not shown on a path. My initial attempts revealed that the caching of menus does not permit one to have the ability to remove menu items per page load.

hook_menu_alter() only runs once after a cache clear and then the menu is retrieved from the cache. Does anyone have any ideas on how to accomplish this or is it a futile attempt?

Thanks.

Yes you can by using an access callback which when defined calls a function. In this function you can analyze the path and based on that return TRUE or FALSE. When you return FALSE, the menu item is not visible. See the documentation of hook_menu for more details.

A simple example:

// in hook_menu something like this, important part is the 'access callback'
 $items["menu/item"] = array(
     'title' => "menu item 1",
     'description' => 'Access test',
     'page callback' => 'node/1',
     'access callback' => 'check_path',
     'menu_name' => 'navigation',
     'type' => MENU_NORMAL_ITEM,
 );

// then define your access callback function
  function check_path(){
    // check path here and return TRUE or FALSE
    return TRUE;
  }

I just asked a similar question dealing with this: How to build a dynamic menu structure. You may find more information in that question that can help you.


Rendering plain text instead of formatted data In my custom module (in Drupal 8), I am using a form field (in a custom form) to use CKEDITOR with the following code which loads the editor fine.

$form['full_detail_text'] = array(
  '#type' => 'text_format',
  '#format' => 'full_html',
  '#title' => t('Full Detail'),
  '#rows' => 5,
);

The following code saves the posted data in the database.

$query = db_insert('my_table')
  ->fields(array(
    'full_detail_text' => $form_state->getValue('english_copy_text')[value],
    'date' => REQUEST_TIME,
  ))
  ->execute();

I am using a view page display to render this output, but the output for this field is displaying data as plain text (no formatting) along with HTML code instead of formatted data same as in the editor.

Is there a configuration setting I need to adjust or perhaps hook_views_pre_render() to transform this field's data from plain text to HTML markup?

I believe you can use check_markup to render the text in the specified format. In your example, you'd want to also save the format, something like:

$query = db_insert('my_table')
  ->fields(array(
   'full_detail_text' => $form_state->getValue('english_copy_text')[value],
   'full_detail_format' => $form_state->getValue('english_copy_text')[format],
   'date' => REQUEST_TIME,
  ))
 ->execute();

Then when you go to render it in the hook_views_pre_render

$rendered_markup  = check_markup($full_detail_text, $full_detail_format),

For more info,
 see:
 https://api.drupal.org/api/drupal/core%21modules%21filter%21filter.module/function/check_markup/8.3.x


How to update drupal 7.7 to 7.8 manually? I found that there is a warning on my site saying that manual updates of Drupal core is required.

How can I do it safely?

See this article from the Drupal.org documentation under section "MINOR VERSION UPDATES".

  To update from one minor 7.x version of Drupal to any later 7.x
  version, after following the instructions in the Introduction section
  at the top of this file:

  Log in as a user with the permission "Administer software updates".
  Go to Administration > Configuration > Development > Maintenance mode. Enable the "Put site into maintenance mode"
  checkbox and save     the configuration.
  Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles'
  directory     and any custom files you added elsewhere.
  Download the latest Drupal 7.x release from http://drupal.org/project/drupal to a directory outside of your web
  root. Extract the archive and copy the files into your Drupal
  directory.
  Re-apply any modifications to files such as .htaccess or robots.txt.
  Run update.php by visiting http://www.example.com/update.php (replace www.example.com with your domain name). This will update
  the    core database tables.
  Go to Administration > Reports > Status report. Verify that everything is working as expected.
  Ensure that $update_free_access is FALSE in settings.php.
  Go to Administration > Configuration > Development > Maintenance mode. Disable the "Put site into maintenance mode" checkbox and save
  the configuration.


How to aggregate results of search engines using drupal I want to develop a site with Drupal 7 that lists the search results of some popular search engines. Is there any module or I should develop a custom module for this purpose?

If you have links to RSS feeds, you can use the Aggregator module that comes with Drupal; the alternative is the Feeds module.
Otherwise, if you want to import the content as nodes, you can use the Feed Import module.


Managing featured content the drupal way I currently have a homepage layout similar to the illustration below:

The featured nodes are all Views in separate block regions displaying a teaser. I'm using  a taxonomy term to filter in the specific node that I want appearing there.

As I'm new to Drupal, I'm wondering if:

a) My choice of using 4 separate block regions was wise. Would it have been wiser to use a view that shows a grid of 4 teasers?

b) If there is a better way of displaying featured content in the region below the slider (such as a 4 column panel)

Any insights into an effective workflow here would be greatly appreciated, thank you!

If your goal is to make a simple workflow for your clients, you have to take into account your clients' general ability to use the Web.  What is easy for one client may be very difficult for another, so it's hard to say which workflow is superior.  For example, when I set up a Drupal website for a CS professor, very little customization was required; on the other hand, when I set up Drupal for my grandfather, I had to do a lot of workflow customization to remove options and simplify things.

As far as easily allowing content to be "Featured," I usually set it up with Flags.  This is a pain to set up but is very simple for end users.  Basically, you have a flag for each section you want to feature.  This flag should allow you to flag nodes of the content type you want to feature.  Then you create a rule using the Rules module that trims the flag to 1; this means that only one piece of content can have the flag at any given time (assuming you only want to flag one piece of content per section).  Then users with the appropriate permissions can simply flag the content that they wish to feature and it will automatically be featured.  Advanced users probably don't need this, but for users with limited computer skills it may be helpful.

As for your concerns about excessive markup, Drupal in general generates lots of wasteful markup.  There are solutions like the Fences module and Semantic Views to try to slim it down, but in general I would not worry about this; you would have to have a huge amount of traffic before the time you spent trying to slim down the markup paid off.


Can I test code contained in module files? Generally a module file contains hooks and doesn't have any class nor namespaces. What I have studied so far is that PHP Unit testing is possible only when the code is contained in classes.

Can I write unit tests for module files?

Unit-testing procedural code
In principle, you can unit test procedural code just as easily as code that is in a class, but you can't really mock it. Therefore, whether your tested code is in a class doesn't matter so much as whether its dependencies are.
Even though procedural code cannot use dependency injection and has to access services via \Drupal::service(), you can put your mocks into a custom container and call \Drupal::setContainer():
$container = new ContainerBuilder();
// ... insert mocked services
\Drupal::setContainer($container);

That means if you call only class code like \Drupal::logger() or \Drupal\user\Entity\User::load() or even \Drupal::database(), you should be able to mock everything, load your .module file, then call all of the hooks and check that they return the correct values.
But if your code references procedural core constants or functions (eg REQUEST_TIME, db_query(), drupal_set_message(), watchdog_exception(), file_*(), user_load()) then those .inc/.module files must be included as well, along with any files used by that code. You'll quickly run into problems that way, as that code will assume it's running in a full Drupal instance. To test such code, a kernel test or functional (ie browser) test will likely be required.
Unit-testing Hooks
With hooks, there is an extra caveat for unit-testing: You are declaring a function that you expect to be called from elsewhere, and which often doesn't do much other than altering and returning arrays.
You can test that as a unit, but because the contract of that code is so vaguely defined, it generally won't tell you much. Most of the errors in such code will only be revealed by testing the results in a functional test.


How to make the subscriptions module produce notifications on a screen? Really struggling with subscriptions on my site or users.

I'm currently trying the subscriptions module, but I am unable to have the user notified on the site iself. I can see it can send emails to the users which is good, but I also would like to have a little notification at the top like stackexchange has.

Anybody point me in the right direction?

Same thing I wanted to do for some kind of notification.
Finally, this was the implementation:

Added one function which returns the count and notification with HTML.
Then added Ajax request to fetch the result and place it on the notification element which is already placed in page.tpl.php
Added JS code to custom.js which works on every page of site.
See below:

But remember don't make it heavy ajax request, it may slow down your site. And remember to add JS code at bottom of page.
Also you can do one thing, put ajax request on click of the element, look what StackExchage do:

on click of notification they send request and fetch the data...


Waiting for table metadata lock getting lock messages as.... “Waiting for table metadata lock” occurs in database whenever there is “truncate cache_entity_node” call execute.

How can we disable truncate action on entitycache module ?

We are having issues with “metadata locks” with the DB so performance continue to be an issue here.

The locking issue is likely related to your database type and configs.

But you definitely do want to keep the truncate operation. To explain why, here is an order of operations on Entity CRUD in the entitycache.module. For example, on Entity update:

entitycache_entity_update() (an implementation of hook_entity_update()) is invoked
Skipping the condition check for a moment, cache_clear_all($id, 'cache_entity_' . $type); fires, and it seems your Entity type is node (hence why cache_entity_node cache bin is cleared. You want this, otherwise you will get stale data.
cache_clear_all in turn calls _cache_get_object($bin)->clear($cid, $wildcard);, and if for example your cache backend is the default cache implementation, this will call DrupalDatabaseCache::clear, which in turn will likely call db_truncate()
db_truncate() calls Database::getConnection($options['target'])->truncate($table, $options);, and that returns the TruncateQuery class
This is just so you can try to do these traces yourself, if you haven't already (or someone else reading can do this).
Skip to TruncateQuery::__toString(). If there is a transaction in progress, the SQL is 'DELETE FROM {' (and if not it's 'TRUNCATE {' (which is much faster). It sounds like you have a transaction in progress, and so you definitely want a row-by-row deletion with locks during (so it can roll back on failure if needed, whereas TRUNCATE is destructive). If you have many rows, depending on your database configs, this could possibly lock the entire table, not just the rows in question during the operation.

If this is the case, you can try various things to resolve it (caveat: you really want to contract a DBA or someone who knows your infrastructure and database setup very well). But for example, let's say your database type is MySQL: you could try reducing the lock wait timeout from the default. You could also try to change the transaction isolation level (preferable to READ COMMITTED). You'll want to read closely the comments above the $databases array in default.settings.php, specifically init_commands (issued for each connection which allow sessions settings to persist – you can set lock_wait_timeout and transaction_isolation here). There are various references to this, like Use READ COMMITTED for MySQL transactions core issue (for 8.x now, was for 7.x initially).

There is no single answer to this question, because like I said it very much depends on your setup. But I hope this gives you some direction toward solving your locking issue.

Update

Based on the issue tied to the patch your comment, I am adding more info to my answer:

Looking over Waiting for table metadata lock on cache_field table, the earlier patch in #3 gave way to an updated patch in #26. However, if you read all the information, in the end it looks like your best bet is to either 1. Not use entitycache module with DB cache backend (as Fabianx said - then again, I have experienced a similar issue using memcache so, again depending on your DB configs YMMV), or 2. try out the Asynchronous Prefetch Database Query Cache module that @mikeytown2 created to resolve this issue.


Which is the theme template file that contains the logo image of the site? I need to change the output of the logo (to make it adapative) of a site. Which is the theme template file that contains the logo image of the site?

The $logo variable is printed from page.tpl.php around line 77.

<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
<?php endif; ?>

Depending on what you want to do though you could also use template_preprocess_page().


Creating a list of child taxonomy terms with Views I have a a taxonomy with 2 levels:

Parent 1

Child 1
Child 2
Child 3

Parent 2

Child 4
Child 5

When I am on /taxonomy/term/parent1 I want to display a view of a list of child terms in a block:

Child 1
Child 2
Child 3

I have been through similar questions on this site, some with accepted answers, but it did not help me. Here is my Views settings.

For now, it displays the term name for each node containing the parent or child term, causing a lot of duplicates.

parent 1
parent 1
child 1
child 1
child 2
child 2

I'm using Views 3 and Drupal 7
If someone has a hint to share it would help me a lot :)
Thanks in advance

I may be wrong but I guess you have created a View of type 'content' while your intention is to list 'taxonomy terms' (I understand that Child # are taxonomy terms). The type of a View is indicated by the label within parenthesis, above the top of the admin lightbox. If my assumption is right, you would want to create a new View of type 'taxonomy term'.


Search order by publish date or custom field I wan't to order my search result first by publish date (or my custom date field), and then by relevance.
Recently posted on Content ranking are not working.
How to do this?

I assume you are using the core Search module. For this kind of functionality I prefer using the excellent Search API module. There are other modules as well such as Solr but with increased complexity.

The core search module indexes only node title and body. Using the module not only allows you to index other fields but also to present the results in any fashion by creating a custom view with the Views module.

In order to use Search API, you need a backend such as the Search API DB module. This needs to be installed and activated along with Search API as well.

In order to create a custom page of results:

Create a search server in Search API configuration
Create an index with all relevant fields THAT you are going to use in the view (next) as well
Create a new view of type index
Add an exposed filter 'Fulltext Search' if you wish
Add any fields you wish to present, usually the rendered entity field (teaser)
Sort by any field you prefer to.


Why drupal_realpath('public://') returns an incorrect path? As in questions. I am calling drupal_realpath('public://') inside module function. I have no idea why I am getting path like: sites/all/modules/current_module/sites/default/files, e.g.

  C:\drupal_path\sites\all\modules[current_module]\sites\default\files

drupal_realpath() has been deprecated and shouldn't be used; since you have a stream wrapper URI you should be able to get the correct path like this:

$uri = 'public://';
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  $path = $wrapper->realpath();
}

Also make sure that your public path is correct in the UI (at admin/config/media/file-system)


How can I send an email to site admin and vice-versa when user returns a product using commerce_rma? I am using the Commerce Return Merchandise Authorization module for handling returns. It is working fine .

But one thing I want that when a user returns an order using commerce_rma then a notification mail should be triggered to the site admin, and also when the admin accepts user request or declines user request a notification mail should go to the user.

How can I do this ?

You could use Rules Module

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events

There are events created in rules when Commerce RMA is installed such as After creating a new return


Using HOOK_username_alter() to hide the real username I'm using a pattern for the username creation using the contrib module: automatic_usernames, this results in the following pattern for my use case: [hotel_name][uid]. Example: Hilton10

Here is the dilemma. This is fine for the business to see, but I do not want them to see their customer's actual username that they just created such as Hilton11 and instead I would like them to see the first name + last name of the customer.

How would I go about this using the following custom fields?

[#field_name] => field_customer_first_name

[#field_name] => field_customer_last_name

function MyCustomModule_username_alter(&$name, $account){
 global $user;
    if(in_array('venue admin', $user->roles)) {
    $name = ? //this is where im stuck
}

The $account argument in hook_username_alter() provides the user entity object with all its field values. You can use its field values for your $name substitution. For example:

function MyCustomModule_username_alter(&$name, $account){
  global $user;

  // This example presumes a field_first_name as a user first name field.
  // It will vary based on your field & language environment.
  // use Devel's dpm() to find your actual value for user entity.
  if (isset($account->field_first_name[LANGUAGE_NONE][0]['value'])
      && in_array('venue admin', $user->roles)) {
    $name = $account->field_first_name[LANGUAGE_NONE][0]['value'];
  }
}


Exract all node field values to json including reference entities with value I am writing a module to export drupal's content to another platform, the module provides a UI to manage content types and their fields to be shared on another platform via API.
So far i have managed to get node field values using this sample code
$nid = 4951;
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = [];
foreach ($node->getFields() as $name => $field) {
  $data[$name]  = $field->getString();
}

the $field->getString(); however do not provides reference entity values and only provide ids.
The out of the above code is like:
{"nid":"4951","uuid":"0fae7e9b-d860-43f0-9559-a8bd6bab22b7","vid":"1272611","langcode":"en","type":"article","revision_timestamp":"1612303794","revision_uid":"1166","revision_log":"","status":"1","uid":"866","title":"xyz Chapter April Update","created":"1555961981","changed":"1612303794","promote":"0","sticky":"0","default_langcode":"1","revision_default":"1","revision_translation_affected":"1","moderation_state":"published","scheduled_transition_date":"","scheduled_transition_state":"","metatag":"","path":"\/wisconsin-chapter-april-update, 17276, en","menu_link":"","body":"some this here, rich_text","field_article_author":"Wisconsin Chapter","field_article_chapter":"541","field_article_endnotes":"","field_article_questions_cta":"1","field_article_recommendation":"","field_article_recommended_link":"","field_article_related":"","field_article_related_link":"","field_article_resource_download":"","field_article_subhead":"Here's the latest news from the abc.","field_article_thumbnail":"","field_article_type":"news","field_blog_section":"","field_meta_tags":"","field_tax_article_type":"24, 28, 45","field_tax_audience":"","field_tax_breadcrumbs":"","field_tax_content_format":"50","field_tax_disease":"55, 56, 57, 58","field_tax_ga_type":"","field_tax_research_type":"","field_tax_topic":"90, 91, 92, 93, 94, 108, 109, 111"}

Scroll last and see for example field_tax_topic
Is there a direct or indirect way of automatically detecting reference entity field and extracting its values, also it should be dynamic solution and that must work with new field types as well.
Any pointer or direction to do it in the right way will help!

If you really really want to do this which you probably wont with JSON API Views and
serialisation
https://www.drupal.org/docs/8/api/serialization-api/serialization-api-overview
eg:
dump(Drupal::service('serializer')->serializer->serialize($entity, 'json'));

But if you really want to ...
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$data = [];
foreach ($node->getFields() as $name => $field) {
   // Get Type.
   $field_type = $node->get($name)->getFieldDefinition()->getType();
   //see https://drupal.stackexchange.com/questions/180373/how-to-get-the-list-of-field-types

   switch($field_type) {
      case 'text_with_summary':
      case 'text':
      case 'text_long:
        $data[$name]  = $field->getString();
        break;
      case 'entity_reference':
      case 'entity_reference':
        $value = [];
        $items = $field->referencedEntities();
        if (!empty($items)) {
            foreach ($items as $item) {
                // here is the crappy part
                $val_1 = $item->get('field_something')->value;
                $value[$item->id()] =  $val_1,
            }
        }
        $data[$name] = $value;
      break;
      // continue for other data types
      // and set a default !
   }
}


Which hook is used to alter a field's description? Which hook should I use to alter description of a field?

I want to add some descriptions to fields in several content types. because number of fields and content types are too many, I prefer to add descriptions programmatically.

To the best of my knowledge there's no hook for that. Instead you'll want to use the following API functions in whatever context makes sense in your site:

field_info_instance()

  Returns an array of instance data for a specific field and bundle.

Use the function to load up an array of instance data/settings, which you can then alter as necessary before passing back to:
field_instance_update()

  Updates an instance of a field.

That will persist your changes to the database, and take care of clearing relevant caches.

A complete example might look like

$info = field_info_instance('node', 'body', 'article');
$info['description'] = t('New description');
field_instance_update($info);


Default .htaccess problem in FilesMatch I installed Drupal 7 on a web server and can;t access the root domain.
When I comment the following lines in the .htaccess file I can load the site without any problem:

<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

I don't want to comment the complete FilesMatch tag as I understand that it protects from unwanted access to files and server resources.

What should I change?

if you use one.com

I just find out, that you can remove or commenting

Options -IndexesOptions
Options +FollowSymlinks

in the htaccess file, and then it should work. I don't know why.


Is it correct to directly modify a supplied Drupal theme? I downloaded and installed the Bootstrap theme for a new Drupal 7.28 site.

Is it correct to simply modify this theme directly to build my site, or should I create a custom theme and somehow "base" it on this theme?

Put another way, is theming analogous to downloading the Bootstrap CSS and overriding selectors, or directly modifying the CSS itself?

No, it's not correct to directly modify a contrib theme (or Drupal core, or a contrib module). Once you start doing that, you cannot easily update the theme anymore. It a few months, you, or another, developers may forget the theme was modified, do what should be a easy update and break everything.

You have two options to change and existing theme. You can rename the theme before making any other change (ie. fork the theme to a custom theme). You can also create a sub-theme of your chosen theme. The sub-theme can override template and theme functions, and adds ins own process and pre-process functions. But it will inherit all non-overridden templates and theme functions and all process and pre-process functions.


How to get achievements notification popup for Ajax Callbacks? I'm using the Achievements module to award the badges to users on certain actions.

In the following example user will get badges after posting 5 and 10 comments.

function MYMODULE_comment_insert($comment) {
  $current_count = achievements_storage_get('comment-count', $comment->uid) + 1;
  achievements_storage_set('comment-count', $current_count, $comment->uid);

  foreach (array(5,10) as $count) {
    if ($current_count == $count) {
      achievements_unlocked('comment-count-' . $count, $comment->uid);
    }
  }
}

The above code is working, user is able to achieve badge after posting 5 comments but since the comment form is being submitted through AJAX, the rewarded achievements notification popup is not being shown until page refresh.

So how can I show achievement notification popup for Ajax callbacks? Any suggestions?

Here is another try at this (various assumptions follow):

The whole thing should run through the Wall module's code, since this is the base for any other interaction happening.
By means of the Form API and AJAX callbacks, there is a possible entry point. This is to wrap the submit callback for the _drupal_wall_comment_post_form into another callback that will make sure the Achievements' related elements are updated.
The steps in this process would be:

Use hook_form_alter to modify _drupal_wall_comment_post_form
Modify _drupal_wall_comment_post_form by hijacking the ajax callback for the wall comment submissions:
$form['drupal_wall_submit']['#ajax']['callback'] =>_your_custom_wall_ajax_callback
Wrap the original callback in your ajax callback and extend it to trigger the Achievements popup functionality using the Ajax framework commands family:

function _your_custom_wall_ajax_callback($form, $form_state) {
  $wall_wrapper = $form['drupal_wall_submit']['#ajax']['wrapper'];
  $wall_content = _drupal_wall_comment_ajax_form_post($form, $form_state);
  $commands = array();
  $commands[] = ajax_command_replace($wall_wrapper, $wall_content);

  // This is where you can write ajax commands to trigger Achievements functionality
  $commands[] = ajax_command_*();

  return array('#type' => 'ajax', '#commands' => $commands);
}

Hope this brings you a step further!


How to use jquery to show divs based on select box? This is a follow on to my previous question. I didn't want to make ajax calls for this and instead loaded all the term field text with views_get_view_result(). Then I looped over the results and created divs within the node add/edit form.

I know have for every term option in the select box a hidden div:

help text for termid 123

I added a

scripts[] = custom.js

to my module.info file with:

(function($){
$("#edit-field-disc-topic-und").click(function(){
    var option = document.getElementById("edit-field-disc-topic-und").value;
    document.getElementById(option).style.visibility ="visible";
})
})(jQuery);

Should I post this on Stackoverflow instead?

you ommited the drupal.behavior, that s probably why it doesnt do anything.
And i would suggest working with classes instead changing style. In your css you create a style with visibility:hidden, apply it to each element and then remove it on click. (and add it again once you clicked on something else ...)

document.getElementById doesnt make much sense there ... you can write it better like this :

(function($){
Drupal.behaviors.taxdescGetDesc = {
  attach: function (context) {
    $("").click(function(event)){
    option = $(event.currentTarget).val();
    $('#'+option).removeClass("hidden");
  }
}


Programmatically update Webform Submission by sid I'm trying create/update Webform Submission programmatically. I already know how the create new submission by following the Drupal 8 API. Now I'm trying to build a update method, I refer to the Webform module source-code and API documents but couldn't find a solution. I guess they remove webform_get_submission webform_submission_update functions in Drupal 8.3 as-well.

$values = [
  'webform_id' => 'attendees_info',
  'in_draft' => FALSE,
  'uid' => $uid,
  'langcode' => 'en',
  'token' => 'at_'.$token,
  'uri' => '/webform/attendees/api',
  'remote_addr' => '',
  'data' => [
    'name' => $name,
    'email' => $email,
    'gallery_url' => 'gallery/'.$token,
  ],
];

$webform = Webform::load($values['webform_id']);
$is_open = WebformSubmissionForm::isOpen($webform);

if ($is_open === TRUE) {
    // Validate submission.
    $errors = WebformSubmissionForm::validateValues($values);

    // Check there are no validation errors.
    if (!empty($errors)) {
       return $errors;
    }
    else {
      // Submit values and get submission ID.
      $webform_submission = WebformSubmissionForm::submitValues($values);
      return $webform_submission->id();
    }
}

Above is my Submission creation code, I don't know how to do the update method. Is anyone face this issue before? Hope someone will help me on this, thanks.

Try using \Drupal\webform\WebformSubmissionInterface::getData(); and
\Drupal\webform\WebformSubmissionInterface::setData($data);

// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

// Get submission data.
$data = $webform_submission->getData();

// Change submission data.
$data['element_key'] = 'custom_element_value';

// Set submission data.
$webform_submission->setData($data);

// Save submission.
$webform_submission->save();

Update: Use a capital "E" in "Entity" for the class name. (Recently got updated).


What are common methods of intrusion into a Drupal website? I am running Drupal 6.28 that was recently hacked and there were scripts being executed out of the /tmp directory, apparently running a bitcoin mining server and other brute force scripts.

I would get random processes sometimes 2-4 at a time that would each consume over 100% cpu(core) for an indefinite period of time. Which would make sense if they were running some type of bitcoin mining operation or brute force attack.

To the best of my knowledge the attacker uploaded a file named 32.tar.gz to the site. Drupal moved this file to the /tmp directory, then attacker extracted into the same /tmp directory, which has 777 permissions.

I would gladly change the permissions on this folder to something more sane like 755, but in doing so, Drupal stops functioning properly.

All files/folders in my drupal install directory are owned like: myUser:www-data, where www-data is the user that PHP/Apache is running as.

The /tmp folder is owned by the same user and group, so I would think that it would be writable at 755, but that just isn't the case for some reason. Is there a way to harden the security of the site that would prevent this from happening?

The first question is how they are uploading and extracting the file. That is likely only possible via a vulnerable contributed module (probably an out of date one) or because they have credentials to your server (either at the drupal layer or the server - ie ssh or sftp layer).

The second question is why your tmp directory is in a publicly accessible location (is it?). If it's not then it seems more likely the problem is arbitrary code execution or credentials compromised.

Solutions: basically you have to "start over."

Audit every single account and permission
Audit every single file of code - download fresh copies from drupal.org and ensure the versions on your site match them exactly.
Install the security review and paranoia modules and read their documentation to ensure they are working properly. They will help audit your permissions and content.


Tokens in field widget don't work I am using drupal 8. I want to add tokens to the paragraph image field widget as data-attribute, but it doesn't work. What can be caused by this problem? Is it need some modules? Here screenshot:

Thanks!

I have used the wrong token field for the paragraph image field. Instead of [media...] token need to use [paragraph:...] token, as the field is paragraph field.


Views joining/relating a custom table entity to users through a field? Using Drupal 7 and Views 3 - I have created a custom entity and can view it fine through Views using EntityDefaultViewsController. The Table is a view shared to the drupal database and is constructed like:

Table A
------------
id_key
data

I have a drupal user field - field_tableA_data that contains the same data type/items in the Table A data field (they are not linked in any way - two separate systems load this data - in TableA the data is generated by another system and the User field is loaded by the LDAP module)

I want to make it so that I can make a "View" such that when viewing Table A Items I can also make a relationship to the User entities such that:
Table A > field_tableA_data > User

Is this possible in code and if so how?

Here is some code I have tried and to no avail:

class TableAEntityViewsController extends EntityDefaultViewsController {

  /**
   * Edit or add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();
    $data['tableA']['data']['relationship'] = array(
      'handler' => 'views_handler_relationship',
      'base' => 'field_data_field_tablea_data',
      'base field' => 'field_tablea_data_value',
      'title' => t('TableA Data'),
      'label' => t('TableA Data'),
    );
    return $data;
  }
}

and in the module (table A entity I have a hook):

function (module)_views_data_alter(&$data) {
    $data['tableA']['table']['join'] = array(
    'field_data_field_tablea_data' => array(
      'left_field' => 'field_tableA_data_value',
      'field' => 'data',
    ),
    'user' => array(
      'left_field' => 'uid',
      'field' => 'field_data_tablea_data.entity_id',
    ),
  );
}

The best this gives me though is User:field_tableA data and no other fields from User - I'm trying to get uid and username.

I know this is not timely, but if someone else is looking for an answer:

Assumptions:
- Using Entity API
- Joining to another entity where the entity id is a field in your entity's base table
- It's a one-to-one relationship

Add the views controller class to your entity info file
function my_entity_entity_info() {

$info['my_entity'] = array(
  'views controller class' => 'MyEntityViewsController',
  ...
 );

2 Extend EntityDefaultMetadataController

class MyEntityMetadataController extends EntityDefaultMetadataController {

  public function entityPropertyInfo() {

    $info = parent::entityPropertyInfo();

    // This exposes the fields as references to views.
    $info['my_entity_base_table']['properties']['uid']['type'] = 'user';

   ....
  }
}


how to filter and show fields of content types in custom page tpl.php file I have the following fields in content type ‘Articles’

Year:
Volume:
Issue:
Title:
Description:
Upload file:

Now I want to create a custom pages tpl.php and categorized based on Year, Volume, Issue. So the output should be like below.
On clicking issues, it should display the all the posts.  (2013/volume 3/Issue 1)

2013
Volume3 – Issue1, Issue 2

2012
Volume 2 – Issue1, Issue 2, Issue 3

2011
Volume 1 – Issue1

Instead of modifying any template files, you should most probably be looking into the Views module, a module that, per its project page, is useful for a variety of tasks, one of which seems particularly on point here:

  You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.


Trying to make view template I have a content-type that has an imagefile and a url; I want the url to wrap around the image. So I'm trying to make a viewtemplate based on the information in Theming information

based on this description

/**
  * This template is used to print a single field in a view. It is not
  * actually used in default Views, as this is registered as a theme
  * function which has better performance. For single overrides, the
  * template is perfectly okay.
  *
  * Variables available:
  * - $view: The view object
  * - $field: The field handler object that can process the input
  * - $row: The raw SQL result that can be used
  * - $output: The processed output that will normally be used.
  *
  * When fetching output from the $row, this construct should be used:
  * $data = $row->{$field->field_alias}
  *
  * The above will guarantee that you'll always get the correct data,
  * regardless of any changes in the aliasing that might happen if
  * the view is modified.
  */

I made views-view-field--my-view--block--field-image.tpl.php to look like this:

$url = $row->{$field->URL}
?>
<a href="<?php echo $url; ?>" target="_blank">
  <?php print $output; ?>
</a>

But I'm getting Cannot access empty property on the $row->{$field->URL} line. Can I only access the image field from within the template for the image field? I was looking at views-view-fields--my-view--block.tpl.php but not sure how to access things from in there

I would do the following:
    <pre>
    <?php print_r ($row); ?>
    </pre>
This will give you the full tree of the $row


Is there a way to add bulk operation options to the admin/content list's 'Update Options'? I have downloaded the views bulk operations module and activated it.  I offers me many new options for changing the settings on my nodes/entities.  I would like to know if there is a way to add these options to the "update options" which is available on the content page of Drupal admin (location: admin/content.)

This menu already lets you do things such as publish, unpublish and delete.  It also picks up options from add-on modules.  It seems that views bulk operations should appear in this menu too.

Bulk operations provided by that module only make sense in the context of a view, so you won't see them on a non-view page like the standard admin content page.

You can install the Administration Views module to replace that page with a View, and then you should see the options you're expecting. Most (all?), of the core actions from the original page should be available. To add more, you can edit the View and change the available actions in the VBO field.


How to change text format of summary/trimmed field? Is there a straightforward way to change the summary/trimmed text to "full html" in Drupal 8?

There are workarounds such as creating separate body fields and using them as the summary but I am specifically asking about changing the text format of default summary/trimmed field of "Text (formatted, long, with summary)".

To put it another way, how to I add the CKEditor bar to the summary/trimmed text.

You can't, it always has the same format. The field only stores a single format. And it has bugs with ckeditor, as you've found.

I would definitely recommend to use two fields. We'd like to remove the text with summary field type, it's unnecessary complexity but it was too late for 8.x.


How to send email invite user fill in webform automatically? I'm using drupal 7, and had a seminar questionnaire form created using webform.

I would like to invite seminar attendee to fill in this questionnaire after they attend the seminar, by sending them email with link to the questionnaire.

Rather than manually open my email client and retyping the same invitation template for every seminar, is there anyway I can have this?

A standard template of email invitation content with webform link
Admin only need to type in different email address of each seminar
Email will automatically sent to address entered
Attendee do not need token or account to fill in the form
It's similar to google form share this form / invite through email function

Is there any module to do this? Or I need to use with other modules such as Rules?

There are a handful of different modules that can let you do bulk emailing (e.g. VBO, Mass Contact, Email Campaigns, etc.), but using Drupal as a batch email client I think only make sense in the context of:

Having regularly visiting user base, with pre-existing accounts.
Needing to contact a relatively small number of people (e.g. hundreds, or very low-thousands).

Your 4th requirement suggests that you'll be supplying any number arbitrary emails for the sake of feedback/lead gathering.

In lieu of a module or Rules (which only make sense in the context of some workflow built into the site), I'd suggest some 3rd-party email service (e.g. Constant Contact, MailChimp, etc.) to accomplish items #1-4.
Any decent 3rd party email service should give you a templating system with substitutable tokens that will let you customize your webform link if you need it to have pre-filled data (e.g. email, name, attended seminar, etc.) and a means to bulk submit email/contact info.

As far as item #5, there's a number of different way to accomplish this. One way is the Forward module which provides a share via email link/form for any node type.


Should scripts/*.sh files be executable? Drupal 7's recommended file permissions don't allow it's /scripts/*.sh files to execute. Should any server user have the ability to run those?

No. You don't need to execute permissions on those scripts in a production server environment.
The only reason you'd need those scripts executable on a server is for running code testing utilities (e.g. simpletest test cases, generating dummy content, etc.) on the codebase. Unless you're wanting to run some of those testing utilities on a CI server, they don't need to be executable for Drupal to work.


Drupal 7 sessions wiped after changing settings.php Yesterday afternoon I had an administrator uncomment and modify the $base_url variable in our production environment. Any changes made in the repository fires off a redeployment which has never been an issue. Upon the server coming back up, we started receiving complaints that user's who were now logged out.

Does changing settings.php do something behind the scenes that I'm unaware about (session.cookie_lifetime or session.gc_max_life).

I do not have access to the database nor can I retrieve it from our prod environment.

Any help is appreciated so that we don't run into this issue again!

This is likely due to the value changing, which changes the way they are recorded:

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_settings_initialize/7.x

$base_url and $cookie_domain - changing these values in settings.php will affect any user who was authenticated before if the values change, and will need to re-authenticate.


Restrict webform component use to certain roles I want to restrict the usage of a custom component only to a specific role.
What's the drupal way of doing that?
I tried https://drupal.org/project/webform_component_roles but this just defines usage permission for all the components not each specific one.

Try Webform Webform Locked Fields module, you can set permission for specific role

  Users who have the "administer webform locked fields" permission will
  see a checkbox titled "Webform creator can modify" when they edit a
  webform component. If that box is unchecked, the component can only be
  modified or deleted by users who have the the "administer webform
  locked fields" permission. Other users who have webform creation
  permission will be taken to a page that says "Not allowed" if they
  attempt to edit or delete that component.


Can drush accept piped commands for aliases? Can drush take piping commands for a multisite command using an alias?

I'm trying to setup a simple refresh function from my prod to dev/staging. Any pointers or tips would be welcome. just started learning this stuff.

drush $prodalias sql-dump --gzip >/tmp/$site.sql.gz

gunzip /tmp/$site.sql.gz | drush $devalias sqlc

It should be allowed to use piping in drush aliases as this feature was added recently by improving escaping options for core-exec.

So you have to upgrade your drush to the recent version (7.x).

See: Are pipes allowed in shell aliases?

If you prefer to use script, here is one which I'm usually using:

#!/bin/sh
# pull-db.sh
# Script to pull the database from remote to local environment.
[ -z "$1" ] && { echo "Usage: $0 @remote (args)"; exit 1; }
SRC="$1"
shift
drush $SRC sql-dump | drush $* sql-cli


Check parent term when checking subterm I have a client with a really large taxonomy, which is used for a certain node type. My client wants that the parent term of a chosen subterm, to also be used for a node.

Let's say that this is the taxonomy:

Parent1

Child1
Child2

Parent2

Child3

If the user checks (they are printed as checkboxes) either child, its parent term will also be used.

Is there already a module for that, or something, or do I have to write my own?

Drupal 7

Taxonomy Term Reference Tree Widget has this option.
install and select it as your taxonomy reference widget and check Select parents automatically in field instance setting form


Pre-Populating a Form Field with something other than its default value I'm having a strange problem. I am constructing a form with checkboxes to toggle email subscription preferences on and off. For the new user sign-up form, this is straightforward:

$form['marketing-container']['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => "False",
);

However, when it comes to the update user form, I'm running into a problem. If I set #default_value to the existing preference, it will check the boxes for those publications you're subscribed to correctly, but if you UNcheck those boxes, the form API just returns the default value....which would still be TRUE.

To work around this, I retrieved the subscriber object at the start of the form function, and I've added hidden fields whose default values are the existing subscription preference values, just like I attempted to do with the real fields in the first place. Then, I used #states to populate the real fields based on these hidden fields, like so:

$form['marketing-container']['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
);

$form['marketing-container']['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => "False",
    '#states' => array(
        'checked' => array(
            ':input[name="existing_restaurant_newsletter_subscription"]' => array('checked' => TRUE)
        )
    )
);

Now this works! The problem is that the first field is visible. Now if I alter this to hide the field:

$form['marketing-container']['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
    '#access' => FALSE,
);

The field is hidden perfectly....but its value isn't copied over to the real field that's still visible.

I've searched all over and pored over the Form API documentation, and I'm stumped.

Is there some way to preserve this default value inside the hidden form so it copies over to another field correctly?

If there isn't, or if it's more efficient, is there a DIFFERENT method I could use to pre-check this checkbox but still keep a default value of FALSE so that if a user unchecks it, something actually happens? Is there another class of field I'm missing that is a sort of on-off switch that returns specified values for each state?

Figured it out on my own. The solution was:

$form['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => $attributes[15]->Value,
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
        'callback' => 'ajax_replace_default_callback',
        'wrapper' => 'restaurant_newsletter_subscription_div',
    ),
);

And for the callback:

function ajax_replace_default($form, $form_state) {
    $field_name = $form_state['triggering_element']['#name'];
    $form[$field_name]['#default_value'] = "False";
    return $form[$field_name];
}

And I also kept the hidden fields in the form:

$form['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
    '#access' => FALSE,
);

This was simpler to store the existing preference variables for comparison in my logic later on than to try to retrieve the subscriber yet again inside of that form submit handler (It already retrieved the subscriber when it loaded the form, to populate the fields....trying to minimize the number of API calls I have to make).

Implemented like this, if a box is checked and becomes unchecked, that Ajax callback function alters the default value to false, rather than returning just the pre-populated value. If you check the box again it still changes the default to false, but it doesn't matter since if the box is checked that's irrelevant.

Not the most elegant fix, you get a little loading circle thing for a second when the Ajax runs, but it works.

Note: I left the Ajax callback function generic because even though I keep using the same field on this page, there are lots of similar fields doing the same thing. Using the triggering_element allows me to just recycle this code for all of them.


File system... How does it work? I am new in Drupal. Now I am trying to understand basic philosophy of Home->  Administration -> Configuration -> Media -> File system. Public file system path here is:

sites/default/files

is set as public path by default and Public file base URLis therefore:

http://example.com/sites/default/files

Couple days ago not knowing about File system I created folder, where I put some pdf files.

http://example.com/custom_files/pdf

In the article I set hyperlinks to these files and everybody may download these pdfs happily.
And now I do not know at all, why should I bother with File system  public path??? What is it good for, when I may use any folder I want?

Thanks for answers

TL;DR
Public file path is used for file uploads that happen in Drupal. Usually you want to use Drupal to manage content, that means article, users and files. This requires you to upload files inside Drupal application and this is where the public file setting comes into play.
Longer version
When you create a Drupal site, you can decide where all file uploads (which are public) should be located. The only rule is, that it have to be inside the webroot, so that they are accessible for download.
By default this is sites/default/files, but it could be /uploads or whatever you like.
This is used for when you actually use Drupal as a CMS and upload files on content like on articles, user profile pictures etc. When you upload files through Drupal and they are public, Drupal will save info about the file, know it's location and can do things with it.
Having the public path configurable is pretty smart, it means to change move or rename the upload folder and you only need you change one setting for it to work.
If you have FTP access you can upload any file to the webserver, it will be accessible to users etc. You should note that uploading files this way, means that Drupal wont know that they exist and can't actually use them in any way. It might be a good solution for your use case, but you are effectively bypassing Drupal as a CMS and if you plan on manually uploading all files through FTP, you will loose a lot of the file management features and the public file setting wont matter one bit.
Hope this clear things up for you a bit.


Is it possible to change the form submit handler from within a validate handler (need to redirect to another form depending on values entered) I have an initial webform (based on 3.x of webform module/Drupal 7) that needs to redirect to a second form if yes is specified in a yes/no choice. Otherwise if No, the first form should submit normally (with a webform result).

Also, if yes is entered on the first form, on submitting the form, the webform result is not to be stored for this form, but the webform result will be stored on the second webform. Values entered in the first form are carried through to the second, to autofill, I use the PHP _SESSION variable to do this.

I'm having difficulty getting this to work completely. It always seems that I can get one part of the above working, but not the other. I'm using the standard approach of hook_form_alter and within this trying various combinations of setting the validate array and submit array and the form redirect property to do the redirect from the first and second form.

My approach now is to have a validate handler function to change the submit handler if the yes is chosen (for proceeding to the second form). Submitted values on the first form are available to the validate handler. The submit handler can do the redirect to the 2nd form.

But when I change the submit handler from within the validate handler, I see that this change gets overwritten by Drupal itself and I don't know why.

I have also found that the submit handler - which I use to set the form redirect, for the 'yes' choice - will not work if other submit handlers are present in the submit handler array. I have to empty the array and have only my function in it.

I had wanted to deal with the yes/no choicepoint at this stage in my own submit handler, but if I had to 'throw away' the other submit handlers, then the 'No' path won't work - the webform result won't get submitted.

Another approach I tried, to counteract my deleting of the other existing default submit handlers, was to programmatically submit a form for the the first form for the 'No' path so that it would get saved. However doing this I got an error about the number of submissions possible, even though it was set to unlimited (-1) in the config. From that I concluded that it was due to that I had already started the first form as a visitor and somehow the webform system 'notes' that, so programmatically submitted form would exceed that supposed maximum.

Note: I can't upgrade to webform 4.x as there are other forms on the site which may be impacted unexpectedly.

You don't need to rewrite form submit handler. You can implement drupal_goto() for your first form with FORM_ID_submit() depending on user input. Pass $form_state['values'] as url options and fetch them from $_GET array as #default_values in second form.