Urls without question mark are served with 404 in Drupal 7 with Nginx I am migrating an Drupal 6 site to Drupal 7. I encountered some behavior, I cannot explain and would like to ask the community.

As I was testing if all urls work, I noticed, that there are urls like example.com/node&a=b (without ?), which return 200 on Drupal 6 site and 404 on Drupal 7 one. (Normal urls like example.com/node?a=b are served with 200)

As I understand, these urls are not correct (maybe lost the question mark on copy/paste), but I think it is still better to serve the page, because the main part of the url is correct. Even better would be to redirect to the correct page with 301.

But I cannot find, if the problem is in the Nginx configuration or if it is a desired behavior on Drupal 7. I am using the Nginx configuration example from http://wiki.nginx.org/Drupal.

Maybe someone could tell, if this behavior (404 on links without question mark is default for Nginx or Drupal 6/7)?

Edit: the malformed links come from access.log, there are some clients, which try to fetch them. Mostly search engines and bots.

After some debugging, I think, I can understand what happens.

Take a look at this Nginx rule from http://wiki.nginx.org/Drupal:

  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().
            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }

I'm using the Drupal 7 rule and it tells Nginx to just execute the /index.php without any argument handling. Next, Drupal initializes and runs the drupal_environment_initialize() function, which calls the
request_path() function. Here Drupal tries to parse the $_SERVER ['REQUEST_URI'] variable. And of course, here is no special handling for malformed urls, I see in my logs.

I think, that's the difference between my old Drupal 6 install and Drupal 7.

Another rewrite rule from Nginx
No url parsing by Drupal

Basically the question is not so big, if some search engine is too dumb to create malformed urls, it's not my problem. But I wanted to handle it, so I modified the Nginx config, by adding a rewrite string, which redirects malformed urls:

  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().

            # redirect bad urls like /page&a=b to /page?a=b
            rewrite ^/([^?]*?)&(.+?)=(.+?)$ /index.php?q=$1&$2=$3 permanent;

            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }


Display plugin block markup raw I have built a custom block plugin in Drupal 8. However, I needed to insert some svg elements in the markup, which get all filtered out. Is there a way for me to specify to display the raw output, so that the svg does not get filtered out?

  public function build() {

    return array(
      '#type' => 'markup',
      '#markup' => '
<svg>.....</svg>
',
    );
 }
?>

I have tried adding '#template' => '{{ value|raw }}' and played some with it - but could not get it to work. There must be some way to allow me to insert svg in there...

You can use an inline template:

  public function build() {

  return array(
    '#type' => 'inline_template',
    '#template' => '
<svg>{{ var }}</svg>
',
    '#context' => array(
      'var' => $svg,
    ),
  );

You can use the inline template with an empty context, if you have no vars that need to be escaped:

  return array(
        '#type' => 'inline_template',
        '#template' => '
<svg>...</svg>
',
        '#context' => array(),
      );


What is the equivalent of hook_property_info_alter()? In Drupal 7, we had hook_entity_property_info() and hook_entity_property_info_alter() which allowed us to add custom properties. (Not everything is a field.)

I can't find anything related to Drupal 8. The only thing I find is how to add it on a custom entity. How should I add properties to an existing entity/bundle?

I suppose you want hook_entity_base_field_info(). By using a computed field based on a class, you can get a behavior similar to properties.

function hook_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = [];
    $fields['mymodule_text'] = BaseFieldDefinition::create('string')
      ->setLabel(t('The text'))
      ->setDescription(t('A text property added by mymodule.'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedText');

    return $fields;
  }
}

I have copied a snippet from Drupal commerce, where a payment gateway reference is appended to a commerce_order entity (commerce_payment module altering an entity from commerce_order module).

/**
 * Implements hook_entity_base_field_info().
 */
function commerce_payment_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_order') {
    $fields['payment_gateway'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment gateway'))
      ->setDescription(t('The payment gateway.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_gateway');

    $fields['payment_method'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment method'))
      ->setDescription(t('The payment method.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_method');

    return $fields;
  }
}

By using ->setReadOnly(TRUE); or ->setComputed(TRUE), you can probably hide them from regular forms, making them behave like properties.


the javascript for dragging and dropping not loading - drupal 7 for some reason when I add new modules the tabledrag.js is not loading.  Tried taking the modules out, clearing cache several times.  Aggregated js as well.
Can anyone help.

I solved this by installing http://www.drupal.org/project/speedy

it minifies core javascript files


Module update manually multiple versions at once Actually my website use module views 7.x-3.5 version. The last version is 7.x-3.11, so i need update. My question is if I can upgrade (replace folders and code) directly to version 7.x-3.11 and run mysite\update.php or I need apply each new version separately running update.php for each, e.g. views 7.x-3.6, views 7.x-3.7...

You can replace it with the latest version and run update.php. Drupal modules keep track of what version data schema it's on; update.php will apply the needed DB updates since 7.x-3.5.


What are the equivalent functions that I should use for HTTP handling? Looking at the functions listed in the HTTP handling page for Drupal 7, I noticed that the following functions don't exist anymore in Drupal 8. (The links are for the Drupal 7 documentation pages, where the links to the Drupal 8 documentation for those functions are missing.)

drupal_access_denied()
drupal_get_query_array()
drupal_goto()
drupal_http_request()
drupal_not_found()
drupal_site_offline()

What functions/methods should I instead use in Drupal 8?

These are the functions/methods/classes that should be used in Drupal 8.6.x code.

drupal_access_denied() has been replaced from the AccessDeniedHttpException class. Page callbacks that need to return the Access Denied error should used code similar to the following one.

// system_batch_page()
public function batchPage(Request $request) {
  require_once $this->root . '/core/includes/batch.inc';
  $output = _batch_page($request);
  if ($output === FALSE) {
    throw new AccessDeniedHttpException();
  }
  elseif ($output instanceof Response) {
    return $output;
  }
  elseif (isset($output)) {
    $title = isset($output['#title']) ? $output['#title'] : NULL;
    $page = [
      '#type' => 'page',
      '#title' => $title,
      '#show_messages' => FALSE,
      'content' => $output,
    ];

    // Also inject title as a page header (if available).
    if ($title) {
      $page['header'] = [
        '#type' => 'page_title',
        '#title' => $title,
      ];
    }
    return $page;
  }
}

Instead of drupal_get_query_array() there is parse_query() (a function in the GuzzleHttp\Psr7 namespace), which is part of Guzzle.
drupal_goto() has been replaced from the RedirectResponse class. Page callbacks that need to redirect users should use code similar to the following one. (Notice that form submission handlers should not use this class.)

// AddSectionController::build()
public function build(SectionStorageInterface $section_storage, $delta, $plugin_id) {
  $section_storage
    ->insertSection($delta, new Section($plugin_id));
  $this->layoutTempstoreRepository
    ->set($section_storage);
  if ($this->isAjax()) {
    return $this->rebuildAndClose($section_storage);
  }
  else {
    $url = $section_storage->getLayoutBuilderUrl();
    return new RedirectResponse($url->setAbsolute()->toString());
  }
}

drupal_http_request() has been replaced from a Drupal 8 service that implements the ClientInterface interface. Drupal 8 code should be similar to the following one.

// system_retrieve_file()
try {
  $data = (string) \Drupal::httpClient()->get($url)->getBody();
  $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
} catch (RequestException $exception) {
  \Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]));
  return FALSE;
}

drupal_not_found() has been replaced from the NotFoundHttpException class. Page callbacks should use code similar to the following one.

// BookController::bookExport()
public function bookExport($type, NodeInterface $node) {
  $method = 'bookExport' . Container::camelize($type);

  // @todo Convert the custom export functionality to serializer.
  if (!method_exists($this->bookExport, $method)) {
    $this->messenger()->addStatus(t('Unknown export format.'));
    throw new NotFoundHttpException();
  }
  $exported_book = $this->bookExport->{$method}($node);
  return new Response($this->renderer->renderRoot($exported_book));
}

drupal_site_offline() should be replaced by an event subscriber, similar to the following one.

public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = ['onKernelRequestMaintenance', 30];
  $events[KernelEvents::EXCEPTION][] = ['onKernelRequestMaintenance'];
  return $events;
}

public function onKernelRequestMaintenance(GetResponseEvent $event) {
  $request = $event->getRequest();
  $route_match = RouteMatch::createFromRequest($request);
  if ($this->maintenanceMode->applies($route_match)) {
    // Don't cache maintenance mode pages.
    \Drupal::service('page_cache_kill_switch')->trigger();
    if (!$this->maintenanceMode->exempt($this->account)) {
      // Deliver the 503 page if the site is in maintenance mode and the
      // logged in user is not allowed to bypass it.
      // If the request format is not 'html' then show default maintenance
      // mode page else show a text/plain page with maintenance message.
      if ($request->getRequestFormat() !== 'html') {
        $response = new Response($this->getSiteMaintenanceMessage(), %03, ['Content-Type' => 'text/plain']);
        $event->setResponse($response);
        return;
      }
      drupal_maintenance_theme();
      $response = $this->bareHtmlPageRenderer->renderBarePage([          '#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page');
      $response->setStatusCode(503);
      $event->setResponse($response);
    }
    else {
      // Display a message if the logged in user has access to the site in
      // maintenance mode. However, suppress it on the maintenance mode
      // settings page.
      if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
        if ($this->account->hasPermission('administer site configuration')) {
          $this->messenger->addMessage($this
      ->t('Operating in maintenance mode. Go online.', [':url' => $this->urlGenerator->generate('system.site_maintenance_mode')]), 'status', FALSE);
        }
        else {
          $this->messenger->addMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
        }
      }
    }
  }
}

drupal_encode_path() has been replaced by UrlHelper::encodePath()
drupal_get_query_parameters() has been replaced by UrlHelper::filterQueryParameters()
drupal_http_build_query() has been replaced by UrlHelper::buildQuery(), which will be removed once Drupal core requires at least PHP 5.4 (At that point, it will be possible to directly use  http_build_query().)
drupal_parse_url() has been replaced by UrlHelper::parse()

Notice that, compared with earlier Drupal versions, there are some important changes. For example, some methods that were in the Url class has been moved in the UrlHelper class; some of the Guzzle classes aren't used anymore.


Custom facets return no results on search page I have created a custom field to the node index of apache solr. Here is the code.

function myModule_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id) {
  if($node->type == "feature") {
    $support = db_select("custom_table", 'a')
        ->fields("a", array('Support'))
        ->condition('nid', $node->nid)
        ->execute()->fetchField();
      $document->addField('custom_field', $support);
  }
}

And then for this custom field I have created the facet. Here is the code.

function myModule_facetapi_facet_info(array $searcher_info) {
  $facets = array();
     $facets['custom_abot_support'] = array(
      'label' => t('Custom Facet'),
      'description' => t('Filters by Support'),
      'field' => 'custom_field'
    );
}

The facet successfully created and it has been present in the facets list. But the problem is on the search page. When I try to search some thing, on the search results page this facet only display the title of the facet block. It does not display any content.

Any one what is the problem?

I have found the solution.

if you wrote this hook hook_apachesolr_index_document_build_node then
you have to delete the indexed data from apache solr search index and
then reindex all the data. if you only reindex data then it will not
work.
and 2nd point. you have to keep care of the prefixes of the field. if it is a single string then use ss if multivalue field then use sm
3rd point is you have to call hook_apachesolr_query_alter.

function myModule_apachesolr_query_alter($query){
   $query->addParams(array('fl' => array('ss_custom_field')));

}


Create two nodes with url aliases on one submission I have a content type "News". With URL aliases pattern and token the URL is like this: news/[node:title].

Is it possible to create two nodes on one submission with different URL aliases? Let's say on submitting on the news node, it will create two nodes with two URLs like this: The first one is news/[node:title] and the second will be news2/[node:title].

The whole point is not to create a two different content types, but one and the clone node will have a different URL aliases, so I can filter a new menu block with visible path news2/* and make other logic too.

Use hook_node_insert() where you can additionally create another node. I am not sure that the url alias will already be available.
If not use the following code, found at Programmatically create alias using pathauto for node, to get the original URL alias and then edit it to match your criteria:
module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module

/*
pathauto_create_alias($module, $op, $source, $data, $type, $language)
@param $module: Your module name
@param $op: The operation (insert, update, return, bulkupdate)
@param $source: Internal Drupal path (i.e.: node/1)
@param $data: Addition data used to generate a pathalias, in this case the node object
@param $type: Type of content that will be used to match a pattern, defined in the backend url alias patterns
@param $language: If you have a multlingual website, you need to pass the language for which you want to generate the url alias
*/

pathauto_create_alias('your_module_name', 'insert', 'node/1', array('node' => $node), $node->type, $language->language); // Language is optional

Set the node alias and create a node with node_save().


Active a menu  when the menu entry is a view page I have a section (call news) that have an "home page". This home page is created via "views" and via "views" I have insert a link item into "main menu" menu based on path (/news). When I go to /news the relative entry in "main menu" is active (the <li> item has "active-trail" class). All works.

How can I active the same menu when I'm into a node of type news ? I have read that I need to use menu_tree_set_path() into a hook_preprocess_page(). So I have tried to add this line into THEME_preprocess_page(&$vars) :

menu_tree_set_path('main-menu','/news');

but it does not work. I have tried with:

menu_tree_set_path('main-menu','news');

Same result. Not working.

In all my search, all tutorials tells to set for the second parameter of menu_tree_set_path a node/NID or a taxonomy/term/NID, but I have not this node/nid. I have a view page path.

So, How can I do it ?  Thanks.

I guess you could achieve this with Menu Position module, where you can set an active parent for specific node/content types.

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


does indexing tables have a bad effect on drupal? I have one or two views which has a lot of fields to show and all of this fields are in filter criteria as exposed filter. now the problem is acting in low speed.

the solution I am now thinking about is to index some fields which are more in use as filter criteria. But I don't know if it has any bad effect on performance or not. Or does it effect views automatically or I should rebuild all views to see the indexing result.

please let me know more about indexing tables in drupal or if you know any better solution let me know!

The gains far outweigh any drawbacks; I'd add the index.


Drupal 7: How to add tags to a new content type? Newbie here!

I go to Structure > Content types > Add content type and create a new content type.

But how can I add tags to my new content type, just like when you go to Content > Add content > Article, you get the option to enter a title, tags and body.

How can I add the capability to add tags to my new content type?

Thanks

From the Manage Fields page of your content type, add a new Term Reference field.  Set the widget to be Autocomplete term widget (tagging).

When you get to the field settings you'll be given the option of which vocabulary to use for the tags (for the default Article content type this is usually Tags I believe).


How can I index only active user accounts in a user index? I'm setting up Search API Solr to make a user search on my site. On this site, when a user account is cancelled, we keep the data but block the account (set the status to non-active). This is necessary to prevent abuse of the system, but I want to eliminate the risk that data from these accounts would be exposed in Solr search, so I am looking for a way to index only active users.

I've been digging around but couldn't find any way to configure the index to not add blocked users. How can I do this?

It turns out that Search API has a built-in filter for excluding unpublished nodes, but not users.

So here's a patch.


Can't save data for Address field I am trying to save data programmatically to an address field from the Address module.

I am not successful.

First, when I dsm() a node with the address field filled out, it looks like this:

        [field_addr] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [langcode] =>
                                [country_code] => US
                                [administrative_area] => CA
                                [locality] => San Diego
                                [dependent_locality] =>
                                [postal_code] => 91945
                                [sorting_code] =>
                                [address_line1] => 123 main st
                                [address_line2] => apt 2
                                [organization] =>
                                [given_name] =>
                                [additional_name] =>
                                [family_name] =>
                            )

                    )

            )

However, no matter how I try to save it to my node, it doesn't work.

I create an array that looks like this:

Array
(
    [x-default] => Array
        (
            [0] => Array
                (
                    [address_line1] => Australian Club
                    [address_line2] => Royal Lane
                    [locality] => Sydney
                    [administrative_area] => NSW
                    [country] => Australia
                )

        )

)

Let's say with the name, $address_save

And then do the following:

$node->set('field_addr', $address_save);

No luck. My node saves with other fields, but this one doesn't. I've also tried it without the x-default key around it as well as without a delta, but neither of those work either.

How can I save values to an Address field inside of a node?

The problem here was due to Drupal failing silently (or obfuscating the error - maybe because I was running this in cron) but it was due to the address not having all of the required fields set to the correct values for the country in question - mainly using the actual country name instead of the country code.

Once the country code was swapped in it worked. I switched the country around to the country code like this:

function MY_MODULE_get_country_code($country) {
  $countries = MY_MODULE_country_list();
  $flipped_countries = array_flip($countries);
  $country_code = $flipped_countries[$country];
  return $country_code;
}

function MY_MODULE_country_list() {
  $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
  foreach ($countries as $key => $value) {
    $countries[$key] = $value->__toString();
  }
  return $countries;
}

It worked correctly.


How do I revert all of my DB tables from MyISAM back to InnoDB? Possible Duplicate:
  How do I convert a database from MyISAM to InnoDB?

Due to a bug in the Backup and Migrate module http://drupal.org/node/1128620 , all of my DB tables were reverted to MyISAM. How to return them all back to to InnoDB. (Perhaps using phpmyadmin?)

I used to use http://drupal.org/project/dbtuner/ in D6 for this. However there isn't a D7 version.

Also, are there any side effects or possible gotchas for switching this in this way?

Update:

<?php
    // connect your database here first
    //
    $sql = "SHOW tables";
    $rs = mysql_query($sql);

    while($row = mysql_fetch_array($rs))
    {
        $tbl = $row[0];
        $sql = "ALTER TABLE $tbl  ENGINE=INNODB";
         mysql_query($sql);
    }
?>

What do I need to add to the section "connect your database here first" to connect to my Drupal DB?

The easiest way is to take a backup with Backup and Migrate, open it in an editor and search/replace "MyISAM" to "InnoDB".  Then restore it.

Personally, I would restore to a new catalog, and then switch the database in settings.php.  This way, you can test before making the new version live.

Otherwise, this is a dup of How do I convert a database from MyISAM to InnoDB?


How to display the number of images contained in a node using Views? I have a content type that has an image field (among other fields).
When creating a node, users can upload up to five files.
What i'm trying to do is to display how many images are uploaded in each node when listing node teasers using views ?

Thanks

Install the module: Field Count Formatter

  A very simple module to provide a formatter for all field types. The
  output is simply a count of the number of items in that field. This is
  most useful on fields which have multiple values as it will show how
  many values are in this field.

Then in the teaser display for your content type, add the image field and set the formatter to count.


Unable to clear cache I am facing an severe issue with Drupal instance. I am trying to clear the cache and the page is redirecting to error page.

This site can’t be reached
The connection was reset.
ERR_CONNECTION_RESET

Please help.

Either drush cc or manually truncate cache tables in the db (Backup first!). Unsure if you are running Varnish, but if so you may want to manually flush this as well.


Using selected value of Entity Reference as filter for another Entity Reference Going to try and put this as simple as i can.

Lets say i have 2 Entity Reference Fields A and B.

A) Gives a list of Countries.

B) What ever country was selected in A should only display list of available State/Province's to that country

Example:
Lets say i have a content type of Countries where i can save the country name in the title, then i also have a content type of state/province's where the state/province name is saved in the title with entity reference field where a county can be selected for that State/Province.

Lastly i have a content type user information, where a user can enter his/her name in the title, a entity reference field country and another entity reference field state/province. When the user select, lets say, USA as a country in the first entity reference field, the second one should only display a list of sates available in the USA.

Can something like this be done where the option of one Entity Reference field can be used as a filter for another entity reference? and if so, how can something like this be achieved? any and all help is much appreciated.

Found a categorically stunning module that does precisely what i needed over here https://www.drupal.org/project/ddf

Its simple to use as well. Install the module, enable Dynamic dependent fields and DDF Entity Reference modules after that.

Once that is done, go to your content type that contains the two or more enetity reference fields, using the example above that would mean editing content type user information. Now, go to manage fields, select edit on the entity refence field you want to be filtered, going back to the example again that would mean the state/province entity reference field, scroll down to the field settings section and on target type select node, on mode select the option Views: Filtered by an entity reference view with dynamic arguments, on views used to select the entities option choose the view that you have created for that entity reference - make sure that entity reference view has a contextual filter in it.

When all that is done, the last option is view arguments field and just below that the DDF module will give you a list of option that can be used as arguments to be passed to the entity reference views contextual filter... select one of them, in the example again, it would be something like {field_er_countries}.

Remember to save all your hard work and you should be good to go...


Change custom entity fields I'm facing very strange problem with changing my custom entity's fields. I've a custom entity with id, type, .. , premium, premium_expires_at, .. fields. It was  working without any problems with its own fields (those declared in hook_schema()) till today, but suddenly I changed its fields, dropped premium, and premium_expires_at fields, added new fields with HOOK _update_n function. I see database schema changed, but those deleted fields are still being shown in base table key under field_sql_storage key.. I've already ran update.php (many times), but no luck.. I thought it's a caching problem, so I've cleared all caches manually, and with drush, no luck, cleared memcached data (with telnet), any changes.Every time I'm getting the same error, like this:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.premium' in 'field list': SELECT ... base.premium AS premium... в функции EntityCacheControllerHelper::entityCacheLoad() (строка 101 в файле /PATH_TO_MY_PROJECT/sites/all/modules/entitycache/entitycache.module)

I don't have any premium field in my db schema, but still getting this error, is there any way to solve it?

(I am using EntityAPI with Entitycache and Memcache Storage modules).

I finally solved this problem somehow.. I think this is an EntityAPI's issue. So, here is my (temporary) solution:

removed those changed fields directly from hook_schema, added new fields directly to it.
removed those fields with db_drop_field function and added new fields with db_add_field function with hook_update_n function. By this way I managed to have the same structure in my (changed) entity and db table schema.
flushed the caches

Error has gone, so far everything is working fine. But I'm not sure this solution will not cause any problems in future... I still can't understand why entity api doesn't see changed fields in hook_update_n function...


How to validate an AJAX form which uses CTools? I have a form which opens in a modal CTools window. The forms submits perfectly, but when I try to use the my_form_validate() function, it never goes to that function, it always go directly to my_form_submit() function? I have tried to "uncode" the CTools modal windows example provided with the module, but I am not able to decipher it.

I have just discovered that I had mistyped mymodule_my_form_validate as my_module_my_form_validate. Your reply has made me look into the function and now it works perfectly. Somehow I thought the method was much more convoluted as involved AJAX. Sorry, this is very embarrasing. In any case, your reply saved me a lot of time.


Background CSS images won't be changed after reuploading & Cache flushing If I Download a css background image of my site, changing it with GIMP (or MS paint for that matter) and re upload it, nothing will happen. Moreover, even after I delete the file from the server, the image stays online... clicking "Flush all caches" nothing happens... I also note that the image basically stays the same --- Same filename and file extension, so it's extremely wired. What would you suggest of checking?

What I already tried and didn't help:

Turning off server external caching tool (for both static and dynamic cache).
Turning off AdvAgg from config/development/performance/advagg (Unchecked "Enable...")
Turning off Drupal's internal cache system.

Update: Working answer found... See below for the answer with green checkmark.

Since all caching aren't able to fix, let's try narrowing down the issue.

First, try to delete the image from your theme. Flush all caches and see if the background image is still there. If it is, open your browser development tool and check the background image URL and try opening it in a new tab, check the URL of the image and follow it in your server's directory if it really still exists.

Second, try restarting the server or any related running services you have in your server.

Hope this can at least give an idea on where to find what's causing the issue.


How to numerate drupal views rows in twig? For css purpuses I want to add custom class name to the first item in view.

I need the number in views-view-fields--viewname.html.twig to make some logic expression like

if(view-num == 1) {

} else {

}

or maybe in one of the variables I get in fields {{fields.view_number.content}}

The fields template is probably not the best place. Normally you would do this in the views style plugin. Grid has such options built in, for Unformatted you can add

loop.first ? 'views-row-first',

to  views-view-unformatted.twig.html:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
      loop.first ? 'views-row-first',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}


Change allowed file types based on certain criteria An admin comes onto the website and creates an assignment which is a content type.  Students come onto the website and create submissions that point to the certain assignment.  There is a file upload field where students can upload their submission.  I want to make it so when the admin creates the assignment, he/she can choose which file types are allowed.  Is there a field that will automatically process what file types the admin chose so that a student can only upload that specific file type?

So, it's the rough instruction step by step as Matt asked:

Add new field where you can specify the allowed extensions of the files.
Alter the form of your submission via hook_form_alter() and find your file upload field
Specify your allowed extensions from your field with extensions into this point


Show content whose "team" field matches the user "team" field The users on my site all have a field named "team" and my content types also have the same field.
I want to create a views page that shows all nodes where that "team" field equals the same field on the user node.
Example:
USERS:
user1, team: team1
user2, team: team1
user3, team: team2

NODES:
node1, team: team2
node2, team: team1
node3, team: team1

When I'm logged in as user 3, I want my view to show node 1.
I know that I have to work with the contextual filters and context but I'm unable to get the output I need.

The easiest way to set this up is through the Content: Has taxonomy term ID Contextual filter.

In Content Views listing your nodes add that Contextual filter and set it up:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
[your vocabulary]
Term ID
Adjust the other option as necessary.
Now if you enter some taxonomy term ID into the Views Preview field, it will be picked up by the Contextual filter and show only nodes that have been tagged with that term.

Create a block Display and place your block in a region shown on entities that have the taxonomy term ID chosen. The block will show all nodes that share the term.

In your case if you place that block on User Profile pages, it will show the nodes related through the same Taxonomy term.

If you want to show that Block anywhere on the site, and have it take the Context of the currently logged in user you have to approach it a bit differently.
There may be more ways on how to achieve this, here's one:

In the original Views where you show a list of nodes add a Relationship for the Taxonomy term field (Field: Team).
Then add another Relationship that is reverse, going from Taxonomy term to the field on Users (Taxonomy term: User using …). This is where the term matching is done, the second Relationship will use the first one. This introduces the User info into your content Views.
Then add the Contextual filter for User ID (User Uid), it will use the second Relationship. Set up the Contextual to use the logged in user context:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Place the Block anywhere on the site and it will only show nodes related to the user that is currently logged in, even if you place it on user profiles and view other users profiles!


Preserve Current Paths before rolling out new Pathauto Alias I'm just about to roll out a new Pathauto Alias to include a new taxonomy term, which will modify about 1000 nodes. Is there a way to preserve the current path aliases I have now, and then bulk update all my nodes to the new pattern?

I assume I'll need to use Path Redirect in conjunction with Global Redirect somehow to keep the old paths pointing to the new paths?

Thanks!

To preserve AND redirect existing aliases when you implement a change like that:

install the Path Redirect module
open the 'Automated Alias Settings' in URL Aliases (admin/build/path/pathauto)
open the 'General' fieldset
change the radio button for 'Update action' to 'Create a new alias. Redirect from old alias' (see screenshot below).

http://img705.imageshack.us/img705/2738/redirectaliasleaveintac.png


Creating view with user's contents I'd like to create view page with contents added by the user. In that page, every user can see contents only added by him. How can I do it?

In your Views UI, at the right, expand "Advanced". Simply add a relationship of User: Author and then create a filter using field User:current and make sure you use setting logged on user


Remove links in admin content list form In the admin content form (admin/content), I am trying to remove links to content page on some content types in a custom module with the following code but I can't get it working.

/**
* Implements hook_form_node_admin_content_alter()
 */
function MYMODULE_veilleur_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
    foreach ($form['admin']['nodes']['#options'] as $option){
      if($option['type'] == "Document"){
        $option['title']['data']['#type'] = "text";
        unset($option['title']['data']['#href']);
      }
    }
}

With this code, I still have the links in the content title. Any idea?

Sorry, it is my fault, I forgot to use the "&" to pass the reference variable in the loop. Here is the final code :

/**
* Implements hook_form_node_admin_content_alter()
 */
function MYMODULE_veilleur_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
    foreach ($form['admin']['nodes']['#options'] as &$option){
      if($option['type'] == "Document"){
        $option['title'] = $option['title']['data']['#title'];
      }
    }
}


Override preexisting rules Currently, changes are replicated by hands (and rules exports) from dev to a test stage available to the customers. There is actually no live site.

We are going to use the Features module and hook_update_N() in order to deploy the live site.

I wonder what will hapen if I add a feature including some rules already existing on the test stage (created by hand before I got assigned on this project).

Will the rules be overwritten? Will I get errors? I read that updating features files actually updates the rules (or whatever is inside the feature).

If you are using Features module in Drupal 7 to deploy the rules. You will get an overriden or needs review flag in the Features UI when you attempt to turn the feature on.  Features will see the existing code and it will not attempt to change it.  Features is designed so that things done through the Admin UI of Drupal are not overriden unless you force Features to do so via a manual review of the feature.

To save yourself a lot of headache later on in the project I would suggest removing the rules before you install the Feature.  Maintain configuration control with Features so that you know if you look at the Features admin page and a feature you have is showing as "overriden" or "needs review" then you have a problem on your website or someone has changed a part of the website.  I personally have a website with about 20 features, all of them never say "overridden" or "needs review" if they do then I know another admin has done something that potentially should not have done.


How do I remove page title/header? In Drupal 8, is there an easy way to configure a page so that its page header/title is not displayed on the page?

I have created a Basic Page, with /home as path alias, and Home as title. I set it as front page.  However, it displays 'Home' at the top of the page, just below the navbar and breadcrumbs.

Is it necessary to create a subtheme of the 'Bootstrap' theme, and somehow add custom CSS?

Drupal 8 places the page title in its own block (called Page title). You can control when and where that block displays on the block layout page: /admin/structure/block


Remove tax line item on checkout page I have installed the *commerce_kickstart* install profile, and I am wanting to remove the Tax line item on the checkout page, and instead have some text instead that says VAT included (or in my Australia case, GST included).

Everything works well and as expected; however, my client would like to remove the line item for the VAT subtotal and just include text somewhere that says "All prices and totals are inclusive of VAT".

Might be a bit late on this one, but there doesn't seem to be a posted solution online. You can remove the tax line using the below.

In your template.php file use the below, this should hide it from your order confirmation email as well. I haven't noticed any problems from this modification, but ymmv. The variation from the standard code is: $rows = array_splice($rows, 2);

function THEME_commerce_price_formatted_components($variables) {
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');

  // Build table rows out of the components.
  $rows = array();

  foreach ($variables['components'] as $name => $component) {
    $rows[] = array(
      'data' => array(
        array(
          'data' => $component['title'],
          'class' => array('component-title'),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total'),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

  $rows = array_splice($rows, 2);

  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}


View API connection to external DB I've a Drupal 7 site setup on an AWS server, and I'm trying to access a mysql db on a AWS RDS.(The Drupal db is located on the Drupal server, the table I'm trying to get is just to access some external data).

When I try to use the Views API I get the following error:

  PDOException: SQLSTATE[HY000] [1045] Access denied for user 'drupal_viewer'@'localhost' (using password: YES) in views_plugin_query_default->query() (line 1293 of /opt/bitnami/apps/drupal/htdocs/sites/all/modules/views/plugins/views_plugin_query_default.inc).

I've setup the mysql user "drupal_viewer" with the correct permissions, and to verify that I've created a short php page in the root folder of the Drupal server. When I run that, it runs fine and connects and executes a test query. So that verifies that the security groups etc are fine and that my Drupal server can "see" the RDS instance.

I've tried various combinations of the user on the mysql setup (@%, @localhost and @127.0.0.1), but the views API keeps trying 'drupal_viewer'@'localhost' which is failing.

I have the db info setup correct in my settings.php (and have done Clear Cache etc).

$databases['pc_propertychannel']['default'] = array (
  'database' => 'propertychannel',
  'username' => 'drupal_viewer',
  'password' => 'xxxxxx',
  'host' => 'pc-live-main-db.xxxxxxxxx.eu-west-1.rds.amazonaws.com',
  'port' => '3306',
  'unix_socket' => '/opt/bitnami/mysql/tmp/mysql.sock',
  'driver' => 'mysql',
  'prefix' => '',

);

What am I forgetting?

[Edited to Add: as a debug, I tried connecting via mysql console from the Drupal server to my RDS instance, using the above credentials, and it works fine. So I'm thinking this may be a Drupal config/issue?]

Eventually figured it out! (obvious in hindsight!)

I shouldn't have had the line:

'unix_socket' => '/opt/bitnami/mysql/tmp/mysql.sock',

in the database setting in settings.php

Removed it for the remote db's and it works perfectly.


Product price formatter In my shop site, on each of the products listed can we please just list the dollar amount i.e. $80.00(for eg.) - and remove the default currency(eg. AUD) and (GST (exc) )text that follows?
How to formatting the price?

You can use module Commerce Currency Settings for formatting of currency.


How to add a second Contextual Filter to the calendar view? (this view is automatically created by the calendar module)? I have enabled the calendar module which generate a new view called calendar.

The calendar view has a page called month with just one contextual filter. It works fine.

The problem is that I to added a second  contextual filter.This is what I've done:

The content type that this view page shows is: "actividades".
This content type has the field "poblacion" of the type (term reference).

Then in the view:

I added a Relationship: Content: Taxonomy terms on node
I added the Contextual Filter :(term form Poblaciones) Taxonomy term: Name .

But it's not working at all. I think I need to modify the path of this view page which at the moment is: actividades/month. But I don't know how...

If I go to the url: actividades/month/barcelona it doesn't work even though I have a node tagged with this term. I guess this happens because the first argument is for the date, here is where I get lost

What are you trying to achieve exactly? You want to restrict the calender to show only nodes tagged with a certain term?

It looks like you're trying to do this by setting up a relationship with the terms and then passing in the term name. Is there a reason why you're not using the Content: Has taxonomy term ID contextual filter? This cuts out the need for the relationship, but requires you to pass a term ID rather than a term name.

If there is a reason why you're not doing this, then ignore me :) Just thought I'd reply in case you didn't know about it.


Count multivalue image field values in views-view-fields.html.twig Making a presentation template for the gallery. The photo gallery has an image field with multiple values. I need to output the number of gallery photos (in the field_gallery_photo). How do I do this? I tried adding a field with a photo to the view, and all the values are shown in one line. The result is not accurate:
{{ fields.field_gallery_photo.content | length }}

In version 7 I did the following:

added the nid field

redefined the template for it

specified the following in the template:
$node = node_load($output);
print sizeof($node->field_gallery_photo['und']);

Your D7 PHP would translate into D8 Twig like this:
{% set node = row._entity %}
{{ node.field_gallery_photo.getvalue | length }}


What is the equivalent of "Referential Integrity for CCK" in drupal 7? Is there a Drupal 7 equivalent for the Referential Integrity for CCK module?

There is a sandbox project for a D7 port that performs cleanup on cron.

Otherwise drupal supports databases that do not enforce referential integrity, so it has not (to my knowledge) been a core issue.


how to install commerce_kickstart on an environment with PHP memory_limit less than 128M? I tried the full core install aproach and got a warning that I only had 96M on php memory_limitand kickstart needs 128M. tried anyway and sure enough got a memory error at the very end of the installation. I looked around my host and I'm sure I can't change that.

How can I make this installation work?

Try the methods listed here to increase the PHP memory_limit value

If none of those work, you may need a new host for that application.


How to display nodes of specific terms and expose only those terms to the user (out of many other terms) I have created a view, where I display two content types. Both of them have field "Country". So in my view I want to display only nodes related to three particular countries, but additionally I want to add filter, so that the user is able to see content only for one country out of the three.

The problem is that when I specify in "Filter criteria" show nodes only for these three countries it works, but when I make this filter "exposed" the view renders absolutely all nodes.

At the same time I want my exposed filter to have only the 3 countries available available.

An exposed filter has no effect by default, so your simplest solution is to add another filter that is not exposed that limits the view to just the countries you want.

It's a useful trick with views to combine exposed and not-exposed filters and sorts.


Block caching based on time I have a simple block that is used in the footer of a multiple language website. The text in the block changes based on user language so I using the following render attributes, which seems to work well.

$render['#cache'] = [ 'contexts' => ['languages'] ];

This block contains an image that is included with the following:

if( (date('Y') %2) == 1)
  $markup = '';
else
  $markup = '';

One image is used for even numbered years and a second image is used for odd numbered years.

What is the correct way to setup caching base on this image changing once per year?

I have a similar situation with the home page of the website which changes each day.  My current plan is to clear all caching levels for the website early each morning just after mid-night.  This includes the Drupal caches, memcached and AWS Cloudfront. For pages like the home page, which change daily, I will need to keep max-age short to limit caching in the user's browser.

Is there any better way?

On this time scale, a cache TTL probably isn't the way to go, since the age is counted from creation time without respecting calendar years. You know exactly when the cache should expire (midnight on New Years') so instead of giving it a one-year maximum age it may be better to just actively clean it with a cron.

To avoid throwing away the entire cache (which can lead to significant performance degradation on some sites), you can use a cache tag:

$render['#cache']['tags'] = ['date:year'];

And then, in the annual cron, just invalidate the date:year cache tag like this:

function custom_cron() {
  $last = \Drupal::state()->get('system.cron_last');
  if (date('Y') !== date('Y', $last)) {
    Cache::invalidateTags(['date:year']);
  }
}

(Note that this solution does the absolute minimum of cache invalidation. If you find that your site performs well even if you completely purge the cache every day, that's fine.)


Suggestions for creating a more complex tiered content type I need to create a content type where users will be able to create a tiered structure. This will be generated into a PDF and displayed using the Drupal templating system as well.  I will need some sort of multi-valued field so that the user can add as many items as they like. I need the content structure to look like this:

Content Title
Custom Category Title

Custom item
Custom item Subheading

Custom subitem 1
Custom subitem 2

Another Custom item

etc...

I'm considering Multifield (We've used field collection before and had issues with translation)

Or possibly a Custom Field type

If I used multifield, one option might be to have the user specify these things for each item ( Is it a subitem parent?, Is it a subitem?, If it is, what is it's parent?)

This is Drupal 7 and we'll be using Entity translation to handle translating this content type for all of our domains.

I would definitely suggest using paragraphs, it's a killer module for multi-valued, arbitrary ordered fields inside content types.


Make email validation message in drupal 7 webform come out in spanish I have a webform in spanish and I have manually put in all of the validation error messages in spanish, however I cannot find where I can make the "Please enter an email address" message which comes out if you put an invalid email into an email type field come out in spanish instead.

Thank you

Try with String Overrides module.

When you go to module settings choose 'Spanish' tab (if you have more than one language enabled), on the left side put "Please enter an email address" (without quotes of course) and on the right side write Spanish translation. (clear cache)

Let me know if this is working.


How to restrict access to specific content types by role? In D8 core you can either set permission for anonymous users to view all or non publish content, but not set permission different by content type.

I've found this that looked promising, but the functionalities doesn't work for this:

http://drupal.org/project/content_access

Any others suggestions for how to solve this?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Notes (to further address your comment below this answer):

  ... I want to give access to anonymous users, I guess they can't be part of a group?

True, an anonymous user, by design, cannot be part of a group. But as mentioned in my answer to "What are the various roles supported by the Group module?": the role "Anonymous" (related to a user that is not signed) is one of the Special Global Roles (apart from Outsider and Member). And it is via that Special Global Role "Anonymous" that you can make the magic happen for any anonymous user. Have a look at the video tutorial, around 10:53, where you can see that it is possible to grant access to anonymous users* to (eg) "View content" to a Group node (of content type "Article").

  ... I would then need to add every person to those groups instead of just assigning permissions to their roles?

If you'd grant appropriate permissions for Outsider (combined with the access you want for Anonymous), they do not have to be part of those groups.

  ... It seem like a little bit bad work-around for my need.

With the above details included in this note, I presume you agree that this part of your comment no longer applies.

Bonus tip:

A possible solution to "... make all 'article' nodes be content of an 'articles' group." (as in another comment added to this answer) is explained in comment nr 3 of the issue titled Bulk assign of content to groups. This is part of what it says:

  The steps to take are roughly:

  Make sure you have a GroupType
  Make sure the GroupType has the right plugins enabled (GroupType::installContentPlugin(); read deprecation notice)
  Create a Group of said GroupType
  Start adding the nodes using $group->addContent($node, 'group_node:NODE_TYPE_HERE');

For D7 one can use Views Bulk Operations (VBO) and Rules as detailed in my answer to "How to bulk assign existing content to a group created with the Group module?").


Cache a block by a custom entity rendered within I struggle with getting a custom block cached correctly:

we have a custom entity "Politician"
For that entity we have several routes where we want to render a "politician header" with some basic information about the politician
the politician header is a custom template which is rendered in a custom block
the problem is: when caching is activated the block always shows the politician data from the first politician which was rendered.

Here is the code for the block plugin - to keep it simple I do not copy the method getPoliticianFromUrl() here:

/**
 * Provides a block with the profile header for a politician. We do not render
 * it on the public edit form path
 *
 * @Block(
 *   id = "aw_frontend_politician_header",
 *   admin_label = @Translation("Politician profile header"),
 *   category = "Abgeordnetenwatch"
 * )
 */
class PoliticianProfileHeader extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician == NULL) {
      return [];
    }

    return array(
      '#theme' => 'politician_header',
      '#politician' => $politician,
      '#cache' => [
        'keys' => ['politician', $politician->id()]
      ]
    );
  }

  public function getCacheContexts() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician != NULL) {
      return Cache::mergeContexts(parent::getCacheContexts(), $politician->getCacheContexts());
    }
    return parent::getCacheContexts();
  }

  public function getCacheTags() {
    $politician = $this->getPoliticianFromUrl();
    if ($politician != NULL) {
      return Cache::mergeTags(parent::getCacheTags(), $politician->getCacheTags());
    }
    return parent::getCacheTags();
  }
}

Then I render the politician header - again I just put in interesting parts:

function template_preprocess_politician_header(&$variables) {
  /** @var \Drupal\pw_basic\Entity\Politician $politician */
  $politician = $variables['politician'];
  /** @var \Drupal\Core\Render\Renderer $renderer */
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($variables, $politician);
  $variables["#cache"]["contexts"][] = 'user.roles';
  $variables['#cache']['keys'] = ['politician_header', $politician->id()];
}

I thought when I define cache keys this ensures that different versions of the render array are cached. This does not happen - not for the custom politician header template (for which I do not find any cached data in cache_render tanle - is this just cached with Twig caching?) and not for the block.

My idea was to create a custom cache context based on my Politician entity but as far as I understand cache contexts they depend on more global circumstances such as the active theme, the current user and things like that. I hoped the Entity API would generate such a context in a magical way so I tried $politician->getCacheContexts() but nothing.

What do I miss?

By any reason I do not really get the block rendering to respect my cache keys set wherever. It only respects set cache contexts so I create a custom cache context:

In pw_basic.services.yml (pw_basic is the name ofthe module)

  cache_context.politician:
    class: Drupal\pw_basic\Cache\PoliticianCacheContext
    arguments: ['@current_route_match']
    tags:
      - { name: cache.context }

The politician cache context class:

class PoliticianCacheContext implements CacheContextInterface {

  use GetPoliticianFromUrlTrait;

  /**
   * @var \Drupal\pw_basic\Entity\Politician
   */
  protected $politician;

  public function __construct(CurrentRouteMatch $current_route_match) {
    $this->politician = $this->getPoliticianFromUrl();
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Politician');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    $cache_context = '';
    if ($this->politician !== NULL) {
      $cache_context = $this->politician->id();
    }
    return $cache_context;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

Then I cleared the block plugin class from any cache logic and just added the following in template_preprocess_politician_header(), the preprocess function of the template rendered within the block:

$variables["#cache"]["contexts"][] = 'politician';

What I do not really like is the service character of the cache context classes. Why is it only possible to set the context in such a global way? Do I miss somethin? I need to use this global workaround and check for the politician from URL which makes this context not as flexible as I want it to be. Is there a way to give a variable to a cache context directly when defining it in a render array?


Display hierarchical entity reference fields inside node I have the following content types in Drupal 8 :

User

field: image
other fields

Organization

field: logo
Entity reference to User [one to many]
other fields

Event

Field: Date
Field: Description
Entity reference to Organization [one to many]

The event nodes need to look like this (display the following):

Event Title
Event Date
Event Description
All the organization logos (from the organizations added as a reference entity to the event)
All the user logos that belong to the already referenced organizations

Is there any way to do this with already existing Drupal 8 modules or do I have to write some custom code ?

You could render this with four different display modes:

1.) The Event view mode to start with:

Event Title
Event Date
Event Description
Reference field for Organization, configured to render the view mode logos1
Reference field for Organization, configured to render the view mode logos2

2.) The Organization view mode logos1 contains one field for the Organization logos:

Image field logos

3.) The Organization view mode logos2 contains one field for the User logos

Reference field for the content type User, configured to render the view mode userlogos

4.) The content type User view mode userlogos

Image field for user logos

To implement two instances of the reference field you need the module Display Suite. Or combine logo1 and logos2 in one view mode with two fields, but then the logos will get mixed. Or use for the second reference field a View, with the help of EVA.


Drupal Quiz Module for retake exam I am trying to implement Quiz module in Drupal 6

The quiz scores will be tied to their accounts, with the ability to retake a quiz if permission is granted by Admin. How can I do this?

Also someone should not be able to advance to the next video unless they have scored a high enough score on the quiz or they have a password to open the next video.

Does anyone have any ideas?

You can look at the Quiz module. It also has an active Drupal Group :)

  The Quiz module provides tools for authoring and administering quizzes through Drupal. A quiz is given as a series of questions, with only one question appearing per page. Scores are then stored in the database.

  This module provides tools for

  Online courses (Audio and Video enabled)
  Self-learning programs
  Training programs
  Supplementary classroom activites


How to hide certain content types from a Link field I created a content type for my slides in a carousel. I make a view to print them all and everything works perfectly. My only problem is that I have multiple use of the Link field from core and the auto-complete form spits out my slides node and my other nodes. How can I limit which node type are shown in all Link field? It doesn't matter if it's site-wide as they will never be needed in those fields.

The short answer is that D8 core link field will always look for all content types. You have to write custom javascript to filter it I believe. To make life easier, I would try Link Field Autocomplete Filter, but personally I like Linkit module much more for its ability to integrate with media.


Difference between hook_query_alter and hook_views_query_alter? I am looking for specific difference in working and implementation of both

HOOK_QUERY_ALTER:

Perform alterations to a structured query.

ONLY queries that have already been tagged (at creation time) can be caught by this hook.
If the query you are hoping to alter doesn't already have a tag (which effectively 'publishes' its willingness to let you mess with it) then you can't alter it using this method.

To find out - inspect the source code of the query you are trying to modify.

HOOK_VIEWS_QUERY_ALTER :

Alter the query before executing the query.

It took me a good bit of time to figure out how to use hook_views_query_alter to modify my view query so I just want to pass on some small bit of knowledge to others who may find it helpful. I wanted to create a view/block that displayed a list of books on my site. I only wanted to list the names of parent book pages not all book pages just book titles. Out of the box, the views module can create a view to display nodes of type "book" but that includes all book pages. The query looked like this:

SELECT node.created AS node_created, node.nid AS nid
FROM
node
WHERE (( (node.status = '1') AND (node.type IN  ('book')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

What I really wanted was below query (that joined on the book table using book.nid):

SELECT node.created AS node_created, node.nid AS nid
FROM
node
LEFT JOIN book ON node.nid = book.nid
WHERE (( (node.status = '1') AND (node.type IN  ('book')) AND (book.nid = book.bid) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

I was able to create the latter query using the hook_views_query_alter. I spend most of the day reading about the views_plugin_query_default api and views_object and tried several query object function calls. Along the trip, I learned how to use the devel module and dpm to display my query in the admin. I tried all kinds of stuff and ended on this two line module.

function my_hook_views_query_alter(&$view, &$query){
  if ($view->name == 'my_hook') {
    $alias = $query->add_table('book','node');
    $query->add_where_expression(0,'book.nid = book.bid');
    dpm($query); //dumps object to admin with devel module
  }
}

The add_table call automatically analyzed the relationship and created the LEFT JOIN above. I had played around with the views_plugin_query_default::add_where but the result was only a simple where clause that only allowed a scalar value (e.g. book.nid = 'book.bid'). The add_where_expression uses the condition type 'formula' to create a complex where. The resulting where clause that just joins on book.bid was :

WHERE (( (node.status = '1') AND (node.type IN  ('book')) AND (book.nid  = book.bid) ))


How to add a role to specific product type customer? I'm trying to add a user role (darshan) to customer buying product from a specific product type (darshan_session), using an EventSubscriber in a custom module.

For now, I'm stuck with the following code, where I need still to check the product type and to load the user from the ID.

namespace Drupal\commerce_darshan\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Drupal\user\UserAuthInterface;
use Drupal\user\UserInterface;

class CommerceDarshanEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events = ['commerce_order.place.post_transition' => 'onOrderPlace'];
    return $events;
  }

  public function onOrderPlace(WorkflowTransitionEvent $event) {
    $event->getEntity()->getCustomerId();

    $user->addRole('darshan');
  }
}

As this is my first custom module on D8, any help would be welcome.

You're using $user before setting it. You have a CustomId it looks like, but have not created an instance of User with that Id.

Perhaps something like this:

public function onOrderPlace(WorkflowTransitionEvent $event) {
  $userId = $event->getEntity()->getCustomerId();
  $user = \Drupal\user\Entity\User::load($userId);
  $user->addRole('darshan');
  \Drupal::logger('mycustom_module_name')->notice('Role "darshan" added to user ' . $user->getDisplayName());
}


Change commerce kickstart admin toolbar logo Hello I want to change the logo of the admin toolbar of commerce kickstart how to do it I cannot find any .tpl with that piece of code for chage that logo

Ho it was easy, just add a css class in your subtheme css with the class

body.toolbar #toolbar-home a span

from there you can change the background image


My content type has a string of words, how do I make them tags? I am very new to drupal. I currently have a content type called 'Issue', which has a plain text field containing something like "money, houses, pigs". How can I look at that string and turn each word into a tag?

The reason I have this is because I read data in from an older database, and they had their tags saved as a string. I read it in using the feeds module.

Is there a way to read in the tags differently? Or is there a way to parse that string and add each word as a tag in my content type?

Note, I read in the database as a CSV file.

My end goal here is to be able to 'query' for all Issues tagged with the word 'house' for example and display those.

Thanks in advance.

You can do it using the Feeds module, you probably could have done it when importing the data for the first time.

Create the Taxonomy you need with all the terms.

Export the relevant nodes information containing the text field, in the CSV copy the text field column and manipulate it so you can use it to import the terms into a multi-value Term reference field.

This requires a bit of Excel/Calc magic. It will probably be term IDs separated by semicolons IIRC.

Then use a Feeds importer to update the existing nodes (the same ones you exported), make sure to map the correct column to the Term reference field for the new Taxonomy.


Disabling the media browser private download option , showing public download as an option In the media module when we upload an image it asks us how to store a file (as public or private). But I don't want to show the user these options. Moreover, the user should not see that option box and the file uploaded should be saved as public file only. How can I implement this?

Upgrade to the latest 2.x version of the media module and file entity module.

This issue was addressed in https://drupal.org/node/2001074

There is now admin configuration at the file system settings page.

In my opinion the configuration ability still needs some improvement but it dos the job for now.


Making custom site wide tokens I'm attempting to add a custom token so I can use it in a view block. Looking at examples I've added this code to my custom .theme file

function mytheme_token_info(){
  $types['mytheme_tokens'] = [
    'name' => t('mytheme Tokens'),
    'description' => t('mytheme token type'),
  ];
  $currentnode_token['current_node_title'] = [
    'name' => t('Current Node Title'),
    'description' => t('Title of the current node'),
  ];
  return [
    'types' => $types,
    'tokens' => [
      'mytheme_tokens' => $currentnode_token,
    ],
  ];
}
function mytheme_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mytheme_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_node_title':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->title->value : '';
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

But in my view in a custom text block I have a header using that token but it spits out

  [mytheme_tokens:current_node_title] Products

And the token isn't replaced. I know for sure the tokenizer is running though because [site:title] did work.

How do you create custom globally available tokens?

Themes can only implement alter, theme and pre/process hooks.

Re-implement those hooks in a custom module and they should work fine.


How to make galleries relative to particular nodes? I have a site with news and I want to make it possible for admin to add image gallery to Articles (nodes) the admin wants. So, the idea is to make gallery image field for every content type from which images should be taken. If admin wants gallery for that article the admin can upload images, if the admin don't the admin can just leave it alone, and Drupal renders that node without gallery perfectly normal.

So, I made that gallery image field for every content type, and used Views module for taking and rendering pictures. But, whereas views taking pictures at content type level not node level, that is the reason why unpleasant consequence appear: gallery from particular node, shows on every node of that type.

My question is how to make galleries relative to particular nodes (specific gallery for specific node)? And it should be extremely easy for admin to manipulate.

The simplest way: Use colorbox module

In the structure of the content type add an image type (with multiple values allowed) and put its display type to be a colorbox gallery

The complex way: use view slideshow and computed field

Still add an image field to the content type, but set its rendering to hidden.

Add a computed field with the value equal to the node nid and the display a view that take the node nid as contextual filter and render the image field using the slideshow plugin.

Set the display of this computed field as unsanitized.

Computed code:

if (!$entity->nid) node_save($entity);

Display Code (PHP):

$display_output = views_embed_view('<your view name>','<your view display name>',$entity_field_item['value']);

You can get an example here: http://agriregionieuropa.univpm.it/content/event/test-antonello (tab "video ed immagini").

The video slideshow uses the second approach (in this case videos, in your case photoes, it's the same), while the photo gallery uses the colorbox approach.


Issue trying to implement the Swagger UI module in Drupal: ReferenceError: SwaggerUIBundle is not defined I am trying to integrate the Swagger UI module into Drupal 8 after adding custom REST routes/resources. I have installed the OpenAPI, OpenAPI_UI, and OpenAPI_Rest modules and I'm able to get a valid swagger json resource back when navigating to <mysite>/openapi/rest after installing all the modules.
The issue I am having now is trying to get the Swagger UI module to render in the OpenAPI module.  After navigating to Administration -> Configuration -> Web Services -> OpenAPI Resources I am able to select the Explore with Swagger button, which should utilize the Swagger UI Module which has been installed following the steps listed here: https://www.drupal.org/project/openapi_ui_swagger
Navigating to the page leads to an empty table, and digging into the console, I get this error:
js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:1544 Uncaught ReferenceError: SwaggerUIBundle is not defined
    at Object.attach (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:1544)
    at js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:59
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:56)
    at js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:284
    at HTMLDocument.listener (js_gIQezLRH6hj-zYPQQ0n_5_ryM5tJpAP9kDSEP7r8TdE.js:276)

This is being thrown inside the swagger.js file inside the Swagger UI module:
 var config = {
        dom_id: dom_id,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl,
          SwaggerUIHideTopbarPlugin
        ],
        layout: "StandaloneLayout"
      }

It seems like the SwaggerUIBundle and other Swagger JS objects aren't being exported properly and JS is throwing the UncaughtReferenceError when accessing these members. Has anyone come across this error before? I am pretty new to Drupal and I'm trying to figure out what the issue is, because it seems like I've followed the steps properly to get everything working.
This also seems to be close to what I am experiencing, but unfortunately there was no posted resolution: https://www.drupal.org/project/openapi_ui_swagger/issues/3073250

I seem to have found a resolution to this issue.
In the installation notes for the SwaggerUI module, the instructions state to add this block of code to the composer.json
"extra": {
  "installer-paths": {
    ...
    "web/libraries/{$name}": ["swagger-api/swagger-ui", "type:drupal-library"],
    ...
  }
}

When running composer install, composer will place the external swagger-api in the /web/libraries/<whatever> directory.
In the openapi_ui_swagger.libraries.yml file located within the SwaggerUI module, it is pulling in the external swagger-api here:
swagger_ui:
  js:
    /libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /libraries/swagger-ui/dist/swagger-ui.css: { minified: true }

swagger_ui_integration:
  js:
    js/swagger.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - openapi_ui_swagger/swagger_ui

The library paths need to be updated to match the directories created in the installation notes:
js:
    /web/libraries/swagger-ui/dist/swagger-ui-bundle.js: {}
    /web/libraries/swagger-ui/dist/swagger-ui-standalone-preset.js: {}
  css:
    theme:
      /web/libraries/swagger-ui/dist/swagger-ui.css: { minified: true }


Find entity id in database I am currently moving a website from Drupal. The information I need to transfer is divided to many DB tables and connected through entity_id (That is my understanding, I have no experience in Drupal).

E.g. I have 2 MySQL tables:
users — contains uids, passwords and emails
field_revision_field_user_profile_phone — contains phone numbers and entity_ids

I believe there should be a table that matches uids and entity_ids, that will let me build a MySQL query to join them, but I can't find it.

How do I join those tables?

In the database that contains entity_id (field_revision_field_user_profile_phone in this case) there is a column named entity_type. That would be a name of the table which contains both uid and entity_id.


Register User with Services (JSON) with Custom Fields I am trying to register a new user on Drupal7 via services with JSON. Actually I am posting info from JAVA (android) with JSON format to the server with services module enabled. A sample successful JSON post is:

    {
    "name": "erfan",
    "pass": "1234",
    "mail": "erfan@example.com",
    "status": "1"
     }

  URL: [siteURL]/[endpoint]/user/register

I was successful creating users with basic info such as name,email,status.

I have added custom fields like field_address, field_phone, etc to the web site and want to send them via JSON to the server.

The problem is I can not figure out how to post these data to the server and couldn't find any documentation about it. My trial and error approach was not successful too, because I am not good in PHP coding. So please help me. Thanks.

Hope this will help you,

In Drupal 7 you can use the below JSON format to add custom fields(field_user_image)

{
    "name": "test",
    "pass": "password",
    "mail": "test@gmail.com",
    "field_user_image": {
        "und": [{
            "fid": "2"
        }]
    }
}

I have tried in my local and it is working fine.

Created new field UUID

Calling the Service using Firefox poster add-on

Code

  {
    "name": "testuser123",
    "pass": "testuser123",
    "mail": "testuser123@gmail.com",
    "field_register_uuid":
      { "und":
        [{
          "value": "65C7DCA4-8F03-473C-9E8F-08B3F29E91AE"
        }]
      }
  }

I can able to create new user with the custom field

References

How do I POST a new node using the Services module?
Services module. How to construct the JSON data with session info for creating node?


Superfish - No output Hi I can't get Superfish to output anything in Drupal 7 Zen Starterkit Sub Theme

I've done everything : Installed the Module For Superfish, Libraries, and jQuery Update, I've installed the Superfish Library, created a Menu, called the Menu in Superfish Module, but no output.

I've tried putting in snippets of code in the page.tpl to call the Superfish menu, but they only caused errors.

Please help.

View here http://www.cambrianvacation.co.uk/safeside

Ant:-)

First off, super fish module doesn't require the jquery update module so uninstall it. It's a PIA module if you don't need it. Second, in the superfish settings, set it to render 1 block. Go to the blocks and find the super fish block. Edit that block and set it for whatever menu you would like to use it for and place it in a region.


Contextual Filters > Default option: PHP Code input option is missing I have two drupal 7 sites.  I'm able to select the PHP Code option to input a default value for a contextual filter on a view on Site A....on Site B I'm unable to find this option.  Is this a version issue or a settings issue?  I'm at a loss to find out how to retrieve this option.

Either the core 'PHP' module is disabled or you don't have the 'Use PHP for settings' permission.


Can we use one product for multiple display nodes in Commerce D8? I used to work with Drupal 7 Commerce and now I need help to work on D8 Commerce.

I have nodes on my D8 website and I need to sell them through Drupal Commerce.
Each node can be sold in the same conditioning with four variations, based on customer types.

I have created a store, a product variation type, an attribute, a product type and one product with four variations, considering that one product would be enough.

Each node needs to be available as an order item.
For that, I have added an entity reference field, linked to the product type.
I have thus filled the default value with the product created.

Now on each node page, I have my add to cart button (through Commerce block or custom Views block, it works).

My problem :

Viewing the node A, I choose the variation and add the product in the cart and everything is fine.

Viewing the node B, I choose the exact same variation and add the product and there I need a second order item line with the node title (added through Views with relation to the entity reference field, not the issue here).

Unfortunately I get one order line item with quantity 2 (if I add the node title, I get two order line items with quantity 2 for each).

It may look obvious but I need to know if I really have to create one product with four variations for each node (2000+)?

Or is there a way to achieve this with D8 Commerce with only one product?

My concern here is to use properly Drupal Commerce and of course avoid the long multiple creation of products, especially in the future for my end user.

Related threads:

Automatically generate product variations

Drupal 8 Commerce does not need product display nodes anymore. When we create a product, we get a page automatically for this product.

But if you need, like me, to keep a "node environment"  on your website then you will have to create as much products as nodes and link them through an entity reference field (Type : Reference > Other...)

To create products, variations and links between nodes and products, I use Feeds, Commerce Feeds and Feeds Tamper. In my case, each feed type is based on upload file technique with CSV file created from Excel.

First, you build a Variations Feed type to create product variations with simple data (sku (unique), price, your_attribute). In my case, customer type was the attribute.

Second, you build a Products Feed type to create products using variations imported before (title (unique), variations (skus), store (required, ID=1 if you have only one). Here goes Feeds Tamper with List explode to get multiple variations for one product.

Third, you build a Nodes feed type to link nodes and products with two data (node title (unique), product title (in entity reference field)).

Finally, you get display nodes with specific products and variations and when you add to cart, products are well separated.

Hope this helps.


Extracting the values of Field Collection I have created a foreach loop in my node template in Drupal 8 where values of the field collection are being printed as 1 and 2. Instead I want the content of the field collection which includes an image and two text fields to be printed here. How do I achieve that? Complete code would be helpful.
My code:

 {% for member in content.field_robot['#items'].getValue()  %}
   <div class="robot-member">
      {{member.value}}
   </div>
 {% endfor %}

I have no experience of playing in the .theme file but can follow basic instructions.

Do you want to access the values or the rendered output of those field collections?

For the second, you're supposed to configure the view display to display the fields of the collection. I don't know how it works exactly. Looking at the code, the field collection itself should have a view display UI, just like the node itself, where you can configure each field.

If you want to access the values, then you should do the following:

Do not use getValue(). It returns non-computed properties only and it returns them as a simple array. You want the field item object.
content is the rendered output, node is the node object with the values. So, you'd use for item node.field_robot. Looking at the code, it seems you'd need to use item.getFieldCollectionItem() and from there, access a certain field again, e.g. item.getFieldCollectionItem().yourfield.value.

But... from looking at the code a bit and that it has two major 8.x branches and not even an alpha release yet... it might be too early to use that project. Maybe you want to look at Inline Entity Form (8.x-2.x actually seems to depend on that) together with e.g. a node type or custom entity type or Paragraphs. We use the second quite actively and it's pretty well progressed for Drupal 8.


Views 3: template suggestion file for header/footer parts? In Views 3, is there any type of template suggestion for header and footer parts of a view?

I know I can paste Full HTML into Global Header and Footer fields, but - as I have the main part themed in a tpl file - I'd also find it more comfortable to have the header/footer parts laid out in an external text file.

There's no template that I know about, but nothing can stop you from overriding the header and footer values in a view's general template like views-view.tpl.php, or even include a separate file instead of outputing the variable directly.


Which nid to use for translated node in a menu I'm not using the Entity Translation but only the i18n modules.

For example in the main menu I want to translate "contact us". So in the German translated menu do I need to give the nid of the German version of English node "contact us" ? Or the original English version one?

EDIT: In the figure node/59 refers to English node while the German version is node/800. So for German menu("contact us") which one do I need to feed? node/59 or the node/800. I fed node/59 for all the translated menu items but then they'd all redirect to English one. I thought that i18n should be able to figure and select the translated node automatically. Looks like I'm missing something.

In Drupal 7 you can use Locale core module to translate.

Locale : Adds language handling functionality and enables the translation of the user interface to languages other than English

After enabling the Locale module , add German language using admin/config/regional/language.

Use English words to create menus.
After creating the menus use admin/config/regional/translate/translate link to translate English string to German.

Search for the string. I'm using About Us to translate. Click the corresponding edit link to translate.

Enter German string


How can I show an Ad popup after search form is submitted? How can I place an Advertisement after clicking the search button and before showing the search results?
can anyone help me with this stuff?

you could try a custom search-results.tpl.php to create a JS overlay while the results are being rendered


Showing the date of the latest edit, instead of node's posting date I have some nodes I update frequently, but in content pane I can see the posting date of node.

How can I make Drupal 7 show the date of the latest edit, instead of the posting date?

I would tackle this in a template_preprocess_node, either in a module or in your theme.

function mytheme_preprocess_node (&$variables)
{
   $variables['date'] = format_date($variables['node']->changed);
}

Depending on your node template, you may also want to do something like

function mytheme_preprocess_node (&$variables)
{
   $variables['date'] = format_date($variables['node']->changed);

   if (variable_get('node_submitted_' . $variables['node']->type, TRUE)) {
     $variables['display_submitted'] = TRUE;
     $variables['submitted'] = t('Edited by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
     $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
   } else {
     $variables['display_submitted'] = FALSE;
     $variables['submitted'] = '';
     $variables['user_picture'] = '';
   }
}

so that your new $date gets used in $submitted, due to the preproccess/process order.

You can also play around with variants.  For example, you could have both created and last edited dates; you would juust need to set up the variables in the preprocess function, and then use them in your node.tpl.php.


How do I know when Hooks are called and in what order? I want to alter a HTTP header and I am looking for the appropriate hook to use.  I can tell a general time of when some hooks are called but not exactly when.  How do I know exactly when hooks are called, and what hook I should be using to change my header?

edit:  I have managed to change my HTTP header. But something else is adding to my header and that is taking precedent over my header portion.  Is there a way to know where this is coming from?

You're looking for an event, not a hook to do this in 8.x

Specifically, you're looking for the RESPONSE event, see \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber for an example. Create a class like that, register it in yourmodule.services.yml and then do whatever you want with the $response object.


Easy way to get this custom module to work with multiple Nodes (NID's) Topsitemaker hooked me up with this custom module that works great with one node when I enable it.  My issue is I need it to work across multiple nid's.  The field name and cid on all the nid's will stay the same, the only thing that will change will be the nid.  I have been trying without success to get this to work.  In this example it works for nid 4, but if the module is enabled, it will return the error for the same field on other nid's.  Is there an easy way to get this module to work with several nid's?

'<?php

/**
 * Implements hook_form_alter().
 */
function sample_form_alter(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

/**
 * Sample validation callback.
 */
function sample_webform_validate($form, &$form_state) {
  // Replace this with the name of your field, cid (webform component ID) and
  // nid.
  $field_name = 'application_name_director_name_manager_name';
  $cid = 10;
  $nid = 4;
  // Check if this is a duplicate.
  $is_duplicate = db_select('webform_submitted_data', 'd')
    ->fields('d')
    ->condition('nid', $nid)
    ->condition('cid', $cid)
    ->condition('data', $form_state['values']['submitted'][$field_name])
    ->execute()
    ->fetchObject();
  if ($is_duplicate) {
    form_set_error($field_name, t('YOU HAVE ALREADY SUBMITTED FOR THAT APPLICATION, PLEASE SELECT A NEW APPLICATION.'));
  }
}

/**
 * Implements hook_form_alter().
 */
function sample_form_alter2(&$form, &$form_state, $form_id) {
  // Make sure that we are selecting the webform forms.
  if (substr($form_id, 0, 20) == 'webform_client_form_') {
    $form['#validate'][] = 'sample_webform_validate';
  }
}

Would have been good if you explained what the module does so we don't have to read through the code to understand the module.

I am going to assume you mean the nid condition in the query.

The condition function of the query object defaults to 'IN' if you send it an array.
eg.

$nid = array(4, 5, 6);

and then:

->condition('nid', $nid)

will check nids 4, 5 and 6.
If you want to check all submitted webforms, just remove the nid condition.


Dealing with MySQL database quotas I have my Drupal site hosted at a society that gave me a 400M database quota.  After 4 weeks of production, it has reached 100M.  I predict that after a year, it will reach the limit.

Is any way to reduce the database size, so I don't have problems with my quota?

You could just shrink the database by optimizing every MyISAM you have

You can use to monitor how much space you database is taking up (in MB):

SELECT
    IFNULL(dbtb,'Total') tablename,
    (datsize+ndxsize)/power(1024,pw) table_size
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb,
    data_length datsize,index_length ndxsize
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A,(SELECT 2 pw) B
GROUP BY dbtb WITH ROLLUP;

This will add up all used data and index space.

I have other queries for measuring the amount of used space for MyISAM and InnoDB

https://dba.stackexchange.com/a/1307/877
https://dba.stackexchange.com/a/5708/877
https://dba.stackexchange.com/a/18952/877

If there is significant difference between in these queries' output and what your OS says you are using, try shrinking each individual table as follows:

SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') OptimizeCommand
FROM
(
    SELECT CONCAT(table_schema,'.',table_name) dbtb
    FROM information_schema.tables
    WHERE table_schema NOT IN
    ('information_schema','mysql','performance_schema')
) A;

Export the output of this query to a SQL text file and run it:

SQLFILE=/tmp/OptimizeSQLScript.sql
SQLCMD="SELECT CONCAT('OPTIMIZE TABLE ',dbtb,';') FROM ("
SQLCMD="${SQLCMD} SELECT CONCAT(table_schema,'.',table_name) dbtb "
SQLCMD="${SQLCMD} FROM information_schema.tables WHERE table_schema NOT IN "
SQLCMD="${SQLCMD} ('information_schema','mysql','performance_schema')) A"
mysql -u... -p... -ANe"${SQLCMD}" > ${SQLFILE}
mysql -u... -p... < ${SQLFILE}

An even faster way without fancy parsing would be to mysqldump the entire dataset and reload it

mysqldump -u... -p... --all-databases --routines --triggers > mydata.sql
mysql -u... -p... < mydata.sql

Give it a Try !!!


How do I set up an action to email all users with a certain role? I'm using Rules 7.x-2.6 and the way it works has changed a bit since I last saw.

I have a rule as follows:

EVENT
A node has been flagged, under "Report content"

CONDITIONS
None

ACTIONS
Send mail to [site:mail]

However, I'd like to, instead of sending directly to [site:mail], send an email to all users flagged with an "admin" role.

Now I know that I'll need to provide a loop do so, but my sticking point is generating the list of users to pass to the loop. So far, I have attempted to add a new action:

"Fetch entity by property"
Entity type: User
Property: User roles
Value: admin

But this doesn't seem to give me what I want in data selection, when passing it to the loop. Can someone recommend what they would set here?

I have "Send mail to all users of a role" available when I add an action.

edit rule
click add action
Under system section select "Send mail to all users of a role"
Select role and save


Using drupal_goto for checkout redirection to add $_GET variable, but gets overwritten So I want to do redirect to the following URL:

  http:/www.url.com/checkout?foo=bar

Tried using this:

drupal_goto($path = 'checkout', $options = array( 'query' => array( 'foo' => 'bar')), $http_response_code = 302);

Now it works, but instally redirects to this:

  http:/www.url.com/checkout/order_id/

...meaning that I lose the GET variable. How do I do this? The same happens if you just type /checkout into the address bar, it redirects to checkout/order_id. I think it might be commerce doing this automatically. Any idea how to resolve this?

drupal_goto should work just fine. You can confirm (e.g with Firebug) that it does the initial redirect to where you want (including foo=bar).
Then you'll see a second redirect to the plain URL which is being performed by another code/module that you haven't told us about.


How to use hook_form_alter to target a specific drupal commerce form? I have a fairly basic question I think. I've written a module that uses hook_form_alter to alter the fields in a product form.

But now I'd like to change the fields in the form for a different product and I was thinking of using my custom module to do so.

However, when I use the Devel module to try and find the specific $form_id for each of my created product forms I see they ALL have the SAME name: commerce_checkout_form_checkout. Soooo, I'm not sure how to target a specific form.

Moreover, I've used dpm() to check the variables in the forms and they all have the exact same values for everything. Even across product types. The only value that is different is #build_id but this changes for every form load so it can't be targeted.

Anyone know how to do this?

To add or alter the pane forms on the checkout page, for maximum compatibility, you should use the Commerce API.

Define new panes in:

hook_commerce_checkout_pane_info

Alter existing panes:

hook_commerce_checkout_pane_info_alter

For example, you could alter the checkout_form callback for a checkout pane to add your customizations.

  checkout_form($form, &$form_state, $checkout_pane, $order): returns form elements for the pane’s checkout form fieldset

You could also add your own custom checkout pane for your custom design there.

You can refer to the existing pane callback to first include or replicate the checkout pane.

Note: I posted a similar answer for adding a custom validate handler to a checkout pane a while ago here: https://drupal.stackexchange.com/a/87061/7153


How to troubleshoot Push Notifications module I'm trying to get the Push Notifications module to work correctly. So far I have successfully gotten my device to register with the service, and now I am trying to test the push back to APN. I went through This entire process and created the .pem file from my certification. When I attempt to test the push, I get the following error

Warning: stream_socket_client() [function.stream-socket-client]: SSL operation failed with code 1. OpenSSL Error messages: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

I'm at a bit of a loss on how to proceed, or how to further troubleshoot. I've tried looking up the error but the definitions seem vague.

This turned out to be my own error, I was using the wrong certificate, one that was not set up for push notifications, otherwise, everything works just like the instructions.