How to embed "Exposed form in block" into top bar? Using foundation theme I have a product search view. I use the "exposed form in block" in order to have only the filters show on all pages and the results show on a separate page. I want to put my filters in the top bar. How would I embed the "exposed form in block"? I know how to embed a view but I cant figure how to embed the "exposed form in block." in the top bar (the nav). The biggest reason is because its not a region. So I cannot place the block in it from the structure>blocks. Ive tried moving my header region to be on top of the nav but this create issues also. I was thinking that maybe there is a way to print the "exposed form in block" in the page.tpl.php... is this possible? Or will I have to use a hook in the template.php? Or Can I redefine the nav bar as a region possibly?

Views UI -> create a page view
Set 'Exposed form in block' -> Yes
Go to Structure -> Blocks
Find the exposed filter block which you recently created and configure the Region and Visibility settings

EDIT:
to specify a new region modify .info file and page.tpl.php file of you page: e.g.
MY_THEME.info:

....
regions[top_bar] = TOP BAR
...

page.tpl.php:

...
    <?php if($page['top_bar']): ?>
    <div class="header_top_bar">
      <?php print render($page['top_bar']); ?>
    </div>
    <?php endif; ?>
  ...

Documentation

or if you want to insert a block into template file here is an issue.


How to compare form value in an ajax call I have a date picker in my custom form. 'from_date'. When I change the value in this, I need to call a function and compare the date value with another custom value and need to show a popup using custom plugin alertify. I have been succeeded up to creating an ajax_call_back function. But I'm stuck in retrieving form data and showing the popup.
...

$form['from_date'] = array(
        '#type' => 'date_popup',
        '#date_format' => 'd-m-Y',
        '#ajax' => array(
            'callback' => 'check_date',
            'event' => 'change',
        ),
        '#attributes' => array('class' => array('date_popup_frm'),)
    );

....

function check_date($form,$form_state){

//how can I compare the value with $value which I will get after calling an SP

}

I found an answer for me after trying various cases. The below is the call back function which I wrote.

function check_date($form,$form_state){
 $current_date = $form_state['values']['from_date'];
 $custom_value = sp_call_and_extract_needed_data();
 $error_message = t('your error message');
 $current_path = current_path();
 if (strpos($current_path, 'ajax') !== false) { //if call from ajax
   $commands[] = ajax_command_after('#breadcrumbs',  $error_message);
   return array('#type' => 'ajax', '#commands' => $commands);
 } else {
   form_set_error('from_date', $error_message);
 }
}


How to store second dropdown value in database function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

I have tried to get city value like this 'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'], but error is coming like

  Notice: Undefined index: city_element_wrapper in
  form_test_custom_form_submit()

How to solve it?

function form_test_custom_form_submit($form, $form_state) {
  $prog_id =1;

  db_insert('tot_prog')->fields(array('state1' => $form_state['values']['state1'],
'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],) // i have metioned like this,  is correct???? but its shows error, how to get the select city value???
        ->execute();
 drupal_set_message("successfully saved Settings");
}

Your error:

  Notice: Undefined index: city_element_wrapper in
  form_test_custom_form_submit()

means that index city_element_wrapper is missing in $form_state variable. Do this:

function form_test_custom_form_submit($form, &$form_state) {
  $prog_id =1;

  db_insert('tot_prog')
    ->fields(array(
              'state1' => $form_state['values']['state1'],
              'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],
            ) )
    ->execute();

  drupal_set_message("successfully saved Settings");
}

Always take the reference of $form variables if you want to fetch values from the variables or update the values of the variable. For more details about PHP reference read this.


Distinguishing form being built for rendering versus submission Is there a way to distinguish, inside a form function, that the form is being built to be rendered on the page, as opposed to being re-built as a result of submission?

I would like to use drupal_set_message() inside the form function, but only while it's being built for rendering.

Take a look at the $form_state elements. You'll want to look at 'submitted', 'rebuild', 'cache', 'programmed', etc... depending on your use-case.  You can get a good idea of those elements and what they mean in drupal_build_form.  I typically use $form_state['submitted'].


Integrate external DB users via their API in Drupal 7 I want to integrate an external API (REST) to login users which are on that external database using the drupal 7 login form on my site.

I have the API specifications for Login, Registering, Getting member details and Check logged in. I also have a URL to test GET and POST requests on that external DB.

How do I integrate it with Drupal database so that users can log in using either Drupal's DB or external DB (integrated with the API)?

I have just discovered Services module but not sure if it is of any help.

I'm not an expert in creating custom modules either so any sample code or any pointers would really help here.

NOTE: External API requests return XML output

In order to implement external authentication you need to alter the login forms (user_login and user_login_block) to alter their validation handlers.

The default validation handlers for the forms are user_login_name_validate(), user_login_authenticate_validate() and user_login_final_validate(). You will need to replace user_login_authenticate_validate which is used to check the supplied username/password against local users table. Your replacement should invoke your API to handle the authentication.

Depending on your need, you may want to provide automatic registration (on the Drupal site) of new user on authentication. In such as case, you can use the user_external_login_register() function to create the account from your user_login_authenticate_validate replacement.

To map the Drupal user to the user on the external system, Drupal provides the user_get_authmaps() and user_set_authmaps() functions. Note that that user mapping mapping is automatically handled when using the user_external_login_register() and user_external_load() functions.

The perform your HTTP requests, you can use the drupal_http_request() function which usually do the job and support HTTPS. Of course, you can also use another HTTP library.

All of this will have to be done in a custom module and you will need good understanding of Drupal's Form API.

A comment on the documentation page for user_external_login_register() provides detailed explanation of the complete process.

Note: The Services module is useful when you need a read/write HTTP-based API for your Drupal site's data. In your case, it would not be usefull since you need to consume an existing API to authenticate the users.


Geo field proximity distance for exact location I'm tried this for a day,but i won't get the answers. I'm using geo field proximity for zip code searching, it's working with 5,25,30 miles search, but i want to search exact location of zip code.

eg
    In search zip code : 73301, all the record in 73301 will be show.

Zip codes don't have exact location. A zip code is an area in which the coordinates are a point within it. In most cases it is probably the centroid.


Popup with the content of the exposed date field I am using "Webform Views Submitted Data" module to show webform submissions report with views. I have one expose filter name "Webform submissions: Submitted" which will give two date options; start date and end date. How do I select the date i want to filter by in a  popup calender?

How about writing a custom jquery code with the help of http://docs.jquery.com/UI/Datepicker. I am not sure whether you are proficient with jquery , but still i would prefer to have a go at this.


How to include multiple Views in an already existing feature? I have to work with an old Drupal 7 site. It's using features. I created some new views, now I have to include these 2 new views into a feature which already has 1 view. How can I do it and which steps or hooks I should follow? Thank you

Feature module provides admin interface for each feature you create.

Just go to this page: admin>structure>feature
Find your feature
Edit it and check which Views to add.
Rebuild your custom feature module which your edited.
Open the code, delete old custom_feature module and add new custom_feature module which you just created.

You are done!


Minimalistic page.tpl.php file Do you know what to write to the page.tpl.php file so that it shows only 5 regions (header, menu, left_sidebar, content, right_sidebar)?
Something like the following code, but to work correctly with other Drupal files and components (like *.info file) and don't collide with Drupal default regions.

<?php print $page['header']; ?>

<?php print $page['menu']; ?>

<?php print $page['left']; ?>

<?php print $page['content']; ?>

<?php print $page['right']; ?>

You want to use render() like this:

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

I'm not really sure what you mean by "but to work correctly with other Drupal files and components."

You should also print all the standard regions and any other variables you might need. You can find a list of the default variables available to page.tpl.php in the documentation page.

Also here's a list of the regions you probably should include:

$page['help']: Dynamic help text, mostly for admin pages.
$page['highlighted']: Items for the highlighted content region.
$page['content']: The main content of the current page.
$page['sidebar_first']: Items for the first sidebar.
$page['sidebar_second']: Items for the second sidebar.
$page['header']: Items for the header region.
$page['footer']: Items for the footer region.


Passing object by reference in form element of type 'value' Given that in PHP5 objects are said to be passed by reference automatically, are there reasons why one must not pass an object through forms ('programmatically')? I hope to create acceptable persistence through using $form_state for use with AJAX or form submit handlers. I've tried the following and it works (but I don't want to be doing something in poor practice/ that might get blocked).

$foo = new stdClass();
$foo->bar = 'foobar';

$form['foo-bar'] = array(
    '#type' => 'value',
    '#value' => $foo,
);

Which then appears in $form_state when the following element triggers an AJAX request

$form['numbers_required'] = array(
    '#type' => 'textfield',
    '#title' => t('Numbers needed'),
    '#ajax' => array(
        'callback' => 'numbers_required_callback',
        'wrapper' => 'numbers_remaining',
    ),
);

Furthermore, the following passage from the drupal_build_form() documentation suggests I might have to set the form 'cache' property to TRUE. Perhaps for others this is the case if they aren't using an AJAX callback. Given that I am, I assume I can ignore this, but thought others might find it useful to know.

  cache: If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which ajax_process_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of $form and $form_state happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.

Objects are 'passed by reference' in the context of being passed to a function in a single page request.

Once the page has reloaded (e.g. when you submit your form), the memory for the original object is freed and it's impossible to maintain a reference to it (at least with standard PHP to the best of my knowledge).

You can keep a copy of the object (which is what Drupal does), and instantiate a version of it on the next page, one that has exactly the same characteristics as the original even, but it's not a reference to it.

What you're doing is absolutely fine, but if you're worried about changes being made to the object after it's been attached to a form, but before it's been submitted, then you should keep hold of the object's identifier instead, and use whatever helper function is available to re-load that object in the submission process. That would be safest I think.

But if your class is dumb, and doesn't have DB persistence/unique identifiers/something that's going to be changed by some other part of the system, then just add it as a value as you're doing already.


Confusion about files permission Accrding to drupal docs:

The following is an example file listing of a safe configuration showing two files in a site where uploaded files are stored in the "files" directory. In order to see the file permissions set for your setup, go to the command line and type: ls -al.

drwxrwx---  7 www-data    greg-group  4096 2008-01-18 11:02 files/
drwxr-x--- 32 greg-user   www-data    4096 2008-01-18 11:48 modules/
-rw-r-----  1 greg-user   www-data     873 2007-11-13 15:35 index.php

After running the shell given in the doc page,

#!/bin/bash
if [ $(id -u) != 0 ]; then
        printf "This script must be run as root.\n"
        exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
# Parse Command Line Arguments
while [ $# -gt 0 ]; do
        case "$1" in
                --drupal_path=*)
            drupal_path="${1#*=}"
            ;;
        --drupal_user=*)
            drupal_user="${1#*=}"
            ;;
        --httpd_group=*)
            httpd_group="${1#*=}"
            ;;
        --help) print_help;;
        *)
            printf "Invalid argument, run --help for valid arguments.\n";
            exit 1
    esac
    shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
    printf "Please provide a valid Drupal path.\n"
    print_help
    exit 1
fi
if [ -z "${drupal_user}" ] || [ $(id -un ${drupal_user} 2> /dev/null) != "${drupal_user}" ]; then
    printf "Please provide a valid user.\n"
    print_help
    exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
    find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
    find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done settings proper permissions on files and directories"

bash fix-permissions.sh --drupal_path=your/drupal/path --drupal_user=greg

After running the above script, the Security review module still warns me that:

Some files and directories in your install are writable by the server.

Ironically the doc page also links to the security review module for double check:

  As a quick test to confirm whether your site is secure or not you can
  run the Security Review module.

Does this mean that there is something wrong in the script? or in the security review module alert if false? Or simply there is no consensus in Drupal community about the files permission? Too bad, if it is so.

This can be a huge security hole when the permission to the uploaded files are not set properly. So I am wondering what is the proper permissions for files for a fairly paranoid setup?

Also, should greg be member of www-data group?

Your example permissions (as listed near the befinning of your question) are fine.  The Drupal docs page you link to is correct and reflects IMHO the consensus of the communty.  The script you're using reflects this consensus.

I'd say that this is a false postive from Security Review. It also appears that this bug has been reported to the module's issue queue.

As stated on the Drupal docs page: All you need to know to review this yourself is that it is only files/ and the directories and files below it that shall be writeable by the server.  So if the character wshow up in anything owned by www-data or the www-data group on your site (letter 3 in the permission string is the setting for the www-data user, and letter 6 is the the setting for the www-data group) - then the site is not secure.

While it may appear insecure that files/, its subdirectories and uploaded files are writeable by the server, this is not the case. Drupal itself and the way Drupal sets up the web server (by means of .htaccess, etc. ) prevents code (shell scripts, php, etc.) that an attacker may upload (disguising it as an JPEG or other "allowed" upload file types) from being excuted.  Drupal has built-in management of uploaded files that ensures, for instance, that file attachements is deleted when the node they're attached to is deleted.  For this to work, the upload directory (e.g. files/) and the files it contain must be writeable by the server.

Also: greg should not be a member of the www-data group.


Exporting a custom module from one instance to another I am new to Drupal. Currently I am using Drupal 7.4.

Hhow to export a custom module from one instance to another instance?

Note: copy the module to the new site didn't work.

Here are the steps you need to do:

Before you try anything, make sure you have a backup of everything
Copy the module directory into the correct directory in the other Drupal site
Enable the custom module

from the /admin/modules page
from the command-line using the drush en MODULE command

If the module requires any configuration, then you will have to do the configuration on the second website as well

If you have used the features module, it can be helpful in transferring module configuration


Block/mosaic type homepage with heavily interactive menu I wanted to know if this was possible to do for a Drupal website like this website has the main navigation how it works and interacts with the main content layout. http://goo.gl/HQ4P8H

What modules must be used to do that? I am okay if it needs .js for the 'effects', but I want to understand how it works when loading new stuff from navigation while in the same page without refresh.

Also when you hover on blocks it gives various/interactive content, menus and links. How is that done on Drupal? Is it something can be pulled of from Views and then applying jQuery to output content in that way while on hover?

So in overall I wanted to know if this can be achieved without custom php coding, because I am not programmer, if it's only .js .css and modules that would be great to know which ones.

Cheers.

There is a module to do that, but you have to customize it. It have the animation option using filter, probably you can try to use that filter as menu or change that filter like menu using CSS.

Views Quicksand see the Demo and website using Drupal.

  Quicksand is a JQuery Plugin that provides a nice animation for
  filtering or reordering lists of content. Views Quicksand integrates this effect into Views. Therefore it provides a views style-plugin, which allows you to alter most settings the quicksand plugin provides.


When should hook_post_update_NAME() be implemented instead of hook_update_N()? What I found so far is that certain actions are unsafe to be performed inside hook_update_N(), but I didn't find any documentation saying which those actions are.

When should I implement hook_post_update_NAME() instead of hook_update_N()?

Normally when you update Drupal core locally you perform the following:
composer update
drush updb
drush cex

Let's say that there's a core module implementing hook_update_N() to update some content or config – an update that triggers entity load and entity save somehow. Now let's say that in some other core module inside some other hook_update_N() are updates to the database schema which in the end handles how this content or config is actually stored. How can you reliably ensure that the schema updates run before the content/config updates, especially when some users update their site skipping some few minor releases at once?
So hook_post_update_NAME() was introduced to guarantee all schema/structure/format updates have run first and now can be relied on when needing to update content or config on top of them.

[Issue] Add hook_post_update_NAME() for data value updates to reliably run after data format updates
[Change record] hook_post_update_NAME() introduced to change content after hook_update_N() runs

Now let me also tell you that the most reliable hook for simple content updates from a custom module is hook_deploy_NAME(). This hook was introduced in Drush 10.3.0 together with the new drush deploy command. Using this new command to replace the old drush updb && drush cim deployment routines all hook_deploy_NAME() implementations will be picked up after configuration import. Which totally makes sense when you want to populate a new field which has only been created and added to config in the same release.

[Issue] Add hook_post_config_import_NAME after config import


rules_invoke_component() - Getting the value of the Provided Variable In my code, I am using rules_invoke_component() to invoke a Rules Component.

On that Rules Component, have 2 variables.

Parameter
Provided

I am successfully able to invoke the Rule and send the Parameter Variable to it (In this case it was $node). But I am just confused on how to get the value of the Provided Variable.

Is that possible?

From the "Tiny book of Rules":

Invoking components programmatically

Rules components are handy tools for allowing site builders to customize their own actions and
conditions. If you are writing a module that allows site builders to set custom conditions (or
actions), you can let them set these up as Rules components and then evaluate selected components
programmatically. This works in a way analogous to invoking events, by using
rules _invoke_component() .

The first argument is the (machine) name of the component, and any subsequent arguments are
variables sent to the component.

// Included somewhere in your custom module.

$component name = $settings [' rules component name'];

// Any variables provided from the component are returned from its evaluation.

$result = rules _invoke_component ( $component_name, $var 1, $var 2 ) ;

So the last 2 lines in the quote above should answer your question.


Downloading a Feature I may be thinking about this the wrong way, but I would like to download a feature that is already created. I know how to create a feature and download it, but how do you download a feature that already exists so you can use it on another site? Preferably in Drush.

I'm using Drupal 7.50. Thanks!

Edit: I figured out that in the UI, if you create "recreate", you can download it from there. How can this be done in drush though?

You can use my very favorite drush command:

drush fu your_feature

This is the same as using "recreate" in the UI except that it will update your feature directly where it resides in your code base (usually at /sites/all/modules/your_feature).

Now you can copy that folder (or zip it up if you like) and use it on any site you'd like.


How do I dynamically modify a block's mark up at render time, in Drupal 7? I have a page with the following structure:

Header zone

Header One Area (block)

Content zone

Content Area (node)

The rendered node has an image attached to it. What I need to have happen is to make the attached image render inside the "Header One Area" block instead of as part of the content.

This is proving difficult, since blocks and their #markup are rendered before a node is processed. The better idea I had is to create a preprocess function for the page, through code figure out the node_id being rendered, grab its images, and then dynamically modify the blocks markup.

I have tried creating a MYTHEME_preprocess_page() method inside my template.php and then accessing the block via:

if ($block = block_get_blocks_by_region('header_one_area')) {
   // what code do I need here to make a #markup modification stick ???
   $block['block_4']['#markup'] = "
TEST
";
   print kpr($block);
}

I'm not quite sure how to actually modify its markup dynamically before it is rendered here.

Do you have any suggestion?

I think you are looking for hook_block_view_alter(). It provides both the alterable $data, as well as $block, which contains the module and delta.

To determine which blocks are available, you could start off with:

function MYTHEME_block_view_alter(&$data, $block) {
  kpr($block->module);
  kpr($block->delta);
}

Then once you find the module:

/**
 * Implements hook_block_view_alter().
 */
function YOURTHEME_block_view_alter(&$data, $block) {
  if ($block->module == 'block' && $block->delta == 1) {
    $data['content'] = '
New content
';
  }
}

Or even:

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_4_alter(&$data, $block) {
  $data['content'] = '
New content
';
}


Recommendation for modules/workflow to build a premium link directory I'm just about to start building a link directory and I'm at odds over the best way to go about it.

The directory will accept both standard (free) and premium subscriptions. Premium subscribers will have extra fields available to them to fill out and display on their 'profile' page (standard link directory model I guess).

The front-end directory itself will be based on taxonomy/views so that's not an issue, but I'm struggling with the best way to handle the subscriptions. Conceptually I guess I would be selling access to a user role for a limited period of time, and showing/hiding various fields on the profile form based on the role's permissions.

I'd prefer to use Commerce and I'm struggling to find a stable module (or example using rules) that would help me plan out this subscription system.

Has anyone built a similar system before? If not can anyone think of a good collection of modules/workflow to accomplish this? I'm happy to write as much custom code as is needed but I'd rather not reinvent the wheel where possible, and it seems like Drupal is made for this kind of thing.

EDIT

Following Patrick Kenny's comment I should add that I don't need these subscriptions to recur automatically, just for the access to the role to expire after a certain amount of time.

If this will be difficult to do with Commerce I'd love to hear any other ideas (Ubercart, etc).

I'm building a site with free and paid memberships now; my use case isn't exactly the same but I'll share what I can.

I'm not using Drupal Commerce; in my case, users make a payment with PayPal and then I manually add a paid role to each account.  I intend to eventually set this up in Drupal Commerce but I haven't had the time yet.

When I add the paid role, a rule is triggered that automatically sets an expiration date using the Role Expire module.  Until very recently the 7.x rules integration was bugged but I am happy to report that it is now fixed and works great.

As for working with Commerce, Randy Fay also did a screencast on setting up content access for a membership site.  I'm not sure if the content access part is relevant but the final part of the screencast covers:

  Create a product representing the premium role.
  Create a rule that grants the premium role on order completion:

  After updating an order
  If the order state is Completed
  And the order contains our premium product
  Add a role to the user who is the owner of the order


User permission to edit only nodes with taxonomy term I want to let my customers only edit nodes that have a specific taxonomy term.

For example i have user TimCook from company Apple. He got the role "customer" and i want to give him the right to edit nodes only with the taxonomy term "apple" of the vocabulary "company".

I didn't find any module for this. Maybe there is one, or someone has a hint where i should start to make an own module.

Taxonomy Access Control Lite module should help you.

  This node_access module governs access to nodes based on the taxonomy
  terms applied to the nodes. A simple scheme based on taxonomy, roles
  and users controls which content is visible.


Query that converts a timestamp to a date Is it possible to convert a timestamp to a date format in a query?

This is the code I am using.

$query = db_select('my_submissions', 's');
$query->fields('s', array('sid','name','company','email','phone','is_customer','submitted','count'));
$entries = $query->execute();

$rows = array();
foreach ($entries as $entry) {
  $row = array_map('check_plain', (array) $entry);
  $row['submitted'] = $row['submitted'] ? date('d.m.Y H:i', $row['submitted']) : "";
  $rows[] = $row;
}

$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(submitted), '%d.%m.%Y %H:%i')", 'submitted_formatted');

http://www.w3schools.com/sql/func_date_format.asp

then in your loop, reference it as $row['submitted_formatted'];


"Aggregate and compress CSS files" and "Aggregate JavaScript files" in performance settings, is not working This thread contains the most information I've been able to find about this: #986558: "Aggregate and compress CSS files" and "Aggregate JavaScript files" in performance settings, is not working

I have 2 d7 sites. One is in public_html/ on my server and has no problems. The other is in a sub-directory, and breaks when turning on Aggregation/Compression of css & js files (in admin/config/development/performance ).

When I turn on js performance, my js doesn't work. When I turn on css performance, no css loads on my site in Firefox or Chrome, but does load in Safari. According the the above-mention issue, it's because of Drupal & my server sending compressed info to the browser, which can't decompress it and thus, I get no js or css.

Following a recommendation, I disabled these in my .htaccess file:

#Header append Content-Encoding gzip
#Header append Vary Accept-Encoding

What that did, however, was break some of my css, and load a "skip to content" area in the top of my website (which, if you do theming, you might be familiar with seeing that as a hidden html element that is loaded).

I'm not sure what to do to fix this. I encountered it the first time I built this site, but was using D7-rc1. I rebuilt it hoping new core/module updates would fix it, but this site is running on D7.7 now.

Please help. Thanks.

Well, this issue is ongoing at http://drupal.org/node/986558 . The Drupal-7.9 should have fixed it, and it did fix my css, but I am still having issues with js.

Note: if you have this problem and upgrade to Drupal-7.9 , make 100% sure you replace all of your .htacess files.


Why is the CSS rule that I applied via the CSS injector module not active on my mobile device? I have a panel row with two regions and I wish to re-order the
display for mobiles. Below is what I wish to accomplish:

And I thought it would be as simple as the below css rule :

@media screen and (max-width:480px)
{
   .pane-2
    {
    display:block;
    }
}

But nothing happened with the above rules.

I am using the CSS Injector module to apply the above css.

Can anybody help me with this one?

Clear cache or CSS aggregation bug

Comment #1 in issue # 1588822 contains some interesting hints that might help to answer your question:

to see the changes, you must clear the cache. Since your question doesn't mention anything like that, make sure you did cear the cache.
bugs in CSS aggregation can be problematic with specific CSS constructs. If you trigger one of those, it can result in CSS being omitted from the aggregation CSS file.

CSS rule overwritten by another module

And the rules provided by this module might be overwritten by another module, as briefly mentioned in the last paragraph of the module's readme.txt ...

CSS edits via external editor

CSS edits via external text editor not displaying (which only applies to the 7.x-2.x version, not to 7.x-1.x) might be what's causing the issue.


Change size of views exposed form search box Im using hook_preprocess_views_exposed_form to change the output of my views exposed search box.  I am able to successfully change the text on the search button, but I am not able to change the size.  I cant figure out where I am going wrong.  Here is what I have:

function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // dsm($vars['form']);
  if ($vars['form']['#id'] == 'views-exposed-form-all-page') {
    $vars['form']['submit']['#value'] = t('Go');
    $form['text']['#size'] = '90';
    unset($vars['form']['submit']['#printed']);
    $vars['button'] = drupal_render($vars['form']['submit']);
  }
}

This is what I am stuck on:

$form['text']['#size'] = '90';

I think it would be better to change the form sooner than during themeing ... the best is to implement a form_alter hook, in this case

  function MODULENAME_form_views_exposed_form_alter(&$form, $form_state)

you can try to dpm($form) first, to see what exactly you should change, and probably also add a condition about module id.

if you install advanced_help, this info can be found on your site at help/views/alter-exposed-filter :)


How allowing img tag in formats can be dangerous? I get this recommendation form Security review module:

  It is recommended you remove the following tags from roles accessible
  by untrusted users: img

I am wondering what real world threats can img pose?

Project page of security review module says

  Text formats don't allow dangerous tags (protecting against XSS)

  Cross-Site Scripting (XSS) attacks are a type of injection, in which
  malicious scripts are injected into otherwise benign and trusted web
  sites. XSS attacks occur when an attacker uses a web application to
  send malicious code, generally in the form of a browser side script,
  to a different end user. Flaws that allow these attacks to succeed are
  quite widespread and occur anywhere a web application uses input from
  a user within the output it generates without validating or encoding
  it.

  An attacker can use XSS to send a malicious script to an unsuspecting
  user. The end user’s browser has no way to know that the script should
  not be trusted, and will execute the script. Because it thinks the
  script came from a trusted source, the malicious script can access any
  cookies, session tokens, or other sensitive information retained by
  the browser and used with that site. These scripts can even rewrite
  the content of the HTML page.

For example you can use img tag as below for XSS attack..

<img src='#' onerror=alert(1) />


create layouts without the use of embedded regions from my experience with Drupal, I could understand, that you can thematize the page.tpl.php file, adding the appropriate html / css and entering regions with php.
So far so good ....
but my approach I'm following this project is to thematize the file. tpl.php corresponding to each of my content type. Now I need a page to bring them all together, I did it successfully using the "Panel". But I would adopt the approach in my opinion the most flexible layout with html / css.
On which page should gather instances of my various themed content type?

Your best option really is Panels, especially once you get comfortable making your own panel layouts (which is actually quite easy).  Along with using preprocess hooks to attach classes (particularly to body) as needed, the combination of the three lets you do pretty much anything you want.  I have yet to been given a design treatment from my creative director (and they are all complex) that I have not been able to tackle this way.


Create link with 'name' attribute only using l() function Is it possible to create a link using Drupal's l() function without an href? For example, I'd like to create a link like the following:

A link here

However, this seems to not be possible. The closest I can come is to use the following:

l(t('A link here'), '', array('external' => TRUE, 'attributes' => array('name' => 'my-anchor')));

This outputs:

A link here

... and that's not valid HTML. It also causes slightly strange behavior in some browsers depending on the CSS applied...

Sadly this cannot be accomplish with the l function because the href is hard-coded in the theme_link theme function.

You can accomplish this by using the html_tag theme function.

It'll look something like this

return theme('html_tag', array('element' => array('#tag' => 'a', '#value' => 'A link here', '#attributes' => array('name' => 'my-anchor'))));

This will return

A link here

Is a bit more work, but it does give you a properly formatted a tag with out the href.


Responsive menu breakpoints I want to change the breakpoint of the Bootstrap Responsive Menu, from 768px to 900px. There is a simple way to do this by modifying @grid-breakpoint in variables.less; I have installed the less module, but yet changes there are not having any effect.

The code for the media query is being called in bootstrap.min.css via CDN. Can someone help? How do you recompile the CSS after making changes to the .less file?

On Bootstrap's site you can configure what you want and download; in Drupal this isn't the case, nor is there any config in the admin UI, to make these simple changes.

You can override the set media queries in your custom css or less files. For the menu, you need to change at least two classes like so:

To hide the menu in a wider breakpoint (> 768)

@media (max-width: 900px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}

To hide the menu in a smaller breakpoint (< 768) you have to override everything from your breakpoint up to 768:

@media (min-width: 480px) and (max-width: 768px){
  .navbar-toggle {
    display: none;
  }
  .navbar-collapse.collapse {
    display: block;
  }
}


Rating system - Five star problem I tried to use 2 modules, FiveStar and Rate to put rating system on a new custom content I created but neither worked.

When I try to put FiveStar in a field of my content it shows me this error:

I don't know why but if I don't put any star on default rating it won't work..
So I have to put my products since they are created all by default with some rank (from 1 to 5 stars or 10 if I change the number or stars they can have)for this to work and that's kind of bad..

I wanted my products to come with no evaluation/rating when they are created.

EDIT:
Now with the rate module I manage to do this, but I now how I change from thumps up/down to stars (from the module or a costumized ones) ?

I recommend using the Votingapi Widgets module based on the Voting API in D8, it works and does the same as Fivestar.
Some more details about this module (from its project page):

A flexible field based Voting System based on Voting API.
You need Drupal Version >= 8.2.3. (Multiple form instances on a page).

Be aware: only an alfa3 release for D8 as of right now.


Excluding inline images in views I have a node type with an image field and insert button to get the image into the text field.

Then there is a view that is getting the content of the text field and shortening it to 150 characters. But if there is an inline image at the beginning of the text the view is only showing three points that are linked to the image.

How can I exclude the inline images from views?

You could use the Rewrite results option on that field and choose Strip HTML tags.

This will "remove" the image from display.

If you have some other HTML inside the Body that you want to keep you can enter them into the Preserve certain tags field, for example <em> <span> <p>.


Build menu based in Vocabulary (Taxonomy)? I just follow this tutorial to build a menu based in the tags vocabulary. Everything is fine but now if I add a new term in admin/structure/taxonomy/tags/list the menu doesn't update, I mean that the new added term doesn't show up.

The problem is that I can't find to check: Synchronises change to this vocabulary because
I don't have this option in admin/structure/taxonomy/tags/edit as showed in the tutorial. Maybe this is because I'm using D7 and the tutorial is for D6? Where are these options in D7?

Try to use the development snapshot for Drupal 7. The update is available in that version.


How to show "Alternative text" of image fields in a custom content type? I created a custom content type that its name is News and has an image field with news_image machanic name and I added an alternative text to it from administration page,
now I want to print that alternative text when the node content type twig template rendered.
what I want to achieve finally is schematically something like below:

<img src="#" title="#" alt="Alternative text">

  It seems this problem can be traced back to custom content type only
  because alternative text can be printed without any problem in default content type like article.

you can get "alt" property with node.FIELD_MACHINE_NAME.alt (and for image title as the same ), So your answer is

<img src="{{ file_url(node.field_news_image.entity.fileuri) }}" alt="{{ node.field_news_image.alt }}" >


How to display a block for pages that don't show nodes? My Drupal 7 module creates a block, and then in admin I can make it available for the Article content type only. I would also like it to be available to the result page for a Product Search. This page is not of a normal content type and comes to life in hook_menu().

The path for the results will be avantlink-search-results/search term and I would like it to show the block with the search form again. I would rather not use the PHP code option in the block visibility options so as to keep it simple for users of the module.

The code is viewable on AvantLinker.

I think you may want to take a look at the context module. That allows you to define multiple conditions for displaying blocks.

However, you should also consider making your module only return content on pages that it makes sense to appear on. So the user doesn't have to worry about complex configuration.


How to change rest export views field alias programmatically When using REST export view, and Fields format, under Settings I can change alias for each field.

How can I do the same with code?

You can create a ViewsField Plugin with the custom module and name whatever you want.


How to change view REST export format This is my settings in view.

Data what I have is now in this format:

[{"created":"1551709414","field_iot_integer":"43"},
{"created":"1551709404","field_iot_integer":"98"},
{"created":"1551709392","field_iot_integer":"58"},
{"created":"1551709382","field_iot_integer":"4"},
{"created":"1551709373","field_iot_integer":"65"},
{"created":"1551709356","field_iot_integer":"23"}]

I would like to change this format in this, rid of all comments. :

[[1551709414,43],
[1551709404,98],
[1551709392,58],
[1551709382,4],
[1551709373,65],
[1551709356,23]]

How I can achieve this?

To change the structure of the Serializer output you should create a custom Serializer here is the steps of your use case:

Create CustomSerializer extends the Drupal\rest\Plugin\views\style\Serializer and update the render method to your needs.

Create MY_MODULE/Plugin/views/style/CustomSerializer.php

namespace Drupal\MY_MODULE\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "custom_serializer",
 *   title = @Translation("Custom serializer"),
 *   help = @Translation("Serializes views row data using the Serializer
 *   component."), display_types = {"data"}
 * )
 */
class CustomSerializer extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $row_render = $this->view->rowPlugin->render($row);
      $iot_integer = 0;
      if (isset($row_render["field_iot_integer"]) && $row_render["field_iot_integer"] instanceof \Drupal\Core\Render\Markup){
        $iot_integer = (int) $row_render["field_iot_integer"]->__toString();
      }
     $rows[] = [
        $row_render["created"]->__toString(),
       $iot_integer
      ];
    }
    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }
    return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);
  }
}

Clear Cache:
Go to your view and change the format from Serializer to Custom serializer like

The result:


How to implement an E-commerce solution for a jobboard? What would be the best way of achieving this goal:

From a jobs board (A content type called jobs)
User picks particular job
User is asked to complete a form including:

Checkboxes (for terms and conditions)
Document upload (CV, picture etc)
Other basic details (name etc)

User then pays a fee via eCommerce caperbility
All the information and documents are available for admin to view.

Any suggestions?

This can be easily done with the Recruiter Distribution and Ubercart or Commerce.

If you are not using the recruiter distribution you can used the Profile2 to created to ask

  - Checkboxes (for terms and conditions) - Document upload (CV,
  picture etc) - Other basic details (name etc)

For the Terms and conditions you can used the Site Disclaimer module.

You need to created a role that allows them to register to the website and created a profile. After that you can add a button to Upgrade their to another role which would give the user the ability to see or do more stuff in your website.

You can follow this tutorial to learn how to upgrade a role with Ubercart. How to Configure Drupal 7 and Ubercart to Sell User Roles


Possible to extract multiple key/value pairs (links) from string in CSV and migrate into multiple link field I am using migrate source CSV and trying to extract a string which contains multiple key/value pairs of links in format:

"Google.com|https://google.com,Yahoo.com|https://yahoo.com"

I need to save the values into a multiple link field.

The logic I need to run is:

- Explode the string on comma ,
- Iterate each item
  - Explode string on pipe |
    - Extract index 0
      - Store to field_link/title
    - Extract index 1
      - Store to field_link/uri

I have it working using a custom process plugin but would like to try and achieve this if possible through chaining of the core process plugins in the migration config yml file.

Thanks

Here is my solution to solve a similar problem:

temp_data:
  -
    source: data
    plugin: explode
    delimiter: ','
  -
    plugin: explode
    delimiter: '|'
destination_field:
  plugin: sub_process
  source: '@temp_data'
  process:
    field_attr_1: '0'
    field_attr_2: '1'
    field_attr_3: '2'

Hope it helps.

Regards,
 M.


How do I programmatically use an external database? How do I programmatically use an external database?

$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store its data.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

Setup the external database on settings.php
Select the correct database

$con = \Drupal\Core\DatabaseDatabase::getConnection('default','my_other_db');

I took the example from
 http://www.drupal8.ovh/en/tutoriels/175/use-multiple-databases-drupal-8.


How come my views suddenly take full width? I don't know what I've changed but now 2 of my views are full width.
Here's 2 screenshots from a view how it was and how it is now.
How can I change this back to normal?

Though it is cut off in the screenshot you have above, the spitfire.jpg image is forcing that cell to 968px wide (968x478) which is larger than your main cell.

This is more a CSS question than a Drupal one so to bring it back to Drupal, I would recommend that you create an image style for this imagefield so that all images are resized according to the width of your main cell. Check out the image module documentation for guidance on how to create styles, you would then just need to tell views to use your new style for your view. Alternatively, you can use one of the existing styles (ex. thumbnail, small, medium, large) to have views display an image that would fit on your page:


How do I hide  the main menu items? I have users who are the owners of some nodes, and each node has a menu link in the main menu. Users can only see the nodes they own, and they cannot see other user's nodes.

The problem now is that the menu is displayed like in the following image, for all the users; it shows links for both the nodes owned by the current user, and the nodes the current user doesn't own.

I would like to display only the menu items corresponding to the nodes owned by the logged in user. How can I do this?

Drupal will hide menu items for paths that users don't have access to. But for this to work, it requires that the access callback for that menu item returns FALSE. If you handle access control in the menu callback instead, Drupal won't know that the user doesn't have access and will display the menu.

A solution would be to implement a custom access control module/function if you can't use any of the existing for the nodes.


User edit form on custom page is resetting roles when user belongs to the "Administrator role" I'm trying to display the user edit form on a custom page with limited fields. Submitting my form works well, but if I have the Administrator role, roles are reset. I don't understand why this is happening.
This is the routing file custom_user_profile.routing.yml.
my_module.default_controller_view:
  path: '/my_module'
  defaults:
    _controller: '\Drupal\my_module\Controller\DefaultController::view'
    _title: 'Account'
  requirements:
    _user_is_logged_in: 'TRUE'
  options:
    no_cache: 'TRUE'

In the controller DefaultController.php I have

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;

class DefaultController extends ControllerBase
{

    public function view()
    {
        $user = User::load(\Drupal::currentUser()->id());

        $html = '';
        $html .= '
Current email is ' . $user->mail->value . '
';

        $data['html'] = [
            '#type' => 'markup',
            '#markup' => $html,
        ];

        $user = User::load(\Drupal::currentUser()->id());
        $formObject = \Drupal::entityTypeManager()
            ->getFormObject('user', 'default')
            ->setEntity($user);

        $form = \Drupal::formBuilder()->getForm($formObject);

        $data['form'] = [
            'form' => $form,
        ];

        return $data;

    }

}

In the my_module.module I have following code.
use Drupal\Core\Form\FormStateInterface;

function my_module_theme($existing, $type, $theme, $path)
{
    $templates = array(
        'my_module_about_form' => [
            'render element' => 'form',
        ],
    );

    return $templates;
}

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if ($form_id == 'user_form') {
        $form['#theme'] = ['my_module_about_form'];
    }
}

In the template file my-module-about-form.html.twig I have the following lines.
{{ form.timezone }}

{{ form.form_build_id }}
{{ form.form_token }}
{{ form.form_id }}
{{ form.actions.submit }}

The form values still persist in the form state, and as they're not printed, the will be submitted as empty and saved accordingly.
Do not hide form element by not outputting them in twig, render the full form there and use [#access] = FALSE; on the form elements you don't want to show. Do so in the controller, to only have that on your custom page. If you do that in hook_form_alter it will apply to the form always (so here also for the profile page aka /user/X/edit).

You're mixing two concepts: Showing a form (where you have full
control and can add stuff before and after with entries in the render
array and use a form-mode for the form, so you can configure the
fields via UI and not code) and altering a form (where you do not
control where it is shown, and want to change it everywhere). I guess
you want to show a form, so I would remove the theme stuff and
concentrate only on the output form your controller.

Or even use a different approach .. and create a new form from scratch, populating with the user's value, and save them back to the user entity on submit (If you only need one "field" and even the password fields can be replicated in the custom form).
And replace the controller with a form callback in routing.yml.


Translate Taxonomy menu items I have a vocabulary that I want to shows as menu. For this, I installed the taxonomy menu module and edit the vocabulary to hang from a menu item of Main Menu. The menu is shown perfectly.

The problem goes when I localize the terms of vocabulary, the menu is only shown in a default language. I have tried to rebuild the menu (by checking the "Select to rebuild the menu on submit." on vocabulary edit page and submitting), but the problem persists.

Entity translation

  Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.

together with Title module - (making the taxonmy terms translatable)

Title module

  After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.


How do I download a dynamically-created file in a form submission? I've got a form that builds an array of data. On submission, it updates a table displayed in the browser, using AJAX; that works fine.

I want a second submit button that downloads the same data as a CSV file. I've tried a number of variations, but I can't seem to both send the file response and satisfy the AJAX requirement for a returned array.

The button:

$form['download'] = [
  '#type' => 'submit',
  '#value' => $this->t('Download data'),
  '#weight' => '40',
  '#ajax' => [
    'callback' => '::downloadCallback',
    'event' => 'click',
  ],
];

...and the response section of the callback:

$file_content = $serializer->serialize($data, 'csv');
$response = new Response($file_content);
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'data.csv');
$response->headers->set('Content-Disposition', $disposition);
$form_state->setResponse($response);

I've also tried using this instead of setResponse:

$response->send();

These all result in an error:

  TypeError: Argument 1 passed to Drupal\Core\Render\MainContent\AjaxRenderer::renderResponse() must be of the type array, null given, called in /mnt/www/html/mowebd8dev/docroot/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php on line 89 in /mnt/www/html/mowebd8dev/docroot/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php on line 45 #0 /mnt/www/html/mowebd8dev/docroot/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php(89): Drupal\Core\Render\MainContent\AjaxRenderer->renderResponse(NULL, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))

I've tried also returning a simple render array with some dummy markup, and that prevents the error, but still doesn't result in a file download. Is there a way to accomplish this? Or should I just not be using AJAX for this purpose?

I was off-track in even trying to do this with AJAX, as Clive mentioned in his comment. Instead, I just made it a normal submit button, and then overrode the form action. The result is that the data is downloaded as a file, the form doesn't reload, and the data output section doesn't update, which is the desired behavior in this case.
The button, along with a new format element:
$form['download']['format'] = [
  '#type' => 'select',
  '#options' => $this->getValidFormats(),
  '#title' => $this->t('Select format'),
  '#weight' => '0',
];
$form['download']['download'] = [
  '#type' => 'submit',
  '#value' => $this->t('Download'),
  '#weight' => '10',
];

The submit function:
public function submitForm(array &$form, FormStateInterface $form_state) {
  switch ($form_state->getValue('op')->__toString()) {
    case 'Download':
      $this->download($form, $form_state);
      break;
  }
}

And the relevant part of the download function:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$response = new Response($file_content);
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'data.' . $format);
$response->headers->set('Content-type', $content_types[$format]);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Content-length', strlen($file_content));
$form_state->setResponse($response);


Using a variable inside a print I have the following code:

print $node->field_carousel_1[0]['filepath'];

What I would like to do is changing the 1, and use a variable instead.

Do you have any idea how I would be able to do this?

What I am aiming for is using a variable to create a looping function to print
"field_carousel_1," "field_carousel_2," "field_carousel_3," etc.

You can just change the 1 to your particular variable in the loop.

Example:

foreach ($values as $k => $v) {
  print $node->field_carousel_ . $v . [0]['filepath'];
}

That should output the values you need.


How can I order views Attachments in views page I have created to views attachments and placed them after my views page.
But the issue is the order of the attachments is in reverse.
How can I add weight to them?

Actually Drupal have re-order display, but I think it is for admin page only.

I also got same problems as you, but finally I found a way.

1) Click to ADVANCE.

2) Click to the machine name and edit it by ABC order.

Hope it will help.


Get only one value from a multivalue field in template node I have a content type which has a multivalue image field. I need to create a template that displays a list of nodes of that type but displays only one value of that multi field, not all of them together.
I know we can do if we use views under 'multiple field settings' which is explained here
views 3: select only one value from a multivalue field but I am not using views, Can we do using only template nodes?

node title1

first image

node title2

second image
etc

Please help.

Assuming you already have a node template for that content type already (if not then you can read more here). Within the template, instead of outputting all content in one print command, you'd break them down into the fields you need. Then you can output the image field and  programmatically limit it to the first value, as described in this SE post.


Entity reference item list with preview images? In a node type 'album' I have an entity reference field 'photo' that can be used to reference nodes of the type 'single_photo'. This works fine – using the module Entityreference view widget lets the editor choose nodes from a lst view with a preview image and optional additional fields:

The actual list of referenced nodes however does only show the node title:

I now would like to have a similar preview in the actual item list – or maybe even also use other fields of the referenced nodes. Is there a similar module or a combination of views and code or the like, that would provide such a functionality? Any pointers, suggestions, links would be appreciated.

The Entity Browser module almost does exactly this (for Drupal 8). The module allows you to create a view display (it adds a new Entity Browser display type) to select items and it also allows you to, via a configuration on the referencing entity's Form Display screen, display a referenced entity's view mode on the edit screen.


The pdf_thumbnail plugin does not exist After I tried to update the database I got the following error:

  Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException:
  [error] The "pdf_thumbnail" plugin does not exist. in
  Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52
  of
  /home/www/sites/stdev/web/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

I tried to find the solution and found one of a similar issue:

drush updb fails with "the 'media_delete_action' plugin does not exist" after 8.4.6 > 8.5.1 update

Alas, I can't apply that solution because I don't know which module uses the pdf_thumbnail plugin. How can I find it out which module uses the plugin and solve the problem with the update?

I resolved this by first re-enabling the PDF module, and then by updating core.

In my composer setup, the PDF module was a git submodule.  However, my shared host would not work with that.  So, I removed the cached information

git rm --cached web/modules/contrib/pdf

And then I added the code in that directory to my main repo.

Next, enable the PDF module.

Finally, proceed with the update process, and run update.php or drush updb


How can I filter the apachesolr_autocomplete results on a custom search block We recently set up solr search and have been happy with it. I started using the custom_search module to set up pre-filtered search results, and while my solr search pages work well, the autocomplete search suggestions return ideas from the full site.

Is there any way to filter them based on content type?

This seems to be the D.O issue for this:

https://www.drupal.org/node/1444038 (enables per-search-page support for autocomplete)

along with this...

https://www.drupal.org/node/326375 (enables having a search form block per each page)


Run hook_init on every page except AJAX page executions In my hook_init functions I often check what the current page is before loading js or css files and in some cases control actions on module stored session info based on values in the session and the current path.

The module I'm currently working on stores extra information for orders users choose to use Checkout by Amazon to pay for. I haven't spent the time to figure out how to make CbA work as a payment method yet so right now I have to alter the Ubercart checkout form to include their widgets and then hijack the form submission to handle the API calls and build its own review and completion pages.

I store the necessary information in a module specific session variable. If the user reviews their order then goes back out to any other page, I keep the session going, only destroying the order so it can be rebuilt when they go to checkout again.

Now the issue I'm having is that I have two cases where the whole session needs to be reset.

If the user completes the order then moves to any page other than the order complete page
If the user goes to any page other than the checkout page from the review page

The second is usually handled because they'll likely hit the shopping cart page to checkout again if they go somewhere else (I'll be adding a tracker to force people to the cart page if they leave the review page sometime soon).

The issue I'm having is that I am doing this with code like the following:

function uc_cba_init(){
  if(strpos($_SERVER['REQUEST_URI'], '/amazon/') !== FALSE || (arg(0) == 'cart' && !arg(1))){
    if(isset($_SESSION['uc_cba']['order']['complete'])){
      // if on order complete page, remove unnecessary session items for the order, including cart products
      // otherwise delete the module session
    }
  }else if(isset($_SESSION['uc_cba']['order']['complete'])){
    // remove unnecessary session items, cart products, and module session
  }
}

The problem with this is that there are a lot of ajax calls flying around and they tend to trigger the init function which means that when the user reaches the order complete page, the ajax call just before that page clears out the session which destroys the order complete information (no order id given to the user for reference or any other instructions for managing their order).

My question would be, is there a simple way to ensure the init only executes its code if the page it is being executed from is not being called from an AJAX hit?

I can test for the shopping cart page, checkout pages and node pages but that won't be fool proof since it won't catch views, taxonomy and other module generated pages that do not have a source path of node/X.

You can check if you're processing an AJAX request or not in your hook_init() and skip your code if you need it.

function uc_cba_init(){
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Is an AJAX request...
  }
  else {
    // Is not an AJAX request...
  }
}

Hope it helps!


Run hook update N in different batches I am trying to update drupal. I want to break the updates into 2 different runs/groups. I want run the second batch of updates after the first is done.
The first batch contains the updates from the drupal update and the second should contain the custom ones.
Is this possible in any way?

I think you can do this by Drush.
Install drush

1. drush up drupal  ->> it will update only core drupal
2. drush pm-update --no-core <modulename>   ->> it will update only mentioned module.


Javascript & Ajax failed to load on many pages like field editing & views editing pages. The site I'm managing is runs by Drupal 7.53 with many contributed modules.

I don't know what happened from yesterday, ajax queries in field editing pages and views editing pages throwing errors or not loading at all. Clearly I can see what is causing this error in JQuery and Ajax.
All the modules installed are contributed modules except one custom module, which doesn't have any Javascript code in it. Cleared the cache few times . No javascript and CSS aggregation. But still wherever JQuery & Ajax is needed , the pages are breaking . How can I solve this problem. How can I figure out what is causing problem?

I'm unable to alter any of the views due to ajax error throwing up.
All help is appreciated.

Jquery Update module is very helpful but new jquery versions can cause issues with other dependent modules. The module is important not only to keep your site up to date but also allow for theme-specific control to ensure compatibility. So the module's settings page is something you might want to visit and test when a new jquery version is released.

Also, the CDN option can cause load issues if the provider you choose is offline for some reason or overloaded. From the jquery update settings warning:

  "NOTE: Using one of the "CDN Provider" options below is the preferred
  method for loading Bootstrap CSS and JS on simpler sites that do not
  use a site-wide CDN. Using a "CDN Provider" for loading Bootstrap,
  however, does mean that it depends on a third-party service."

So use this option with caution.


How can I survey anonymous users before they can read content? I want to do a survey for all non-logged in users (a webform or something similar) before they can read a certain piece of content. I want authenticated users to not be bothered with it. These surveys will only be for selected pieces of content.

I have been looking around. I can't find a solution for Drupal 7. I'd like to use webform, but I am open to learning about different options.

Thanks for the help.

I ended up using the rules module along with rules url argument module.

I used the rules module to watch out for anonymous users, and query strings of "?surveycomplete=yes". I did this check for all nodes of my desired type that did not have a node reference to a webform.

If a user was anonymous and did not have the query string, then I redirected to the webform that the node was associated with.

To make the webform redirect appropriately when it was completed I changed the redirect location to the original node with the query string appended.

The downfalls with this approach is that every node that there is a 1 to 1 relationship for content to webforms when a many to 1 would be nice. Also, anyone could technically by pass the survey via appending the query string.


How to change "Save Draft" value on Webform? I want to change the button text value from "Save Draft" to "Save". How can I target the button (CSS or custom module works for me)? I used to target forms like this:

$form['actions']['submit']['#value'] = 'Ask question';

As there are multiple submit buttons, I don't know how to target the one with the class "webform-draft form-submit".

function customisations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {

  }
}

Code to change the text for Save Draft button is:

function customisations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {
    $form['actions']['draft']['#value'] = 'Save';
  }
}

This would change only for Save to Draft button. In order to change the submit button text of the webform, we can use the configuration of the Webform to change it. URL for the same is node/88/webform/configure.

Hope that this helps.


How to pull pictures and summary information from external web pages when posting links? When posting a link (external web page) to my Drupal blog, is there a way to have Drupal automatically pull the picture and summary information from that link and include it in the post on my Drupal blog the way Facebook does it when a person posts a link from an external web page on their Facebook wall or group?

If it is possible, can somebody please point me in the right direction on how to do it.

AFAIK there is no module available for this specific use case. However FBSMP module has its own implementation of crawling links/image/video and other media types from the given URL.

You may need to take that as a base and develop your own version.

Below is the sample code on how its crwaling the links

$result = drupal_http_request($url, array('timeout' => $options['timeout']));

  if ($result->code != 200) {
    fbsmp_log_error(t("Could not connect to @url, HTTP error @error", array('@error' => $result->code, '@url' => $url)));
    return $data;
  }

  $page_url = $url;
  if (in_array($result->redirect_code, array(301, 302, 307))) {
    $page_url = $result->redirect_url;
    $data['title'] = $page_url;
  }

  if (stripos($result->headers['Content-Type'], 'image') !== FALSE) {
    $images = array();
    if (($imagesize = _fbsmp_link_validate_filesize($page_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
      $images[$page_url] = $imagesize;
    }

    $data['images'] = $images;
  }
  else {
    _fbsmp_link_detect_charset($result->data);

    $document = new DOMDocument();
    if (@$document->loadHTML($result->data) === FALSE) {
      fbsmp_log_error(t("Could not parse the content on @url", array('@url' => $url)));
      return $data;
    }

    $xpath         = new DOMXPath($document);

    //Get title of the page.
    $titles        = @$xpath->evaluate("//title");
    $data['title'] = trim($titles->length > 0 ? $titles->item(0)->nodeValue : $data['title']);
    //Get description of the page.
    $descriptions  = @$xpath->evaluate("//meta[@name='description']");
    $data['description'] = trim($descriptions->length > 0 ? $descriptions->item(0)->getAttribute('content') : $data['description']);

    if (!$emfield['emvideo_valid'] && !$emfield['emaudio_valid']) {
      $hrefs         = @$xpath->evaluate("/html/body//img");
      $images = array();

      if (!fbsmp_include_library('url_to_absolute.inc', 'url_to_absolute')) {
        fbsmp_log_error(t("Could not find url_to_absolute.inc file in the libraries folder"));
        return $data;
      }

      for ($i = 0; $i < $hrefs->length; $i++) {
        $image_url = $hrefs->item($i)->getAttribute('src');
        if (!isset($image_url) || empty($image_url)) {
          continue;
        }
        $abs_url = url_to_absolute($page_url, $image_url);
        if ($abs_url && ($imagesize = _fbsmp_link_validate_filesize($abs_url, $options['max_imagesize'], $options['min_imagesize'], ($options['timeout'] - timer_read(__FUNCTION__) / 1000))) != -1) {
          $images[$abs_url] = $imagesize;
        }
        if (($options['timeout'] - timer_read(__FUNCTION__) / 1000) <= 0) {
          fbsmp_log_error(t("Request timed out for @url", array('@url' => $url)));
          break;
        }
      }
      asort($images);
      $images = array_reverse($images, TRUE);
      $data['images'] = $images;
    }
  }

  //Cache the results.
  if ($options['cached']) {
    cache_set($arghash, $data, 'cache', REQUEST_TIME + $options['cache_duration']);
  }

You may also check following references,

embed.ly
Using Yahoo API to crawl the link


Alter existing routes doesn't work I'm working on a D8 project trying to add custom access rules to some pages.

I want to restrict access to specific users based on their id.

I checked this and seems easy but I can't make it work!

I want to change the access for the route

  entity.webform_submission.canonical
  /admin/structure/webform/manage/{webform}/submission/{webform_submission}

But as I didn't manage to make it work I tried an easier example

  contact.site_page
  /contact

(Which also doesn't work)

So I created my routing file under my_module/src/Routing folder :

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route_item = $collection->get('contact.site_page')) {
      $requirements = $route_item->getRequirements();
      unset($requirements['_permission']);
      $route_item->setRequirement('_access', 'FALSE');
    }
  }
}

After that I added the service file in my_module's root folder:

services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

But I don't get Access denied when I visit those pages.

Also, is there any way to test it by using dsm or var_dump?

Any idea/help/suggestion is valuable!

Thank you in advance.

you need to enable kint() to get the routs but you need to make sure the permissions for using kint() is correct.
and you can add your debugging into alterRouts()


Can't set options on form ajax callback I have created a custom form in a custom page in the admin of my Drupal 7 site. On this form I have two sets of radio buttons (cities and sectors). I want it so that when I change the cities radio selection, the sector radio values swap to my new set values.

I have the following code in the main form declaration which initially sets up the form.

$form['module']['cities'] = array(
    '#type' => 'radios',
    '#title' => t('City'),
    '#ajax' => array(
        'event' => 'change',
        'wrapper' => 'sector-wrapper',
        'callback' => 'module_field_city_change_ajax_callback',
        'method' => 'replace',
    ),
    '#options' => array("1" => "New York", "2" => "Moscow"),
    '#required' => TRUE,
);

$form['module']['sectors'] = array(
    '#type' => 'radios',
    '#title' => t('Sectors'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => array("Sport"=>"Sport", "Media"=>"Media"),
    '#required' => TRUE,
);

This creates forms. You can see I've added a callback 'module_field_city_change_ajax_callback'. The code for the callback is as follows:

function module_field_city_change_ajax_callback($form, $form_state){
    $form['module']['sectors'] = array(
        '#type' => 'radios',
        '#title' => t('Sectors'),
        '#prefix' => '
',
        '#suffix' => '
',
        '#options' => array ('Aerospace' => 'Aerospace', 'Art' => 'Art' ),
        '#description' => t('Some text to show the div was updated?'),
        '#required' => TRUE,
    );
    return $form['module']['sectors'];
)

It almost works. The old sectors are updated with the new form element apart from one major part - the actual radio buttons (#options). I know the div has updated and the form rendered because it has the text 'Some text to show the div was updated?' injected. However there are just no values to click.

Any ideas?

I recently answered a question similar to this over at stack.

Basically, you should be doing all the form building and manipulation in the form builder function. The ajax callback function in your case should just return the form element.

This is because when the ajax is fired, just before the ajax callback function is executed, the form is rebuilt and the form building function is executed again (this time with a different form_state which will include the ajax elements current state)(I think).

So you would have something similar to:

$form['module']['cities'] = array(
    '#type' => 'radios',
    '#title' => t('City'),
    '#ajax' => array(
        'event' => 'change',
        'wrapper' => 'sector-wrapper',
        'callback' => 'module_field_city_change_ajax_callback',
        'method' => 'replace',
    ),
    '#options' => array("1" => "New York", "2" => "Moscow"),
    '#required' => TRUE,
);

  // Check if a city is selected and set sectors
  //something like this.

  // $sectors = array("Sport"=>"Sport", "Media"=>"Media");
  // if(city is selected){
  //   $sectors = array ('Aerospace' => 'Aerospace', 'Art' => 'Art' );
  // }

  // you should be able to check if a vocabulary is selected by checking the
  // $form_state['values'] or $form_state['input'] (I forget which)

$form['module']['sectors'] = array(
    '#type' => 'radios',
    '#title' => t('Sectors'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => $sectors,
    '#required' => TRUE,
);

ajax callback

function module_field_city_change_ajax_callback($form, $form_state){
    return $form['module']['sectors'];
)


Image style URL from theme path I am trying to generate a URL for an image style, generated from an image in my theme directory:

$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';
$banner_file = file_build_uri($image_uri);
$banner_url = image_style_url('my_image_style', $banner_file);

The $banner_url looks to be correct, however when I browse to it directly, I get a general Drupal error.

http://www.mysite.local/sites/default/files/styles/my_image_style/public/sites/all/themes/mytheme/images/banners/projects-banner.jpg

I had tried to pass $image_uri into image_style_url, but understand this need a URI and not a path. Can someone please point me in the right direction.

You're right, the image_style_* functions only work with files in the managed file system. You can get round it by using the imagecache_external module, though, which takes remote images and stores them where we need them.

It might seem a little strange to be requesting local images as if they were remote, but this ensures the integrity of the image_style system without further hackery.

$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';

$absolute_image_url = url($image_uri, array('absolute' => TRUE));
$banner_file = imagecache_external_generate_path($absolute_image_url);

$banner_url = image_style_url('my_image_style', $banner_file);


Content by credit/level in Drupal? Ideally I want users to earn "credits". These credits will allow them to redeem "content" (nodes). My goal is basically to allow users to only gain access to content they "redeem" using their credits, and they only gain credits by submitting content which I approve and assign value to. So if user X submits content, I think its great and rank it 8 out of 10 and decide that he gets 8 credits, he then gets 8 credits. He can then use those 8 credits to redeem content, and content can have different values.

What is the best way to go about getting this functionality in Drupal?

The Userpoint provides a mean to store a user credits and can be combined with the Userpoints Node Access to sell node (ie. content) access in exchange of userpoints (credits). The User points Nodes and Comments allow you to setup automatic rewards for content contribution (ie. nodes and comments creation). But it doesn't seems to provides the rating feature you ask for, nor does any of listed User Points Contributed modules.

What should be easily doable, is to use the Fivestar to rates node and then to grant, and revoke userpoint to the rated node author on voting (hook_votingapi_insert() and hook_votingapi_delete()). By restricting access to voting (ie. the 'rate content' permission or through an hook_fivestar_access() implementation), you can control who is allowed to grant credits to your users.


Programmatically get current multi-site instance name Let's say I have the following multi-site setup:

$sites['hello-world-a.com']       = 'a';
$sites['stage.hello-world-a.com'] = 'a';
$sites['dev.hello-world-a.com']   = 'a';
$sites['hello-world-a.localhost'] = 'a';

$sites['hello-world-b.com']       = 'b';
$sites['stage.hello-world-b.com'] = 'b';
$sites['dev.hello-world-b.com']   = 'b';
$sites['hello-world-b.localhost'] = 'b';

Works fine. Both share the same theme and more or less the same features. Now let's say I have a very simple preprocess function that adds a CSS class to the body:

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {

  $variables['attributes']['class'][] = 'foo';

}

How can I now add the multi-site instance's name as body class dynamically?

Without going through all possible domain names and string comparison?
Also possibly without working with the human readable site name, which may change?
Maybe with cache contexts?
Or UUID?

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {

  $variables['attributes']['class'][] = 'foo';

  // Basically along the following pattern.
  if ( @@@ SITE A @@@ ) {
    $variables['attributes']['class'][] = @@@ SITE A @@@;
  }

}

Thanks to @Clive for telling me about DrupalKernel::findSitePath which takes the current $request to then return the path of the matching multi-site directory.

And thanks to @4k4 for the tip that there's also a service for that:

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {

  $site_path = \Drupal::service('site.path'); // e.g.: 'sites/default'
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $variables['attributes']['class'][] = 'site-' . $site_name;

}


Multi country page - avoid repeating content I have a site that has several pages, and it will be available in 2 primary languages: Spanish and English.  However, in Spanish I'm creating other languanges:

Spanish - Argentina
Spanish - Colombia
Spanish - Peru
Spanish - Chile
...

The question is:  I don't want to repeat all the content for the Spanish speaking countries, but change 2 or 3 pages instead:  And mainly that's because I want to replace the country name in some pages.

What would be the best way to create country-specific versions of the site without duplicating all the content for each Spanish speaking country?  Thanks!

NOTE:  Would creating a 'language neutral' page a good idea?  And then create the English version and the changed Spanish versions when necessary?  Not yet sure what 'language neutral' is for.

With domain access module you can share content
and set content to show on only one specific domain name

i.e
Argentina.Spanish.com
Colombia.Spanish.com
Peru.Spanish.com
Chile.Spanish.com


After rearranging field order in a view, how do I export this modification in features? I am using drupal 7, I rearranged the order of the fields in a view, using the contextual menu link 'raerrange' (see image). But now I am not able to export this modification into the feature related to this view. The feature is still in 'default' status. Which is the feature component that is storing this modification? Which component should I add to the feature?

Any help will be really appreciate.

I found out there was no component to add to the feature: the modification was already there even if the feature status didn't change.
The field order is stored into the file: 'feature_name.views_default.inc'.  In order to update the file with the modification, the feature must be 'generated'. (Go to feature --> recreate--> advanced options --> generate feature)


How To organize Taxonomy Vocabulary with overlapping terms - Content Display pages and future proofing I am trying to get a handle on Taxonomy Vocabularies and when to have a separate vocabulary vs when to have multiple fields feed into one vocabulary. How this relates to term pages and Views pages and diplaying content in general.

I have 4 fields:

Artist Name
Song Writing Credit
Song Performance Credit
Song Composer Credit

Most of the time the 'Artist Name' is the same as the 'Song Performance Credit' and most of the time there's a different composer and writing credit.

I have 2 options when creating Vocabularies:

have all fields feed to one Vocabulary called "Artist Name"
have a different Vocabulary for each field

The reason for option 1 is being able to display all content the artist is related to in a View. example: Artist Joe Blow performed on song 6 of an album. It's not his album but if a customer loves him they should be able to go to his artist page and see that album displayed. Therefore any time his taxonomy term is used on a performance credit or written by credit or composer credit it will be associated with that same taxonomy term and therefore be connected to that artist.

The reason for option 2 is if I want to display a list of all composers on the site, or all song writers or all performers. If i bundle everything into one vocabulary, then a taxonomy page for "Artists" will show all taxonomies in that vocabulary including the composers, performers and writers. So keeping each field associated with a unique Vocabulary will allow for this separation. However then Joe Blow might be in various vocabularies and not necessarily linked to his artist page.

On an artist display page I would like to show a list of all Albums he/she is associated with including their own album but also albums they are featured on. This leads me to believe I should have only one taxonomy term of their name in the system therefore only one Vocabulary where all artist names live.

Questions

what's the best practice with taxonomy and at what point is it good to have different Vocabularies for each field vs one Vocabulary that multiple fields feed into
How are they suppose to be entered and organized for future relational connections?

I'd not use a taxonomy at all for implementing what you're asking for. Instead I'd use the Entity Reference module and add an entity reference field like so (in the order specified):

create an extra content type (say) "Artist".
create a node for each Artist you ever want to be able to reference in any of those 4 fields.
make each of your 4 fields an entity reference field.

That's all you'd need.

If I may say, this would still be a solution that could work if some day you have hundreds (thousands?) of Artists. If however you'd use your option 1, or option 2 (using vocabularies), do you think that would still be "usable" (practical)?

However, you may then also want to enable the Inline Entity Form module which, as mentioned on its project page, "provides a widget for inline management (creation, modification, removal) of referenced entities".

More info

Have a look at the answers to these questions for some related topics:

What is the feasibility of using Entity Reference instead of Taxonomy?
Entity reference vs. taxonomy.
Convert taxonomy to entity reference.
Article about Inline Entity Form.

PS: this could work for either D7 or D8.


Reducing redundancy (code duplication) in templates The front page of my site needs a very different layout to every other page on the site, so I want to use page--front.tpl. However, the front page still has many of the standard regions, and shares the same main_menu as the rest of the site.

I have just tried moving the shared "outer" parts of my page.tpl (including main_menu and page_bottom) into the html.tpl because I want to use page--front.tpl without duplicating code if possible.

Unfortunately, many of these variables, notably main_menu are defined only for page.tpl, so I've had to hack it into X_preprocess_html. This makes me nervous because I don't know what other variables I might be missing: I basically want to refactor it to avoid code duplication.

Am I going about this the wrong way? Or if not, how can I be sure I still have all the variables and regions I need pushed up to html.tpl?

Yep, you can do it in a simple manner, just follow this

It simply states you can (for example) use
<?php include 'page.header.inc'; ?> on a template and include the code for that header.
In this .inc file you just enter the code you want to reuse


The "migration" entity type does not exist." error after switching site file structure I am working on D6->D8 migration. We initially stared the site out using the [drupal-project](https://github.com/drupal-composer/drupal-project template), and I had my migration working. However, the site is hosted on Acquia, and Acquia requires a different file structure, so to get started, I spun up a D8 site on the Acquia free tier, and cloned that repo to my local. I got all my contrib modules and themes installed via Composer, and installed our custom modules, including my migration module. However, I am unable to bring up my site or even run a drush command (including trying to uninstall/install my migration module) because I get the following error:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "migration" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I have removed the migration configuration records from the config table and run a cache rebuild, but to no avail. I've also tried to run the drush migrate-upgrade --configure-only command, but I get this error:

Argument 3 passed to migrate_plus_migrate_prepare_row() must be an instance of Drupal\migrate\Entity\MigrationInterface, instance of    [error]
Drupal\migrate\Plugin\Migration given migrate_plus.module:66

How do I get around this?

Thanks.

The proof is in your last error message, it was expecting an Entity but it is now getting a Plugin. Migrate changed from using Config Entities to Plugins in Drupal 8.1.x so I'm presuming you've somehow triggered an upgrade.

See the change record: https://www.drupal.org/node/2668742


How to prevent Devel module to be installed on production environments Using the new Drupal 8 Configuration manager, how can I prevent it from installing the Devel module on certain environments? As far as I know, installing it on my local means the next time I export the configuration and move it to my other environments (dev, test, prod), it will automatically be enabled.

Method: Drush

Drush can ignore the enabled states of extensions when synchronizing configuration.

drush cex --skip-modules=devel

drush cim --skip-modules=devel
With Drush CMI tools you can operate with a list of configuration to ignore.

drush cexy --ignore-list=/path/to/config-ignore.yml

drush cimy --delete-list=/path/to/config-ignore.yml

Method: Modules

You can use the Configuration Split module that allows you to:

Split off some configuration to dedicated folder
Blacklist configuration
Ignore a set of configuration
Configured by configuration entities

Configuration Read-only mode module

  This module allows to lock any configuration changes done via the
  Drupal admin UI. This can be useful in scenarios where for example
  configuration changes should not be done on the production
  environment, but only on staging or local environments.

$settings['config_readonly'] = TRUE;
And another module is the Environment Config that allows you to override configuration on a per-environment basis.


why some PDOException errors are displayed in details on users screen and some other not A user reported to me seeing the following error on his screen:

The watchdog entry for this error looks like this:

PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: INSERT INTO (.............)

I would like this kind of errors not to be displayed in detail on user screens.

However, I am not able to replicate this problem of displaying error in detail on the screen. During my tests, SQL errors are NOT displayed in detail at all. So, even if I apply a solution (like setting display_errors to FALSE in settings.php) I won't be able to test it, because I can't replicate this particular scenario which causes errors to be displayed on screen with details.

As part of the testing, I've made a deliberate mistake (in table name) in a database query in mymodule_node_view to test how such error will be visible on user screen. The problem is that in both cases, whether display_errors is turned "on" or "off" (checked on Site Status report: http://example.com/admin/reports/status/php), the result is identical. On user screen the error is displayed as:

It's not displaying any details, although  in the watchdog log, it is similarly also a PDOException:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydb.nodeaa' doesn't exist: SELECT (..............)

So, I don't understand. Why is Drupal displaying details of some PDOExceptions on user screen and not displaying details of some other PDOExceptions? How to effectively check whether a setting (e.g. display_errors set to "off") will fix the problem for all sorts of PDOException?

The problem is - error that gets displayed means "Hey, I cannot connect to database! To many users already!". And the setting you are using to prevent error display are in database. And watchdog's log is in database. That's why Drupal shows it - it cannot know you set it not to, the very error prevents it from knowing. And even if it could, it cannot log it in any other way than to user's screen

To get this sorted out, you need two things:

database-independent log module, like File logging
set variables responsible for not showing alerts in settings.php