Use Webform for multiple possible inputs I want to create a webform that will replace a excisting excell file
(visitors download a excell file, fill it in and send it back to the company).
Under here a simplified example of the excell file...

As you can see above the visitor can fill in one line or more lines...

I could make a webform for entering one-line (one product), not so difficult.

But the client should be able to fill in more than one demand (if he wants).
So after putting in one demand, there should be a possibility, to say/click add one more...

Don't know if this possible with only "webform" module, or is there a other module for this.

Any tips, links, video's ,  comments are welcome!

K.

The Webform Table Element module will allow you to setup your webform in a tabular format.

But I don't think it allows for unlimited number of lines as an excel sheet would. Still it could be a reasonable (quick) solution for your need.


Can we migrate basic Metatag data without customization? I'm ought to Migrate-upgrade from D7 to D8 and deleted all modules besides Metatag (and its dependencies --> Ctools and Token).

You might have an idea how could I keep all the basic Metatag data for my nodes? By "basic" I mean only to the Page-title, Page-description and Meta keywords (And maybe also the Abstract tag); Nothing beyond that.

AFAIK, as for 2016 there is no migration-path for the Metatag module and people should generally copy their metadata manually; This situation kind of negates the whole migration experience since the all issue is to migrate nodes with their most common data.

Will cherish any advice.

There's a patch at https://www.drupal.org/node/2563649, currently at "Needs work".


migration process plugin not registering My plugin aims to strip out html tags from titles being imported from xml
Here is the error I'm receiving:
FVFXF0ETHV2F:process$ drush mim complinet_xml_to_node
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "stripouthtml" plugin does not exist. in                                          [error]
/Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:

Here is the plugin which lives in custom/complinetmigration/src/Plugin/migrate/process

<?php

/**
 * @file
 * Contains \Drupal\complinetmigration\Plugin\migrate\process\StripOutHTML.
 */

namespace Drupal\complinetmigration\Plugin\migrate\process;

use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

 /**
 * @MigrateProcessPlugin(
 * id = "stripouthtml"
 * )
 *
 */
class StripOutHTML extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    // $value: cut off .<nnn>Z and replace by Z
    if( is_null($value) )
    {
      return $value;
    }

    // $old = $value;

    $value= strip_tags($value);
    // drush_print_r( $old . ' -> ' . $value );

    return $value;
  }

}

and here is the migration

# This migration demonstrates importing from a monolithic XML file.
dependencies:
    enforced:
      module:
        - complimentmigration
id: compliment_xml_to_node
label: XML feed of nodes from compliment
migration_group: compliment
migration_tags:
  - advanced xml import
source:
  # We use the XML data parser plugin.
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  # Normally, this is one or more fully-qualified URLs or file paths. Because
  # we can't hardcode your local URL, we provide a relative path here which
  # hook_install() will rewrite to a full URL for the current site.
  urls: private://FINRAManual08-08-18.xml
  #  - /migrate_example_advanced_position?_format=xml
  # Visit the URL above (relative to your site root) and look at it. You can see
  # that <response> is the outer element, and each item we want to import is a
  # <position> element. The item_xpath value is the xpath to use to query the
  # desired elements.
  item_selector: '/quickpipe/section/section/section'
  # Under 'fields', we list the data items to be imported. The first level keys
  # are the source field names we want to populate (the names to be used as
  # sources in the process configuration below). For each field we're importing,
  # we provide a label (optional - this is for display in migration tools) and
  # an xpath for retrieving that value. It's important to note that this xpath
  # is relative to the elements retrieved by item_xpath.
  fields:
    -
      name: versionid
      label: 'Version Id'
      selector: 'version[1]/@recordId'
    -
      name: title
      label: 'Title'
      selector: 'version[1]/title'
    -
      name: content
      lable: 'Content'
      selector: 'version[1]/content'

  # Under 'ids', we identify source fields populated above which will uniquely
  # identify each imported item. The 'type' makes sure the migration map table
  # uses the proper schema type for stored the IDs.
  ids:
    versionid:
      type: integer
destination:
  plugin: entity:node
process:
  # Hardcode the destination node type (bundle) as 'migrate_example_beer'.
  type:
    plugin: default_value
    default_value: article
  title:
    plugin: stripouthtml
    source: title
  uid:
    plugin: default_value
    default_value: 1
  sticky:
    plugin: default_value
    default_value: 0
  body: content
migration_dependencies: {}

The module was in a funky state. I ran drush pm-uninstall complimentmigration which gave the following message.

  complimentmigration is already uninstalled.
  There were no extensions that could be uninstalled.

Then I ran drush en complimentmigration which gave the following message.

  The following extensions will be enabled: complimentmigration
  Do you really want to continue? (y/n): y
  Drupal\Core\Config\PreExistingConfigException: Configuration objects (migrate_plus.migration.compliment_xml_to_node) provided by                      complimenttmigration already exist in active configuration in /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Config/PreExistingConfigException.php:65
  Stack trace:
  0 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Config/ConfigInstaller.php(496): Drupal\Core\Config\PreExistingConfigException::create('complimenttmigrat...', Array)
  1 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/ProxyClass/Config/ConfigInstaller.php(132): Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module', 'complimentmigrat...')
  2 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/Extension/ModuleInstaller.php(150): Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module', 'complimenttmigrat...')
  3 /Users/Sites/devdesktop/drupal8test/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller->install(Array, true)
  4 /Applications/DevDesktop/tools/vendor/drush/drush/commands/core/drupal/environment.inc(131): Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array, true)
  5 /Applications/DevDesktop/tools/vendor/drush/drush/commands/core/drupal/environment.inc(198): drush_module_install(Array)
  6 /Applications/DevDesktop/tools/vendor/drush/drush/commands/pm/pm.drush.inc(1180): drush_module_enable(Array)
  7 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(422): drush_pm_enable('complimentmigrat...')
  8 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
  9 /Applications/DevDesktop/tools/vendor/drush/drush/includes/command.inc(199): drush_command('complimentmigrat...')
  10 /Applications/DevDesktop/tools/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
  11 /Applications/DevDesktop/tools/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
  12 /Applications/DevDesktop/tools/vendor/drush/drush/drush.php(12): drush_main()
  13 {main}

I ran drush ev "\Drupal::service('config.manager')->uninstall('module', 'complimentmigration');", followed by drush en complimentmigration, which gave the following message.

  The following extensions will be enabled: complimentmigration
  Do you really want to continue? (y/n): y
  complimentmigration was enabled successfully.

This fixed the issue I had.


How can I make a curl type http request after a node submission? Basically I have a node type which I've named "rss". Its purpose is exactly as I'm sure you guessed, all of these nodes are available as an rss view at a specific url (ex: http://mysite/rss/feed).

When a node of that type gets created (or updated I suppose) I need to make an http request to a specific url (the details to that are irrelevant to this question).

So lets say I create a new "rss" post on my drupal site, after it gets submitted I need an http request to the url ex: http://myapplication/blog?status=fetch

I know that I can make such a request happen with the visit url function in actions core module, and "trigger" it on node creation (not of a specific type though) but I think it does exactly that, and actually VISITS the url, whereas I just need it to make a curl type request.

I'm also using the scheduler module, so posts of this type can be scheduled, so I would need to trigger the action in sync with the schedule, if it is scheduled to be posted at a certain time/date, that is.

I'm guessing I need to use some sort of hook functionality and make my own module, true? Or is there any other way of doing this?

There's no pre-configured action for making a back-end request like that, so you will need to write some code. It's not going to be terribly hard to accomplish, though. Drupal has a function called drupal_http_request() to hit the external URL. You'll execute that function within a hook_nodeapi() implementation, which runs at various times in the node creation process.

Drupal 6:

<?php
/**
 * Implements hook_nodeapi().
 */
function MODULENAME_nodeapi(&$node, $op) {
  // In D6, this hook is executed at various points in the node creation/render process.
  // We only want to run code during the node's "insert" operation.
  if ($op == 'insert') {
    // Only run for RSS nodes.
    if ($node->type == 'rss') {
      // Make a back-end HTTP request to an external resource.
      $url = 'http://my-url.com';
      $response = drupal_http_request($url);
    }
  }
}
?>


How to completely turn off caching? I am developing a site in Drupal 7 and caching slows my work significantly. For example, I had a theming function for a form. I was puzzled, why doesn't it work. Until I cleared the cache and it was fixed.

How to turn it off completely?

You can replace the default cache backend to one which does not actually do anything.
Simply add this to your settings.php file:

if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data.
$conf['cache_default_class'] = 'DrupalFakeCache';
// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Just to be sure, set the cache expiration time to none on the Performance page.

I actually use this in a settings.local.php file which, if it exists, gets included at the bottom of my settings.php file so I can sync settings.php from the live or staging environments to my dev environment without having to worry about using the wrong database settings, accidentally pushing dev settings to live, etc.

settings.php:

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


Using Drush site-install with multisite and a single database I am trying to make a script that will create and configure a new multisite in a drupal 7 install using drush 5.8.

I have scripted creating the site folder and settings.php file manually and adding the database information (to get around a bug i was having with --db-url and sql server).

I am setting the dbprefix to be $newSite so that all the tables can live in the same database.
The first thing drush site-install tries to do is drop ALL the tables in the database. This includes all the tables created with a different prefix in a previous install.

Is there any way to stop this from happening?

Thanks for your help in advance!

Joe

this is how I do mine...

drush -y site-install standard --db-url=mysql://$username:$pass@127.0.0.1:3306/$dbname --site-name="$sitename" --sites-subdir="$sitename"

sitename for instance could be test.drupalserver.com and to keep it in good practice for dbs i strip out the periods and the $dbname would be test_drupalserver_com.

I believe the way my drush command works, it creates a new db that matches the name of the site.


selecting a referenced node from 1000's of nodes I've a cck field "address" of node type Address within Building node type.
My site may have tons of such addresses. So let me assume that already 10000 nodes of type Address exist and then one visitor tries to create a node of Building.

In the node reference field of address how'd one be able to select the correct address from 10000 addresses from "auto complete text field" address field?

As far as I know auto complete address would show only the node titles and  many addresses can have same titles so how one would be able to select a particular address in the address auto complete text field ?

If you truely need to have a design that needs that many nodes to be referenced, you need to either have data integrity (Make sure that the nodes have proper titles so they can be found with the AC widget), or instead you need to build your own and more advanced widget.

The AC widget is not build for referencing 10.000's of nodes, if that is your need, you should create your own widget, that allows the users to input more data and thus easier find the address node they need. With CCK you can build your own widget.

Building a widget is in itself no small task, and building one that can handle these needs will not be any easier. There are a bunch of blogs with guides on how to do this, and you can look at the CCK module to see how it does it to get a better understanding.

Update:

I don't know what this Area 1-4 is all about, but my hunch is, that this could be built more clever to avoid this mess, I could be mistaking, but it seems like a flawed design, if a user needs to pick a reference from a list of 10.000's.
One way to deal with this, would be to let the user actually enter the address, and behind the scenes search for it. If it exists create the reference, if not create the node with the info and then create the reference.


select list in webform containing the list of node titles how can we create a select list in webform containing the list of node titles of specific content type.

I have a product content type through which I have added several product nodes. Now I want to create an inquiry form which should allow the visitors to select the *products from the select list about which they want to send inquiry.

*the products in the select list will be the product node titles.

Check out https://groups.drupal.org/node/71588 for providing dynamic select options to the webform module. You'll have to specify the content type, but here's a query that can be used to populate it (replace product with the machine name of the content type):

SELECT nid, title FROM {node} WHERE type = 'product' AND status = 1 ORDER BY title ASC


Webform Localization I created a form in English. I used the localization webform module to translate the fields of the form. In configuration -> Regional and Language -> Translate interface -> Translate. It works!

Now I'd like to translate different e-mails in several languages. For this I enabled the option: "Synchronize webform recipients e-mail across node translations."

Now what I need to do more? I wanted to set up E-mails with  confirmations in different languages or even use different email. I'm a little confused on this part.

Thank you for your help.

Best regards.

If you add a select field in your webform, for example ( language ) then you can filter emails using that select field. You can rather let the user select the language or do it with a language detection script.


Better exposed fiters with Views: how to show quantity of nodes tagged with certain term? I use better exposed filters with views. I chose to show field "term reference" as hierarchical checkboxes on my exposed filter. It works great.

But now I need to add quantity of nodes having certain term near each checkbox inside filter.
What is the best way to do it?
Thank you!

I ended up with editing \sites\all\modules\better_exposed_filters\better_exposed_filters.theme

Inside it I made a query to field_data_, got all terms with nodes count:

function theme_select_as_checkboxes:

$res = db_query('SELECT field_dance_styleee_tid, COUNT(*) as count FROM field_data_field_dance_styleee
 GROUP BY field_dance_styleee_tid');
    $allNodes = array();
    while($record = $res->fetchAssoc()){
        $allNodes[$record['field_dance_styleee_tid']] = $record;
    }

Then passed $allNodes to

  $output .= bef_checkbox($element, $key, $value, array_search($key, $selected_options) !== FALSE, $allNodes);

function bef_checkbox($element, $value, $label, $selected, $allNodes=array()) {

$value = check_plain($value);
  $label = check_plain($label);
  $id = drupal_html_id($element['#id'] . '-' . $value);
  // Custom ID for each checkbox based on the 's original ID
  $properties = array(
    '#required' => FALSE,
    '#id' => $id,
    '#type' => 'bef-checkbox',
    '#name' => $id,
  );

// Prevent the select-all-none class from cascading to all checkboxes
  if (!empty($element['#attributes']['class'])
      && FALSE !== ($key = array_search('bef-select-all-none', $element['#attributes']['class']))) {
    unset($element['#attributes']['class'][$key]);
  }

// Unset the name attribute as we are setting it manually.
  unset($element['#attributes']['name']);

$checkbox = '';

$properties['#children'] = "$checkbox $label". ((
      $element['#name'] == 'field_dance_styleee_tid' && isset($allNodes[$value])
  )? "(".$allNodes[$value]['count'].")" : '')."";

$output = theme('form_element', array('element' => $properties));
  return $output;
}


Cannot edit my views.. I get a JSON string? I'm using Drupal v7.22 and whenever I try to Modify the Display on views, and press the 'Add and configure' button on adding a field, or any button that sends data to the server, the page reloads and I just get a long JSON String returned in Chrome, or IE will try to download the return...  Sometimes it'll accept my change, but more often than not, it won't.

It was doing this on 7.21 and then I updated to 7.22 and it stopped for a day or two, now it's doing it again.  I am extremely new to Drupal, but I am a quick learner and most things are going smoothly.

What did I break and how can I fix it?

Based on @Clive's suggestion in the comments, I found this issue:
JQuery Update breaks Views UI

So Views UI is not compatible with jQuery 1.8, and the OP has already confirmed that this was the problem.

This problem isn't limited to Views though. Other contrib modules depend on the default core version of jQuery (including Rules). An issue exists in the jQuery Update queue to Allow different version for administrative pages. And a patch was applied to dev on 20 MAR 2013.

The dev version of jQuery Update provides a update to the Configuration Form that allows you to select a different version of jQuery on administrative pages.

Before

After

I can confirm that setting the "Alternate jQuery version for administrative pages" select list to "1.5" after upgrading to the dev version of jQuery Update fixes the issue with Views.


Create Drupal 7 Multi Site on Mac OSX 10.10 I want to create a Drupal Multisite so I can share my theme and users between two sites. I want to set it up locally before I upload it on a webhost.

I am using Mac 10.10. However, many of the tutorials seem to be written for older versions of Mac OSX and don't work properly.

For example, this tutorial suggests the following:

Edit /etc/apache2/http.conf to add the following:

NameVirtualHost 127.0.0.1:80
<VirtualHost 127.0.0.1:80>
DocumentRoot /Users/YOURSITE/Sites/drupal
ServerName drupal1.localhost
</VirtualHost>

<VirtualHost 127.0.0.1:80>
DocumentRoot /Users/YOURSITE/Sites/drupal
ServerName drupal2.localhost
</VirtualHost>

Then edit  /etc/hosts to add the following:

127.0.0.1     drupal1.localhost
127.0.0.1     drupal2.localhost

You can now find your site at: http://drupal1.localhost & http://drupal2.localhost

When I do this, I just get the message "It Works" I am unable to go to the Druapl installation page to start installing the site.

I've had a search for other tutorials, but they all seem to be written for MAMP.

How can I fix it, without using MAMP?

It sounds like you don't have your directories configured properly.

Assuming that you have this file structure:

/users/
    /drupal/
        /sites/
            /drupal1.localhost/
                /settings.php
            /drupal2.localhost/
                /settings.php

Note that the folders under /sites must match the http.conf server name.  (unless alias's are set up).

With the above structure, your http.conf would look like this:

DocumentRoot "/users/drupal"

<Directory "/users/drupal">
    AllowOverride All
</directory>

NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal1.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal2.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Note that the document root points to the base Drupal folder, not /sites.  Drupal will handle this part automatically.

Your hosts file would remain the same:

127.0.0.1     drupal1.localhost
127.0.0.1     drupal2.localhost


Boost don't generate CSS I have a major problem: the boost module is great but SOMETIMES i find some pagers without any CSS or JS like the image below:

https://drupal.org/project/advagg/ should solve this issue. Odds are the cached page is older than 30 days (limit of CSS/JS aggregates in D7 Core).


Using the Commerce Kickstart distribution to sell non-standard products I've been using the Commerce Kickstart distribution for physical products and it work great.

Now I find myself in a situation which could be the common for many of us.

I need to start a new project where the product to sell is a Parcel Delivery Service. Very similar to this one: http://www.parcel2go.com/

Then, from my point of view, the process is:

  1) The user enters required data (Collection, Destination, Weight,
  etc)

  2) Clicks the button "quote"

  3) System generates a single product with a calculated price (based on
  the data entered by the user)

  4) The user add the product to the cart and follows the checkout in the standard way

The difference is that there is no previously created products in this site. I think that  there is just one product which I can call "Delivery Service" but this product has no price. This price will be generated on the fly by a formula using the data entered by the user.

Is this the right approach?

Can I use the Commerce Kickstart distribution for this case? If so, which other module could be useful for this case?

Not really an answer, but only my point of view.

I would create a dummy item without price and add the calculated price to the carrier fees.
You can trigger almost every action you need from Rules.

Add FOO item to cart.
Add the transport fee to the order.

This rules are already there in Kickstart, you will only have to tune the Carrier fee calculation rules to fit your use case.
Of course I don't think Kickstart is designed with selling services in mind but I don't think you are going to find any major problem in going this way. Think of a store with only one product that ships worlwide with different transport fees. The carrier can well be a variation type of your product.

My 2 cents.


How to install Chosen using Drush Make? From Chosen module page:

  This module comes with a Drush make file, which will automatically download the jQuery plugin if you use Drush make to set up your website.

I have Drush Make, but commands like..

 drush dl chosen
 drush en chosen

..don't help.
Should I use drush make ... command instead? Maybe there are other commands for quick libraries download.

P.S. I'm working on already installed copy of Drupal.

I found a way:

# cd to Drupal root folder
drush dl chosen
drush make sites/all/modules/chosen/chosen.make.example --no-core
drush en chosen -y

Update 04/29/2014: Chosen now provides Drush command chosenplugin.

This answer is still useful for other projects with *.make.example files but without custom Drush installation commands.


How to join the `field_data_field_*` tables with `node` table using SQL? I apologize if I ask for something obvious, but I am asking because I could not find a simple answer anywhere.

I know how to work with these tables in the PHP Drupal code, which built-in functions to use, etc., but for some reasons, I have to write a literal SQL query to the Drupal database.

That's why I'm asking what condition I need to use in the SQL query to connect the field_data_field_abc table with the node table?

If the data in the field_data_field_abc table contains the entity_type column with the value "node", can I do something like this:

SELECT *
FROM node n
LEFT JOIN field_data_field_abc abc ON n.nid = abc.entity_id
WHERE abc.entity_type = 'node'

Yes, you are right :)

In general, for each table from field_data_field_* family, if its entity_type is equal to  the "node" value, then it can be associated with the n.nid from the node table and if the entity_type is equal to the "user" then the entity_id value is associated with the uid value from the users table.

I hope it will help somebody.


How to make breadcumbs grab taxonomy terms and use tokens I have tried about 4 different breadcrumb modules now and none of them seem to do what I want. I want them to act in a similar way to Pathauto whereby I can mix and match tokens. There seems not to be a way to do this, for some reason or another. Example, I have a school that belongs to a country name and city name. City and country are part of a taxonomy, so:

/united-states/los-angeles/school-name

I want this to be:

Home > Destinations > Parent Term > Child term > Node title

I even might want to add my own text for one of these breadcrumbs.

First of all if you have not tried Taxonomy Breadcrumb module yet, give it a try.

If you already have tried that module and had no success , you can write your own code.

the simplest solution can be achieved by implementing hook_preprocess_page, then you should check if there is a node and node is of a certain type used to store school type and then you can change $variables['breadcrumb'] to modify breadcrumb as you wish.

in drupal 7 you also can use drupal_set_breadcrumb to change breadcrumb in a code and in drupal 8 you can implement hook_system_breadcrumb_alter to make it done.


hook_page_alter called once I have a Drupal 7 theme which is a Bootstrap child theme.

In my version of page.vars.php, I have a THEME_page_alter() call which runs only once until I do a clear cache. Other hooks such as THEME_process_page or THEME_preprocess_page are called each time I reload the page.

A second theme, with the same page_alter hook works just fine and is called each page-reload without the need for a clear-cache first.

What could be causing this?

Theme settings are specific to each theme. Go to /admin/appearance/settings/yourtheme and check for any theme-specific caching options. I can't tell you exactly what the options would be because that depends on your theme.


References module doesn't specify/read a pager limit when field is using a view to generate potential references Discovered an oddity that seems inherent in the node_reference.module 7.x-2.1. It is a rather specific use-case, so I can see why it might not have come up frequently before. Just wondering if anyone has any work around ideas, either that or I'll document my findings if I reach a solution.

How to reproduce the issue:

Create a reference list view, and use it to power an autocomplete field.
Create another view and attempt to use the created field as a filter.
Everything will work fine, unless that field has a large number of values. The field I'm using has upwards of 90,000 items.
This is because the views filter UI attempts to render all possible values as a checkbox list.

The reason it trips up is because:

function _node_reference_options($field, $flat = TRUE) {

Goes on to call:

$references = node_reference_potential_references($field);

Without any options. Which leads to:

references_potential_references_view(
  $entity_type, $view_name, $display_name, $args, $options);

Being called without any options, and it seems this code does not read the pager settings to get its limit value. Instead it relies on $options['limit'].

$limit = !empty($options['limit']) ? $options['limit'] : 0;
$view->display_handler->set_option('pager', array(
  'type' => 'some', 'options' => array('items_per_page' => $limit)));

I'm not sure which bit of the code is at fault — i.e. who should definite a limit, or read the pager settings — but there definitely needs to be a defined limit and not 0. Especially when dealing with so many possible values. Setting a limit specifically for the pager in Views UI does not work as it is circumvented.

Currently I can't even get to edit my view with the filter specified, unless I hack the references module to pass:

$references = node_reference_potential_references($field, array('limit' => 10));

I'm only adding this as a filter so I can state that the field isn't empty. I could just leave the hack in until I've set the filter to a state that doesn't read the values. However this feels rather unsafe — especially if someone else was to take over the code at a future point.

I haven't found a neat general solution to this issue, but in terms of a specific solution you can use hook_query_alter. Basically in one of my bespoke modules I added the following:

/**
 * Implements hook_query_alter().
 */
function bespoke_module_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views_autocomplete_for_ref_files')) {
    $view = $query->getMetaData('view');
    if ( !empty($view) && $view->current_display == 'references_lead_image_by_default' ) {
      $query->range(0, 10);
    }
  }
}

  NOTE: Awkwardly there doesn't seem to be an ability of SelectQuery to get back the current range settings. The code could be more general if it could detect that no limit was set.

Out of the above views_autocomplete_for_ref_files is the machine name of the reference list view, and references_lead_image_by_default is the name of the display. I can focus on the default display because I have code elsewhere that switches the view in use depending on certain contexts. The default display is never actually used by the site, except when it is requested by the Views UI (because the widget hook below is not used for the Views UI display).

/**
 * Implements hook_field_widget_form_alter()
 *
 * Modifies the autocomplete path for autocomplete widgets
 */
function bespoke_module_field_widget_node_reference_autocomplete_form_alter (&$element,
    &$form_state, $context) {
  $instance = &$context['instance'];
  $field = &$context['field'];
  /// only step in if the field uses a view to populate
  if ( $field['settings']['view']['view_name'] == 'autocomplete_for_ref_files' ) {
    /// switch the view display depending on content type
    if ( (arg(0) == 'node') && ($node=node_load(arg(1))) && ($node->type) ) {
      $field['settings']['view']['display_name'] =
        'references_lead_image_for_' . $node->type;
    }
    /// hijack the current autocomplete path to point to our own callback
    $element['nid']['#autocomplete_path'] =
      $instance['widget']['settings']['autocomplete_path'] . '/' .
      $instance['entity_type'] . '/' . $instance['bundle'] . '/' . $field['field_name'];
    /// hijack the autocomplete validate function, to validate with our own criteria
    $element['nid']['#element_validate'] =
      array('bespoke_module_node_reference_autocomplete_validate');
  }
}

I'll keep looking to see if I can find a more general solution.


How to alias pages generated by panels (node edit or view pages) I have a panel page that is in the form:

"/productsByMfg/%nid" where nid is the node id of the a manufacturer.  This is not a node edit or view page since I already have that.

I have about 100 of these pages /productsByMFg/1, /productsByMfg/2 etc...
How do I create aliases so I can use something like /productsByMfg/IBM, /productsByMfg/Microsoft?

Sub-pathauto (Sub-path URL Aliases) works for me. It takes care of situation like yours. Here is a quote about it (from the module's project page):

The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


How to conditionally change email content from Webform submissions Reading the docs I can see that you can conditionally change the recipient of a webform email based on a field value, but that's not quite what I want to do. I want to modify the content of the message based on a form input. For example, based on a webform field like:

Favorite Color:
[] Blue  [] Yellow  [] Red

Upon submission the user should receive totally different email messages saying either:

  You probably like the sky...

or

  You probably like bananas...

etc. (you get the idea).

Note: it would be clever and would solve this minimalistic example to create the options like

the sky|Blue
bananas|Yellow

and then use their tokens, but that's not an option in this case as it's multiple paragraphs of text I want to be different in the conditional messages.

This is more of a coding solution but you could implement hook_webform_submission_presave() in a custom module and use that to save the appropriate text to a hidden webform field type, then see if the token for that field will work in the email.

Alternatively, you could implement hook_webform_submission_insert() and send the email programmatically there, which would give you full conditional control of the email recipients and contents.


LoadTest fail due to "chmod(): Operation not permitted" I downloaded and installed a new Drupal 8 site via Composer.
I generated a new module using Drupal Console.
I tried running a phpUnit functional test of the newly generated module, and it keeps failing due to some folder permission:

  Exception: Warning: chmod(): Operation not permitted
  Drupal\Component\PhpStorage\FileStorage->createDirectory()() (Line: 168)

What grind my gears is that it was working OK a few days ago. Something is clearly wrong with my system, I just don't know what that is, or what changed since then.

I'm running a WSL with Apache 2.4.37 (PHP Version 7.2.12-1+ubuntu18.04.1+deb.sury.org+1).

I have all the detailed steps to reproduce the case, my full phpinfo, and some more relevant information in this gist I created.

I spent the last few days browsing for a known solution, and some cases appear to be similar, but none of them seems to hit the spot.

I am using Windows 10.0.17134.407; the tests from the browser are passing. All the files and folders on the project are owned by 'zoio' (user and group); the file permissions for folders and files in modules, sites/default/files, and sites/simpletest are set to 0777.

I tried to follow the tips on this WSL issue, but I just ended up with a different failure, still related to permission and ownership.

  Drupal\Tests\sandbox\Functional\LoadTest::testLoad()
  Exception: User warning: mkdir(): Permission Denied
  Drupal\Component\PhpStorage\FileStorage->createDirectory()() (Line: 174)
   /mnt/c/www/temp/d8_temp/web/core/lib/Drupal/Core/Test/HttpClientMiddleware/TestHttpClientMiddleware.php:51 (...) /mnt/c/www/temp/d8_temp/web/modules/custom/sandbox/tests/src/Functional/LoadTest.php:33
  ERRORS!
  Tests: 1, Assertions: 1, Errors: 1.

The thing is, the chmod wasn't really working.

It was an issue with the mounted drivers in the WSL Ubuntu installation. Based on Stefanos Petrakis' comment, simply trying to unmount and mount the driver with the proper options enabled wouldn't solve the issue by itself. What solved was a bit more drastic:

Factory reset the ubuntu (how-to);
re-mount the driver, with the metadata option included (source):

sudo umount /mnt/c
sudo mount -t drvfs C: /mnt/c -o metadata,uid=1000,gid=1000
Install php, Apache, and everything.

Only then, the phpunit tests did work properly.


How to get the country from shipping address in a view? I am using Drupal Commerce Kickstart!
I want to get 'Only' the country name from the shipping information of a particular order in a view,
The shipping information field in my view shows the entire shipping address including the country at last, is there a way that I can extract only the country name from that? or a db query using the order_id?

Implying that you have the Order ID in your view:

Add a relationship to Commerce Order: Referenced customer profile, for the shipping address (Relate this entity to the customer profile referenced by its commerce_customer_shipping value)
Add field for Commerce Customer profile: Address - Country

My output after those steps:

Order ID: 4
Bulgaria

Order ID: 5
United States

FYI the data is located in field_data_commerce_customer_address table commerce_customer_address_country column.


Can we use Deployment Module with multi DB Drupal Site or Cross DB Connection Drupal Site? I have scenario in which I am using Cross DB connection on my Drupal 7 Site, I specified my DB connection in settings.php file. Second DB is used as a source db.

Can I use Deployment Module to deploy updates on my default drupal DB only or can also deploy updates on second DB too?

I tried and got this solution, sharing with you all

While using hook_update_N() in your deployment module - .install file, you have to active the DB for which you want to deploy the changes.  I tried it on my server and it works, I am sharing a piece of code, have a look:

function hook_update_N(&$sandbox){
db_set_active('dbsourcekey');
variable_set('clean_url', 0);
variable_set('site_403', 'access-denied');
db_set_active('default');
}


Advice for categorizing content? I'm new to Drupal 7 and UberCart and loving it.
I'm working on a site that is automotive based and am having a problem wrapping my head around the catalog.
I have 4 different parent catagories, then year/make/model and part category.  A product can be anywhere and belong to multiple categories.

Right now I have a vocabulary that contains parent category/make/model/part category and another that contains year.

I need the menu to work like

Parent Category 1

Make 1

model 1

year
sub-cat
model 2

year
sub-cat

Make 2

model 1

year
sub-cat
model 2

year

sub-cat

Am I making this too complicated?
The sub-cats would be unique to the Parent Category but make/model/year could belong to any Parent Category and subcat.

Can anybody give me any advice?  Thanks in advance.

edit I guess I'm asking If I put year make model together in a vocabulary and Parent Category and subcat together in a vocabulary (which I think would work well), how can I incorporate that into UberCart catalog menu?

@Drupality was right...It does require custom coding.
I installed Multi Term Views which will allow nodes to be filtered that contain different, multiple taxonomies from different vocabularies.
So you could have a filtered view at taxonomy/term/27+35 which will show all nodes in term id 27 and 35 or you can have taxonomy/term/27,35 which will show all nodes that are exclusively in both 27 and 35.  After that was set up I just wrote a custom menu and put it in a block in the sidebar.
So I have 3 vocabularies that are Year, Make/Model, and Type.  Make/Model is two terms deep.
Not the best solution - but if a highly customized menu is needed then apparently this is what must be done.

Thanks @Drupality for your help.


Disable user login, register and password reset I am working on a Drupal 8 site that for all intents and purposes will be used as a company intranet. I'm also using the Social Auth Google module to allow only company-registered GSuite accounts to use the site.

I have tested this module, and it works great! However, I'd like to remove the /user/login, /user/register, and /user/password routes, as well as the associated tabs (as per screenshot below), to prevent anyone using anything but the Google Social Auth login feature.

Sure, I could use CSS to hide these elements, but that doesn't feel right to me.

I'd appreciate any guidance on how to achieve this.

in a custom module that we call 'custom', have custom.services.yml with content :

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

then create the file src/Routing/RouteSubscriber.php with the following :

<?php

namespace Drupal\custom\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) {
    // Always deny access to unwanted routes.
    $disallow_routes = [
      'user.login',
      'user.register',
      'user.pass',
    ];
    foreach ($disallow_routes as $disallow_route) {
      if ($route = $collection->get($disallow_route)) {
        $route->setRequirement('_access', 'FALSE');
      }
    }
  }

}

enable the 'custom' module and this should work :)


Render main menu in page.tpl.php, with override from template.php In Drupal 7, I'm trying to add a <span> tag inside the <a> tag of an item in the Main Menu, but it only works for the 'Navigation' menu which is a block, however, I am trying render it within page.tpl.php

I've been searching this up for a while now and can't seem to get it to work.
I was attempting to follow the information from How do I insert a <span> </span> tag inside the <a> </a> tag on my main menu

Here's a snippet from page.tpl.php

  <nav id="main-menu" class="navigation span8">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
     )); ?>
  </nav> <!-- /#main-menu -->

and from template.php

function THEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

//$element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

$get_title= $element['#title'];
$element['#title']='<span>' . $get_title .' </span>';

$element['#localized_options'] += array(
    'attributes' => array(),
    'html' => TRUE,
  );

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

The function you need to override is theme_links() and to do that just for the main menu you can use mytheme_links__system_main_menu as the function name. To add span tags you can then modify the part that starts with if (isset($link['href'])):

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link['html'] = TRUE;
  $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
}


Using Panels and Views to override taxonomy listing - which argument to use? I'm using Panels to override the taxonomy display at taxonomy/term. I just enabled the term_view page that comes with Panels and it works great.

So going to mysite/colours/blue shows the Panels page no problem.

Now I want to add a View to the panel that lists the returned nodes. I create the view, and add a relationship 'Content: taxonomy terms on node' (selecting the required vocabulary 'colours').

The I add an argument (contextual filter) on 'Taxonomy term: name'. This works great in the view preview if I enter the value 'blue' but not if I enter 'colours/blue' (no results). And it doesn't work in the panel because 'colours/blue' are the arguments being passed to it.

How do I get the view argument to work with this URL?

In the Views UI, each Content Pane has "argument settings". In there you have, at least, two options.

The easiest to configure, is "From panel argument", and its option in this case, "Second argument". This works fine in your situation.
The most flexible, that I always use, require more understanding of the Ctools context.

The argument setting then is "From context" and in this case "Taxonomy Term" -> "Name".
Save the View, go into the Panels UI, add the View Pane, not just a View.
Assuming your Panel Page now has a taxonomy term, which is always the case on the /taxonomy/term page, you will get a dropdown, most of the time with just one option, that lists the available terms that you pass on to the View.

If you for example had a path like /color/red/blue, because you wanted two terms, the second version will allow the re-use of the same View on the same page, with different content.


My site thinks it's a new install I had an error (related to Date module I think? Can't remember.) on my site so I tried to do an update. Caused a WSOD so I svn reverted. Didn't help. Manually disabled each module in the database. Didn't help. Fixed some permissions. Helped... sort of.

Now I get this:

  Drupal already installed To start over, you must empty your existing
  database. To install to a different database, edit the appropriate
  settings.php file in the sites folder. To upgrade an existing
  installation, proceed to the update script. View your existing site.

Running the upgrade script gives this error:

  PDOException: SQLSTATE[HY000] [2002] Can't connect to local MySQL
  server through socket '/var/lib/mysql/mysql.sock' (2) in
  drupal_get_installed_schema_version() (line 150 of
  /public_html/includes/install.inc).

Any other page redirects back to install.php.

So it seems like it can see the database to know that it's not empty, but can't really connect to it... what does this mean? What do I do about it.

I figured this out. It's able to see the settings.php file but instead of the right database credentials it was showing this:

$db_url = 'mysqli://mynamedrupal:xxxxxxxxxxx@localhost/myname-drupal-6';

That's goofy! I'm not even using Drupal 6! There wasn't any updated version of this later in the file; this was the only database connection info. It makes sense that this was in here, since it was originally a D6 site that I upgraded, but it's unusual that it worked so long without an updated array of DB connection info.

So I pasted this in from another D7 install and changed the un/pw accordingly:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'myname-drupal',
      'username' => 'myname',
      'password' => 'xxxxxxxxx',
      'host' => 'server.host.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

I can't say for sure if this works because now I'm having different, unrelated problems. But I think this solved this particular issue, as far as I can tell, and now I'm on to troubleshooting the next thing. w00t.


How do I remove white space from Bartik? I like to move the left hand side further left to remove the white space, as well as move the right hand side towards the right, so that the centre has more space. I like to remove line wrapping with entries and with the majority of my endusers using widescreen monitors it doesn't look that great.

Essentially I like to move the left and right sidebars towards the edges of their respective edges so the centre can become wider. I tried using the inspector and grepping for the relevant CSS code to modify but none of it seems to work.  Nothing else has been modified it is out of the box Bartik theme with no extensions.

Update

.layout-container {

  max-width: 95%;  /* 860px */
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}
@media all and (min-width: 95%) {
.layout-container {
max-width: 95%;
 }
}

/**
  * Main
  */
  .layout-main-wrapper {
   min-height: 300px;
  }
 .layout-main {
   margin-top: 20px;
   margin-bottom: 40px;
 }

This works if I edit the /core/themes/bartik/css/layout.css if I copy the theme and place it in the /themes folder it doesnt work.

First, you should not attempt to manually override and of Drupal's core files (or any other module or theme for that matter) because your changes will be overwritten during updates. So do not search for the CSS and attempt to alter it.

Make a copy of the bartik theme instead, move it to sites/all/themes and rename the folder and the .info file. Finally alter the info file to give your theme a new name.

All Bartik lay-out code can be found in layout.css. So you will have to modify widths and margins there.

Finally, I wanted to make you aware of the Responsive Bartik theme which is already slightly wider for widescreen monitors, but also optimized for mobile phone usage. You might find it usefull to use that instead, or use it as a base theme for your modifications.

Update for Drupal 8

You have the core/themes/bartik/css/layout.css file where you have to alter the max-width for wide screens:

/**
 * Container
 */
.layout-container {
  max-width: 860px; /* <- This is the default width. */
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}
@media all and (min-width: 851px) { /* <- Bigger than this means it is a wide screen */
  .layout-container {
    max-width: 1290px; /* <- This is the max-width for wide screens. */
  }
}

Most of the CSS properties are defined in percents and so they should scale along.


How can I remove an action link? I have a form that I'm creating and I'd like to get rid of the 'Add contract' button that is being put there automatically.
Is there something different I can do here:

function my_module_theme($existing, $type, $theme, $path) {
  module_load_include('inc', 'my_module', 'includes/admin/my_module.admin.forms');

  return array(
    'my_module_setup_form_contract' => array(
      'render element' => 'form',
    ),
  );
}

Or is there some other hook I can use?  I've been looking in the theme_my_module_setup_form_contract and my_module_setup_form_contract, but it looks like it's too late there.

This is for 7, btw.

You can remove local actions within hook_menu_alter().

If this is a generic action it will be removed on all of those forms. E.g. local actions for nodes - changes would be seen on all content types.


Using VDD with Drupal 6 site I'm trying to get a Drupal 6 site up and running with the Vagrant Drupal Development project.

I can get VDD going.. get my site installed, the database imported etc.. but I need to make VDD use an old version of PHP. I see some instructions online that say you can set which PHP version to use, but it isn't happening.. it doesn't say where in the json the setting needs to appear.

I tried with the following json, but it ended up as PHP Version 5.4.39-1+deb.sury.org~precise+2 :

{
  "php": {
    "version": "5.2.17"
  },
  "vm": {
    "ip": "192.168.44.44",
    "memory": "1024",
    "synced_folders": [
      {
        "host_path": "data/",
        "guest_path": "/var/www",
        "type": "default"
      }
    ],
    "forwarded_ports": []
  },
  "vdd": {
    "sites": {
      "drupal6site": {
        "account_name": "root",
        "account_pass": "root",
        "account_mail": "box@example.com",
        "site_name": "drupal6site",
        "site_mail": "box@example.com",
        "vhost": {
          "document_root": "drupal6site",
          "url": "drupal6site.dev",
          "alias": ["www.drupal6site.dev"]
        }
      }
    }
  }
}

VDD of  8 version doesn't support the feature of changing PHP version. You may try other Vagrant box for Drupal. For example this one, it has very good documentation.


Can you stop embedded Flickr Images from following their link if the user clicks the image, thus leaving your Drupal website? Using Drupal 7.37, Omega4-SubTheme
Acquia Dev-Desktop Stack (Development)
Windows 7 HP

Using Media Module with the Flickr provider Module installed, the Media_YouTube, and the Media_SoundCloud providers installed as well (along with their dependencies).

I set up some dummy-content via a customized Create-Content node. Added Flickr-Images as a field-type bundled with various tags to distinguish properties of my Media-Files for later categorization.  I have other Media-File-Types and their Providers installed as well (Media_YouTube, Media_SoundCloud) and they work fine without adding outbound-site-leaving-links.

Then I set up Views to output all the content of the website along with respective fields.  All this works and displays small representations of the media in a table along with my added fields.

In this Views display, Flickr embedded-images show up fine and can be styled, but unlike YouTube-Videos or SoundCloud_Audio-Files, Flickr-Embedded-Images will leave the website when clicked.  Both YouTube and SoundCloud do not exhibit this behavior and instead only play their respective Media.

Is there anyway to block, stop, or (best) redirect the Flickr-Images to show their associated node rather than linking to Flickr?

I have tried every configuration Option I can find.  I have tried options in the Create-Image-Content node GUI but I see nothing to suppress the outbound-links.  I have tried the Views-Display GUI, but again, I see nothing in the Views-Settings that suppresses the outbound-links.  And I have also tried the Administration>>Configuration>>Media>>File-Types setting for my Image-File-Types (this control-panel is very mysterious).  In none of these locations can I come across something which shuts-off this outbound behavior.

I have spent much time trying all kinds of option-permutations and searching for any kind of documentation but have come up with no solution.

Is there an option-solution or a css-workaround or do I have to abandon the Flickr-provider-module because this is its hard-wired behavior?

For now I have completely disabled Flickr as well as Media_YouTube and Media_SoundCloud in favor of using the Media_Oembed Module. Media_Oembed handles the all of the above Embed needs (and more).  In Media_Oembed, the Flickr Module does not out-link.  Probably a better overall solution in general.

  There are two OEmbeds!! At first, I tried Oembed, which is still in beta (as of 2015-06-03) and I could not get it to work; I don't know what the problem was, but Media_oEmbed seems to work fine.


Checking if a machine_name exists or not My EntityForm has a field where

  '#machine_name' => array(
    'exists' => array($this, 'load'),

To check the validation of this, I wanted to know about writing the function load() in my EntityListBuilder to check its validation.

A way around would be to use ctools:

ctools_include('export');
$result = ctools_export_load_object('module_entityname', 'names', array($field_id));

However, I wanted to avoid using ctools.
Are there any Drupal 8 APIs available to check the validation of #machine_name?

The exists key wants a callback that it can test for boolean true/false. The machine name to test will be passed as the first (and only) argument to that callback.

Since your entity class (not the list builder class) already has a load method, inherited from Entity::load(), which accepts an ID and returns either an entity object or a null/false value, you can (and probably should) use that.

So, assuming your entity is defined as \Drupal\mymodule\Entity\MyEntity, you would use the following:

'#machine_name' => array(
  'exists' => '\Drupal\mymodule\Entity\MyEntity::load',

Exactly the same method is used in the CommentTypeForm, and probably others:

$form['id'] = array(
  '#type' => 'machine_name',
  '#default_value' => $comment_type->id(),
  '#machine_name' => array(
    'exists' => '\Drupal\comment\Entity\CommentType::load',
  ),
  '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
  '#disabled' => !$comment_type->isNew(),
);


Views slideshow without jQuery Cycle I have a view slideshow that I managed to set up by following these instructions.

I want to use a responsive slider plugin instead of the jQuery Cycle plugin in Views Style Settings. How can I use this JavaScript code to create the slideshow.

This isn't exactly what you asked for, however:

I have tried a bunch of slideshows that claim various degrees of responsiveness and the best out of the box solution I have found that works as expected, is easy to set up, and is properly responsive, is the flexslider module, which can either be used by itself, or can be used with the views slideshow module.

If you haven't tried it it is definitely worth trying.


How to get the children terms of a taxonomy in views? I just created a view to show terms of a given vocabulary. I works but the children terms aren't shown.

How do I do to get children terms?

Depending on how many levels of the tree you want to show. If entire, complex vocabulary, then Views Tree module would be an answer.

  This module provides a tree-based style plugin for Views.

However if this is just a 2-level tree, you might want to set up a view that displays terms and groups them by their parent. For that you'd need to select also Term: Parent, exclude it from display and group the view by Parent.


How to use view's relationships to pull user entity reference data? I created 2 new user fields for the user (object/entity) on my D7 site. Using views, I can select 'content' or 'user' for querying data. When I use views to query the 'user', the 2 new fields come up just fine. However, when I select 'content', the 2 new fields are not there. This makes sense to me since the 2 new fields are tied to the user entity.

For my purposes, I need both content AND user data. The strange or weird thing is, when I select 'content' for my base and use relationships to find and pull user entity fields, SOME old custom created fields already tied to the User Entity is present and I can select them, BUT my 2 new fields are not.

I tried clearing caches and making sure I had active content with the 2 new fields enabled. So why can I find in relationships, entity references to old custom fields, but not my new fields I created?

It feels like a catch 22. If I select user, I have my new fields, but not the content, and vice versa.

There is a Relationship that introduces "backwards" Entity reference info into the Views.

In Drupal 7 that is called something like this (you can find this in the list of Relationships in your Content Views under the Entity Reference Category):

  Entity Reference: Referencing entity
  A bridge to the User entity that is referencing Content via field_[myERfield]

After you have that you will be able to add the User: Name field, it will automatically use the above Relationship, and it will show which user referenced that particular node, for your each Views row.

In Drupal 8 the Relationship is called

  User using field_[myERfield]
  Relate each User with a field_[myERfield] set to the content.

The procedure is the same, you can now add Fields or Filters relating to User fields/data, if they're set to use the Relationship the user shown will be the one referencing the content of that Views row.


If I don't see the "Full HTML" and "Filtered HTML" input formats, is it OK to add them manually? I currently only have a "plain text" format.
Is it ok for me to add additional "Text formats" on the "Configuration" screen? Eg. Full html, filtered html etc?

Or should these have been created automatically when I installed the ckeditor and IMCE modules?

By default, Drupal 7 includes plain text, filtered HTML, and full HTML text formats.

If you are not seeing these as choices, you are probably not logged in as an administrator and you do not have the appropriate permissions.

Non-administrators are not given access to full HTML by default because this can be a security risk.

Try logging in as an administrator and going to the permissions management page.  Verify the permissions for Use the Filtered HTML text format etc. under Filters.

Of course, if you need an input filter with a custom configuration, you can certainly create your own.  Just be careful to not give your users any input options they shouldn't have.


Workaround to post inline JS code at any time in D8? In Drupal 7 this worked:

drupal_add_js("jQuery(document).ready(function () { console.log('Hello!'); });", 'inline');

which aims to print the messages from the PHP code onto DevTools JS console in realtime (on each page request), however in Drupal 8 the above function has been removed in favor of #attached.

I'm aware that I should use #attached in my library, but sometimes the $form is not accessible and I'd like to invoke some JS code on certain functions and conditions (e.g. in hook_tokens) for debugging purposes (like injecting some PHP variables into the JS message during the processing).

Is there any other way of doing this?

Sometimes the $form is not accessible and  I'd like to invoke some JS code on certain functions and conditions for debugging purposes.

Not sure if this will do for you, but posting this anyways just in case.
I use Greasemonkey for Firefox and Tampermonkey for Chrome which allows your browser to load any js file that you write locally on this app/your computer.


Set default selected radio button on webform I have a standard contact page created using webform, which has a set of radio buttons. How can I make one of the radio buttons selected by default?

This quesion is similar, but it relies on the refering link, which I would rather not.
Set default radio button on webform

There should be an option to set a default value when you go to edit that field in the webform. You have to set it to the "key" of the value you want selected by default. Your options should be listed as key|value under the field options.


Load node by value of a field and update value for another field I'm trying to load a node by a value in a custom field (field_one) to change the value of another custom field (field_two) on that node.

I am using the following code to load the node:

$nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_one' => $fieldValue]);

I am then trying to update the value of "field_two" using the following code:

if ($node = reset($nodes)) {

    $node->set('field_two', 'New value');
    $node->save();
}

The above results in the error "InvalidArgumentException: Field field_two is unknown... "

It works if I try to set the value of the title ( $node->set('title', 'New value') ) but I can't get it to work for custom fields?

Thanks to the comment by @No Sssweat I realized that I simply needed to specify a content type:

$nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_one' => $fieldValue, 'type' => 'CONTENT_TYPE']);


Files in the file_managed table with status of 0, not deleting on cron I have a form where I am uploading files to the "sites/default/files" directory. I am using the managed_file type in my form API definition. This is all working fine and I notice that in the file_managed table, I see my uploaded files with a status of 0 meaning they are temporary. I was under the impression that these files that have a status of 0 should get deleted, not only from the database, but physically from the server on cron run, but I do not see this happening. I see lots of files with a status of 0 and they are NOT in the file_usage table, so they are not being used by anything, yet if I force a cron run, I don't get errors, yet the files do not get deleted either. Am I misunderstanding how this system works?

Thanks

They are deleted, but during cron tasks, and just when:

They aren't marked as permanent
They are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE seconds
No module contains a reference to those files

The code that deletes those temporary files is contained in system_cron().

  // Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. See http://drupal.org/node/352956.
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        if (!file_delete($file)) {
          watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->uri), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('file system', 'Did not delete temporary file "%path" during garbage collection, because it is in use by the following modules: %modules.', array('%path' => $file->uri, '%modules' => implode(', ', array_keys($references))), WATCHDOG_INFO);
      }
    }
  }

If the files are not getting deleted, and you don't see any error message in the watchdog log database, then you need to check cron tasks are executed and the files are older than 6 hours. In the other cases, you should get an entry in the watchdog database table, even if that would be a generic Could not delete temporary file.


Drupal8 site status - "unsupported release" / "not supported" is this deliberate? Is this a deliberate message as drupal8 is not yet the latest production release?

The reason for raising this question is that it was unexpected in my opinion to see this. I would not have expected to see messages about unsupported / not supported - after all, Drupal 8 is being very actively developed, so to my mind it IS supported. Maybe it depends on the point of view - i.e. for production, then no, not yet. Please advise, thanks!

(see screenshot below)

Tried searching issue list for drupal 8 on drupal.org a few times but blank screen - perhaps volume of issues and peak time may be causing the results to not be displayed. Haven't raised this as an issue because it may be something I've not done right in the setup.

Wondering if it might be related to this problem (which appears to be just a warning, though):

$ drush up
The external command could not be executed due to an application error.

(Discussed here: Error when updating modules with Drush )

My system setup

Running on a puphpet.com configured VM, Ubuntu 12.04 LTS 64bit
PHP 5.5.12-2+deb.sury.org~precise+1 (cli) (built: May 12 2014 13:46:35)
mysql  Ver 14.14 Distrib 5.5.37, for debian-linux-gnu (x86_64) using readline 6.2
Drush Version   :  7.0-dev

Obtained drupal8 doing the following:

$ git clone --branch 8.x http://git.drupal.org/project/drupal.git drupal8.localvm
Cloning into 'drupal8.localvm'...

and then

$ git pull
Already up-to-date.

That was probably a warning in Alpha. We're now at Beta 7, and it's now yellow instead of red:
There are currently 55 critical issues remaining:
https://www.drupal.org/project/issues/drupal?priorities=400&version=8.x
Which still gives a nice trend line toward 0, and release candidates:
https://plot.ly/~xjm/37/remaining-critical-issues-during-the-drupal-8-beta/


How to make my blocks switch to another block when session was set? I have 2 header block, default 1 is the login form and the other block was for logout button. I want to make this two blocks switching after triggering the login button

You can do this in code:

if (\Drupal::currentUser()->isAnonymous()) {}

Or in block layout by configuring the visibility of roles:

When the user has the following roles

Anonymous user
Authenticated user
Administrator

The first block for anonymous users and the second block for authenticated users.


Generate a Barcode from Form Data & Submit Form Data to Database (for Views) I'm trying to create a bar code generator like the one at http://qr.insready.com/node/add/vcard . This generator is created with Drupal 7 & the Barcode contributed module (by the module's creator).

What I need my application to do is accept a number of items of user data input into a form, concatenate the field entries using tokens into the barcode input field, then generate a bar code on form submit as well as save the data into a database.

This is what I've accomplished so far. I have created a custom multi-part form module following the example in the Examples module, & got it to input data into the database. (I don't know if this will be exposed to Views, since I'm learning this as I go; it's a table I created within Drupal's database specifically to store the data.) Independently, I have created a custom content type with a barcode field that gets tokens from other fields in the form, & successfully creates a bar code encoding the data from the fields in concatenated form.

I would appreciate some pointers on getting this working together. What I need is a way of getting the barcode field into my custom form. Then it can pull data out of the other fields using tokens just as with the custom content type I created.

I can post code snippets if they are needed.

Have taken a look at these modules.  MERCI Barcode, Views Bulk Operations Barcode Select , Barcode

The first two are for Drupal 6 only so they will not work in a Drupal 7 site out of the box. If you save the files without installing them you can read the code and see what they did.  The Third one has a beta for Drupal 7.x, so it can be installed.  Feel free to borrow code to learn how.

As for getting it to work together...we would need specifics to provide answers.  Ask about whatever your stuck on.


How to get field data for Panels style plugin? (ctools context?) I think this is a Ctools context question. I'm writing my first Panels style plugin and am having trouble getting field values from nodes inside the pane. I'm basically trying to recreate the plugin from this tutorial, http://precessionmedia.com/blog/creating-custom-panels-style-plugin-background-image-support, but I have changed it from a region plugin to pane plugin. The pane contains a list of node fields generated by Views, and I need to get the info from an image field but I'm not sure how to proceed.

In the link above, the render region callback uses this function: ctools_context_keyword_substitute($string, $keywords, $contexts, $converter_options = array()), where $contexts is $vars['display']->context, but this array is empty for me. I'm also not sure what values to use for $string. In the example link above, $string is replaced by the value entered into the style plugin settings form and the example given in the tutorial plugin is %node:field_image, isn't this just a token? I'm not sure if this is the right token to use, but I believe the missing context array is what is breaking this function for me.

Thanks, any help is greatly appreciated.

I had to add a Relationship to the File from the Context section of the panel variant (e.g. File from Node (on Node: Image [field_featured_image])). Now you will be able to use %file:url in the image field. Basically, the token you use needs to be listed in the summary of contexts.


Get profile2 fields based on user I am trying to retrieve some fields from my Profile 2 profile but am not sure how I should connect the table dr_field_data_field_resources to its relevant user.

In profile it is possible to add a field term_reference 'resources', then I want to be able to retrieve those values in an array based on a user I specify. I did see some other docs for profile2_load, but I using an example turorial. I am getting called to undefined function for profile2_load().

$userskillsresources = db_query("SELECT dr_users.name as 'username', dr_taxonomy_term_data.name  as 'userresourceterm'
    FROM dr_users
    JOIN dr_field_data_field_resources
    JOIN dr_profile ON dr_users.uid = dr_profile.uid
    JOIN dr_taxonomy_term_data ON dr_field_data_field_resources.field_resources_tid = dr_taxonomy_term_data.tid
    WHERE dr_users.uid = '10'")->fetchAssoc();

If you really do have Profile2 installed and enabled, then you shouldn't get getting undefined function errors.  Double check that it is enabled.

Otherwise, you are going about this in the wrong way.  You really don't need to do queries like this.  Leverage the API:

$account = user_load(10);
$profile = profile2_load_by_user($account);

If you have a single profile for the user, $profile will be a node object.  Otherwise, it will be an array of nodes.  Then you can do something like:

$resources = field_get_items('node', $profile, 'field_resources', $profile->language);

Also take a look at this article for a handy helper function or read more about the Field API.  If $resources are taxonomy terms, then take a look at taxonomy_term_load for loading the associated terms.


Is there a hook I can use to alter the way comments are rendered? Is there a hook I can use to alter the way comments are rendered? Not for altering the comments form, but the listed comments themselves. Obviously, I can target with CSS, but I was wondering if I can hook into core and change the way they are displayed from there?

Thanks

You can use hook_comment_view():

  The comment is being viewed. This hook can be used to add additional data to the comment before theming.

e.g.

function hook_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->time_ago = time() - $comment->changed;
}

Or use a standard theme preprocess hook

function MYTHEME_preprocess_comment(&$vars) {
  // Make changes to $vars that will be available in comment.tpl.php
}

You can also override the standard comment.tpl.php file in your theme to have full control over the markup.


Class Autoloading include file Class autoloading isn't working in custom module to extend webforms. Trying to call a function like this:

$utility = new webform_kk_utility();
$utility->getComponents('aaa')

getting this error:

[Mon Sep 21 20:29:28.287580 2015] [:error] [pid 15908] [client ******:39831] PHP Fatal error:  Class 'webform_kk_utility' not found in /var/www/html/sites/all/modules/webform_kk/webform_kk.module on line 12

Here's my code:

webform_kk.info:

name = Webform kk
description = custom webform code
core = 7.x
package = Webform
dependencies[] = webform
files[] = includes/utility.inc

webform_kk.module:

<?php

function webform_kk_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_1') {
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'webform_kk_submit_1');
    }
}

function webform_kk_submit_1(&$form, &$form_state) {
    $utility = new webform_kk_utility();
    echo $utility->getComponents('aaa');
    die();
}

includes/utility.inc:

<?php

Class webform_kk_utility {
    function getComponents($components) {
        return $components;
    }
}

I tested the code without calling the external function, the code is running and the form submit dies where expected. I tried disabling, uninstalling the module and clearing the cache.

Thanks for the help.

"Class" -> "class".
It needs to be lowercase, or else Drupal does not discover it while scanning the file.


BLOCK_NO_CACHE with Normal page cache enabled I'm trying to create a block, which shouldn't get cached, even for anonymous users. But there's "Normal" page caching enabled on the website. As I've read in various places, the BLOCK_NO_CACHE setting doesn't really count for anonymous users when page caching is enabled.

As it stands, it's not an option for me to turn off the page caching, as the website receives moderately high traffic.

I've first tried injecting some HTML with hook_footer but this function doesn't get called as well when page caching is enabled.

The block I'm trying to implement is a very simple one, it only has a bit of text and a link, which upon clicking, sets a cookie on the user's browser (with PHP), and returns the user back to the page where they clicked the link on. Upon returning to the page, the block needs to attempt to read the cookie, and if the cookie is set, the block should no longer be displayed.

However with page caching turned on, if AnonymousUser-A clicks the link and no longer sees the block, then AnonymousUser-B comes to the site, they also don't see the block.

Is there a workaround I can use to get around this issue? As you can see from my use of hook_footer, I'm not heavily inclined to implement this as a block. Any solution that will fit the above purpose is welcome.

Ajax Blocks or Ajaxify Regions (since you're in D6) allow dynamic blocks within cached pages.


looking for views gallery module compatible with lightbox module I would like to achieve a behaviour like this:

At the bottom of the screen there are thumbnails. Above them is a big image styled for 800x600 which changes after clicking a thumbnail. When the user clicks on the big image, then an overlay with lightbox opens and the image is not 800x600 but full size, scaled to screen. There are working Next and Previous buttons on the lightbox (not necessarily linked to the underlying thumbnails gallery).

How to achieve it? I am interested in a solution working either out of the box or having  clear tweak instructions. Any gallery module and any lightbox will do, as long as they are compatible and have next/previous buttons working.

So far I tested Views Galleriffic and Lightbox2 and Colorbox, using patch from here and I managed to open the big image in original size using lightbox2 and colorbox. However, Previous and Next buttons are not working in either case.

Have you tried Views Slideshow with Views Slideshow Xtra?
Here are some more details about these modules (quotes included are from their project pages):

Views Slideshow:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Views Slideshow Xtra:

... is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in  overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.


Is there a "registry rebuild" command? I just did a fresh Drush installation, and now I have version 8.1.15.

When I run drush rr, I get the following error message.

  The drush command 'rr' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions.

Even after running drush cache-clear, I still get that rr is not a known command.

Is this still available in Drush 8?

Take a look at https://www.drupal.org/project/registry_rebuild

The documentation is there:

  How To Use Registry Rebuild With Drush

  This is the preferred technique, and it should work with multisite installs.

  You can just drush @none dl registry_rebuild-7.x and drush will download it into your .drush folder. (Alternately, you can obtain the package another way and copy the folder into .drush yourself.)

  Make a backup of your database.

  Clear Drush own cache with drush cc drush

  On a multisite install, either use correct drush alias, or cd into the site you're rebuilding, as in cd sites/mymultisite

  Run drush rr or drush @sitename rr for soft rebuild (default), or:
      To force aggressive rebuild from scratch run drush @sitename rr --fire-bazooka


How to handle a node translation containing an entity reference with a managed field property I have a custom field that contains a managed file. The node that the field is attached to and the field are enabled for translation.

I create a piece of content, which defaults to the site default language EN. The content contains a managed file, let's say FID 1.

From the admin content screen I select Translate and add a translation. When the node edit form is rendered, it contains the values from the original content as it should, and contains the file information as well, so that I need to remove the original and add a new one.

When I save this version, language ES, both appear on the admin page and in the db. The property for the managed file in ES has FID 2.

The issue is when switching back to English using the language widget on the home page, a 500 is received. The reason is that removing the managed file from the Spanish translation in order to add the correct one resulted in the actual file being removed as well as the FID 1 file_managed table entry, but 1 still remaining in the property value for the managed file in the custom field.

I could probably finagle the custom field widget to not present a default value for the managed file property somehow in the case of adding the node, but that seems wrong, because it's possible that the user to leave the file the same.

Is there a standard way to handle this?

There are a number of issues with reference counting files: see this overview. You might be affected by $entity->isDefaultTranslation() behaves incorrectly when changing default translation, causing file/image field usage to be set to zero, causing files to be deleted.

Note that due to the potential for lost data, as of 8.4 the default behaviour has been changed to not delete files even if their ref count reaches zero. See the CR for more.


How to restrict download file for authentication in drupal I have create one file field in my node create form , file is accepting (txt,pdf,xlx,docx) files only.
 but in node view page, i want to authenticate our file before download.

I have create one term and condition checkbox, if user check this term and condition checkbox , then he should be able to download the file..

This functionality i need to do, please suggest me any module is available for this..

or if this functionality is possible through conditional fields , so please suggest me, how can i do

You can try Field Permission Module

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

Demo Video


How to transmit parameters to Rules Component upon using Rules Scheduler programmatically? Now I'm trying to create a Rules Scheduler task programmatically.

I've created a Rules Action with parameters and callback, also I've created a Rules Component with this Rules Action.

But upon trying to create the Rules Scheduler task programmatically I can't transmit it parameters for the Rules Component.

I'm using code, found here.

$now = new DateTime();
    $component = 'yrv_invitation_coupon_test_rule';
    $task_id = $now->getTimestamp();

    rules_action('schedule', ['component' => $component])
        ->executeByArgs([
            'date' => $now->getTimestamp()+10,
            'identifier' => $task_id,
            'param_uid' => 10,
            'param_rid' => 5,
        ]);

It works, but with default parameters.That is, executed Action in the Component can't get param "uid" with value = 10 and param "rid" with value = 5.

Could ou clarify me, how can I assign parameters ?

Here's my Action

$actions['yrv_invitation_coupon_user_remove_role'] = [
        'label' => t('Remove a role assigned upon activation an invitation coupon'),
        'group' => t('System'),
        'base' => 'yrv_invitation_coupon_remove_role_callback',
        'parameter' => [
            'uid' => [
                'type' => 'integer',
                'label' => t('User ID'),
                'default value' => 1,
            ],
            'rid' => [
                'type' => 'integer',
                'label' => t('Role ID'),
                'default value' => 1,
            ]
        ],
    ];

And here's my Rule Component

$rule = rule();
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', ['uid' => 1, 'rid' => 1]);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;

Fortunately, I managed to find the solution.

Namely, a Rule component should be created such way.

function yrv_invitation_coupon_default_rules_configuration()
{
    $configs = [];

    $rule = rule([
        'uid' => [
            'type' => 'integer',
            'label' => t('User ID'),
        ],
        'rid' => [
            'type' => 'integer',
            'label' => t('Role ID'),
        ],
    ]);
    $rule->label = 'YRV Invitation coupon test Rule';
    $rule->class = 'Rule';
    $rule->action('yrv_invitation_coupon_user_remove_role', []);
    $rule->active = TRUE;

    $configs['yrv_invitation_coupon_test_rule'] = $rule;

    return $configs;
}


White screen appears when viewing huge number of nodes as view result I have a View which display fields of nodes. I have to display all of the items. I cannot introduce a Pager.

There are approximately 4000 nodes as the result of the view. The View preview works perfectly fine, i.e all 4000 nodes are displayed, in the View preview result.

Placing the View on a panel page and loading the page gives the "White screen of death".

What could be the problem?

Why not try use this module View Infinite Scroll to try stagger the amount of results returned by Views in one go? This would help the web server from running out of memory returning 4000 results in one go, but is better UX wise than implementing a pager.


View Path TaxonomyTerm/sub-page I am looking to create a QUESTIONS view for all terms in a taxonomy vocabulary. Let's say I have a taxonomy that has terms apple, orange, banana. We use pathauto to go to domain.com/apple which shows one content type.

But what I am trying to do is create a sub page for each term with the path:
domain.com/apple/questions

I have already set the view and added a contextual filter but for some reason, its is not working.

The path that I have for the view is (/taxonomy/term/%/questions)

Is this correct? Am I approaching this the right way? If you have a better suggestion please let me know.

The Panels module provides the views content panes which is a display type for views, there you can create your view easily, make it fetch input argument from context and show the results, then you can simply include your pane in the place you want.

if you are not much familiar with Panels module, then this tutorial can make you became familiar, hence this is for Drupal 7 but you can use it in drupal 8 as well.


Migrating a Drupal 6 site to Drupal 7 can I copy the D6 database as a local source? I am trying to migrate a small D6 site over to D7 and the Migrate/D2D modules look like they will handle most of my content. Is there any way to simply copy the D6 database over to the D7 machine and use it as a local source to migrate into the D7 database?  Or, do I need to specify a path and access credentials to the mysql server on the active D6 website?  Thanks.

Yes, you can source the migration from a copy of the D6 database running on the same database server as the D7 site's database. Be aware: the migrate D2D wizard will ask you for a "File prefix". In the "File prefix" field, you must specify a path to the uploaded files directory of the D6 site. Those could be a local copy also.

If in addition, you are asking how to copy a MySQL database from one server to another, that may be out-of-scope for Drupal Answers. There are tons of resources on the Internet for that—your own hosting provider may provide tools to do this. But I won't stop someone else from answering if they please. Apologies if that is not an aspect of the question posed.


Beginner Drush question. Can't get Drush to do anything! I can't get Drush to do much.  I can connect to my site by typing cd and then dragging my files to the terminal window in OSX using Acquia DevDesktop. My overall goal is to create a sub theme of Omega.

When I type drush omega-wizard I get:

  The drush command 'omega-wizard' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions. [error]

  Drush was not able to start (bootstrap) the Drupal database.         [error]

  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a
  configured database. In this case you can select another site with a
  working database setup by specifying the URI to use with the --uri
  parameter on the command line. See drush topic docs-aliases for
  details.
  connect the database through a socket. The socket file may be
  wrong or the php-cli may have no access to it in a jailed shell. See
  http://drupal.org/node/1428638 for details.

I think this means that I haven't shown Drush where the settings file is.  For the life of me, I'm not able to do that.  Normally, I would do something like:

cd sites/nameofsite.localhost

or

cd site/nameoffolder.localhost

I've tried every iteration of this command: with the localhost, without the localhost, different folder names, etc.  I always get "No such file or directory".  Can anyone tell me what I'm doing wrong?  What does Drush need me to tell it?

Thanks so much in advance,

Jason

There is a known problem of using Drush with DevDesktop on MacOSX.

Quick fix

Instead of running drush like this:

$ drush status

Run it like this:

$ DEVDESKTOP_DRUPAL_SETTINGS_DIR="$HOME/.acquia/DevDesktop/DrupalSettings" drush status

Permanent fix

Everything is explained in this article:
http://btmash.com/article/2015-03-24/using-dev-desktop-composer-drush

Why is it happenenig?

Acquia DevDesktop keeps all credentials in a specific folder and let PHP have access to that location via a $_SERVER variable called $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']. This variable is provided by Apache and PHP only sees it is run by Apache. But when you use Drush, PHP is called directly and that variable does not exists anymore and Drush cannot find the database credentials.


How to create content / entity via ajax on a view? I have a view listing some content and I want to have an "Add new" button, which should load the node form via ajax (either modal or into a div). After I save the form, it should still stay on the page. Updating the view would also be nice, but for the first thing I'm trying to load the node form via ajax. How can I do that?

The most basic version would be to add 'use-ajax' to the "Add new" button link pointing at a controller which returns an ajax command replacing the div. See https://www.drupal.org/docs/drupal-apis/ajax-api/basic-concepts#s-trigger-ajax-request-with-a-link.
Modals use also the 'use-ajax' class but need additional 'data-dialog-*' attributes. Then you can load normal HTML content in a dialog box, you don't need an Ajax controller in this case. See https://www.drupal.org/docs/drupal-apis/ajax-api/ajax-dialog-boxes
In a submit handler of the form you have to make a redirect to a URL you have setup to display the updated view together with the form.


Using computed field value in Rules I'm using Commerce module and I have a line item with a computed field that's calculating a date. This field finally shows a date.
Then during the checkout process I have a form with a Date field (part of the Order). I'm running some Rules and finally I have to copy one of the calculated dates to this field but i couldn't by rules.
I tried with a simple rule "set a data value" trying to copy the Computed field value to the other field. I put a "has field" with the CF. Then in actions, the field doesn't appear in the data selector.
This is normal? Is there another method to do it?

You may want to give it a try to use the NOT commonly known/used alternative available for the Computed Field module, i.e. the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Known issues

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


Move File Field storage from public:// to another stream wrapper (like s3://) I've been looking around for this a bit, and it seems like it would be relatively easy in Drupal 7, since D7 supports stream wrappers, and Fields are part of core... but I can't find any documentation.

I have a file field with a few thousand files attached to nodes, and it's using public:// right now.

I also have the AmazonS3 module installed, and some other file fields are already set to use the s3:// stream wrapper.

I now want to migrate the file field using public:// to s3://, and I want all the files already uploaded to the site's files folder to switch to s3. I can manually copy over the files to a bucket on S3, but what exactly would I need to do in Drupal/the database to get the files to be loaded over s3 instead of public?

I thought about just writing a custom query to update all rows in the file_managed table with public://custom/path to change to s3://custom/path, but (a) there are some older files that were migrated with different paths than custom/path, and (b) I'm not sure if this is the right way to get Drupal to use S3.

[Edit: Just noticed the file_move() function in the API—would I be able to move files using this (after switching the field storage in the Field UI) instead of having to manually copy files and update the database?].

For the paths that match across the two servers you can just change the paths in file_managed to start with s3://, clear the caches, and the S3 module will handle the rest.

This module should be really helpful, I've just written a module for someone which is pretty similar to what you're trying to do (except the files are pruned from the local file system to S3 on a cron) and the module in that link was a great starting point.

Since the S3 module implements a fully functional stream wrapper you can use all of the usual file functions (file_copy, file_move, file_delete, etc) as normal, without having to worry about where the files are.


add a field to registeration to subscribe to newsletter module I want something like the enewsletter module (it is for Drupal 6) for Drupal 7.

I used simplenews module, it add a subscribing field to user registration and it is well, but my problem is that in registration user select with category(from favourites taxonomy) want to be subscribe, and in creating simplenews content type select the term that this email send to them,( send simplenews content type according to taxonomy terms ).

I found simplenews terms module but it is for Drupal 6.

I try newsletters module but it is very complex and doesn't provide something I want.

in /admin/config/services/simplenews/add add multiple category you want,
by adding any category here, add term to newsletter category and you can do any thing with its taxonomy


How to render a user register form for a Profile2 type Since all of the Profile2 registration forms have the same id 'user_register_form' (even when using Profile2_RegPath module) how can I specify a Profile2 type when calling:

print(drupal_render(drupal_get_form('user_register_form')));

I need to be able to let the user create an account without having him leave the page. I'm able to print the Register and The Profile Fields to be edited, but they each have their own Action button which is what I do not want.

After looking through the Profile2 Git repository viewer for v1.3. I believe you want to do something like the following using profile2_attach_form. The `profile2_attach_form has the following API comment and function signature:

 /**
 * Attaches the profile forms of the profiles set in
 * $form_state['profiles'].
 *
 * Modules may alter the profile2 entity form regardless to which form it is
 * attached by making use of hook_form_profile2_form_alter().
 *
 * @param $form
 *   The form to which to attach the profile2 form. For each profile the form
 *   is added to @code $form['profile_' . $profile->type] @endcode. This helper
 *   also adds in a validation and a submit handler caring for the attached
 *   profile forms.
 *
 * @see hook_form_profile2_form_alter()
 * @see profile2_form_validate_handler()
 * @see profile2_form_submit_handler()
 */
function profile2_attach_form(&$form, &$form_state) { /* ... */ }

So, you could use it as follows by slightly modifying your code:

$user_register_form = drupal_get_form('user_register_form');
$form_state['profiles'] = array(
    'CUSTOM_PROFILE_TYPE_NAME' => profile2_get_types('CUSTOM_PROFILE_TYPE_NAME')
);
profile2_attach_form($user_register_form, $form_state);
print(drupal_render($user_register_form));

If you need to tweak any profile entity form displayed in some of your registration page(s), you may want to implement the specific FORM_ID version of hook_form alter, hook_form_profile2_form_alter().

EDIT 01/15/2015

minor API clarification and code cleanup from comments.