Access denied for unpublished content in drupal 7 When i unpublished a content in drupal 7, I am getting an access denied message. But for some other unpublished content i am getting page not found message. I need page not found message to all unpublished content. How can i do that? Thanks

Few things to check for to figure out the problem based on your configuration:

Are you logged in or logged out while accessing the content?
Which user are you logged in with? Is this user the author of this content?
Check the permissions of this user (the ones related to unpublished content)...

Let us know if you need help or more details on any of the above.

Cheers.

UPDATE: if you want to customize the message that is displayed when access is denied, you can create a new page containing the custom message and then go to "Administration -> Configuration -> System -> Site information -> Default 403 (access denied) page" and set the path to your created page.


Add another item button goes missing with unlimited, repeating dates Unlimited + repeating date fields seem to not work together. I would like to be able to add unlimited date fields that may or may not have repeating functionality.

I currently have both unlimited and repeating options enabled on a date field:

But the "Add another item" button is missing when utilizing the field on node creation:

It should be more like this except with the repeat functionality as well:

Is this possible? Has anyone seen this issue before?

Thanks!

This is not an issue. According to documentation found here - https://www.drupal.org/node/295239

  If the Date Repeat API is enabled, you will see 'repeating' as an alternative to allowing 'unlimited' multiple values.


How to create Omega 4 subtheme with new "default" libSass based starterkit? I am trying to install omega 4, now at 4.4, which uses liBsass for the default starterkit.
How do I proceed about this - I understand I need now npm and gulp instead of the previous Ruby stuff required for Omega 4.3?
Everything installs fine, but drush omega-guard complains about gemfile (which it should not use, as I understand).

I've had a lot of problems getting started with the new starterkit. It seems to me as if omega-guard does not yet support the new kit. You can still accomplish the same by running gulp in the subthemes directory. This will start the gulp watching process in foreground.

For more information about gulp and the libSass starter kit, I can recommend this post: https://www.drupal.org/node/2537364#comment-10287771


Mix taxonomy and node title in ordering in a View I have a View which lists books (nodes). They are sorted by alphabetical order (Title). Good. They are linked to taxonomies (categories). I could sort by taxonomy to group books of the similar theme together, and a second sort by title. Good.

Now the problem. My client want to list both taxonomies (categories) names and title books together, so we have the following beautiful omellete of data (imagine that the lists which are book titles beggining with prefix "-" are hidden after you click on the taxonomy they belong):

 Antologies (category)
  - Interesting antology (book) *hidden until you click Antologies*
  - More interesting antology (book) *hidden til you click Antologies*

 Book about everything the meaning of life (book) *visible*

 Cooking books (category)
   - A guide on cooking data (book) *hidden til you click Cooking books*
   - How to cook an alien (book) *hidden til you click Cooking books*
 Course of the pyramid (book) *visible*
 Decameron (book) *visible*

Nonetheless to say, I am completely at lost here. I have considered to use an extra field data to the content (node = book) to set an alias, which is the category. Then order by alias and to achieve  the " - " indentation, use some hook code to identify the taxonomy.

I would try Views Tree.

Edited: To use Views Tree, the genres would have to be a content type and the books would the use entity reference. It will do an alphabetical list as OP asked but it's unsuitable for his requirements.


Transfer drupal 7 content types I have a Drupal install with 10 content types and 30 views being used as web app. The app uses MySQL as a database.

What I would like to do is to reuse the same app but with SQLite. Is there a way to migrate the theme, content types and views without re-building them from scratch? I am not interested in the content.

You can export all your config using Features module: This module dumps to code several config data as content types and Views (but no content), generating modules that once enabled in another site regenerate dumped config.

One you have your config exported install a new Drupal site over SQL Lite and enable the exported modules with the config.

To 'migrate' the theme you only have to copy the theme folder to the new installed site right folder (usually /sites/all/themes/ or /sites/all/themes/custom/).


Drupal set message class I've been trying to add a class to a drupal_set_message() function. i found one article that said it worked, but i could not get it to work on mine. am i missing something?

I have drupal_set_message(t('an error has occured'),'custom-error');

these are the only output i get from the html

×
an error has occured

any help would be appreciated.

For drupal set message below is a syntax.

drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE);

Parameters

string $message: (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.

string $type: (optional) The message's type. Defaults to 'status'. These values are supported:

'status'

'warning'

'error'

You should pass any one of the status message with your custom class separated with space as shown below

drupal_set_message(t('an error has occured'),' status custom-error');


How do I avoid having to clear the cache when changing a module configuration parameter? I have a simple configuration parameter for a custom module. I use this parameter to decide how to render a field using a custom render element:

class Jmol extends RenderElement {

/**
 * Define the available options for our new render element.
 */
public function getInfo() {
$class = get_class($this);

// Produce the default settings for our render element.
return [
  '#pre_render' => [
    [$class, 'preRenderJmol'],
  ],
  '#version' => NULL,
  '#theme' => NULL,
  '#id' => 'mydiv',
  '#info' => [],
  '#attached' => [
    'library' => [],
  ],
];
}

public static function preRenderJmol($element) {

// Examine the config file to see which library version to use.
$config = \Drupal::config('jmol.settings');
$version = $config->get('version');
// Look at the element to see which version the user would like to use.
// They may have changed it from the default.
if ($element['#version'] != NULL) {
  $version = $element['#version'];
}

// The twig template to use.
$theme = "";

// Add the correct library to any the user has already provided.
$library = $element['#attached']['library'];
if ($version == 'full') {
  $theme = 'jmol_full_template';
  $library[] = 'jmol/jmol_full';
}
elseif ($version == 'lite') {
  $theme = 'jmol_lite_template';
  $library[] = 'jmol/jmol_lite';
}

// Only add the theme if the user has not specified one.
if ($element['#theme'] == NULL) {
  $element['#theme'] = $theme;
}

// Add the info array to drupalSetting so the JS can access it.
$id = $element['#id'];
$drupalsettings['jmol'][$id] = [
  'info' => $element['#info'],
];

$element['#attached'] = [
  'drupalSettings' => $drupalsettings,
  'library' => $library,
];

return $element;
}

If I visit the module settings page and change the value of the "version" parameter, my module continues to behave the same until I clear the cache.

The submit portion of my configuration form is:

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('jmol.settings');
  $config->set('version', $form_state->getValue('jmol_version'))
  ->save();

  parent::submitForm($form, $form_state);
}

Is there something else my submitForm function needs to do, or is there a different way I need to be reading the config parameter?

You need to set the cache tag to invalidate your output if the configuration changes. That's as easy as adding this to your render array:

$element['#cache']['tags'] = $config->getCacheTags();


Hook name in module doesn't seem to work I've been at this for days, but I finally think I maybe kinda sorta found part of the problem, maybe...but I don't know how to fix it.
I'm working on a Drupal site with the CiviCRM module running.  I have a form on which I'd like to alter the data before saving it to the database.  As a result, I've been struggling with getting ANY of the available CiviCRM hooks to fire.
I installed the civicrm_developer module, which is sort of a complement to Devel, in that it is used to help see into objects and other variables.  Looking in the module's .module file, you see all of the CiviCRM hook functions, which are being used in the module to dpm() whatever variables were passed to them.
function civicrm_developer_civicrm_buildForm($formName, &$form){
  drupal_set_message("hook_civicrm_buildForm called: formName is $formName");
  dpm($form);
  dpm($formName);
}

There are no includes or anything else, just hooks and printing  variables, for each and every hook available in CiviCRM. The civicrm_developer module indeed works as intended. On the specific page I'm working with, there is a CiviCRM form and this module prints a populated Krumo above that form, as would be expected when dpm()-ing a variable in Drupal.
However, attempts at making a custom module which uses one or two of those same hooks, can never seem to get to that same data.  I've gone far as copying the code from that module (just one .module and .info file) to my custom module and changed the hook nomenclature from "civicrm_developer" to, let's say, "mymodule".
So, my module, which is practically an exact copy of that module, with the exception of the hook name, will not generate a Krumo above the form as the civicrm_developer module did when it was enabled. Yes, I've made sure that my module was enabled.
For example, this is the same function from earlier as written in my custom module.
function mymodule_buildForm($formName, &$form){
  drupal_set_message("mymodule_buildForm called: formName is $formName");
  dpm($form);
  dpm($formName);
}

It might also be worth mentioning that the mymodule name in use is unique to that module. It doesn't match the theme name or anything else that would cause a name collision, at least that I know of.
I can't figure out why the same hooks work in a module but not the other.  It just doesn't make any sense.

there is no hook_buildForm() hook in Drupal. The hook you are trying to implement is hook_civicrm_buildForm(), so to get it work you should use mymodule_civicrm_buildForm().
You can always use hook_form_alter() or, more specifically, hook_form_FORM_ID_alter() to make changes on any Drupal form.


How does one concatenate fields in title field in Panels (Pages)? I have learned how to concatenate fields in Views, now I need to do the same thing in the title field in Panels. I have these fields
- first name
- last name

and I would like the title of the Panel to be
first name + last name

I'm using a module which enables me to automatically update the title field and hides it. The automatic generation includes the first and last name plus the date. I don't want this to display on top of the panel for this content type.

TIA

You need to use replacements tokens in your "Content" configuration page, this is how is looks on my local instance:

Good luck!


How to add a checkbox to form builder component settings form? I have webform and formbuilder modules installed.

In the file field settings form I want to add an extra checkbox field just like the required field but I am unable to do that.

I can add it to the webform_component_edit_form like the following

$form['validation']['check'] = array(
      '#type' => 'checkbox',
      '#title' => t('Check'),
      '#default_value' => ($component['check'] == '1' ? TRUE : FALSE),
      '#description' => t('Check this option if the user should be able to upload files.'),
      '#weight' => -1,
      '#parents' => array('check'),
    );

But it is not displaying in the formbuilder file settings edit form form_builder_field_configure.

Is there any way to add a field to form_builder_field_configure form and save with the node just like other fields?

you have to do it inside the form_id 'form_builder_field_configure'.
Example :

hook_form_alter($form,$form_state,$form_id){
`switch($form_id){
     case 'form_builder_field_configure':
     // You put your code here
     $form['check'] = array(
       '#form_builder' => array(
         'property_group' => 'validation'
       ),
       '#type' => 'checkbox',
       '#title' => t('Check'),
       '#default_value' => '',
       '#description' => t('Check this option if the user should be able
    to upload
     files.'),
      '#weight' => -1,
);
  break;
 }

}
     `

I hope it'll help you.


Menu item to view with wildcard I created a view that dynamically displays some nodes depending a wildcard in the path.
The view path is something like /fruits/%
So /fruits/apples would show all the apple nodes, /fruits/oranges all the orange nodes and so on.

Works great when I directly go to a path like www.mysite/fruits/apples but I can't create a menu item with the path 'fruits/apples', I always get the message The path 'fruits/apples' is either invalid or you do not have access to it.
Also tried creating URL aliases for the path but same message.

/* Update */

I use this code to get the argument I need to load the right 'fruit', it returns false when no term_id is set, and that seems to be a problem. When return true, I can set the menu item but then the view will always try the display the page in stead of showing the 'No Results Behavior'

$term = taxonomy_get_term_by_name(arg(2), 'fruit_type');
$term_id = key($term);
if(isset($term_id)){
  $handler->argument = $term_id;
  return TRUE;
}

return FALSE;

Don't confuse fruits/apple with fruits/apples. Drupal will not allow you to create menu entries for paths whose Views Contextual Filter argument does not validate.


Contextual Shared comments on nodes that are clones of one another I'm creating a Drupal 8 system where I need commenting to be shared across cloned nodes. When cloning a node the new node is assigned with a new nid, but the title contains the cloned title of the previous node. I was thinking I can use that as a contextual variable to show the shared comments, but I'm unsure of how to go about this.

Or maybe there is better way of solving this approach to display shared commenting?

There's many routes which to take for this. Drupal 8 gives you a bit more flexibility than previous versions. For the sake of managing a shared comment section, you can go about creating a new body-less content type that only contains:

A comment field
A node reference field with 2 entries (one for the parent & child cloned node)

Upon your clone operation, you can create a new entity with a dummy, to-be-hidden, title and the node reference field populated with the parent/child nodes.

For display/commenting, you can create a block view that uses a Provide default value: Raw value from url (Path component: 2) (i.e. the node id) contextual filter so the block only displays the shared comment entity on viewing the child/parent nodes.


Viewing an image file breaks if view mode has responsive image style I have an image file that I am viewing programmatically. When I set the image format to "responsive image" in file display settings, it breaks with an error

Error: Call to a member function getMetadata() on null in file_entity_preprocess_responsive_image_formatter() (line 488 of modules/contrib/file_entity/file_entity.module).

My render code:

$file = File::load($fid);
$build = [];
if ($file) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder($file->getEntityTypeId());
  $build = $view_builder->view($file, 'embed');
}

"embed" is the file view mode that sets the image to display as responsive.

There seems to be missing the "item" in the build array resulting from this, which is expected to be a fielditem. Am I doing something wrong?

This is not a proper answer, but a workaround in case someone else has this issue: detect if a responsive style is used, load it, and apply via theme layer (the style name is hard-coded to be "embed"):

if ($file) {
  $view_mode = \Drupal::entityTypeManager()
     ->getStorage('entity_view_display')
     ->load('file.' . $file->bundle() . '.embed');
  $content = $view_mode->get('content');

  // Responsive.
  if (!empty($content['uri']['settings']['responsive_image_style'])) {
    $build = [
      '#theme' => 'responsive_image',
      '#responsive_image_style_id' => $content['uri']['settings']['responsive_image_style'],
      '#uri' => $file->getFileUri(),
    ];
  }

  // Non responsive.
  else {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($file->getEntityTypeId());
    $build = $view_builder->view($file, 'embed');
  }
}


How do I re-order tabs in user page? I'm developing a drupal 7 based website where the user profiles need some modification. Now I need to know how can I re-order tabs in user profile page such as, View, Edit, etc.

i'd like to keep the current tabs, but just reorder them. I'm looking for an easy way to do that.

You can use hook_menu_local_tasks_alter for example in the bellow example i will change the order between tab 2 and tab 3:

/**
 * Implements hook_menu_local_tasks_alter().
 */
function YouModule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if (isset($data['tabs'][0]['output'])) {
   $data['tabs'][0]['output'][0]['#weight'] = 0;
   $data['tabs'][0]['output'][1]['#weight'] = 2;
   $data['tabs'][0]['output'][2]['#weight'] = 1;
   $data['tabs'][0]['output'][3]['#weight'] = 3;
   $data['tabs'][0]['output'][4]['#weight'] = 4;
  }
}


How to implement user hierarchy with different levels of roles under different branches, groups etc I have to create a web portal, that should have a number of users from super administrator to employee. Users have single or multilevel access (either to data of one branch or to multiple) on the system.

Some can add/edit data and some can only view some data. The system has different branches, different departments etc.. How can I implement such a system using Drupal?

I had created multiple roles and given permissions to them. But how can I achieve those multi branch multi groups kind of user hierarchy?

Update:
Can I achieve it by using TAC : https://www.drupal.org/node/31601 ?

Have you looked at Organic Groups.

Im using it for a similar use-case. I would allow you to create content types that can act as 'Departments' and add different roles within those.

You can have for example:

'department' content types with following roles: admin, supervisor
'branch' content type with completely different roles: it programmer, temp

It is very flexible and access control works with views as well. Nice tutorial can be found here.

If you opt to however to write your custom access control module, make sure that you read up on that here

Hope that helps.


How do I display the content type's description in a view's header? I have a view that lists nodes of a single content type, where the content type is given as contextual filter.
I'd like to add the name of the content type and a description to the header, for example as the following.

Content Type: Cooking
The Cooking content type is for cooking-related content

I can show the content type name by by adding a hidden field to the view and then using <h1>{{ type }}</h1> in the header, but I don't see such an option for the description.
Is there a way to achieve this?

Here's what you can do:
First, add then config the contextual filter like this:

Then you update the header like this:

You can update the header status at this step also.
And then here is the result:

One more thing need you to handle:
The exception when the filter value is not in the url.
Can it be your part?


Custom TWiG template for SELECT element I have created twig template to override SELECT element for SELECT-element in user exposed filters.

However I can't figure out how to make it only work within a specific view "testing" ?

You should implements hook_theme_suggestions_HOOK_alter() to add a suggestion for 'select' element. Then create a new twig template in THEME/templates folder with the name 'select--$view_id.html.twig'.

Example code:

function HOOK_theme_suggestions_select_alter(array &$suggestions, array $variables) {
  $routeObject = \Drupal::routeMatch()->getRouteObject();
  $view_id = $routeObject->getDefault('view_id');
  $display_id = $routeObject->getDefault('display_id');

  if (!empty($view_id)) {
    $suggestions[] = 'select__' . $view_id;

    if (!empty($display_id)) {
      $suggestions[] = 'select__' . $view_id . '_' . $display_id;
    }
  }
}


I get an exception when re-installing a module I have re-installed modules before, but I can't get it this time. These are the steps I take:

Uninstall the modules (by deselecting them on the module list and clicking submit changes)
Remove the Module Files from the module folder
Check the database for any potential left over tables (specifically sms_feed)
Check the system table for any left over rows dealing with my modules
Delete anything related to my modules in the database
Clear the cache
Reinstall the modules

I always get the following error:

  DatabaseSchemaObjectExistsException: Table sms_feed already exists. in DatabaseSchema->createTable() (line 657 of C:\xampp\htdocs\amaware\includes\database\schema.inc).

Do you have any idea?

What you have done in the first step is disabling the module, not uninstalling it. To uninstall it, you need to click on the "Uninstall" tab, select that module, and then click on the "Uninstall" button.

The exception raised from DatabaseSchema::createTable() is because it contains the following code.

  if ($this->tableExists($name)) {
    throw new DatabaseSchemaObjectExistsException(t('Table %name already exists.', array('%name' => $name)));
  }

The code in DatabaseSchema::tableExists() is then the following one.

  $condition = $this->buildTableNameCondition($table);
  $condition->compile($this->connection, $this);
  return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();

You could also manually remove the database table, but if the information about that table is still contained in information_schema.tables, DatabaseSchema::createTable() will raise an exception.


How to force a JavaScript library to load in the  of a Drupal 8 page How do I force a JavaScript library to load in the < head > in Drupal 8?

Here's my themename.libraries.yml file:

zaccordion:
  version: 1.x
  js:
    js/jquery.zaccordion.js: { header: true }
    js/jquery.zaccordion.min.js: { header: true }
    js/zaccordionUsage.js: { header: true }
  dependencies:
    - core/jquery

It still loads in the footer however.

header: true needs to go under your js declaration, not within each file.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

  By default, all JS assets are now loaded in the footer. Being loaded
  in the header is now an opt-in choice, that is only necessary for
  critical UI elements that cannot be shown unless their corresponding
  JS has already run.

js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

  You have to set the new header property on asset library definitions
  to true, to indicate that the JavaScript assets in that asset library
  are in the critical path, and should therefore be loaded from the
  header. Note that any dependencies — direct and indirect — of asset
  libraries marked as being in the critical path are also automatically
  loaded from the header, so you don't need to worry about dependencies
  being unavailable.


Are there alternative ways to creating themes in Drupal 7? Specifically I'm looking for something as simple as having the HTML/CSS/JS theme ready as static files and then just filling in the dynamic parts using PHP/Drupal. This is more or less how WordPress and other CMSs do it.

Are there any modules or other theming engines that do this?

Thank you.

The short answer is "no." At least not at the level you are looking for.

A .info file is always required for a Drupal theme, this is how Drupal recognizes that the theme exists. Adding CSS and JS within this file is important because of CSS/JS caching which is important for site performance and other reasons. You should read the Drupal Theming Guide for more information, if you haven't.

There is, however, no requirement for template.php in a theme. If you do not want to utilize RDF on your site, you can disable the core RDF module.

There are other Theme Engines for Drupal, but they have all been abandoned in favor of PHPTemplate in Drupal 7. There are also a number of contributed base themes for Drupal, which are helpful for getting started with theming more quickly.

Unfortunately, the theming approach of Drupal is often a shock for users coming from other CMSes, especially Wordpress. The inherit flexibility and functional power in (and legacy of) Drupal core necessitates an extremely complex theming layer. You are not going to find a Wordpress-like experience in Drupal 7.


Only ask for a shipping address if a real product is ordered I'm using the Drupal Commerce module with Shipping 7.x-1.0. I created a webshop with both real and virtual products.

My problem is that the shipping address is required even if all the products are virtual (so there is no shipping). How can I make sure that the shipping address is only asked for if the shoppingcart contains real products?

you could use hook_commerce_checkout_pane_info_alter and do

unset($checkout_pane['customer_profile_shipping']);

only if all line_items contains physical products:

function mymodule_commerce_checkout_pane_info_alter(&$checkout_pane) {
  global $user;

  foreach ($checkout_pane as $pane_name => & $pane_data) {
    if ($pane_name == 'customer_profile_shipping') {
      $order = commerce_cart_order_load($user->uid);
     if ($order) {
       $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
       $lines = $order_wrapper->commerce_line_items->value();

       $ask_shipping = FALSE;
       foreach ($lines as $line) {
         if ($line->type == 'product') {
           $line_wrapper = entity_metadata_wrapper('commerce_line_item', $line);
           $product = $line_wrapper->commerce_product->value();
           if ($product->type == '---> you physical product type <---') {
             $ask_shipping = TRUE;
           }
         }
       }

       if (!$ask_shipping) {
         unset($checkout_pane['customer_profile_shipping']);
       }
     }
   }
 }
}


Letting users login with facebook to an existing account My client wants to add FaceBook integration into an existing site. I've successfully setup fboauth and openid_selector. New accounts can login without an issue. However, we liked to let an exiting user authorize a login from Facebook to their account.

I can see how to do this using openid_selector's http://yoursite.com//user/xxx/openid. Might there be a way to duplicate this for FaceBook authentication?

Update: I found this node https://drupal.org/node/1624374. It seems that if a user is already logged into Drupal and then clicks the FB connect button, FBOauth will link the accounts. Though I'd prefer to have something like this managed through an interface like openid_selector (pictured in this post).

Configuring OpenID for each services is so painful. I have also gone through the same process when I had to enable FB, Gmail & Twitter login at my website, but anyhow it was giving me problem even if I configured with the supported modules oauth & connector.

At last I found another module named HYBRIDAUTH & it worked so fine. Configuration is easy & there is no need of any other addon module with this. Best part is, it's free, otherwise most of the module of this kind are from some paid service provider..

Try this & I hope you will find all the services which you require along with facebook.


Alias path precedence rule? I just checked that an alias path named, say, any/path can point to N different existing paths. Is there any fixed precedence order as per which one will be processed? Or is it a random order?

Using the user interface, it is not possible to set the same alias pointing to different destinations for the same language.
If a module would execute code similar to the following one, it would be possible to have two records for the same alias.

$path = array(
  'alias' => 'homepage',
  'source' => 'node/1',
);
path_save($path);

$path = array(
  'alias' => 'homepage',
  'source' => 'node/2',
);
path_save($path);

drupal_lookup_path() contains the following code to retrieve the internal path associated with a path alias from the database. $path_language is the last argument passed to the function; when the function doesn't get that argument, it uses the value of $GLOBALS['language_url']->language.

    if ($path_language == LANGUAGE_NONE) {
      unset($args[':language']);
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language = :language_none ORDER BY pid DESC", $args)->fetchField();
    }
    elseif ($path_language > LANGUAGE_NONE) {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args)->fetchField();
    }
    else {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args)->fetchField();
    }

If $path_language is equal to LANGUAGE_NONE (i.e. you are looking for the internal path associated with the language-independent alias), drupal_lookup_path('source') returns the internal path which is saved in the path_alias table with the higher pid (which normally is the latest created row).
If $path_language is not equal to LANGUAGE_NONE, the database rows are ordered to get the language-specific alias before the language-neutral, and then by pid. Also in this case, the returned internal path would be the last created one.

Suppose url_alias contains the following values.

pid   | source    | alias      | language
4     | node/1    | homepage   | und
5     | node/2    | homepage   | und
8     | node/21   | homepage   | it
9     | node/22   | homepage   | it
10    | node/31   | homepage   | xx-lolspeak
11    | node/32   | homepage   | xx-lolspeak

What I would get from that table is:

drupal_lookup_path('source', 'homepage'): node/2
It returns the last created alias that is language-independent.
drupal_lookup_path('source', 'homepage', 'es'): node/2
There isn't an alias for Spanish, and the function fallback to the language-independent alias. It gets the last created alias.
drupal_lookup_path('source', 'homepage', 'xx-lolspeak'): node/32
It returns the last created alias for Lol Speak.


Views Taxonomy Term argument to represent "no term" With Views 2.x, Drupal 6, I've created a taxonomy and have enabled it for a Content Type. I then create some content:

node_1 is associated with term_1 (tid=1)
node_2 is associated with term_2 (tid=2)
node_3 has no term association

I've created a Node View that has an Argument for "Taxonomy: Term ID". In the argument configuration, I enable "Allow multiple terms per argument".

Using the Live Preview for the View, I can pass in arguments. So I pass in "1" and the view shows me node_1. I pass in "2" and the view shows me node_2.  I pass in "1+2" and the view shows me node_1 and node_2. This is good.

What I can't figure out is how to pass an argument that will return me just node_3. Is there something I can pass to Arguments that essentially means "no argument"?

Just in case anyone else stumbles upon this answer, we solved this problem with the following approach:

function MODULENAME_views_query_alter(&$view, &$query) {

  if($view->name == 'your_view_name')){

    //Flip the term table join to a LEFT join
    $view->query->table_queue['term_node_value_0']['join']->type = 'LEFT';

    //CLear the extra condition (removes a where clause on the join limiting only matching term ids)
    $view->query->table_queue['term_node_value_0']['join']->extra = null;

    //Look through the where clauses and add a null condition clause
    if($index = array_search('term_node_value_0.tid = %d', $query->where[0]['clauses'])){
      $query->where[0]['clauses'][$index] .= ' OR term_node_value_0.tid IS NULL';
    }
  }
}

It changes the JOIN type to a LEFT join, removes the limiting clause from that join and adds a condition to match against null values.  It's obvious limitation is that it should be using aliases instead of hard coding the field name.

The function should go in your modules views.inc file where Views expects to find this hook.


page--front.tpl.php not showing up in Zen subtheme I am developing a subtheme of a Zen-based subtheme. I have created a page--front.tpl.php template but it isn't being recognized. All I see is the page.tpl.php template being used for the front page.

I have cleared the cache multiple times, looked for any other page--front.tpl.php files in the subtheme I am basing mine off of (there are none). I have restarted apache to make sure nothing is being cached, so I am at a loss as to why this is not working. I am using Drupal 7 on a linux server.

Any ideas as to what may be causing this issue? I have googled similar problems but most had to do with clearing the cache (which I have already done).

Using Theme developer, it shows that page--front.tpl.php is not a canditate template to use. In fact it doesn't show any candidate templates that could be used while on the front page of the site.

Thanks.

Found out the problem was caused by the Context Layout module. Apparently this module overrides Drupal's normal template file search order. The solution was to either to disable the Context Layout module or include the templates (like page--front.tpl.php) in the layouts definition in the themename.info file. I went with the latter solution.

Here is an example of what should appear in the .info file:

; Layout: Landing
layouts[landing][name] = "Landing Page"
layouts[landing][description] = "A layout for landing pages."
layouts[landing][template] = "templates/page--front"
layouts[landing][regions][] = "search"
layouts[landing][regions][] = "highlighted"
layouts[landing][regions][] = "mega_menu"
layouts[landing][regions][] = "slider"
layouts[landing][regions][] = "sidebar_first"
layouts[landing][regions][] = "sidebar_second"
layouts[landing][regions][] = "footer"
layouts[landing][regions][] = "bottom"

Notice the layouts[landing][template] line where we define where and what template file to use. This is key to getting this to work with Context Layouts.


Why can I not find the og table after installing Organic Groups? I am using Organic Groups  module.

After installation why do I not find the og table?

I only have these five tables:

Here is a screenprint from the Drupal log with messages from around the time the og module was enabled:

Note: I installed the og module using a new Drupal site (which doesn't have any other contributed modules enabled yet), and I tried a disable/uninstall of it. Then re-installed the module but it did not fix this problem.

The Drupal 7 version of Organic Groups doesn't have an og table. The Drupal 6 version does, but it's removed as part of the upgrade process, and never exists in the newer version.

You can always find out what tables a module is responsible for by checking its implementation of hook_schema() (in this case og_schema()).


How to rename uploaded file using form API and Drupal managed_file field I make a Drupal Form using FAPI (Drupal 7)
in this form I used managed_file field

$form['image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
);

I want to rename the uploaded file (make the filename = filename+date)

How can I make something like that

Assuming you know about file status, file_save & file_usage_add.

In your submit callback:

$file = file_load($form_state['values']['image_fid']);
$file->filename = 'somefilename';
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'yourmodule', 'foo', 1);

More info at the Form API Reference.


Get variable from controller in twig using template I have a php variable in my controller and i want to use it in twig.
So i do this :

Controller :

$firstLetter = '2017'; //dynamic variable but for the test it's a constant

$build ['list'] = array(
      '#theme' => 'liste-adh2',
      '#content'=>$result,
      '#filters'=>$ListApport,
      '#filters2' =>$Listline,
      '#test' => $firstLetter,  //sending to my template
   );

return $build;

Template :

function adh_apport_theme($existing, $type, $theme, $path)
{

    return [
        'liste-adh2' => [
            'variables' => ['content' => NULL, 'filters' => NULL,
                            'filters2' => NULL,], ['test' => NULL,],
                        ],
            ];
}

Twig :

{{ test.firstLetter }}

i got nothing in twig and i don't know why.

Thanks for helping.

I’m not sure why you’re expecting test to be an object, you declared it as a string.

Assuming the value of “2017” from your example is what you’re trying to get the variable is just:

{{ test }}


Configuration form and submission handler I am using the following code for Drupal 6.

 foreach (variable_get('cleanupeditform_formkeys', 0) as $key => $value ) {
    $form['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key] = array(
      '#type' => 'checkbox',
      '#title' => t('Hide ') . $value,
      '#default_value' => variable_get(CLEANUPEDITFORM_HIDEPREFIX . $key , 1),
    );
  }

I need to convert this code to Drupal 8.

In buildForm() I generate the form. I need to save the checkboxes values, and I am using the following code.

public function submitForm(array &$form, FormStateInterface $form_state) {
     foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: 0) as $key => $value ) {
       parent::submitForm($form,$form_state);
       $this->config('cleanupeditform.admin_settings')
         ->set('element', $form_state['cleanupedit_hide'][CLEANUPEDITFORM_HIDEPREFIX . $key])
         ->set('element', $form_state['cleanupedit_allow'][CLEANUPEDITFORM_ALLOWPREFIX . $key])
         ->save();
     }
     parent::submitForm($form, $form_state);
  }

Please help me to find out a solution.

There are the following errors in that code:

You call parent::submitForm($form, $form_state) inside the foreach() loop, when it should be called once, outside the loop
You keep setting element, which means you are only saving a single value
Your code is still accessing the FormStateInterface object as an array, as it was done in Drupal 7

I cannot comment about the \Drupal::state()->get('cleanupeditform_formkeys') part, except that I would probably inject the service as dependency, but I would rather use the following code.

public function submitForm(array &$form, FormStateInterface $form_state) {
  foreach ((\Drupal::state()->get('cleanupeditform_formkeys') ?: []) as $key => $value ) {
    $this->config('cleanupeditform.admin_settings')
      ->set(CLEANUPEDITFORM_HIDEPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_HIDEPREFIX . $key))
      ->set(CLEANUPEDITFORM_ALLOWPREFIX . $key, $form_state->getValue(CLEANUPEDITFORM_ALLOWPREFIX . $key))
      ->save();
  }
  parent::submitForm($form, $form_state);
}


How to deactivate keyboard navigation when using the “Views Slideshow: Swiper JS” module So I am using the Views Slideshow (7.x-3.9) module in conjunction with the Views Slideshow: Swiper JS (7.x-4.0) under Drupal 7.61 and it’s working great for my needs. But have run into an issue. The version of the Swiper JS library I have installed is 4.4.6.

While the “Format > Slideshow > Settings” clearly has an option that you need to check a checkbox to enable keyboard navigation, and I have that option unchecked, I can assure you that keyboard navigation is clearly enabled.

Looking at this issue request on the Drupal page for Views Slideshow: Swiper JS shows a similar issue where the Drupal module settings seem to not be respected by Swipe JS when loaded, but the “solution” (kludge?) of downgrading to a 3.x.x version (such as 3.4.2) doesn’t work for me. Beyond not wanting to be behind the curve in patches and development on Swiper JS, when I attempted to swap my 4.4.6 version to 3.4.2 made the slideshow go a bit haywire.

So what can practically and simply be done to disable the keyboard functionality of Swiper JS under Drupal?

Okay, so I solved this. It’s clear to me that the Views Slideshow: Swiper JS is somehow not passing all the config options it claims to handle to the final Swiper JS instance that gets loaded on the page.

So my solution that—works directly in the view—is to go to the Swiper JS settings “Format > Slideshow > Settings” scroll down and select “Events” and then add the following to the swiper.on('init', function() {} event:

this.params.keyboard.enabled = false;

Apply the settings, save the view and… et voilà! It works and cleanly disable keyboard navigation.


Feeds module is stripping html tags from xml I tried my best to find an answer, but now I am finally stuck.

I am using Drupal 7.36, Feeds 7.x-2.0-alpha8 and used already 7.x-2.x-dev.

I am trying to import a XML file using the Feeds module with a simple structure:

<?xml version="1.0" encoding="UTF-8"?>
  <persons>
    <person>
      <number>
12
</number>
    </person>
    <person>
      <number>

2

</number>
    </person>
</persons>

But all I get after the import is the plain text 12 without any HTML tags.

I created a custom Content type named Persons and added one field to it, which accepts as text processing 'filtered text'.

For this purpose I checked, that my filtered text is accepting p, li and ul tags. For that I edited all relevant text formats at:
admin/config/content/formats

Anyway, after for the purpose of solving this issue I do actually just use Full HTML now, without any restrictions. If I type in HTML manually into a Person content entity the HTML tag stays there properly.

In the Feeds module I added an importer and chose under Processor (in my case node processor) 'texte-format' Full HTML. Here I added as a bundle my Person content type.

As parser I use XPath XML parser.

Fetcher is File-Upload.

The importer is properly attached to Persons content type under basic settings.

Anyway, always, when I import my XML, it strips off the HTML tags.

I do not use any WYSIWYG module.

What am I doing wrong?

I appears to me that the issue you are trying to resolve, might be related to the issue described in issue # 2224643 (on D.O).

If that's the case, then you might want to try the commit mentioned in #22 in that issue (or the patch attached to #20 there).


Updates: keep panels pages, views, etc.. updated via hook_update_n? im having a little trouble keeping a project update.

I track the code via a private git repo, and for each update I follow those steps (first on stagin, then on production):

update all the 3rd pars modules (from drupal.org)
Update database (via drush updb)

Then if everything is ok:

update my modules (via git repo)
update database (drush again)

All works perfectly, except for pages/views exported via Features module: in my module i hav a function like this:

/**
 * Implements hook_default_page_manager_pages().
 */
function mymodule_default_page_manager_pages() {
    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    // Second page...
    $page = new stdClass();
    // page definition, display, etc..
    $pages['page_machine_name'] = $page;

    return $pages;
}

The structure is the same for views.

I noticed that if i update that function changing something in a previous declared (and imported) page (add a pane, change a configuration on a content, etc..), this one wont get updated! (yeah, i flushed the cache different times both via UI and via drush)

Am I doing something wrong? There is a specific way to update those elements?

Well, this can not be the best solution but it works:

function mymodule_update_7001(&$sandbox) {
  // Views.
  if (is_callable('views_save_view')) {
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_delete_view($view_object);
    }
    // Rebuild it.
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_save_view($view_object);
    }
  }

  // Pages
  module_load_include('inc', 'page_manager', 'plugins/tasks/page');
  if (is_callable('page_manager_page_save')) {
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_delete($page_object);
    }
    // Rebuild it
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_save($page_object);
    }
  }
}

Basically just keep updated the views and pages definitions (views_default_views and default_page_manager_pages), the delete and rebuild them.

Obviously, this remove all customizations done via the Drupal's UI, so only do it for the views and pages you need to update!


Controlling the display order of custom field sets that are shown both in a webform and in CiviCRM, via the webform_civicrm integration module I've created a webform that is integrated with my CiviCRM implementation. The webform has five major sections to it, each of which is reflected by a custom field set within the CiviCRM module as shown below.

All five custom field sets are linked to a specific activity type as indicated in the first screenshot. The five custom field sets are ordered, by weight, in the list of custom field sets within CiviCRM because I want the summary information displayed first to the administrator viewing the activity.:

However I want the summary questions displayed at the end of the webform, as presented to the user, so I've used webform's flexibility to let me do that.

So far so good. But when I submit the webform, the CiviCRM activity record, when in view mode, reflects the field order as specified in the webform, rather than as specified in CiviCRM, which seems odd.

However, if I edit the activity record, the field order and field sets are as ordered in my original CiviCRM field definitions.

How can I set it up so that the field order in the Activity record, when viewed rather than edited, reflects the order specified within CiviCRM?

(I'm aware that this question is more about CiviCRM than it is about Drupal per se, but given that CiviCRM is a Drupal module, and there's no SE site dedicated to CiviCRM - yet - I hope you'll bear with me and allow answers to this question.

This bug was resolved in CiviCRM 4.5.2, the relevant issue was CRM-15435: Case ActivityView popups do not respect custom group weights.


create views page using entityreference I have two custom content types, Speaker and Presentation. Each speaker can have many presentations. I am using the EntityReference module to attach a Speaker to a Presentation.
Using Views, I would like to create a page of Presentations that also lists the Speaker associated with the presentation such the page would look something like:

Presentation 1
details
Attached speaker details

Presentation 2
details
Attached speaker details

Presentation 3
details
Attached speaker details

How do I do that in Views. I followed the EntityReference documentation but it only talks about creating a block for a single node. I want to be able to show multiple Presentation nodes on one page using Views and EntityReference. Thanks in advance for any help anyone can provide.

I assume that you have your entity reference field (pointing to speaker) on the content type "Presentation" below and that it is called "field_speaker".

In Views add a new View. Choose Show:Content (nodes), of type: Presentation.

Now you have all your presentations listed, with their titles. Let's leave it at that for now.

Open up Advanced to the right and open up Relationships, choose "Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field_speaker".

Now we have the same result as before but we will be able to fetch data for the speaker through the relationship in the content type Presentation.

Under fields, click add and add the field called "Content: Title", now you have a dropdown that says "Relationship". Choose the only on available (field_speaker). Click apply.

You now have each presentation listed with it's title and the title of the presentations speaker.

Now you can go ahead and add the fields you wanted, sort the list etc.


How to use Drupal Commerce to extract all the people who purchased a specific product? I want to create a report (a list) of all the people who purchased a specific product.

I want to use this list for a report to verify purchase when people pickup registration packs etc., so that I can confirm those people when they arrive.

How do I get this in a report format that I can extract from Drupal Commerce?

Not 100% sure what you mean with "reports on line items" or "a line item report" (consider refining what actually this means). But since the question is tagged with the reporting tag, maybe you may want to consider the Forena module.

It would probably take a bit of time to achieve perfection, but you'd have all of Forena's xHTML-power available to finetune the ultimate result (report), for things such as:

look-and-feel (styling/theming).
maybe add some charts to it also (using selected data about commerce).
saving the ultimate output (report) in formats such as PDF, DOC, etc.
creating eMail campaigns about selected records.
pulling in information stored in other databases related to this report.

For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here is some more info about the other databases in mentioned above:

Using a SQLite instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.


drupal 7.21 views exposed form The question is - what may be the reason for exposed form to not be working/showing in a block? Thanks so much - hope someone has an idea about that.

Assuming that you have chosen 'block' as the display rather than 'page', you have to set 'Use Ajax' to 'Yes' in the Advanced options (See this issue on Drupal.org: http://drupal.org/node/1115782#comment-4384348):


Programmatically building a Quicktabs instance What I need to do is merge the usermenu ( user tasks ) with a Quicktabs menu I have on the same page.

So what I'm trying to do at the minute is to programmatically build a Quicktabs instance.

Based on the infomation at https://www.drupal.org/node/2119625  I have created a module 'userquicktabs'  heres the .module . Ive enabled the module, and I take it after this I should be able to see a new instance with the others instances I've created in the Quicktabs UI.  Do I need to make a block for the instance?

<?php

function userquicktabs() {
$tabs = array(
$tabs[] = array(
  'title'   => t('Node 1'),
  'type'    => 'node',
  'nid'     => '1',
  'weight'  => 0,
),
$tabs[] = array(
  'title'   => t('Node 2'),
  'type'    => 'node',
  'nid'     => '2',
  'weight'  => 1,
),
);

 // Configure the QuickTabs options
 $quicktabs_options = array(
'style'   => 'commons',
'ajax'    => FALSE,
'renderer'    => 'quicktabs',
);

$quicktabs_name = 'newinstance';

 print drupal_render(quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs));

}

Yes, programmatically created instances are not registered with those created trough the UI, but at least they are more flexible.


hook_menu_alter information I am using drupal 6.22.

I have written a framework module that relies on submodules, when I install the submodule, I would like to update the administration menu to include some administration properties for the submodule.

This is the hook_menu implementation on the framework and it works no problem:

function svm_mail_menu() {

$items['admin/settings/svm-mail'] = array(
  'title' => 'SeeViewMedia Mailing Framework',
  'description' => 'Framework Settings for the SeeViewMedia Mailing application',
  'page callback' => 'mail_settings', //this needs to direct to a tabbed page that holds the framework options such as general settings and account add/edit/delete
  //This page should also be a "welcome" page for the module listing where everything is found
  //'access arguments' => array('Administer SeeViewMedia Framework Settings'),
  'type' => MENU_NORMAL_ITEM,
);
$items['admin/settings/svm-mail/add-account'] = array(
'title' => 'Add Mailing Account',
'page callback' => 'add_mail_account',
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
);
$items['admin/settings/svm-mail/view-accounts'] = array(
  'title' => 'View Mailing Accounts',
  'page callback' => 'view_mail_account',
  'access arguments' => array('Administer SeeViewMedia Framework Settings'),
  'type' => MENU_LOCAL_TASK,
);
return $items;
}

and this is the hook_menu_alter that I tried using, but it replaces my entire menu system

function ymlp_svm_mail_menu_alter(&$items) {
$items = svm_mail_menu();

$items['admin/settings/ymlp-svm-mail/update'] = array(
  'title' => 'Update YMLP Accounts Manually',
  'page callback' => 'ymlp_update',
  'access callback' => TRUE,
  'type' => MENU_LOCAL_TASK,
);
return $items;
}

How would I just add this little bit of menu to the original menu that I created without destroying everything else?

If all you are doing is adding to an existing menu, there is no need to use a menu alter. Instead stick with plain old hook_menu().

function ymlp_svm_mail_menu() {
  $items['admin/settings/ymlp-svm-mail/update'] = array(
    'title' => 'Update YMLP Accounts Manually',
    'page callback' => 'ymlp_update',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

Don't forget to flush the menu cache after the module is installed


Use of Twig template for webform email I'm trying to help my father out by building a webform (D8 version) for the 4 theaters his Old Abbey Friends are putting up.

I've made the webform, now i'm setting up an email handler so that people get a confirmation email.  Straightforward enough, however, i'm getting lost when using the twig template option of that email handler on following items:

how do i check if there's at least one checkbox checked in a checkbox element (containing 4 checkboxes)?
how do i check which of the checkboxes is checked in the above element?
how do i get the number in a number element that's part of a custom composite?  I tried using the data.composite_elementkey.elementkey syntax, but that just shows up blank.

Any feedback much appreciated!

Alright, after a lot of searching and testing things out i've found the following things to work:

For the checkbox it won't work with the data.element_name syntax (or at least in any variation that tried, and that's a couple dozen).  What will work is this: {{ webform_token('[webform_submission:values:ticketselectie]', webform_submission) }}.  In this example "ticketselectie" is the name of the checkbox element with 4 checkboxes in it (options).  What you get from this is a string containing the option text for each checked checkbox, seperated by comma.

You can use the twig split filter to extract an array out of checked checkboxes.
Turns out you need to use data.custom_composite_element.0.element_key as the syntax.  given that a custom composite element only ever has one row, it's always the 0 delta you need, and then the name of the key behind that.  So given a custom composite with the name "abonnementen", and in there two number fields with the names "minderjarigen" and "anderen", that leaves with the following syntax: data.abonnementen.0.anderen or data.abonnementen.0.minderjarigen

That's it really.  Took way too long to find that, and it's kind of weird to me that the "data." syntax didn't work for the checkbox element.  So if anyone knows a better way, please do reply.


How do I check if a user may access a given route? I am trying to render a link from a Url object and verify the user actually has access to that URL, like when viewing a node.

For some reason, this always returns FALSE, although the node is accessible when $language is the set language.

$_url = Url::fromRoute('<current>', [], ['language' => $language]);
if ($_url->access()) {
  // The code inside here is never executed.
}

How do I verify a user may access the given path, without actually loading the entity behind that path?

edit: current state:

$currentPath = \Drupal::service('path.current')->getPath();
$urlObject = Url::fromUserInput($currentPath);
$routeName = $urlObject->getRouteName();

$linkUrl = Url::fromRoute($routeName, [], ['language' => $dataLangId]);

debug($languageData['languageName']);
debug($linkUrl->toString());

if ($linkUrl->access()) {
  debug('access');
}
else {
  debug('denied');

}

results in:

  Some mandatory parameters are missing ("node") to generate a URL for route "entity.node.canonical

I don't know why

$_url = Url::fromRoute('', [], ['language' => $language]);

Doesn't work with route name <current> but it works with other route names.
For example with route with name some_module.some_route_name the following
will work.

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $_url = Url::fromRoute('some_module.some_route_name', [], ['language' => $language]);
  $userCurrent = \Drupal::currentUser();
  if ($_url->access($userCurrent)) {
    //- Do Stuff
  }

In your case for the current route. Try this out.

use Drupal\Core\Url;

  $request = \Drupal::request();
  $_url = Url::createFromRequest($request);
  $userCurrent = \Drupal::currentUser();
   if ($_url->access($userCurrent)) {
     //- Do Stuff
  }


Change the amount of content displayed per page in Content Management -> Content I'm trying to do a CSV export of all my content, but it only shows 50 per page and I have 50+ pages. I want to be able to check all and export as one csv. Is there a way to change the pagination settings for Content Management -> Content?

Use Views to generate a list of all your contents, create a new view of type node, add fields what you like, then use Views Bonus Pack to export content list as CSV.


Group of CCK fields assigned to the same NID without an additional Node type and Node referrence I want to implement a 1 to N relation of a group of CCK fields into the same Node type

Picture this: I have some projects and some expenses per year
I have to define each year and it´s total expenses and provide a short description and some images for each year...

I wanto to make it into the same page... not define two types of content to implement a node referrence where I define the years and it´s corespondent description and images

something like this:

I don´t know how can I implement this with Drupal...
There is a matrix/array type of CCK field but it doesn´t support the installed CCK
it has it´s own stadard types..integer, text etc... so it won´t do ..

Is there any way to obtain this?

the main functionality (ignore the layout ..it can be horizontaly as well)

when I click Add More, ... to add All those fields grouped so I can edit them....
It´s like embeding the other content type into the related NID upon creation of the NID...

Using Drupal 6 and the last CCK available
upgrades are not a problem, I can use the latest versions as long they are for D6

re-edit

I have to explain myself better because what I´ve described I see is not very understandable...

Picture the following requirements (based on a relational database concept)
I have a content type named Project Expenses (title, description, project status)

Now I want to describe for each year how much I´ve spent for the project and add a gallery of images with the projects achievements for that particular year.

Now, the common thing would be to add another content type with the following CCK fields (year, amount, image (unlimited multiple values) and a node referrence to the project itself )

The problem I have is at data input.. you have to first create the project...save it
then add another node for each year and selecting the project in the node reference dropdown doing the relation between the node and the other (1 to N relationship in therms of a database)

So 2 forms instead of one... 2 saves...
This is not cool for the user experience, because normal users don´t know the steps or it results too complicated..(this is a simple example but it can get really complicated with having to fill in a lot of nodes if we have more relations)

Ok, so the solution: embed into one form everything..(multiple pages input would be also a solution) but my ideal would be something like in that image that i gave you

define on the same page the other node as well automaticaly making the relation when saving the main node (the project)

I don´t have any ideea how it´s possible (I could find only one module that does that but the values arren´t in fact CCK fields so can´t use them propperly it´s called matrix field )

Show how is the best way to do this?

It appears to me you are needing a compound CCK field type.

If so, take a look at http://poplarware.com/articles/cck_field_module for a rather in depth discussion of how to write your own.

If you don't want to do that, the 3.0 branch of CCK for Drupal 6 apparently has a Multigroup Module.  Check out How to add cck custom date field? for discussions about that option.


views contextual filter by current year missing granularity In a view I need a contextual filter: all nodes with creation date in the current year.

In D7 i was able to provide the current date as default value and set a granularity for the date, e.g. the year.

In D8 I don't have any options to granular configure the filter.

Is there any other solution to set this contextual filter?

I think you need to use specific granularity field that you wish to add.
like there are multiple option given in contextual filter which are as under.

Created year >> Content Date in the form of YYYY.

in that field you can specify in "Provide default value"  as "current date".


How to override limit of only 10 items showing in Create an Order page in Drupal Commerce? On the Create an Order page (/admin/commerce/orders/add), my client is not able to see more than 10 items in the dropdown when using the 'Add Line Item' for a Product.  I can see that in the commerce_product.module that the function function commerce_product_autocomplete() is limiting with the following line:

// Get an array of matching products.
$products = commerce_product_match_products($field, $instance, $tag_last, $match, array(), 10);

..but how can this be overridden? Trying to implement a change in a custom module does not seem to be read by the system. Can anyone explain why this is, and how it can be changed?

Any help is greatly appreciated. Thanks!

This should be the screen you are referring to yes?

The field here is an auto complete field that is widely used in Drupal Commerce.  And yes the hints are limited because if they were not limited then the AJAX call could take a very long time to run.  You have to keep typing to narrow down your options in the provided guesses.

Short answer: No you cannot change this without hacking Commerce.

Long answer: To change this would require a lot of work because the create order form (/admin/commerce/orders/add) is built by attaching fields from the entity. Specifically here is the code that creates the form in the image above. So in order to change this you would have to alter the field types of the order entity. Specifically the Product SKU field would have to be altered and it's call back replaced with one that would load more than 10 items.  Doing so would of course alter Commerce and any upgrade you did to Commerce would erase your alterations.

// Add the field related form elements.
$form_state['commerce_order'] = $order;
field_attach_form('commerce_order', $order, $form, $form_state);

This uses field_attach_form to attach elements to the existing form based off the entity, in this case the entity 'commerce_order'.


Random product variations "not available" Of ~800 Commerce product variations, ~30 are not available for purchase on their respective display pages. These offending variations are completely set up like their brothers & sisters, Title, pricing, sku, and status. I see nothing wrong with them, through the /admin/ gui. But when visiting the display pages, for these offending products, Add to Cart is displayed as Product not available.

I can't find any information online concerning a similar problem. I'm also novice enough, to not know the best way to go about solving this issue.

Drupal and Commerce are the latest versions. If there's any other information I can offer, please let me know.

In my case it depended on which variation I physically have first in the variation list. If the product I have first in the variation list has a price and positive stock number, then I get an Add To Cart button for all variations.

If the product I have first in the variation list does NOT have a price greater than $0 and positive stock number then for ALL variations I get "Product Not Available".

So for me physically dragging and changing the order of the variations is what changed whether I saw Add to Cart, or Product not Available - I had to have an eligible product listed first in the variation order.

The only catch is, it allows you to click the Add To Cart button on products that are not eligible for checkout, however it does not add anything to the cart or functionally mess things up.

Naturally I would prefer the Add To Cart button change dynamically depending on the status and info of that variation, but technically this works.


URL alias for File field on a Content Type I have a File field on one of my content types and I'd like a URL alias for downloading that file regardless of how many times the actual uploaded file has been updated. Any advice?

I've been looking into the Attachment Links module as it accurately describes what I want to do, but it seems it isn't actively being maintained. Is there a community best practice for this type of functionality before I run with Attachment Links?

Well attachment links module does exactly what you want, this module is still being maintained, the fact is that there is not a new stable release for this module, but the manteiners are solving issues in the issues queue, and they commit changes to the 7.x-1.x-dev download that version and you will see it works like a charm. Check also Upload replace module is good also use the 7.x-1.x-dev version of this module. Both modules are for the same purpose but they do it in a different way.


Listing Polls and choices on same page I have couple of polls, I want all of them on one page.
Like this:

Any clue?

You can use Views to do this . create a view of poll and show display as content (full content) not field and you're done


Make Openlayers center & bounds context aware I'm creating geospatial database for multiple municipalities. Each should be able to work in it's own context (not only see only own data, but also have custom center & bounds for input and output maps).

I tried to find this functionality in OpenLayers module, but wasn't successful. I only found "zoom to layer" functionality, which isn't applicable, because there will be different layers for each municipality.

The most straightforward way I can think of is using geofield-defined bounds in user entity, which OpenLayers could use.

Do you know about any solutions?

I figured it out. The key is adapting https://drupal.org/node/904898 by switching Geo Taxonomy to Geofield or Postgis for Drupal 7.


How do I theme the user profile? I would like to create a custom template for the user profile view. With the help of "Theme debug" I figured out that I need to create a template named html--user.html.twig, but even if I copy all content of page.html.twig to my new template, I do get a blank page for any user profile now. Can anyone tell me what I'm doing wrong? I cleared all caches though.

Which content do I have to copy to a custom template (suggested file name)?

html--user.html.twig would be the template file used instead of html.html.twig when viewing a user profile (for example, for http://example.com/user/1). It is not the template file that shows the content of a user profile, but it's the template file that contains the basic structure of a Drupal page; in fact, its default content is the following one.

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

page.html.twig is the template file for a generic page; that is why you are getting a white page for user profile pages.

The template file for a user profile is user.html.twig, and its default content is the following one.

<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

As you see the variable it receives are completely different from the ones the other two template files (html.html.twig and page.html.twig) receive. That is why using the wrong template gives you a blank page.


Replace token by value in mail I sent an email in a function.

My email body is like "Hello [user:name], blablablala --  Team [site:name]".

But the token aren't replace by their values in the email.

What's wrong ?

Cordially

You need to run token_replace on the email body and pass in the user object for the target user. In your function:
$global $user;

$emluser = user_load($user->uid);
$body = "Hello [user:name], blablablala -- Team [site:name]";
$body = token_replace($body, array('user' => $emluser));

You don't need to pass anything for the site tokens to be replaced.


How to remove all the divs inside the $widget of a views exposed filter? I need to remove all the divs inside the $widget of a views exposed filter. I need only the single form fields without any html around it.

I don't know PHP.

Any suggestions?

Go to the modules directory and look for the 'views' module.

There is a 'theme' folder within this.

In the theme folder, copy the 'views-exposed-form.tpl.php' file to your theme.

You can then edit the template as you require.

Note, when you copy a file like this you will want to clear caches for this to work.

*****UPDATE*****

To edit specific components of the form I suggest you override the following function in your themes template.php file.

template_preprocess_views_exposed_form(&$vars)

This can also be found in the views module folder 'theme.inc'.


Add JS to specific pages AFTER all other JS I am working with JSON to theme Google Maps in the api v3.

I have my custom JSON script as an external JS file, and I am currently referencing it in html.tpl.php after the other scripts are loaded. This works great, and maps are themed, but on any pages that don't have a GMAP on them, i get the following error in Dev Tools...

  "Uncaught TypeError: Cannot call method 'addHandler' of undefined"

So I am trying to add the JS file to just the pages that have a GMAP, in template.php I use the following under the MY_THEME_preprocess_page function.

  if (isset($vars['node']) && $vars['node']->type == 'venue') {
      drupal_add_js(drupal_get_path('theme', 'MY_THEME') . '/js/mapstyle.js');   }

This loads the JS for all pages that are of the content type "Venue". The problem I am having is that the JS file is loading BEFORE the gmap scripts, and the style is not being rendered.

How do i get a JS file to load after all of the other scripts? I also need to load the JS file on a views page mysite.com/venues , but as a views page doesnt have a "node/id" alias, I am struggling to figure out how to only load the JS on that page using template.php

Using the following in my template.php file for my theme, I achieved what I wanted to do.

function MY_THEME_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'venue') {
    drupal_add_js(drupal_get_path('theme', 'MY_THEME') . '/js/mapstyle.js',
    array('weight' => 15));
  }
}

I couldn't add the JS to my .info file as it would add to all pages, so I used the drupal_add_js fallback in template.php, and the now the error no longer shows on a page that doesn't have a GMAP on it.


How to implement arbitrary editable content areas I'm trying to figure out the best way to implement pages with multiple editable content areas, each area on each page having a different set of HTML markup. The only solution I've found so far is to add a content type for each area so that I can create a custom block.

For example, on the homepage I have a mantle with image, title, and content:

Here's some example HTML I'd like to use for the structure of the editable content:

<?= $title ?>

            <?= $content ?>

I'd like for the user to be able to edit the image, the title, and the content, without editing the HTML that makes up the structure of the page. Each page on the site will have a different HTML structure, as well as different content areas that need to be editable.

Take a look at the Panels and Panelizer modules; they'll provide the basic building blocks you need for the kind of layout and editing experience you want.

They'll let you create arbitrary layouts (Panels comes with a few...creating new ones is easy) and embed panes of content including just custom HTML (called a custom content pane) at arbitrary URLs or, using Panelizer, by customizing individual nodes on a per-node basis.

Use the Fieldable Panels Pane (FPP) module, or the Bean module, to let you define fieldable components that can be placed into a layout using Panels or Panelizer.  So you could create an "image" FPP that has a field for a user to attach an image.  You would then control the actual rules for how that image is output, and the markup that surrounds that image, by configuring the view modes for that FPP.  Rinse and repeat for all the different sorts of elements you want users to be able to create.


How to use drupal_add_tabledrag() with paging feature? I have set up a table to reorganize content based on custom weight field. Everything works well without pager.

But if I add a pager to the form, only the items displayed will be reorganized - causing conflicts with items in other pages. Why drupal_add_tabledrag doesn't consider only the weight values that are in the current page. This would avoid any item in current page to take the same value as an item in another page.

The Taxonomy Core module do it perfectly. For example in the form where you can reorganize terms, there is a pager (admin/structure/taxonomy/[vocabulary]):

In Taxonomy form, when there are several pages, the last item of a page will appear in in first in next page (so user can drag & drop either against next items or/and previous items)

How can I do the same in a custom form?

/**** EDIT ****/

Due to @Aneek Mukhopadhyay answer, I updated my post.

Actually the issue is not related with pager, but drupal_add_tabledrag(). The pager is working well.

The drag & drop feature too. The problem is that when reorganizing content in a page, some items will take a weight value already used by another item (in another page).

For example here is the first page of my form (before dragging any item):

And the second page:

If I move the item "Test 11" for example, new weight value for the item "Test 2" will be 2:

And the weight value 2 is already used by item Test 1 (in second page)

To achieve that I used drupal_add_tabledrag() this way:

drupal_add_tabledrag($table_id, 'order', 'sibling', 'example-item-weight');

I tried several options with drupal_add_tabledrag() but didn't find any other way to make it working without issues.

I also checked the taxonomy module but cannot figure out how they work with drupal_add_tabledrag().

This can be done. If taxonomy module does it then its doable isn't it? So to do that you have to mainly follow 2 functions.

function taxonomy_overview_terms(..) in line # 249 @ /modules/taxonomy/taxonomy.admin.inc
function theme_taxonomy_overview_terms(..) in line 548 @ /modules/taxonomy/taxonomy.admin.inc.

The first function is the form that generates the list of items present in the term listing page. (The screenshot you attached)
The second function is the hook_theme implementation of the prior function and adds the table drag functionality to the page. If you look closely, the form has navigational steps added in it and then in the theme function they are made available for JavaScript to handle the back and forth navigation you mentioned. These are $form['#back_step'] & $form['#forward_step']. Those are converted to backStep & forwardStep and added to Drupal's JavaScript settings. So also you have to look at the taxonomy.js in where these are called and handled.


Enable DropDown using Ajax Call As given in the code below, I tried enabling select list $form['answer']['answer1'] through AJAX callback, textbox is getting populated with value, where as the dropdownlist is not getting enabled. Any help?

function mymodule_search_block_form($form, &$form_state) {
  $options = array();
  $options['key1'] = t('value1');
  $options['key2'] = t('value2');
  $options['key3'] = t('value3');
  $options['key4'] = t('value4');

  $form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $options,
    '#ajax' => array(
        'callback' => 'ajax_select_callback',
        'wrapper' => 'profile-wrapper',
        'event' => 'change',
    ),
  );

  $form['answer']['profile_name'] = array(
    '#prefix' => '
',
    '#type' => 'textfield',
    '#title' => 'Profile Name1',
  );
  $form['answer']['profile_name2'] = array(
    '#type' => 'textfield',
    '#title' => 'Profile Name2',
  );
  $form['answer']['answer1'] = array(
    '#type' => 'select',
    '#disabled' => 1,
    '#title' => 'Profiles',
    '#options' => $options,
    '#suffix' => '

',
  );
  return $form;
}

function ajax_select_callback($form, $form_state) {
  $form['answer']['profile_name']['#value'] = 'Profile 1';
  $form['answer']['profile_name2']['#value'] = 'Profile 2';
  $form['answer']['answer1']['#disabled'] = 0;
  return $form['answer'];
}

Interesting question. The way I see it there are actually two parts to this. This first is, of course, your actual question and that can be easily solved:

// Your code in ajax_select_callback().
unset($form['answer']['answer1']['#attributes']['disabled']);
$form['answer']['answer1']['#disabled'] = 0;
// More of your code in ajax_select_callback().

When you set the #disabled property of a form element to TRUE, what Drupal does is simply add the disabled attribute to the element and allows the renderer (i.e. drupal_render()) to do its job. In your AJAX callback, the $form array passed is that of the rendered form. This means that the your dropdown element already has the disabled attribute on it. Therefore, when it is rendered again, it still shows up disabled. So, to prevent this, we simply remove the attribute.

However, you'd notice that when you submit your form after this, the value of the disabled dropdown (in $form_state['values']) may not be the value you chose after "enabling" it. This is because your form is not being re-built on the server which means that Drupal still thinks your dropdown is disabled and will refuse to process your input, simply ignoring it and using the default. If you are able to reproduce this, comment on this answer and I'll update this post with a solution for that problem.


Field sort random via PHP I have a image field and use on cycle.

field.tpl.php:

<?php
?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

My field items sorting default alphabetical but i want random. How can i do this?

EDIT: I find this codes, it valid for me? And how can i use this code for my field?

function my_theme_preprocess_field(&$variables, $hook) {
 if($variables['element']['#field_name']=="field_project_release_packages"){
 usort($variables["items"], "_my_theme_sort_package_list");
 }
}

function _my_theme_sort_package_list($a, $b) {
    return $a["#title"] > $b["#title"];
}

You should be able to use template_preprocess_field() and shuffle() to do this. This is an example randomizing the entries in field_photo for a theme called dummy:

  function dummy_preprocess_field(&$variables) {
    if ($variables['element']['#field_name'] == 'field_photo') {
      shuffle($variables['items']);
    }
  }

You could also try to replacing you call to usort() in your original code with shuffle($variables["items"]).

The above isn't tested, but I think it should work.


How can I set a flag to be flagged unlimited number of times? I have a flag on a node that anyone can flag. The flag is tied to a Rule that executes an action. Essentially I need to be able to allow any user to flag a node as many times as they wish and track the flag count.

The problem: It appears that with the Flag module, the flag needs to be unflagged for the user to be able to flag it again. This essentially makes the flag count pointless as they are adding, removing and re-adding the same flag over and over.

As Triskelion mentioned, the Flag module might be the wrong tool for your use case. Despite that, if you're looking to allow multiple flagging (instead a flag/unflag toggle) you can add a Unflag a Node action (or whatever your flagged entity is) to the other action you have on a flag event.


Switch between databases I was wondering if it is possible to switch between different databases on one Drupal installation.

I have a different DB which another application uses it. Both DB are on the same server (localhost) and I was wondering if it is possible to temporarily connect to that DB in order to READ and WRITE data from/to it, using Drupal.

You can, of course, use the database API that comes with PHP.

To use Drupal's database API, configure your databases as described in How to connect to multiple databases within Drupal and use db_set_active() to switch between databases.


Displaying node reference select list as ordered menu list I want to display the Node Reference Select List (usually a long list of nodes, unordered and generally quite long) as an ordered bunch of nodes, that replicate the structure of the menu system.

The whole idea, is for a user to be able to choose another Node, but as there are so many nodes already on the website - it can be difficult to find the correct one in the select list. I have attached a screenshot to show a random example of how I would like this to look. This is just a quick mock-up image that I hope can be achievable.

The new "menu style" select list makes it easier to find the particular nodes you want, as they mirror the menu system of the website.

I looked into using Views to replicate the structure of the menu in Drupal, but this doesn't seem possible either. If this was possible, I could simple use the "Advanced - nodes that can be referenced" and just list out the pages by the menu with the order - but it doesn't look possible to integrate Views and the drupal menu system.

Any help would be excellent with this. Thanks, Garry.

You can use view to display all node you want and use expose filter to search for a specific node
or to display as tree
I guess there is a module to display taxonomy as a tree reference to make it like parent and child
so you can convert your node to be taxonomy to easy make it as a tree or change the module structure to display nodes


Small problem with Facebook Autopost module / Facebook App I have installed the Facebook Autopost module after setting up my Facebook App. When I add a new content, my rule should post it to facebook, however I get the following message:

Facebook SDK threw an error: OAuthException (#200) The user hasn't authorized the application to perform this action

Do you know what I have or haven't done correctly and how I could resolve this? I think it's something to do with permissions or something in my Facebook App?

Thanks

I managed to fix this by setting appropriate permissions for each role under /admin/config/services/fbpermissions


Create custom front page without adding content I am trying to create a custom welcome front page, it should contain two parts (left block and right block).

Each block has a background image (editor can upload), a logo (1 logo for each block), a description text...

Creating a new content type, is not a good idea in my opinion, because I don't like editors to add as much as they want nodes of that content type, so it should be only one content the editor can edit it each time he want to edit the background or logo...

I am thinking of creating a new setting form for this specific front page content containing those fields in a custom module. In this case, can I use picture module to make the background load a responsive image and not the default one uploaded by the editor ?

Thanks in advance.

In your case, yes you can create settings form, where admin will load background images, logo and enter description. But why you want use picture module? You can define new variables in hook preprocess_page for front page. Where in variable you put url to background image, url to logo, descriptions. After in front page template file, set url background to our block, logo and place descriptions.
Finally add styles to block class or id in css file for align background at the block. For this you can use something like this:

.your-class {
    background: transparent url("path/to/background.jpg") no-repeat scroll 50% 50% / cover;
    width: 100%;
}

background url you add in template. I write path to url in code for quick example, you can place this code in some div, add correct url and see result.


Wrong time value in a date field I've got a Date field in Drupal that I want to preprocess. Unfortunately

$node->field_date_time->value;

Gives me a value off by one hour (8:00 when expected is 9:00). I believe the issue has something to do with the way Drupal stores the date vs how it displays it later (taking into account Timezones). I tried passing in the default timezone to the DateTime object but that didn't help. I also tried using the \Drupal::service('date.formatter') to format the date but the result is still off.

When debugging I found that by using:

$node->field_date_time->date

I can see the expected date under a protected DateTimeObject property (see screenshot).

Does anyone know how to extract it or maybe there's something else that I'm missing? I'm running Drupal 8.1.9

When displaying a date field, Drupal typically converts it to the timezone of the currently logged in user. If no user is logged in, the site's default timezone is used. Perhaps you're logged in as a user that has a different timezone set?

Also, note that the time is internally stored as UTC, so you'll see a time that is off by an hour when simply printing the date's value or using a debugger. If you want to print the time in the user's timezone, try something like:

\Drupal::service('date.formatter')->format($date->getTimestamp());

This will use the user's timezone, or fall back to the site's default timezone.


Programatically create a new role I am trying to create a module which will easily allow me to set up basic sites with specific settings on the fly for a project I'm working on. I am having trouble creating a new user role. I have tried the following code within hook_update_N(), but it doesn't seem to work.

$role = new stdClass(); // create your Class
$role->name = 'editor';
user_role_save($role);

How do I programatically create a new role?

$roles = array('role1','role2','role3');
foreach($roles as $name) {
 $existing_role = user_role_load_by_name($name);
 if (empty($existing_role)) {
  $role = new stdClass();
  $role->name = $name;
  user_role_save($role);
 }
}

I have placed the same snippet in module install file and it is working just fine. You need to enable and then uninstall the module and re-enable it, I hope it will work.


Facet pages bring site down because of bots We have a search page that uses facets and recently our website has been going up and down.  When looking at the logs I noticed that bots (Bing, Ahrefs, etc..) are hitting these facetted pages a lot.  Since the facetted pages are not cached I think it is causing this issue.

I did add Search-specific caching but that did not help.

I have seen these related issues with caching and facets:

facets will disappear, when you enable caching for a views page
Facet blocks not displayed with cached Search API View
Facet blocks disappear when Views caching is enabled

Has anyone else ran into an issue like this?  For now I blocked all bots from accessing the facetted urls (so they will still be able to see the main search page).

For example, my facet page path starts with /library.  I created a Firewall rule in Cloudflare to block anyone visiting a page that contains /library/ so a facet result page like /library/xxx/bbb/ccc and is a known bot will be blocked.


how to distingush multiple ajax submit in single ajax callback I trying to do add more functionality for adding video urls which I am able to do by using Ajax callback.I am referring a drupal examples for it.It has one remove one button which removes last created text field from form. But I want a remove button for each text-field to remove it.

I am creating textfields and remove button in form hook like

for ($i=0; $i < $form_state['num_names']; $i++) {
        $form['names_fieldset'][$i]['title'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('Video Title'),
            '#default_value' => $webinar_videos[$i]->title,
        );
        $form['names_fieldset'][$i]['url'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('Video Url'),
            '#default_value' => $webinar_videos[$i]->video_url,
        );
        $form['names_fieldset'][$i]['remove'][$i] = array(
            '#type' => 'submit',
            '#value' => t('Remove'),
            '#submit' => array('webinar_add_more_remove_one'),
            '#validate' =>false,
            '#ajax' => array(
                'callback' => 'webinar_add_more_callback',
                'wrapper' => 'names-fieldset-wrapper',
            ),
        );
}

Now a 'webinar_add_more_remove_one' submit callback is like

function webinar_add_more_remove_one($form, &$form_state) {

    if ($form_state['num_names'] > 1) {
        $form_state['num_names']--;
    }
    $form_state['rebuild'] = TRUE;
}

and 'webinar_add_more_callback' this callback returns a wrapper element like

function webinar_add_more_callback($form, $form_state) {
    return $form['names_fieldset'];
}

My question is How I can pass a video id to particular remove submit button so that I can delete particular video in 'webinar_add_more_remove_one' callback?

Thank you in advance

Any help appreciated.

Last time I had to do this I used this method:

When creating the form create an array to hold deleted ids:

$form_state['deleted_items'] = array();

And give each remove button an ID relating to that items index:

$form['names_fieldset'][$i]['remove'][$i] = array(
    '#type' => 'submit',
    '#value' => t('Remove'),
    '#submit' => array('webinar_add_more_remove_one'),
    '#validate' =>false,
    '#ajax' => array(
        'callback' => 'webinar_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
    ),
    '#attributes' => array(
        'id' => 'item-'.$i,
    ),
);

Then in webinar_add_more_remove_one check the id of the button that was pressed:

function webinar_add_more_remove_one($form, &$form_state) {
    $form_state['deleted_items'][] = str_replace('item-', '', $form_state['clicked_button']['#attributes']['id']);
    $form_state['rebuild'] = TRUE;
}

And then when building the form check the array of deleted items:

for ($i=0; $i < $form_state['num_names']; $i++) {

    if(in_array($i, $form_state['deleted_items']) continue;

    // rest of code....
}

You will also need to check the deleted item array in the submit and validate functions as we don't actually removed the deleted item from the $form_state array.


Convert Database object into database URL string I've define my own database connection in my Drupal settings file as follow:

$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal',
  'username' => 'root',
  'password' => 'root',
  'host' => 'localhost',
  'prefix' => '',
);

To read that in Database object format, you can run:

drush eval 'print_r(Database::getConnectionInfo("default", "migrate"));'

And now I would like to have the string representation (similar to $db_url in Drupal 6) to use it in some drush commands on that database e.g. drush --db-url=${DB_URL} status.

So I would like to convert above Database array format into database URL string format (e.g. mysql://root:root@localhost/drupal).

Is there any easy way of doing that via function, PHP code or drush?

Additional info:

There is update_parse_db_url() function, but it's converting database connection URLs and return D7 compatible array.

Using Drush:

drush sa @site --with-db-url

Or, to isolate just the db-url:

drush sa @site --with-db-url --format=csv --fields=db-url --field-labels=0


How do I export data into yaml with mapping? I am exporting module's libraries from PHP in modulename.libraries.yml. I am using the YAML parser.

\Drupal::service('serialization.yaml')->decode($data)

The issue I have encountered is that I cannot indicate JavaScript or CSS files to be minified because instead of filename: { minified: true } I will end up with the following.

filename:
  minified: true

Basing on a brief IRC chat, I get this is not possible. Is that correct? If it is so, is this a bug? Differently, can anybody tell me how can I achieve this?

Those two are semantically the same thing. The only difference is that the {} format is more compact.
See the output in these two links.

Regardless, the second argument to the dump method lets you configure the verbosity of arrays. See Writing YAML Files.


Combining two node forms: is that possible? I am using Drupal 6 and I got a node form for a content type. I want to alter the other content type node form inside the first one; is that possible?

You can also use Flexifield to get 2 content types on the same form.

Like docs says:

  You define a field combination by creating a node type and adding
  fields to it. On a different node type, you can add a flexifield, and
  then on its configuration form, specify which node types to use as
  items within the field.


Redirect users to an external URL Is it possible to redirect users from a controller?

I tried using the following code, but it doesn't work.

public function hello() {
  $query = $db->select('coop.oad','x');
  $query->fields('x', ['oad_url']);
  $query->condition('x.oad_soc', $column_name,'=');
  $result = $query->execute()->fetchField();

  return new TrustedRedirectResponse($result);
}

This should do it:

$redirect = new TrustedRedirectResponse($url);
return $redirect->send();


Feedback module block doesn't follow visibility rules I'm using the Feedback module on my Drupal 6 but I found out a strange behaviour about its block's visibility.

The module appeared even if the block was in the disabled region, not assigned to any site space, and moreover it still appears even if I set for example a PHP code which returns false, or if I set it to appear only on listed pages without giving it any valid page.

If I move the block to different regions it still appears on the bottom right corner, so I have no control on how it works.

Am I missing something or is it a wanted feature of the Feedback block to be always there?

Wow.  It's pretty snarky, for no better word, and does the following...

/**
 * Implementation of hook_footer().
 */
function feedback_footer($main = 0) {
  if (user_access('access feedback form') && $_GET['q'] != 'admin/reports/feedback') {
    $block = (object)module_invoke('feedback', 'block', 'view', 'form');
    $block->module = 'feedback';
    $block->delta = 'form';
    $block->region = 'footer';
    return theme('block', $block);
  }
}

...which basically puts it on every page except admin/reports/feedback by stuffing the form into page.tpl's $closure variable.

So, yes, it does appear to ignore standard block visibility rules somewhat on purpose.