Save PDF file using webform2pdf I am using Drupal 7.12 and Webform2PDF 7.x-3.0. Is there any feature to save the PDF file to server using this module? Or how can I do this with this module? Or is there any other module ?

No you cannot save it on the server. One way would be to create your own code to grab the pdf with a tool like cURL and save it to the server. You could trigger your code to run every time a webform is submitted throught Rules and Webform Rules. You could issue a feature request to the module developer in case he wants add this fuctionality.

There is also this module: Fill PDF that does what you require. It is quite harder to get it to work with Webforms since you need to build your own pdf form template.


How to extend duration of the the one time login link? Is it possible to change the valid duration time of the one time login link that is send out by mail to the new user? I think by default it is 24 hours, ist it possible to change this to 72 hours?

For Drupal 7: In your settings.php try adding this:

$conf['user_password_reset_timeout'] = '259200';


How to change the user profile edit page? What is the best way to change the user profile edit page? I need to add a new field alongside the password.

You can add new fields to the users profile page at admin/config/people/accounts/fields

You can also manipulate the form by implementing hook_form_user_profile_form_alter(&$form, &$form_state, $form_id) and hook_form_user_register_form_alter(&$form, &$form_state, $form_id)

To add new profile pages you can use the Profile 2 module.

You can also edit the user edit template by implementing hook_theme().


How do you make Varnish cache update when Drupal content changes? I just started playing with Varnish cache. Looks like an awesome thing to have for speeding up page load times!

How does one force the cached copy of a node/page/content to be updated when the content changes in Drupal? Would it be something in the VCL file? I am using the VCL from Four Kitchens.

There are many ways to achieve this. A very common way is by using the Expire module (https://www.drupal.org/project/expire).

It can easily be configure to clear specific pages, or sets of pages from varnish when they are changed. It has been well documented and is up to date, a great module and does exactly what you require.


How to use Rules to transform upvotes and downvotes towards User Points? I know that there is the Userpoints Karma module, and this is only updated to Drupal 6 version.

Are there any techniques for transforming votes towards User Points? Or can you point me in the direction of reference for creating a custom module for this purpose?

Note: The votingpoints module is not available for Drupal 7, so I was looking into using Rules to grant points to the creator of a node, when a user votes on it.

in these pages you can find what you need.

User Points This is a module

User Points Contributed modules more modules!

Choose the one that fits in your website.


Password Security for Downloading PDF in drupal7 i have a file upload field type in my content type.
so user can upload PDF file in that. i want to make password security for  downloading the PDF.
Can anyone help on this?

Thanks in Advanced.

There are two methods to ensure security of your files:

1) You can choose the "Private downloads" method in admin/settings/file-system, and

Either set your files path to a directory outside your web root so
that they don't have an URL
or leave them where they are and protect them with some .htaccess directive (Order deny,allow and deny from all).

Apache won't serve them directly, and Drupal will read them and serve them with a virtual path system/files.

Then you can set permissions for the files by using an access control module (content_access or nodeaccess or node_privacy_byrole or og) and restricting access to the posts where they were uploaded, so that only some user roles can see them.

Caveats:

Your file-related modules must support the private download method
The private method is a bit slower because of the additional processing.
If you already have uploaded files their links may break if you change the download method now.

2) You can use pdf using mpdf module. it offers the ability to password protect your files.


7 - How to create a view using ApacheSolr? How am I able to create a view using ApacheSolr as base in Drupal 7?

All I can see when creating a new View, is ApacheSolr localhost server which doesn't give me the fields that I need, found few links online but none of them helped! very confused!

I am using :

Apache 7.x-1.0-rc4
Drupal 7
Views 7.x-3.5
Apache Solr Search Integration 7.x-1.0-beta1

I add a full response.

If you want a full integration with Solr and Views you should use Search api with Search Api Solr (there several modules that work with Search Api, see the Search Api page).

You will be able to:

create search pages (like normal search pages), with Search Api Pages
create every type of view based on the Solr Index, using filters, relations, contextual filters
add facet, with http://drupal.org/project/facetapi, to search pages and views

There are many usefule modules that work with Search Api: autocompletation, indexing files, create index on file taxonomies and users, spellcheck, sorts, ranges, saved searches etc.

Every day I use Search Api at work, for views and for default search, I think is the best solution.


Adding JS to field widget being created in my module Cross-posting to stackoverflow.com

I am creating a custom field to eventually be displayed in a custom paragraph.  I need to upload a JS file for the widget view, but can't seem to get it to work.  Can anyone see what I am doing wrong or need to do differently?

I can add the field to the paragraph, add the paragraph to a document and see the fields, but I see no evidence of the JS being attached (the file is not downloaded in the browser and does not activate).

Any help or suggestions are appreciated.

file: src/Plugin/Field/FieldWidget/get_libguides_listings_widget.php:

<?php

namespace Drupal\get_libguides_listings\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

class get_libguides_listings_widget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(
               FieldItemListInterface $items,
               $delta, array $element, array &$form,
               FormStateInterface $form_state) {
    $element['Subject_IDs'] = [
      '#type'=>'textfield',
      '#title'=>$this->t('Subject IDs to Display'),
      '#description'=>$this->t('BLAH'),
      '#default_value'
           =>isset($items->getValue()[$delta]['Subject_IDs'])
          ?$items->getValue()[$delta]['Subject_IDs']
          :'',
      '#states'=>[
        'visible' => [
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'subject']],
          'or',
          [':input[name$="default_value_input[field_libguides_listing][0][SearchBy]"]'
                =>['value'=>'both']],
        ],
      ],
    ];
    $element['Subject_IDs']['#attached'][]
          = 'get_libguides_listings/get_searchby';
    return $element;
  }
}

file: get_libguides_listings.libraries.yml:

get_searchby:
  js:
    js/get_searchby.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

file: js/get_searchby.js

/**
 * @file
 */
(function(){
  alert('hello there');

  (function ($, Drupal)
  {
    Drupal.behaviors.get_searchby = {
      attach: function (context, settings)
      {
        alert('hello');
      }
    };
  }(jQuery, Drupal));
}());

You forgot the library key:

$element['Subject_IDs']['#attached']['library'][] = 'get_libguides_listings/get_searchby';


Dynamically grow menu based on terms in vocabulary? As terms are added to a vocabulary, I need these terms to be incorporated into a menu with a custom URL structure.  For example, I might have the Restaurant Taxonomy which has the following terms:

McDonalds
Taco Bell
Wendys

I need to have a menu generated that matches a particular pattern with the term names plugged in - this pattern can be arbitrary.  For example, I have the pattern /restaurants/<term-name> would generate a menu with the following links:

/restaurants/mcdonalds
/restaurants/taco-bell
/restaurants/wendys

As terms are added, this menu needs to grow dynamically.  How can this be accomplished?

The Taxonomy Menu module will be able to handle that...

  Transform any of your taxonomy vocabularies into existing menus easily!

  Features

  Custom Menu per vocabulary
  Uses the default taxonomy term path or custom paths
  Integrate with Views
  Integrate with Pathauto: use URL/path aliases
  Does not interfere with other menu modules

The module page also links to a tutorial called How to add a block menu of tags (or other taxonomy terms) on a Drupal site in conjunction with the Menu Block module in case you need that functionality.


How to move drupal 7 site in a different path from Home directory what is the way to move drupal 7 site in a different path from Home directory. Currently my website is based on d7, so how i should move drupal 7 site to www.example.com/a/ instead of www.example.com

Depending on your server setup, it should not be hard. My only recommendation will be to disable the clean urls and the 444 permission of the settings.php file before moving the site over. After the move is done check if the .htaccess file is there, clean the cache, re-enable the clean urls and restore the permissions to the settings.php file to 444.


Close a webform when total seats reach a maximum I would like to know if it is possible to set-up a specific event registration webform to close automatically when the number of total reserved seats (reserved seats field) reaches a certain maximum.

A little background:
I have a few different event registration forms on my website, each event is held in a different venue with a maximum number of seats. The forms each have a reserved seats field, users can reserve up-to 2 seats(max) per submission. I cannot use the submission limit feature of the webform because the number of submissions do not map directly to the number of total seats that users are reserving.

Is it possible to have the webform calculate the sum of the reserved seats field and close the form when it reaches a certain maximum number? How would I go about setting that up?

I built a custom handler to process seat reservations. I just wanted to share my code for anyone else looking to do the same thing. @jrockowitz let me know if you want to add this into webform core.

<?php
namespace Drupal\webform_reservations\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
* Form submission handler.
*
* @WebformHandler(
* id = "webform_reservations_handler",
* label = @Translation("Reservations Handler"),
* category = @Translation("Form Handler"),
* description = @Translation("Manage maximum seat reservations"),
* cardinality =
 \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/

class ReservationHandler extends WebformHandlerBase {

 /**
 * {@inheritdoc}
 */

  public function submitForm(array &$form, FormStateInterface $form_state,
  WebformSubmissionInterface $webform_submission) {
  $webform = $webform_submission->getWebform();
  $formid = $webform->id();

//query the db for all submissions of current webform submission
$query = \Drupal::entityQuery('webform_submission');
$query->condition('webform_id', $formid);
$result = $query->execute();

//load all the submissions from the results
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();

foreach ($submissions as $submission) {
$submission_data[] = $submission->getData();
}

$current_reserved = 0;

//add up all the values in the 'seats needed' field of each submission and save it to a variable.
for ($i = 0; $i < count($submission_data); $i++){
    $current_reserved += $submission_data[$i]['seats_needed'];
}

//when a registration form is submitted, check if the current reserved seats exceeds the value specifed in the maximum allowed seats field of the form.
if ($current_reserved >= $webform->getElement('max_seats')['#value']) {
    $webform->setStatus('closed');
    $webform->save();

 $message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ' the form will now be closed';
  } else {$message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ', the form will stay open';}

//log the output to the drupal logger, to indicate if the webform is still open or closed after each submission.
\Drupal::logger('webform_reservations')->info($message);

}
}
?>


I get notification for TB Sirate Starter update despite that I use new fresh drupal installation I get notification for TB Sirate Starter update despite that I use new fresh drupal installation, never setup TB Sirate Starter. This repeated many times and on many of my new drupal project.

I only tested it in the past on my local server. But I always setup fresh and clean drupal installation.

Is there any soultion

Despite not using the distribution any more I keep getting the message to update TB Sirate Starter

====================================

I had this issue before and yes, I took notes.
In my case it was solved by finding the culprit(s). They were jquery_plugin and jquery_update

# grep -r "tb_sirate_starter" .
./sites/all/modules/jquery_plugin/jquery_plugin.info:project = "tb_sirate_starter"
./sites/all/modules/jquery_update/jquery_update.info:project = "tb_sirate_starter"

The fix / workaround?

I deleted the directories jquery_plugin/ and jquery_update/

Then reinstalled them.

# grep -r "tb_sirate_starter" .
#

No more messages "Update Available - TB Sirate Starter "
And I think this is what the OP asked :)


Quicktab problem on the argument of view and block I used to make a view shows a page of a project in the url:  projects/[node:author]/[node:nid], this view works well.

Now I want to display this view in the quicktab, but the problem is I can't view the content of the view. I think it is because of the configuration of argument of quicktabs. In the quicktabs, I have selected this view and display it as page, but the problem is I am not sure how to config the arguments.

As you have seen the url of view, is projects/[node:author]/[node:nid], in which there are 2 arguments, when I set it as %0/%1, not working, %0/%1/%2, still not working, and set it as projects/%0/%1, not working either.

Is there any problem with my config?

Also in the quicktabs, I also display the comments related to that content, previously I made another block with default value as contextual argument like projects/[node:author]/[node:nid], but when I try to put it the quicktabs as a block, it also doesn't show.

Looks to be an issue with the quick tabs module. I have the same issue on version 7.x-3.4. It seems to break as soon as you use the % URL variables

UPDATE: After looking at the code, the module calls args(), in my case, the values returned from that are different than the URL. For example, my URL is "product/reading" however, quicktabs gets this Array ( [0] => node [1] => 180 ). So I have to change my view to use the node ID instead of the node title. This should have been noted in the modules documentation.


populate taxonomy from another taxonomy I have 2 exposed filters in a search page "drop down lists", I want to populate the second exposed filer "taxonomy" from the first one:

example
vehicle {car, plane, ship}
and the second should be {BMW, Honda, etc}
only if vehicle car is selected in the first drop down list.
thanks

Found the solution for this, I used Hierarchical Select
and it worked like a charm.


Organizing content in a hierarchy I created a website with some content nodes in D8. Right now, all the nodes are on the same level, however, I would like to achieve something like this:

- Products
- - Product A
- - Product B
- - Product C
- About Us
- - Offices
- - Contact

Naturally, I would like the nodes' URLs to respect the hierarchy, so that there would be URLs like mydomain.com/products and mydomain.com/products/product-a and so forth.

I know about Node Hierarchy being available for 7, but it seems there's no such solution for D8 - however, since this is such a basic requirement, I suppose there's a way how to do this I don't know about. So, how to? Is the book module maybe the right solution for this?

I would set up a vocabulary, with a machine name such as site_nav,

then on your nodes, you would add a taxonomy term reference field to the site_nav vocabulary.

Then set up automatic path aliases using pathauto at /admin/config/search/path/patterns

You could use the title of the page or add an additional field, such as field_short_name to use in the url.

Then the pattern would be

[node:field_site_nav:url]/[node:field_short_name]

or

[node:field_site_nav:url]/[node:title]

or some such (I forget the exact pattern for urls of terms).

You could also use the content type names, if you have content types such as "products" and "about us", then the pattern would be

[node:content-type]/[node:title]

There are some more examples here:

https://www.drupal.org/node/1044980


Drupal 7 Domain Access Module Gives 500 error, WSOD for subdomains I am attempting to get Drupal 7's domain access module working.
I have the original domain that the site was built on, and 2 more domains,
all configured from a local apache virtual host configuration.

I can log in and configure with the original domain name "localhost",
but when I try to log in with any of the other domains I configured I get a 500 Internal Server Error.

Domains Configured (for local use):
1)localhost
2)drupalx.domainaccess.com
3)drupaly.domainaccess.com

This is the domain configuration page for domain's in Drupal.  Note I have 3 domains configured, localhost, drupalx, drupaly.

I know that the domains I set up work because if they did not then this next image would have a warning saying that the domain module could not access files on the domain name.
I also verified this by using the drupalx/drupaly domains and I was able to access css files in a subfolder of the drupal install using these domains.

Here is the home page for the drupalx domain. The only page that can be accesssed is the home page.

If I try to go to any other page in drupalx or drupaly I get a 500 error, WSOD.

Here is my virtual host setup

I don't have any drupal reports on this, and my apache logs only gave the 500 error info

ie:
127.0.0.1 - - [24/Apr/2014:16:54:46 -0700] "GET /user/register HTTP/1.1" 500 530

OK, might as well add a tentative answer on this one.

Add your subdomains using ServerAlias within the same single VirtualHost, because they all have the same document root.

ServerName www.example.com
ServerAlias drupalx.example.com
ServerAlias drupaly.example.com

Fix the stray rewrite stanza in virtualhost scope.

e.g put it inside the Directory block.

<Directory "C:\xammp\www">
  <IfModule mod_rewrite.c>
    RewriteEngine on
    # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
  </IfModule>
</Directory>

However, the latter isn't really needed if using the default .htaccess file in your doc root. Alternatively, remove .htaccess and copy its contents to the Directory block instead.


Make taxonomy term only link to term page if multiple nodes have that term? I have a free tagging taxonomy term field. How can I make it so on the node page the term only links to a term page if there are multiple nodes with the same term?

Otherwise this link and page are pointless, and are bad UX as the user will be expecting to see other similar nodes. So if there is only 1 node with a term then I would like the term to not be a link.

UPDATE ive tried creating a custom module called taxonomy_link_my.

In my taxonomy_link_my.info

name = Taxonomy link my
description = Stop taxonomy term being a link if no other nodes are tagged with the term.
core = 7.x

In my taxonomy_link_my.module (topic is the vocabulary name).

<?php

/**
 * Implements hook_node_view
 */
function taxonomy_link_my_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['topic'])) {
    foreach ($node->content['topic']['#items'] as $delta => $item) {
       if (count(taxonomy_select_nodes($item['taxonomy_term']->tid)) < 2) {
         $title = $node->content['topic'][$delta]['#title'];
         $node->content['topic'][$delta] = array();
         $node->content['topic'][$delta]['#markup'] = $title;
       }
    }
  }
}

However it seems to have no effect.

Looks possible implementing  hook_entity_info_alter()

  Modules may implement this hook to alter the information that defines
  an entity. All properties that are available in hook_entity_info() can
  be altered here.

Here is some sample code

function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
* Entity uri callback for taxonomy terms. Add special exception to redirect users away
* from taxonomy term pages to the associated program node page.
*/
function mymodule_taxonomy_term_uri($term) {
  if (count(taxonomy_select_nodes($term->tid)) > 1) {
    return array(
      'path' => 'taxonomy/term/' . $term->tid,
    );
  }
  else {
    return array(
      'path' => '',
    );
  }
}

You need to make some tweaks to get term id by term name.I have not checked about returning the path if node count is 1.


How to change the currency symbol according to language in site? I have enabled i10n, i18n, entity translation, title and variable modules and built a multilingual commerce site with language English as default language and $USD as default currency. And French and Poland as additional languages.

But I am unable to change the currency symbol in other languages.

How to translate currency symbol also?

Have a look at the Currency module, here is a quote about it (from its project page):

  ... provides your website with currency conversion, currency information & metadata, and amount/price display functionality.

This module facilitates Localized price display. Here is an excerpt from that link also:

  ... displays prices/amounts based on users' locales, so they are formatted in a way that is familiar to them. The different formats can be configured at Home » Administration » Configuration » Regional and language » Currency localization. Locales consist of a language and a country, and formatting patterns are configured per locale.


Remove field attributes using hook_form_alter() How do I remove form element attributes from a form using hook_form_alter()?
For example, given the following HTML markup, how do I remove form-text?
<input type="text" class="form-text required" maxlength="255" size="60" value="" name="title" id="edit-title">

Insert the following into your custom module:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id){
  switch($form_id){
    case 'YOUR_FORM_ID':
      $form['title']['#required'] => FALSE;
      break;
  }
  return $form;
}

That makes the title field optional. You can check the different form element types and the properties that go with them here: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

And you can read more about hook_form_alter here: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7


Solr 5 incompatible schema.xml An error kept showing after installing Search API for solr and after creating a server on drupal. (Solr 5.x)

You are using an incompatible schema.xml configuration file. Please follow the instructions in the handbook for setting up Solr.

Already copied alll configuration files from drupal module into:
/opt/solr/server/solr/my-core/conf

what else to check?

On Centos systems Solr assumes your cores will be stored in /var/solr/data/[core-name].

So if your core is named my-core, Solr might already have created the folder /var/solr/data/my-core for you. Simply place the conf directory in that folder, overwriting anything that might already be in conf.
No need to touch any of the other files.


give node author ability to position the image when uploading content I have a field of type image "COVER IMAGE" in my blog entry content type. The users should have the power to place it wherever they like...top, down,right or left, if not more and re size it. right now it appears at the bottom of the content and of the same size as that uploaded.

Can this be done?

Regards

Of course it can! Was covered in docs and in even more docs and is supported by Wysiwyg, with helpful modules like Insert to make it even easier.


Allow anonymous users to load site contact form without granting admin privileges I'm including the site contact form on a page with these 2 lines.

  module_load_include('inc', 'contact', 'contact.pages');
  print render(drupal_get_form('contact_site_form'));

The page loads as expected when a user is logged in, but for an anonymous user the page returns a 403.

If I give the "Administer contact forms and contact form settings" permission to anonymous users, then the page will load for anonymous users. I gave the "Use the site-wide contact form" permissions to anonymous users, but they still get an access denied error.

Is there a way to allow the form to load for anonymous uses without giving them admin privileges?

The Access Denied error is returned because the following code executed by code_site_form(). (Notice the call to drupal_access_denied().)

  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

Users with the "administer contact forms" permission don't get that error, since the limit for the sent messages doesn't apply to them.

Check those Drupal variables have not been set to different values that lower the number of allowed messages. The default is 5 messages in 1 hour.

As side note, render(drupal_get_form('contact_site_form')) would cause a "call-time pass-by-reference" warning in PHP 5.3, since render() is expecting a variable passed by reference, but drupal_get_form() doesn't return a reference. PHP 5.4 will raise a fatal error for that same code. The code calling render() should always use a variable.

module_load_include('inc', 'contact', 'contact.pages');
$form = drupal_get_form('contact_site_form');
print render($form);


Entity Reference Colorbox Format Display I'm having trouble in creating an album with many galleries, that reference images through entity reference content type from Biblio. I have tried many ways to create the following. But all partially failed.

In my last try I followed the following tutorial: Creating-a-drupal-7-image-gallery-using-content-types-nodes_tech , it works out fine with the referenced image.

But couldn't complete the tutorial in the following step:
I need to change the referenced image format to colorbox, from the Manage Display of Node Image content. Is there way to do the following on a referenced entity?

Is there a better solution?

In the manage display change the format for the referenced image to rendered entity. Then select the gearbox and select colorbox view.

You will need to edit this view mode.So go to biblio content type and manage display. Select colorbox view and change the image field format to colorbox.


Import files into a file field in Drupal 7 I have a content type that accepts a PDF document as a file attachment.  I have a bunch of entries that currently have no attachment, but I have the files for each entry and need to associate the files with each of their respective entries.

Currently, all of those files are stored in public://publications, so they're already in the public file path where they should be, I just need to "hook them up".

Rather than hack this with Ruby which I would normally do, I'd like to kick the bad habit and use the Drupal API.  I've looked at the following articles:

Programmatically attaching files
http://drupal.org/node/330421

..but haven't been able to really wrap my head around it.

Curious if others have dealt with this situation and what they've done to address it.  Thanks.

UPDATE

I've got the files copying as they should be.  However, I'm not encountering an error, and the error happens during the node_save call.

Here is the error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] => 0
    [:db_insert_placeholder_1] => 1
    [:db_insert_placeholder_2] => 1330491978
)
 in drupal_write_record() (line 6975 of /var/www/website/drupal-7.4/includes/common.inc).

And here is the code.

$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

// THIS IS A PROBLEM LINE
$node->field_publication_attachment[LANGUAGE_NONE] = $file;

node_save($node);

If I comment out the line labeled THIS IS A PROBLEM LINE then no error occurs, but that obviously isn't desirable because that means it's completing but without attaching my file to the node!  Help!

SOLUTION

$node = node_load($bib_value->nid);

$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file,'public://publications',FILE_EXISTS_REPLACE);

$node->field_publication_attachment[LANGUAGE_NONE][] = (array)$file;

node_save($node);

Needed to set display and description on $file as well as cast $file as an array when adding it to the attachment field.  All worked smoothly after that.

I am currently working on the exact same thing, except using photos.  If you click my profile name, you will see a series of questions related to learning how to do what you are asking to do.

I was able to easily accomplish the code to loop through all the files in my folder and add them to my nodes.

$file = new stdClass();
$file->filename = basename($local_path);
$file->filepath = $local_path;
$file->uri = $local_path;
$file->filemime = $mime;
$file->filesize = filesize($local_path);

// Set this at the very beginning to correspond to USER you want posting items.
$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' => $file->fid,
'alt' => $page_data['title'],
'title' => $page_data['title']
);


Alter results programmatically I'm using views data export module to output results as csv, xls, xml and txt files

I'm using  Batched export (with Segment size 100) because there are many results.

I have some fields which I want to alter their values.

I have implemented hook_views_pre_render to replace field values with ones I'm getting from webservice.

The problem that some values are correctly changed, others not

Is there a solution for that?

Instead of a pre-render function, I think the correct spot to modify values is actually hook_views_post_execute().  This is invoked after the query has run, but before the data has been passed to rendering.

  Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.

It has been a while since I've personally played with Views Data Export so I'm not 100% sure why you're seeing only some values change and not others, but I recall the rendering of the export being a little abnormal compared to the usual render process.


Load a plugin definition? I want to load a plugin definition by its string id within a controller extending ControllerBase. What is the relevant service or class I am looking for?

You can use the plugin manager to fetch a plugin. You only need to find the correct plugin manager service:

$type = \Drupal::service('plugin.manager.service'); // Fill your own plugin manager service.
$plugin_definition = $type->getDefinition('plugin_id'); // Fill needed plugin id.


How to change the default date format in Rules? I've created a rule to send an html email which contains a date, printed using tokens as [commerce-order:field_delivery_date]. In email, the date looks like 2016-07-08 00:00:00 to 2016-08-02 00:00:00. The date may or may not be an interval.

How can I alter the date format in Rules?

I know that I can use something like [commerce-order:field-delivery-date:value:custom:j m] - [commerce-order:field-delivery-date:value2:custom:j m Y] which outputs 08.07 - 02.08.2016.

But, I don't always have an interval, I can only have the start date, which should be printed as 08.07.2016.

Try to use what you have defined as the format for short / medium / long format in your Drupal date settings, using either of these tokens:

[commerce-order:field_delivery_date:value:short]
[commerce-order:field_delivery_date:value:medium]
[commerce-order:field_delivery_date:value:long]

However, since your date seems to be a data range, you may have to enable the Entity API module and its "Entity tokens" sub-module to access the date values.

Also, be aware that Entity tokens replaces underscores  (= "_") in the tokens names by dashes (= "-"), so in your case "field_delivery_date" becomes "field-delivery-date". And with that, this is how it should look like:

[commerce-order:field-delivery-date:value:short]
[commerce-order:field-delivery-date:value:medium]
[commerce-order:field-delivery-date:value:long]


Theme a view of one content type with node references to another I'm attempting to theme a view containing of content type 'Activity' which includes Node References to a second content type 'Category'.

When using the views-view-list template it appears I cannot access or the fields which are included through Node References.

Any help would be appreciated.

What you need to do is add a view relationship (in Views 2 and Views 3) that uses your node_reference field to create the relationship. This will make these fields available to your view.

Thats the quick answer, this video explains it better:

http://gotdrupal.com/videos/drupal-views-relationships


Latest tweets from a specific user (bonus: rotating slideshow) I want to display the latest 3 tweets on my homepage from my Twitter account for all users. A rotating slideshow of the tweets would be cool and it looks that with the Twitter module it might be possible but I can't get it working.

I have tried Twitter Block (http://drupal.org/project/twitter_block) but that is still under development and it seems the only thing not working with it is display a specific user (which is what I need).

I have searched far and wide, tried and tested a lot of modules and cannot find one that actually allows this. Does anyone have anything to point me at? Tutorial, walkthough, functioning module?

Here's how I would implement this:

Use Feeds to aggregate your tweets to a custom content type, map tweet id to node title and tweet body to node body.
Create a View to display x amount of tweets from the custom content type.
Use Views Slideshow to rotate the content.


How to automate database table access as objects and provide common operations, like CRUD and views integraion? I think this is a pretty normal use-case: Developer has a database. Tables and columns have meaningful names and helpful comments, possibly also sane set of relations. Now he needs a module to be build on it.

Is there any automated way to provide CRUD and views integration, either dynamically or by creating a module backbone for developers to edit? Like scaffolding available in Cake PHP and other frameworks and languages? Doing it by hand for large number of tables is repetitive and boring, and that's both waste of time and source of errors.

Automatically, no (although if someone want to prove that wrong I'd be delighted to see the solution). However, everything you've asked for is easily attainable through Drupal's API:

For the database table, implement hook_schema() (no foreign keys are enforced in Drupal 7, though the relationships can be described for documentation)
For views integration implement hook_views_data()
For CRUD forms use the form API.

I think the closest you'll get to doing that automatically is the Entity Construction Kit. You can define your custom data as an entity, and I believe that module will create the appropriate entity forms for you. Integration with the Entity API module and Views means you can also expose that data, and you get field functionality built right in.

However, going that route will probably end up taking more code than doing it manually, and the reliance on the entity/field system will introduce extra overhead.

You might also want to look at the Doctrine ORM module; I haven't used it before, and it's only in dev, but if you can get that working it would give you objects mapped to DB tables as you're looking for. Exactly how that would fit into Drupal I'm not sure.

Things in Drupal 8 should be much better.


content types vs. paragraphes types + taxonomy I have quite a complex content structure and found the paragraphs module (in combination with taxonomies) can be very powerful for creating complex compound fields and dynamically reusing existing content types.

Example: 1 content type "equipment" tagged with a term from a taxonomy "mobility devices" (terms: car, aircraft, bike...) and with different fields of paragraphs types representing the different attributes for each of the devices. This way I'd only use the car_paragraphs_field if the equipment is tagged as a car and leave the other paragraphs fields blank. This in contrast of having multiple different content types "car", "bike"...

I'm wondering whether this a reasonable approach in terms of later displaying data in views, storing data to the DB, internal Drupal complexity/load when having let's say 100 different paragraphs types and only using 1 for each new content (i.e. leaving many paragraphs types fields blank), instead of having one separate content type for each.

Personally I don't think this is a good use case for paragraphs. I don't see any benefit of having only a single content (node) type, you are just moving comeplexity from nodes to paragraphs.

I think the key here is to carefully plan and reuse fields across entities. If your car equipment and your plane equipment both have a weight attribute, reuse the same field (or to be more precise: reuse the field storage), so e.g. you can use it to as filter in a shared view for both equipment types.


how to save uploaded file in a custom user registration webform in D7? I implement the myModule_webform_submission_insert($node, $submission) {...} function in my Module.
It's a regestration webform so I want to save all the data from the webform into a the new user. The user has to upload a file during the registration. I have no idea how to save this file in the user as in $submission[15]['value'][0] I only receive a integer. I have no idea how to get the path the file was actually saved.

Can somebody tell me if it's possible to save the file (uploaded with webform registration form) in the $user_data Array which is the parameter for user_save()?

For example I have this

function blabla_webform_registration_webform_submission_insert($node, $submission) {
// $node->nid will be the node id of your webform
if ($node->nid == 22) {

$submitted_data = $submission->data;
//Get data from field
$file = $submitted_data[15]['value'][0];

//Now $file has the value
// $file[value][0] = 46

}

What can I do with '46'? :)

Best regards,
Christian

I believe 46 is the File ID or FID in Drupal. You can load it via file_load() and re-save, move it or attach it to a user profile however you like.

Webform has already saved the file in the system somewhere. You can find out where by inspecting the $file object after $file = file_load(46); and doing a print_r or vardump on $file.


workbench access warning message when I click preview Has anybody come across a warning message which appears when you preview content? This message only displays when the workbench access module has been installed and the following setting has been checked 'Require a Workbench Access form element'

The messages:
"*Warning: array_keys() expects parameter 1 to be array, string given in workbench_access_node_form_element() (line 1465 of C:\wamp\www\dev\sites\all\modules\contrib\workbench_access-7.x-1.2\workbench_access\workbench_access.module).*

*Warning: Invalid argument supplied for foreach() in workbench_access_node_form_element() (line 1466 of C:\wamp\www\dev\sites\all\modules\contrib\workbench_access-7.x-1.2\workbench_access\workbench_access.module).*
"

Cheers!

You can find the related bug here and the patch here.

You can then download the patch into the workbench_access directory and execute

patch -p1 < 1935190-wa-array-keys_0_1.patch


Getting the image URL from a field_image on a node So I have this Node:

object(Drupal\node\Entity\Node)[1862]
  protected 'values' =>
    array (size=17)
      'vid' =>
        array (size=1)
          'x-default' => string '7' (length=1)
      'langcode' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=1)
                  'value' => string 'en' (length=2)
      ... (more fields)
      'field_image' =>
        array (size=1)
          'x-default' =>
            array (size=1)
              0 =>
                array (size=5)
                  'target_id' => string '1' (length=1)
                  'alt' => string '' (length=0)
                  'title' => string '' (length=0)
                  'width' => string '150' (length=3)
                  'height' => string '120' (length=3)

Now the field_image has an array with x-default and some basic image data. How do I show the image, or create a link to the image inside the Twig template?

Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.

{{ file_url(node.field_image.entity.fileuri) }}


How to add Search form/Advanced search form view to advanced forum pages? I found two things in Advanced forum.

1. Advanced forum provides the views, one of which is advanced forum search as shown in the following image, which provide the specific search on the forum.

2. But it is a separate link, and totally separate page, if it will be under the title of the advanced forum topic and on every forum discussion page, it will be very suitable for visitors. As shown in this image.

Now, how to add that advanced forum box and advanced option selection box provided in views under the forum title? I mean all on all the pages of forum except the first main page. Very Thanks.

You need to display the exposed filters in a block, and then display that block on single forum node pages.

Here's how to do that:

Edit the Forum Search view: /admin/structure/views/view/advanced_forum_search/edit.
Under "Exposed form" -> "Exposed form in block" choose "Yes".
Save the view.
Navigate to /admin/structure/block.
Enable the "Exposed form: advanced_forum_search-page" block, and show it for example in the "Content" area and only for "Forum topic" nodes. You can change this to your liking of course.

Users now can use this form from single forum nodes, and submitting it will take them to the search page.

Update

If you want to make this available in your templates and position it within other elements, you'll have to edit the template.php of your theme add a hook_preprocess_X() implementation.

Choice depends on the template you want to add the form to. For example:

hook_preprocess_node() - to make the form available in node.tpl.php
hook_preprocess_page() - to make the form available in page.tpl.php
hook_preprocess_html() - to make the form available in html.tpl.php

Here's the code:

function YOUR_THEME_preprocess_REPLACE_THIS(&$variables) {
  // Load the view and generate the search form.
  //
  // You can have any dynamic conditions here (e.g. limit to some content types
  // and so on).
  $view = views_get_view('advanced_forum_search');
  $view->set_display('page');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $variables['search_form'] = drupal_build_form('views_exposed_form', $form_state);
}

Then in your .tpl.php file you would use this code to display the form:

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

Note that this way the visibility settings in admin won't be applied.


Uploading images into separate directories for every new content My page, created using Drupal 7, will contain multiple galleries. I created new "Content Type" - "gallery" with an unlimited numer of "Image" fields. For each content of this type I want all of its images to be placed under different directory, eg. sites/default/files/gallery_01, sites/default/files/gallery_02, etc.

There is a "File directory" setting but I don't know how to make it content-dependent (when I create new content I want all uploaded images to be placed in a different directory).

Is there any way I can accomplish this ?

Why you would want to do that, I don't know. However, you can use Filefield Paths module with tokens. If you use the timestamp token you can have each directory created named based on timestamp. That will make them unique.


Content Type with tabs I am new Drupal user working on a Drupal 7 site. We have a content type that allows us to add related content in tabs that are aligned down the left side of the page. How do I duplicate (clone?) this content type and make slight modifications?

Look at the Bundle Copy module. It'll let you clone a content type.


Make support ticket subscriptions visible by default I have a Drupal 7 site using the Support Ticketing System module. When viewing a ticket, the client would like the Subscribed fieldset (id="edit-subscribed") visible by default. Currently it is collapsed, and you have to click on it to expand the field.

This problem is similar to a previous post, where hook_form_BASE_FORM_ID_alter() allowed me to expand the Subscribed field by default when the ticket was being edited.

But when viewing the ticket, the form in question is the comment-form, and I can't find the right array to target the edit-subscribed fieldset, if in fact the hook_form_alter is the right way to do this.

It proved far easier to just add a line of JQuery to the page. jQuery('#edit-subscribed').removeClass('collapsed'); added to the footer took care of it.


Executing view twice with different filters returns same results Here's my simple scenario :

Execute view with exposed filter (min & max dates)
If there are no results, execute again with min date = 0 to get all results

Unfortunately, the query static cache will execute the same query twice.

$view           = views_get_view('my_view');
$view->set_display('default');

$date       = $view->get_item('default', 'filter', 'created');
$date['value']['min']   = date('Y-m-d', $date_from);
$date['value']['max']   = date('Y-m-d', $date_to);
$view->set_item('default', 'filter', 'created', $date);

$view->pre_execute();
$view->execute();
$results = $view->result;

$view->destroy();

// do logic here to determine if view needs to be queried a second time

$view           = views_get_view('my_view');
$view->set_display('default');

$date       = $view->get_item('default', 'filter', 'created');
$date['value']['min']   = date('Y-m-d', 0);
$date['value']['max']   = date('Y-m-d', $date_to);
$view->set_item('default', 'filter', 'created', $date);

$view->pre_execute();
$view->execute();
$results2 = $view->result;

$view->destroy();

// $results and $results2 are identical

If I comment the first part of the code, the second query will work correctly and $results2 contains a lot more results.

I've tried answers from this question [1], but no luck.

The only solution I found is to clear the entire static cache with drupal_static_reset();

How to elegantly solve this problem? I believe clearing only the static cache for the queries will solve this, but I fail to find the good $name argument.

[1] Clear views cache after node inserted in Drupal 7

The second argument to views_get_view is $reset:

  If TRUE, reset this entry in the load cache.

So second time around you just need to pass that:

$view = views_get_view('my_view');
$view->set_display('default');

...

$view = views_get_view('my_view', TRUE);

That will reset the static cache and the data will be fresh.


Multisite with some shared content and some different content I need to create 7 magazine sites with different themes but some content should be shared (like some common pages, some pictures etc).

There should be a common control panel for all websitea so that my customer can upload data on all websites from the same panel. The same content is required because the customer will upload articles on one and it should publish on all site.

I have already setup two demo site with different database on one hosting place and single Drupal installation.

You don't really want a multi-site at all by the sounds of it. You're looking for Domain Access

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

In fact, the ORIGINAL use case for Domain Access was for magazine sites (from the documentation), so it should fit your needs perfectly!


How do I add local tasks menu to a views page display I have created a views page display that has the path /node/%node/sessions, contextually filtering by content ID. It also creates a "menu tab" called "Sessions".

Therefore when I got to node/12 I see a local tasks menu: "View / Edit / Sessions" etc.

When I go to /node/12/sessions I see my view, filtered correctly by 12, but WITHOUT any local tasks tabs.

How should I make a local tasks menu appear on the view page node/12/sessions, (with the local tasks the same as the node/12 but with the sessions tab as active)?

Using this entry in my_module.links.task.yml succeeds in adding an entry to the node local tasks (still present if 'no menu' is selected in view UI). But it doesn't add the node local tasks to the views page.

view.event_sessions.page_1:
  title: Sessions
  route_name: view.event_sessions.page_1
  base_route: entity.node.canonical

Using views.view.event_sessions.page1 as the route throws a route not found error (although that is usually the correct route for a views page, so that's weird).

@Eyal was right. Some information:

Find the current route : /devel/routes gives you all the registered routes.
Or better : use the devel module & web profiler submodule to display the Symfony2 toolbar, you will have a lot of useful information, especially the current route.

  You should find a route name as view.my_page.page_1 for example.

Create a modulename.links.action.yml (or modulename.links.local.yml) with this content:

view.my_page.page_1:
  route_name: view.my_page.page_1
  title: My button title
  appears_on:
    - view.my_page.page_1


When do I need a contextual filter vs. a relationship? Can someone explain the functional difference between contextual filters and relationships?

I understand that a relationship is a table join, and a contextual filter is passing parameters to the view. Both adjust view data. How would you describe when each should be used?

I have been building complex views for a few months now, but sometimes I still don't have an intuition for what I need - I generally have to find a tutorial on exactly what I am trying to do, and I think it stems from not really understanding these two capabilities.

Edit:

Thanks for all the answers helping to describe the SQL building. On that topic, I found this advice very helpful.

Just think of it terms of SQL:

a 'relationship' is a JOIN on another table
a 'filter' (contextual or not) is a WHERE clause.

'Contextual' just means the parameter comes from the current context, e.g. part of the URL, something in the session, etc


Custom block template PHP page, possible to make content editable in UI? I have custom PHP files for a few blocks, e.g., /sites/all/themes/at-commerce/templates/block--block-10.tpl.php

Is it possible to make this content editable using the block editing UI mechanism in Drupal administration, so the customer can make changes him/herself?

For example, customer visits URL admin/structure/block/manage/block/10/configure and can edit the content.

What you're describing is already in Drupal 7 core. It's called the Contextual Links module. When enabled, modules can define menu paths that enable a set of links that is contextually relevant to the content.

In your case, a user with Use contextual links & Administer block permissions will see a gear icon that produces a dropdown link from where they can configure & edit content of any custom block.


Fetch values from Field Collection or Multifield on Node to Entityform I am working on a booking system where I have a content type of "Company" with an unlimited Field Collection of "Services". The "Services" field collection has 2 fields: "Service Name" and "Price".

I want users to be able to book any of the Services using an Entityform I have created, so that the Node Title, Service Name and Price fields be loaded automatically on the Entityform during submission.

I have tried using tokens and the Prepolutate module by passing the field values in the URL but I can't seem to pass the values from the Services field collection because field collections are entities on their own, and also this is not very secure as the price can easily be manipulated/changed in the URL.

How should I go about this? Or is there a module that load an Entityform from the URL for example http://www.example.com/company/nid/book, with values of fields and fields collection from the node. Every suggestion will be appreciated.

The best way to do this is hook_form_FORM_ID_alter().

Modules can implement hook_form_FORM_ID_alter() to modify elements and values in the form before it is rendered. You'll have to look quite deep into the form array but it should be possible to set the #default_value for the required elements.


How to get path of an element of a kint printed array? In D7, when you used DPM to print out an array / object, you could double click each line to get the "path" of the element (like: ['#target']['tid']). In D8 am totally missing this feature.
I also saw on a site where I can see this feature. But my "stable" devel module just doesn't seems to have this feature. Am I missing a config issue?

you need to install and enable Search kint module


Messed Up Drupal Site, truncated all cache, menu_router, registry_file and now I can't access site After disabling comment module, I could not access some modules, so I researched how to get that fixed and end up following this. I cleared all the cache_table, menu_router and registry_file.

This is the exact command I ran:

TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_entity_og_membership`;
TRUNCATE `cache_entity_og_membership_type`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_metatag`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_token`;
TRUNCATE `cache_update`;
TRUNCATE `cache_variable`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;
TRUNCATE `menu_router`;
TRUNCATE `registry_file`;

Now I have an empty site, I can't browse or go to anywhere. Even the front page Gives page not found error saying "/" not found.

I tried to rebuild the menu and registry with these commands but it didn't work.

chdir('path/to/site/root');
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

registry_rebuild();
menu_rebuild();

I tried with drush using drush cc all but it says

  No Drupal site found, only 'drush' cache was cleared.
  but drush status shows it find the site

 Drupal version         :  7.23
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /path/to/site/root

What can I do? How to get the site back after this?

Best thing is to restore it from a backup to make it work.

If you want to fix it, replicate the site from a back up (db and files).
Then truncate tables one by one to see which one is causing the problem (It should be menu_router).

Truncate first all cache table and check
Truncate menu_router and check
Truncate registry_file and check.

About the code you did, try to remove registry_rebuild from your code.
Create a file fix.php and paste this code

<?php
error_reporting(E_ALL);
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

menu_rebuild();

save it into your drupal root and visit mysite.com/fix.php .


What should be used instead of raw filter? Drupal 9 theming documentation indicates that the Twig raw filter is deprecated in favor of verbatim.
The ds-field-expert.html.twig template uses raw to render the input in the prefix and suffix field, which is often HTML.
{{- settings['prefix']|raw -}}

verbatim in the Twig 2 documentation is not a filter, but instead wraps around content in the template, so wrapping the line of code does not actually go and get the prefix/suffix content. It just renders the twig.
What should I use instead of raw in this case so the markup I enter into the prefix and suffix field of a Display Suite expert field template renders as HTML and not plain text?
Will this template break in Drupal 9?

The raw filter is still fine to use. The filter is not deprecated, only the raw tag.
From the Drupal 9 theming documentation:

As of Twig 1.x, the raw tag is deprecated in favor of verbatim.

Looking at the Twig 2.x documentation, you'll notice that the raw filter is not deprecated.
However, in the Twig 1.x documentation for the verbatim tag you can see that it replaced the raw tag in Twig 1.12. This is the cause of the deprecation in the Drupal 9 theming guide.
Note that there's a notice at the bottom of that page that says the tag was changed to help prevent confusion between the raw tag and raw filter.

The verbatim tag works in the exact same way as the old raw tag, but was renamed to avoid confusion with the raw filter.


Contextual filter "Allow multiple values" is gone Why can't I see the "More - Allow multiple values" option on my contextual filter product view?

This is my view:

This is what should appear:

Found the reason: My site was in maintenance mode and the green message was preventing the block to appear... So it's a matter of css. Super stupid, but it took me a while to figure that out. Might be useful to someone having the same issue.


DrupalGap index.html No connection found on ios simulator The app is working on web-app, but when I test iPhone" simulator, then have problems with connection:

index.html - No connection found

Failed connection
http://app.newwweb.info
Check your device's network settings and try again.

I reviewed the changes in settings.js and index.html and are correct.

What can I do?

I met the same problem, but solved it by including the plugin of network-information. Then both ios and android work fine.

cordova plugin add cordova-plugin-network-information


How to override some admin theme CSS rules? Is there a way to override just some CSS rules used by the admin theme, without touching the admin theme itself (via some theme functions or module hooks)? For example, I'd like to add a text-align: right to every integer field in admin forms (and in edit nodes too).

I did it just using:

function mymodule_preprocess_html(&$variables) {

  global $theme;

  if ($theme === variable_get('admin_theme', 'seven')) {

    // Reference your custom stylesheet.
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mymodule.css', array('weight' => CSS_THEME));
  }
}

That's a bit more readable for me.


Images not showing correctly I'm adding a logo image to my page.tpl.php template this way:

<img src="<?php print drupal_get_path("theme", "my_custom_theme"); ?>/img/logo-mobile.png">

The image is being displayed fine in the homepage, but if I go to the /user page, for instance, the image won't show up.

Any ideas why is that happening?

Thanks!

Without a leading '/' (or '/foo/' if the site is in a subfolder) the browser will always to try to find the image relative to the current path, not to the root of the site. That's why your current code works on the home page, but not on other pages.

To fix it you just need to add the base path as well:

  <img src="<?php print $base_path . drupal_get_path("theme", "my_custom_theme"); ?>/img/logo-mobile.png">


How to get the taxonomy translated in URLs? I have a bilingual site with localized taxonomy terms used as categories.

I would like to achieve this:

http://www.mysite.com/about/pageinenglish

http://www.mysite.com/apropos/pageinfrench

(A propos means about in French)

But I only have:

http://www.mysite.com/about/pageinfrench

How can I translate the taxonomy in urls?

EDIT

I have pathauto configured with i18n terms (which are only available in TAXONOMY TERM PATHS)

I've been able to do that, using Entity Translation instead of Taxonomy translation (part of i18n) for translating taxonomy terms, and using the Title module to replace the name field of the taxonomy term and making it translatable.

It works so far.


Modules to set credits/points I'm looking for a module to allow myself or other moderators to set credits/points for each site member. The site members can use the credits to purchase items in the store.  I don't want to use any real world currency for the transactions, just virtual points.

This site is for an online guild. My hope is to set up a reward system and give each member points for being active in the guild, they can turn around and use the points to get content for their characters in game.

Is there any module that would help me achieve this?

I did a google search and found the Commerce Credits module; it sounds like what you're looking to do.

  Commerce Credits allows you to have users buy or win credits. The credits these users buy or win are fully configurable and can expire after some time. The process used for these credits is also fully configurable through Rules. It allows you to entirely define your own process for the payment and the use of these credits.


Access image/file with REST and Basic Authentication I'm trying to access images/files in Drupal 8 through REST. They are only accessible for authorized users. I'm able to get the URL to the files, but when I try to load them using Basic Authentication, I get a 403 error.

Using cookies, I'm able to access the files after login, but I'd prefer to use Basic Authentication.

Is there any way to accomplish this?

Thanks.

In my view, Basic Authentication will work only for giving username and password whereas cookie will use the authenticated user cookie set in browser and display results.

If you want to use basic authentication and get file information just see below code:

$username = 'SITE USERNAME';
$password = 'SITE PASSWORD';
$url = 'SITE URL';
$response = \Drupal::httpClient()->get($url . "/entity/file/FILE ID?_format=json", [
  'auth' => [$username, $password],
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);
$json_string = (string) $response->getBody();


How to Make Managed File Field Available to Twig Template? I am wanting to make it so that users can upload images to a block configuration form for a pre-existing (views-generated) block (views_exposed_form) and have the images available in the block's template file. Here's my block class:

<?php

namespace Drupal\exposed_filter_images\Plugin\Block;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsExposedFilterBlock;

/**
 * Provides a 'Views Exposed Filter' block.
 *
 * @Block(
 *   id = "exposed_filter_images_block",
 *   admin_label = @Translation("Exposed Filter Images Block"),
 *   deriver = "Drupal\exposed_filter_images\Plugin\Derivative\ExposedFilterImagesBlock"
 * )
 */
class ExposedFilterImagesBlock extends ViewsExposedFilterBlock {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['image_1'] = [
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/steps/',
      '#title' => t('Image 1'),
      '#description' => t("Image on the left"),
      '#default_value' => $this->configuration['image_1'],
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg'],
        'file_validate_size' => [25600000],
      ],
      '#states' => [
        'visible' => [
          ':input[name="image_type"]' => ['value' => t('Upload New Image(s)')],
        ]
      ]
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['image_1'] = $form_state->getValue('image_1');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $output = parent::build();

    $output['#theme'] = 'views_exposed_form';
    $output['#files'][0] = $this->configuration['image_1'];

    return $output;
  }
}

Here's my exposed_filter_images.module file:

<?php

/**
 * Implements hook_theme().
 */
function exposed_filter_images_theme($existing, $type, $theme, $path) {
  return [
      'views_exposed_form' => [
          'variables' => ['files' => []],
      ],
  ];
}

/**
 * Implements hook_block_alter().
 */
function exposed_filter_images_block_alter(&$plugins) {
  if (isset($plugins['views_exposed_filter_block:elder_index-page_1'])) {
    $plugins['views_exposed_filter_block:elder_index-page_1']['class'] = \Drupal\exposed_filter_images\Plugin\Block\ExposedFilterImagesBlock::class;
  }
}

And then in the views-exposed-form.html.twig file, I can have a number returned with this simple debug: {{ files.0|json_encode }} (without the |json_encode filter, nothing shows up), but I'm not really understanding what this number is is or what I can do with it.

So I'm looking for what I would need to do in the class or in the twig file in order to have an image or at least the URL to the image appear on the front-end.

Thanks in advance!

Since my rep isn't high enough to comment... yet, I have to add my comment as an answer.

My initial thought is that the file would be saved as an entity.  After reading up a bit on some d.o comments, there is/was a bug where managed_files are temporary by default.  Somewhere in the mix you'll need to add something similar to

   $image = $form_state->getValue('image');
   $file = \Drupal\file\Entity\File::load( $image[0] );
   $file->setPermanent();
   $file->save();

to make the file permanent.
(credit to This question)

Most likely you will need to save the file itself as an entity in the blockSubmit function.

    $file = \Drupal\file\Entity\File::load($image_id[0]);
    // Change status to permanent.
    if(gettype($file) == 'object'){
      $file->setPermanent();
      // Save.
      $file->save();
      $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
      $file->setOwner($user);
    } ... and so on.

After that, you should be able to pass the filename or file entity to your theme layer and load it in your preferred method.

Examples modified from This d.o post


Javascript not working in body field. Using Full HTML I have created a basic page. Inserted the following tripAdvisor your rating widget code in that which contains some javascript. Used Full HTML formatting. But instead of displaying the rating widget it's just displaying the TripAdvisor logo. How can we insert javascript in body?

Edit:
I have tested the same code on another Drupal 8 Website and it's working without any issue in that.

The site on which the code is not working was upgraded to Drupal 8 from Drupal 7 and it's also configured on cloudflare. I tried to put cloudflare on development mode and also disabled the AdvAgg module but thats still not working.

Is there any settings in Drupal 8 which can disable javascripts scripts in Body field?

Most likely , your FULL HTML content authoring text format settings are limiting the markup you can use, stripping out the script (that's default behavior).

You can either:
1. Modify the settings for the text format to not restrict markup
2. Create a new text format, without any of the filter options enabled; then switch the format on the body field in which you want to insert the script.

If these options still fail, you may have a theme where a preprocess hook or twig filter is stripping out the script.


How to get checkboxes values in a form? This is my code :

$form['how_many'] = [
  '#type' => 'checkboxes',
  '#required' => true,
  '#options' => [
     '1' => t('one'),
     '2' => t('two'),
     '3' => t('three')
  ],
  '#title' => t('How many')
];

I want to get the checkbox values.

When I do $form_state->getValue('how_many');, I get an array with filed value as well as non-filled as 0.

If i do $form_state->getValue('how_many[1]');, I get nothing and if I do $form_state->getCheckedCheckboxes('how many'), the page shows nothing.

May be you can try this:

$result = $form_state->getValue('how_many');
$value = array_filter($result);

//print to check the value

print_r($value);


Why does my content type need to be reviewed before it can be saved? I created a new content type and when I want to create new content of this content type, on the bottom I only get the Preview button, the Save button does not show up and I can not find in the content type settigns how I disable this "must preview before save"-feature...

In Drupal 7, you can manage this via admin/structure/types/manage/CONTENT_TYPE in the Submission form settings:

In Drupal 6, you manage this via admin/content/node-settings:


Payment Method displays after Page Refresh I am using uc_hotel booking module with Ubercart. When I add a hotel to cart and checkout it shows No Payment Required in Payment Method.

After Refreshing the Page it shows the credit card in payment method.

Why not it displaying the credit card option at first time when I click on Checkout.

Solved by unchecking Free order from Payment Method.


ON/OFF toggle as a custom view field I have a table view output of node data. The node type has a list field called status.
Status is set to accept a single value. It has the following option to select from:

Inactive
Active
Submitted
Approved

They work in pairs. When a node is created it's Inactive by default. Someone reviews it and sets it to Active. Upon further work it is set to Submitted and eventually someone else will set it to Approved.

What I am tasked with is creating a toggle button against each row of the table output
containing [Inactive|Active] or [Submitted|Approved] which a user can simply click on and change it's status rather than go to the actual nodes' edit page.

I'm interested in ideas on how I can accomplish this or perhaps if there is a module that fully or partially does this.

For Drupal 8 You have to use Toogle Editable Fields https://www.drupal.org/project/toggle_editable_fields


Override favicon output Some of search engines (yandex in my case) want me to output favicon with type image/x-icon.

But drupal 7 outputs it without this type.
How could i override this through template.php or any other suggestion?
Thanks!

To alter or remove the favicon URL Drupal 7 points to by default (not just add another favicon link) try this:

function YOURTHEME_html_head_alter(&$head_elements)
{
  // Search the head elements for the Favicon
  foreach ($head_elements as $key => $element) {
    if (!empty($element['#attributes'])) {
      if (array_key_exists('href', $element['#attributes'])) {
        if (strpos($element['#attributes']['href'], 'misc/favicon.ico') > 0)
        {
          // Change the URL
          $head_elements[$key]['#attributes']['href'] = '/'.drupal_get_path('theme', 'YOURTHEME').'/path/to/favicon.ico';

          // Or, delete the favicon link entirely
          unset($head_elements[$key]);
        }
      }
    }
  }
}


Loading module-related files only on certain pages I installed the Chosen module and it is conflicting with my JavaScript code. That module gets loaded on every page, even if there is no select box on the page. It is definitely unnecessary to load the files from that module when they are not necessary at all.

What I want to do is modifying the module to only load on certain pages.

How should I go about doing this? What function do I have to call or look for within that module?

You should use hook_js_alter() within template.php

function yourthemename_js_alter(&$javascript) {
  if ('this is true') {
    unset($javascript['sites/all/modules/chosen/chosen.js']);
  }
}

I'm wondering if either solution will result in caching issues though.  If I may: I would first try to figure out why my JavaScript collides with the module and fix it there.

You can also use the hook within a custom module if you already have one that relates to what you're trying to accomplish here.


When in admin overlay, submitting form over 400 times I have built a very simple module which just implements a block with a custom form. When submitted, the content is emailed to me. I show this block on the dashboard, and without the admin overlay it works totally fine.

But when I access the dashboard in the overlay and submit the form, I get no feedback at all (I user drupal_set_message() when the email is sent, but that doesn't show up) and half a minute later I find 437 copies of the same email in my inbox.

Unfortunately I have no idea at all where I could start debugging THIS. Maybe the overlay is just a coincidence. But what else could cause this massive submission of email and/or the form?

Any ideas are appreciated.

Thanks,

Victor

UPDATE: The (simplified) code below, this very basic form still has the same problem. How is this possible?

<?php

function mvp_form_test_block_info() {
  $blocks = array(
    'mvp_form_test_test_block' => array(
      'info' => 'Test Form',
      'cache' => DRUPAL_CACHE_GLOBAL,
      'properties' => array(
        'administrative' => true,
      ),
    ),
  );
  return $blocks;
}

function mvp_form_test_block_view($delta='') {
  if ($delta != 'mvp_form_test_test_block')
    return array();

  return array(
    'title' => 'Test Block',
    'content' => drupal_get_form('mvp_form_test_test_form'),
  );
}

function mvp_form_test_test_form($form, &$form_state) {
  $form = array();
  $form['sometext'] = array(
    '#type' => 'textfield',
  );
  $form['button'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

function mvp_form_test_test_form_submit($form, $form_state) {
  watchdog('mvp_form_test', 'Form submitted with text '.$form_state['values']['sometext']);
  drupal_set_message('Form submitted with text '.$form_state['values']['sometext']);
}

?>

Not sure what is exactly causing this, but maybe you can use a static variable as a workaround for this issue.

function mvp_form_test_test_form_submit($form, $form_state) {
  $sent =& drupal_static(__FUNCTION__);
  if(!$sent) {
    watchdog('mvp_form_test', 'Form submitted with text '.$form_state['values']['sometext']);
    drupal_set_message('Form submitted with text '.$form_state['values']['sometext']);
    $sent = true;
  }
}


How do I initially show 3 blank fields on a form when cardinality is unlimited? I have created a field programmatically that has 'cardinality' => FIELD_CARDINALITY_UNLIMITED. This is the functionality that I want. I want users to be able to add as many items as they need to. However, when the form first shows, I'd like to have 3 blank fields ready to be filled out before having to click the "Add another item" button. Is this possible?

Lots of answers on the web about how to set the cardinality, but that's not what I'm looking to do. I just want to show 3 blank ones to get started while still keeping my cardinality as unlimited. I hope this question makes sense.

You can alter your form to add your proposed blank fields , to do that you need to implement hook_form_alter in your module and inside you would have :

if (empty($form_state['field_counter'])) {
  $form_state['field_counter'] = 3;
}
else if($form_state['field_counter'] < 3)
{
  $form_state['field_counter'] = 3;
}
for ($i = 0; $i < $form_state['field_counter']; $i++) {
  $form['YOUR FIELD NAME'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Your Lable'),
  );
}


How to detect modules enabled incorrectly? If some errors occurs in the process of enabling modules (WSOD due to OOM and others), it happens that the modules are shown as enabled. But in such cases the features of those modules are broken since the enabling/installing of the modules were not completely run.

How do I detect such modules state without re-enabling every single module?

Update: Obviously logs can be disabled/cleared/lost, don't mention them please.

The problem is that it depends on each module. When enabled, a module sets up its environment (create tables, variables, declare URL, etc) but this environment is not declared explicitly so you can't automatically check that the module has been installed correctly.

You may check the install file for the modules's scheme (tables defined by the module) and the hook_enable to see what tasks needs the module when is enabled.

I think best way is to uninstall modules and try to install them again, so all modules's environent are cleared when unisntalling and set up again when enabled again.

Using drush this tasks is very easy and handy.

Ah, and try to clear caches to see if modules works, but you won't be sure modules installed correctly...


Pass an array of nids to a view How do I pass a view an array of node ids?  I can create the view using the ui, but the query I want to run is outside the scope of views.  I want to run the db query independently, gather the node ids into an array, and then pass it to the view for display.  Howvian I make this happen, if at all?

You can add a "Content: Nid" contextual filter to your view, so your view will narrow down the content to the NIDs you provided. Make sure you check the "Allow multiple values" box when configuring the contextual filter. This will allow a url like example.com/myview/12+45+78 which would limit the results to node IDs 12, 45 and 78.


Creating iframe to be used in other websites I've created a controller with the route "/get-info", the controller return a template custom-info.html.twig

my_module/src/Controller/MyController.php file:

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {

  public function content() {

    return [
      '#theme' => "custom_info",
    ];
  }
}

my_module/templates/custom-info.html.twig file:

<h1> Hello World </h1>

When visiting the path: www.mySite.com/get-info I get response with the header an footer of my site and "Hello World" as content. but when using <iframe src="www.mySite.com/get-info"></iframe> in an other Drupal project I get an empty iframe.

Is this the right way to create iFrame-ready Widgets in Drupal 8? if so what should I add/remove to make it work?

The problem was solved by installing and enabling Allow site iframing contrib module.

  Drupal 8 has a feature built into core that stops the site from being
  rendered within an iframe, there are good reasons for this -
  https://www.drupal.org/node/2514136 But sometimes you want your site
  in an iframe, so that's what this module does.


Where can i try searching the module "File_styles"? I have installed the media module for drupal 7 but it requests me the installation of a module I cannot find File_Styles.
Where can I searching this module?

File Styles is a module that is part of the Styles project.


User_save is very slow for no apparent reason As you could see on picture, saving data for users is very slow. Queries run fast, but for some reason it takes up to 2 minutes to save user data. The same happens with logging in.

What is more strange, I have DB versions of this site and have a previous version where this works normally and all of a sudden this started to happen.

I checked errors in log
Disabled modules
Cache reseting
Exported DB tables from working DB (user, user_roles, variables) to non working
Checked for missing modules
Tried older version of drupal (7.33).
Disabled some custom code modules

Tried everything I could come up, but still user_save is slow like on image and no errors or warnings appear. Really don't have a clue anymore what could be wrong, something in DB level must been wrong, not sure what to try anymore and where to look?

I found the answer, well the reason. I had a in a module
hook_user_update()

that has a CURL that connects to remote site and beacuse of it took much time to save, well to connect and then to save.  Need a way to make this CURL connection not affect the user save.


Getting error {"message":"No route found for \u0022GET \/standortimporter\/region_node_rest_resource\u0022"} custom rest POST I am creating custom rest resource using this code:

<?php

    /**
     * Provides a resource to get view modes by entity and bundle.
     *
     * @RestResource(
     *   id = "region_node_rest_resource",
     *   label = @Translation("Region node rest resource"),
     *
     *   uri_paths = {
     *     "canonical" = "/standortimporter/region_node_rest_resource"
     *   }
     * )
     */

 namespace Drupal\standortimporter\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\Entity\Node;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

    class regionNodeRestResource extends ResourceBase {

      public function post() {

              $node = "hello here";

      return new ResourceResponse($node);
      }

    }

And getting this error:

  {"message":"No route found for \u0022GET
  /standortimporter/region_node_rest_resource\u0022"}

To create a custom rest resource:

Enable rest module: drush en rest -y
Create the plugin like the following YOURMODULENAME/src/Plugin/rest/resource/RegionNodeRestResource.php:

namespace Drupal\YOURMODULENAME\Plugin\rest\resource;

use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "region_node_rest_resource",
 *   label = @Translation("Region node rest resource"),
 *   uri_paths = {
 *     "create" = "/standortimporter/region-node-rest-resource"
 *   }
 * )
 */
class RegionNodeRestResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->currentUser = $container->get('current_user');
    return $instance;
  }

    /**
     * Responds to POST requests.
     *
     * @param string $payload
     *
     * @return \Drupal\rest\ModifiedResourceResponse
     *   The HTTP response object.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post($payload) {

        // You must to implement the logic of your REST Resource here.
        // Use current user after pass authentication to validate access.
        if (!$this->currentUser->hasPermission('access content')) {
            throw new AccessDeniedHttpException();
        }

      $payload = ["hello here"];
        return new ModifiedResourceResponse($payload, 200);
    }

}

You should enable your resource using restui:
go to admin/config/services/rest you can see your endpoint and enable it.

And configure it like the following:

 4. To test you should use rest client app like Postman like:

For more informations read Custom REST Resources page.


Problem Sending data send to a block after form submit in a page its return some value,I want to prnt this value in a block .how can I do this?
and I want the form and the block are in the same page.

Use hook_block_info and hook_block_view. Something like this:

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_block':

      $blockContent = '
Nothing to show
';

      // assuming we're getting it from POST but the source can be whatever you want
      if (isset($_POST['key']) && null != $_POST['key']) {
          $blockContent = '
' . $_POST['key'] . '
';
      }

      $block['subject'] = t('My Block Title');
      $block['content'] = array(
          '#markup' => $blockContent
      );
      break;
  }

  return $block;
}


How to grant permission to specifc role to perform CRUD operations on a particular content type only? I've set up different roles and in my site and I want a specifc role to grant permission to perform CRUD(create, Read, Update, Delete) operations on a particular content type only. But I can't find any such option in drupal admin.

Any suggestions?

Use Rule module. And create action assign role.

How to use.


Want to Install picasa gallery and best is PWI I want to use http://code.google.com/p/pwi/   in drupal. it is a jquery library and with my knowledege as far as adding libraries need to code a little. need to use (hook library or add library) don't know which suits, I am not a PHP guy. but Drupal has been fun and want this badly. If little help or pointing will climb up. Tried other picasa modules like picasa node ,Brilliant gallery but none has features like this.

Thanks

I copied the folder(js,css,images to the root ) and created a node using the demo code given. It works. Now need to find how to format it, this got me the answer but don't know whether this  is right way or not.As I am new to drupal.


How does resizing of images work with lighttpd? I switched the Webserver from Apache to Lighttpd. Since then, resizing images according to the defined sytles (/admin/config/media/image-styles) does not work anymore.

Anybody knows what may be missing?

Edit: Added excerpt from phpinfo():

gd

GD Support: enabled
GD Version: 2.0
FreeType Support: enabled
FreeType Linkage: with freetype
FreeType Version: 2.4.8
T1Lib Support: enabled
GIF Read Support: enabled
GIF Create Support: enabled
JPEG Support: enabled
libJPEG Version: unknown
PNG Support:    enabled
libPNG Version: 1.2.46
WBMP Support: enabled

imagick

imagick module: enabled
imagick module version: 3.1.0RC1
imagick classes: Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version: ImageMagick 6.6.9-7 2012-08-17 Q16 http://www.imagemagick.org
ImageMagick copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
ImageMagick release date: 2012-08-17
ImageMagick number of supported formats: 206
ImageMagick supported formats: [.....Many!!]

Change your lighttpd rewrite rule to this :

url.rewrite-final = (
"^/system/test/(.*)$" => "/index.php?q=system/test/$1",
"^/([^.?]*)\?(.*)$" => "/index.php?q=$1&$2",
"^/([^.?]*)$" => "/index.php?q=$1",
"^/rss.xml" => "/index.php?q=rss.xml",
"^/(.+/files/styles/.+\.+.+)\?(.*)$" => "/index.php?q=$1&$2"
)

That must work. if not disable the clean ulrs to see if the problem is solved or not .


Using Gulp JS in multiple theme development I use Gulp JS in my themes but the issue I'm having is we work on many themes in our drupal site (sometimes up to 40!).

I want to avoid repeating the same "node_modules", "gulpfile.js" and "package.json" files in every single theme. If we want to change 1 of those files, we would have to update each file in every theme across all sites which is going to get too messy.

I would like to have the Gulp files live in sites/all/libraries and have gulp watch my theme that I'm working on.

To anyone experienced with Gulp, any idea's on how this can work?

Edit:

I have moved the 2 gulp files & node_modules folder into /sites/all/libraries/gulp
I have edited gulp.js to point to the theme I'm working on, code is below (I have tried a few different combinations including an absolute path):

gulp.task('less', function() {
  gulp.src('../themes/theme_name/css/style.less')

When I type gulp in the command line in my theme directory I get this error:

Local gulp not found in /var/www/site_name/sites/all/themes/theme_name

If I go into sites/all/libraries/gulp, type gulp in the command line, the gulp process starts, but if I edit a Less file and save it, gulp doesn't compile the css.

Thank You

I have finally found the best solution for this so I'm posting it incase anyone has a similar issue:

Add gulp (package.json, gulpfile.js & node_modules) to a centralized location (eg: sites/all/libraries/gulp)
In the root of each theme, create 3 symbolic links that point to gulpfile.js, package.json and node_modules


Different colors and fonts dependent on roles in views results Views listings are made from many users, but some of them have special role that is more important.
Is there an easy way to give that special role different background color or font or font size when viewing views results ?

In your theme template.php file add this function

function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role {
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

This will add the current role(s) to the body classes.

Now you can style it like this

body.role-admin .view-VIEW-CLASS {
  background: #eeeeee;
  font-size: 16px;
}


How to disable creating links for content types? I don't want my slideshow text and image to be accessible in url (it is a contentype called slider).

Because normaly nobody will access that, but if he knows the url he can access that and also google bot etc.

I am using this content type only in Views Block.

I don't need pages.

How to do that?

Any module or template?

I always use the Rabbit Hole module in this situation.

  Perhaps you have a content type that never should be displayed on its
  own page, like an image content type that's displayed in a carousel.
  Rabbit Hole can prevent this node from being accessible on its own
  page, through node/xxx.

You can set redirects from the pages too, so you can add a 301 or a 404 (for example)


How to show Search API search box? No block available, nothing from I'm updating a site to use Search API (with Search API DB) instead of the built-in search module. I've set up my Search API server and search, indexed everything, and now am just trying to replace the old search box with the new one in the theme.

But I can't find any way to do this.

Before disabling the built in search module, there was only one search block. After disabling, there are none, including after clearing caches. According to Integrate core search block with search_api and Solr and various other sources, I should get a search block automatically, but I don't.

Before, I got the search box into my template .tpl file with <?php print render($search_box); ?>. After, this throws an error.

I can't find anything on what to use instead, and the relevant documentation page about search forms talks only about search results pages, not about how to put a search box on other pages. I'm confused at how hard it is to find how to do something so basic. I can't find anything about how to find the code to either populate this variable in template.php or access any inbuilt template variable.

How do I show a basic search block on the front page that integrates with search api? is similar but the asker reports its answer doesn't work, and I'm not fussy about whether it's specifically a block or specifically on the front page or connected to a view, I just want the search input element.

How do I add a Search API search box to a theme? How do I make it generate the block or load the search box from code?

Maybe not the best option, but to get a usable Search Block from the Views module (that includes the Search API Views submodule), you need to activate the "Expose Form >> Exposed form in block" option in your Views advanced configuration. This is what it looks like:

Good luck!


Is the path_alias table queried for all URLs? I'm trying to generate SEO-friendly URLs for a set of exposed filters. For e.g.:

/analyst-relations/firm?related_firm=5072 would look like

/analyst-relations/firm/forrester

one way I imagined doing it was by adding/updating/deleting this path programmatically to the path_alias table upon creation/modification/deletion of the relevant term or entity. However I seem to have misunderstood how path_alias works. I was able to successfully add the path /analyst-relations/firm?related_firm=5072 and the alias /analyst-relations/firm/forrester, but the exposed filter links still load like the former. Is the path_alias table not queried for all URLs? If not, is it possible to somehow 'attach' this path and alias to an entity?

EDIT:
I'm using Better Exposed Filters to exposed the filters as  links, so afaik there is no form submission

While @Clive's comment is in most cases correct, from a SEO perspective it can make sense to expose certain filters as links and make them searchable through Google. Path aliases are implemented in AliasPathProcessor. Since the core alias lookup system can't handle query parameters and you can alias without a lookup table by querying the entity data directly, you could add your own path processor. Inbound you have to change the path to the internal path and add the query parameter to the request, outbound vice versa (but use $options to remove the query parameters because this is for all outgoing links, don't use the request).


Commerce limit the quantity of product to 1 I want to restrict quantity for certain products. Want to add a product only once in cart. How to achieve this?

There are 3 products in my store and I want the users to add only 1 product in the cart at a time.

Which hook do I need to use?

What you will want to do is add an event subscriber to the Add to Cart event (https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/cart/src/Event/CartEvents.php#L30).

Here is an example piece of code that would react to that event. This is for a Drupal Commerce site which only allowed purchasing one product at a time with a quantity of one.

/**
 * Sets quantity to 1 and ensures only one product in the cart.
 *
 * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
 *   The cart event.
 */
public function onProductAdded(CartEntityAddEvent $event) {
  // We only want 1 quantity.
  $cart = $event->getCart();
  $added_order_item = $event->getOrderItem();
  $cart_items = $cart->getItems();
  foreach ($cart_items as $cart_item) {
    if ($cart_item->id() != $added_order_item->id()) {
      $cart->removeItem($cart_item);
      $cart_item->delete();
    }
  }

  $quantity = $cart_items[0]->getQuantity();
  if ($quantity > 1) {
    $cart_items[0]->setQuantity(1);
  }

  $cart->save();
}


How to use $token_service->replace? I am using following code to replace current-user:email token.

 $pattern = '[current-user:mail]';
 $output = $token_service->replace($pattern, array('current-user' => $account), array(
            'clear' => TRUE,
            'callback' => xyz_function($pattern_array),
          ));

In the callback function i am doing

foreach ($replacements as $token => $value) {
  $replacements[$token] = _cleanstring($value);
}

I guess i am passing wrong array('current-user' => $account) argument. Where am i doing wrong?

Tokens for the current user [current-user:*] don't need any data. Leave the array empty.

What you might referring to are tokens for any user [user:*]. They need an account as parameter 'user'.