How do I programatically submit a webform via drupal_form_submit? Drupal 7, Webform 3

I want to programmatically submit a webform via drupal_form_submit. However, I'm having difficulty finding a $form_state structure that works. I've submitted my webform via the ui and examined the $form_state variable in my validate callback function, but I still can't get it to work.

My webform has one textfield named "first_name". Below is a snippet of code I've used to test. Whenever I run it, $form_errors is null. With no errors, I would expect the code to have worked.  However, when I check the webform results, it says there are no submissions.

<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

Am I doing it wrong?  Is there a better way?  Should I be using webform_client_form_submit instead?

I looked at this Q&A, but it doesn't work for me and seems a bit convoluted: How to submit webform programmatically with Ajax?

I used PhpStorm and xdebug to step through the form.inc code and finally found the correct structure for my $form_state.  The structure I posted was close, just needed to add the 'op' => t('Submit').  See my final working code below.

To answer my questions:

Yes, drupal_form_submit is what I should be using.
See code below for the magical $form_state structure.

<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
    'op' => t('Submit'),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>


hook_node_grants() implemented by a custom module is not invoked I am using the following code in a Drupal 7 module.

define('BNA_ACCESS_REALM', 'billetsalget_nodeaccess');

function billetsalget_nodeaccess_node_access_records($node) {
  $producttypes = array('internal_product', 'external_product', 'call_product', 'event_product');
  $grants = array();

  if (in_array($node->type, $producttypes)) {
    $grants[] = array(
      'realm' => BNA_ACCESS_REALM,
      'gid' => $node->nid,
      'grant_view' => TRUE,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  }

  return !empty($grants) ? $grants : array();
}

function billetsalget_nodeaccess_node_grants($account, $op) {
  dpm($account);
  die(var_dump($account));
}

hook_node_access_records() is working and running as it should, adding data to the database.
As far as I can see hook_node_grants() is never invoked. I have tried with all sorts of stuff in there, but it just looks like it doesn't even run.

It didn't have anything to do with my code. I'm new to Drupal so I didn't know hook_node_grants() don't get invoked when I'm signed in as an administrator.
Newbie mistake from my side :)


How do I add watermark to the image with insert module I use the combination of Wysiwyg and Insert modules to insert image.

How do add watermark while upload the image?

Can the watermark selected in certain taxanomy?

Your question is threefold:
Adding a watermark
For this, I suggest using ImageCache Actions module. Of the effects it provides, first one is:

Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

Selecting watermark
Image field does not know about taxonomy field when it decides how to render it's content. You could hack it together in your template. I would rather go for Formatter Field - not exactly what you described, but use case on module page seems to fit your needs:

For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Preventing original image from being downloaded
Drupal modifies user-provided content on display, not on save. This means your original image will be up there, without watermark. Image Style Access claims to be the solution:

This module provides access control for image files. Each access configuration can be set to allow or deny access to images and their derivatives by:

Disclaimer: I never used this one .


Force View to be displayed only in a specific domain I am using the Domain Access, Domain Access Views and Views modules.

I want to create a domain-specific view that will be displayed only in a specific subdomain of the website and if someone tries to access it from a different subdomain, he will be redirected to the proper domain.

So for example when a user navigates to:

http://www.example.com/myViewPath

or

http://customers.example.com/myViewPath

he should be redirected to:

http://blog.example.com/myViewPath.

Is there a way to do that?

One solution would be to use hook_preprocess_html()

function MYTHEME_preprocess_html(&$variables) {
  global $_domain;
  if (arg(0) == 'myViewPath' && $_domain['subdomain'] != 'blog.example.com') {
    drupal_goto('http://blog.example.com/myViewPath', array(), 301);
  }
}

Note that the global $_domain variable is provided by the Domain Access module.

Alternatively, in a custom module you could use hook_boot()

function MYMODULE_boot() {
  if (arg(0) == 'myViewPath' && $_SERVER['HTTP_HOST'] != 'blog.example.com') {
    exit(header('Location: http://blog.example.com/myViewPath', TRUE, 301));
  }
}


Specify a template for referenced nodes I was wondering how to specify a specific template for rendering a node when it's referenced from another content type.For example I have a content-type (product) and I use the node--product.tpl.php template to render nodes of this type. Then I have a content-type named container that have a node reference field that may related a number of product nodes.I would like to use a different template when rendering a product when the product is referenced from the container content-type.
I just installed the theme developer module and check suggested templates, I then created a new template named node-reference--product.tpl.php in the same folder as node--product.tpl.php but this file is only used if node--product.tpl.php is removed.
I guess one approach would be to use some kind of theme_preprocess hook and load a node based on the arg(1) value and then check if the type is container and if it is add a template suggestion in the $variables parameter.

The simplest thing you can do is provide a new "View Mode" for nodes, so that you can use it with the "Rendered Node" display option for the node reference field.

This would be done in a small custom module using hook_entity_info_alter() like so:

function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['node_reference_product'] = array(
    'label' => 'Node Reference Product',
    'custom settings' => TRUE
  );
}

Once the module is installed you'll have a new view mode under the "Rendered Node" display format options:

Now you can simply use the same node--product.tpl.php template file as normal and just test for the view mode to define what you want to display:

<?php if ($view_mode == 'full') : ?>

  <!-- HTML output for the full view mode -->

<?php elseif ($view_mode == 'teaser') : ?>

  <!-- HTML output for the teaser view mode -->

<?php elseif ($view_mode == 'node_reference_product') : ?>

  <!-- HTML output for your new view mode -->

<?php endif; ?>

Of course you still have access to the view mode in any hook_preprocess_node function so you could put your logic in there instead:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'product_node_reference') {
    $vars['content'] = array('#markup' => 'Some other content');
  }
}

But perhaps the best part of solving your problem this way is that Drupal honours the new view mode in the UI, so for each content type you will now have a new view mode which you can choose options for as normal:

Just like the standard full and teaser view modes you will be able to decide which fields are displayed, and the ordering and format in which they are displayed too. It's entirely possible that after writing that tiny one-function module you won't need to write another line of code to solve the problem.

You'll also have this view mode available system wide for use in, for example, Views/Panels etc.


How Can I send sms confirmation when user creates a new account in my website? Can I send sms confirmation when user creates a new account in my website?

How Can I? what modules I have to set for this?

Rules module will allow you to do something when something happens in the system. You can send email or sms when an account is created. This is a very handy module, you should have it.

In regards to SMS, there are a few options.

SMS Framework module
Messaging module
VoIP Drupal module

In regards to the SMS framework, I don't know how stable is the 7.x development release. You need to make some decisions here.

There are a tons of video/other tutorials on how to use Rules module, I recommend googling it and you will come across several sources. Do try the free videos provided by DruaplizeMe, they are very useful.


Is deactivating modules safe regarding settings? I had a strange error after uploading a module to a shared hosting server when going to admin/modules before even activating the module (image_desaturate_formatter).

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'sites/all/modules/image_desaturate_formatter/image_desaturate_fo' for key 'PRIMARY': INSERT INTO {system} (filename, name, type, owner, info) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => sites/all/modules/image_desaturate_formatter/image_desaturate_formatter.module [:db_insert_placeholder_1] => image_desaturate_formatter [:db_insert_placeholder_2] => module [:db_insert_placeholder_3] => [:db_insert_placeholder_4] => a:11:{s:4:"name";s:26:"Image Desaturate Formatter";s:4:"core";s:3:"7.x";s:7:"package";s:5:"Field";s:7:"project";s:26:"image_desaturate_formatter";s:12:"dependencies";a:2:{i:0;s:5:"field";i:1;s:5:"image";}s:7:"version";s:11:"7.x-2.0-rc1";s:9:"datestamp";s:10:"1356346648";s:11:"description";s:0:"";s:3:"php";s:5:"5.2.4";s:5:"files";a:0:{}s:9:"bootstrap";i:0;} ) in system_update_files_database() (line 2307 of xxx/htdocs/site/modules/system/system.module).

Now the update module isn't working anymore but just showing the following message, when I try to start the update process manually:

  Failed to get available update data for 27 projects.

Could the module upload error be related to the update module not working?
Is it safe to stepwise deactivate the modules to check if update isn't working due memory issues? Do I loose all the settings I've made?

EDIT/UPDATE:

I have limited access to server logs and there is a

  The timeout specified has expired: ap_content_length_filter: apr_bucket_read() failed

and the "reports" section doesn't show anything except the PDO above.

I now have disabled every module except core and tried to run update in between with no effort. The update module isn't working anymore. Is there something else i could do?

It's impossible to say from here. Theoretically yes.
It depends on the module - a specific module could easily clear its variables in hook_disable(), or hook_uninstall(), or not at all. You'll have to check the install file for each module you disable to see how it will affect what you're doing.

It sounds very much like you have two copies of the image_desaturate_formatter module in your Drupal install though; that could account for the error.

Regarding server logs - your host should give you access to these (I've never come across a host that would deny you access to your own logs, it's criminal!) so give them a call, they might have valuable information in them.


Is there any module to create a set of field without creating new entity field for each one? My objective is to have a module which gives me the option to create a entity field that can have multiple field values.

For example, the location module. It creates an entity field of type 'location' which can have a set of field values (country, province, city, address, etc.). In the database this module creates a table 'location' which stores all these values with a key 'lid'. The main entity field has a  'lid' value to connect with the set of values. And we are able to used tokens for all these field values.

I have tried Field Collection, Multifiefld, Composed Field modules, but none of those actually do this.

If the objective is to have one entity field that stores a primary key into a custom table schema, the answer is probably no. Location (and its associated Location CCK module) achieves this by its own widget form (via hook_field_widget_form) & element type (via hook_element_info). It creates various processing functions to store the data in its custom data schema. I think such a module you're describing would need to dynamically generate data schema and hook callbacks to achieve what you're wanting.


Update a field on a node after hitting save I am working on a Drupal 7 custom module and would like to update a field on a node after hitting save.  Based on some post that I have seen this should be possible.

As it is now I have the $node object is a parameter to the node_submit hook after hitting save.

However, I am not able to update my field on this node object.  Any pointers or examples of how to do this would be greatly appreciated.

Thanks,
Derek

Depending on your exact usage, you'd want to use either

1) hook_node_presave - Called on any node being saved (inserted or updated). see here

2) Attach a submit handler to the form: Allows to change the form's values before the submit is completed.


Displaying Price Ranges on Views Let's say I have 3 products in a product display that cost $5.00, $3.00, $7.00.

Right now in Commerce Kickstart 2, the view displays the first product's price which happens to be $5.00.

I would like the View to display the price range, $3.00 - $7.00, but only if there is a variance in prices (if all the products are $3.00 - just display $3.00).

I've done it using Display Suite code field like that:

<?php
$max['amount'] = 0;
$min['amount'] = 0;
$products = field_get_items('node', $entity, 'field_products');
foreach($products as $product) {
  $product = commerce_product_load($product['product_id']);
  $commerce_price = array_shift(field_get_items('commerce_product', $product, 'commerce_price'));
  if($commerce_price['amount'] > $max['amount']) {
    $max = $commerce_price;
  }
  if($commerce_price['amount'] < $min['amount'] || $min['amount'] == 0) {
    $min = $commerce_price;
  }
}
return $min['amount'] < $max['amount'] ? commerce_currency_format($min['amount'], $min['currency_code']) . ' - ' . commerce_currency_format($max['amount'], $max['currency_code']) : commerce_currency_format($min['amount'], $min['currency_code']);
?>


How to display (automatically in a field) all media that references this node? I have a content type, "Fruit". Using that content type I have created a "Bananas" node. It contains text and link fields that constitute "banana information".

I have media type, "Fruit Image", with a field, "FruitShown". Using that media type I have numerous images of bananas and other fruit.

On my Fruit pages, how can I display automatically in a field all images of bananas (i.e. All images of media type "Fruit Image" that have "bananas" in the "FruitShown" field)?

CONTEXT:
I believe I am able to display the banana images in a block using a View with a contextual filter. However I prefer to display the images in a field so that I can wrap the images around a "banana information" CSS float, not just place them in a separate rectangular block (which leaves empty space in my theme).

WHAT I TRIED:
I am able to display the banana images in a field by using an entity reference field with an entity reference view reference method, but when adding the "Bananas" node, the images must be selected manually one-by-one. I prefer all of them to display automatically.

Use the Views Reference Field module

When you've created your view, go to your node strcuture and create a field type using the module above. On node edit you then can select your banana view. This way your view is wrapped inside the same markup just like any other field of your node.


How to set page/content title/header from a controller I have a custom route and module that outputs content to a page.

I want to also have a page/content title/header on the page. I've figured out how to set the browser title, but I can't figure out how to add the headline title.

When creating a basic page with no custom template, the headline is part of that html. I want to replicate this.

Here is what I have in my controller:

return array(
    '#title' => 'This sets the browser title',
    '#markup' => 'This is the html output',
);

I've been banging my head on this for a few days now... help!

I've already tried setting $variables['title'] in theme_preprocess_page_title, but that doesn't seem to get called. I've also tried it in preprocess_page, but that does nothing.

To clarify - I am wanting to change the text that is by default displayed in <h1 class="page-header"> from within my controller.

You set the title in the route in the _title parameter:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title: 'Page title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

Or you can use a route callback:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title_callback: '\Drupal\mymodule\Controller\MyController::title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

And then put the title callback in the controller class, which receives the same parameters as the controller, so that you can determine a title on that information.


Drupal commerce order list view - payment status Is it somehow possible to add payment status and payment method to ordes list view?
I tried to use relationship inside orders list view but the commerce payment transaction is not available.
Thank you for help.

It's not impossible, but the amount of Views foo required to do it is beyond most mortals.

The tricky part is that an order can have many transactions, and also several which is completed. That is the data model would allow you to pay half by credit card and half by paypal. Also different payment methods might have different status for complete/incomplete payments. That logic is hard to build into a SQL query, which is the limitations of Views.

That said you could add a custom relationship from the order to the payment transactions and probably make something that can work. Doing this will require that you can create a module, know a bit about Views and have a lot of patience, unless you have done this type of thing before.


Drupal multi site 404s, sub directory site subpages going to default site We have a strange set of errors going on with a dev (and stage) version of our drupal multisite.
We have some sub directory sites, and some sites server up on different urls. One URL is an internal one to the Host. The other is an external one (that goes through a firewall).

The essence of the problem is this

the sub directory site homepage displays fine, but any sub pages you click through to come up as 404s -- the 404 that is thrown is on the default site. This happens with sub directory sites on both URLs (external and internal).
I am unable to access site pages using index.php?q=
Some pages that get served up properly, are still showing up as a 404. This doesn't seem consistent on all sites, but it seems weird to begin with.

What I know

The .htaccess is being used by the sites
ModRewrite is on.
At our request, the ISP put some restrictions on one of the URLs.
The same structure works fine on our production site (minus the restricted URL)
sites.php is working fine, so far as I can tell.

What are the things that we could still have configured wrong (our hosting company is equally perplexed)? The problem seems to coincide with locking down the internal URL (to be only visible to VPN).

For now, I can share this URL: http://contentdev.sierraclub.org/coal
Click on a sub link.
Compare to http://content.sierraclub.org/coal

Any ideas would be very much appreciated.

You didn't mention anything about sites.php, so I'm going to guess that's where the problem resides.

Google it: https://www.google.com/#q=drupal+multisite+sites.php
D7 example: https://api.drupal.org/api/drupal/sites!example.sites.php/7.x
D8 example: https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x

Please post your sites.php file if you're unable to fix the issue after taking a look.


Refresh button instead pager in views Recently I developed a cg related image gallery with drupal, here: http://cgart.ir/en.

top rated images displayed in quicktabs and provided by views. I need a refresh button instead pager. currently I theme next link as refresh button and hide previous link.

how can I add refresh button in views?

What you could do is hooking into the pager function and changing its functionality in that page.

I would also recommend using mini pager instead of pager since its much shorter and easier to manipulate.
take a look  here
and here


How to fix sorting by node title in glossary View when viewing page in non default language? There is ton of materials how to do it in 7, but I was not able to find or adapt based on those solutions.

My View has fields:

Content: Title
Title first letter [hidden]

Filters:

Content: Publishing status (= Yes)
Content: Content type (= Basic page)
Content: List page in glossary (= True)

Sort criteria:
- Content: Title (asc)

Relationships:
- Node

Rendering Language:
Interface text language selected for page

When viewing page with default language (which is a source language for a nodes) sorting is working good. After switching language sorting not working well, seems like it's based on source translation content every time.

Generated SQL:

SELECT node_field_data.title AS node_field_data_title, node_field_data.nid AS nid, node_taxonomy_index.nid AS node_taxonomy_index_nid
FROM
{node_field_data} node_field_data
LEFT JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
LEFT JOIN {node} node_taxonomy_index ON taxonomy_index.nid = node_taxonomy_index.nid
LEFT JOIN {node__field_glossary_enabled} node__field_glossary_enabled ON node_field_data.nid = node__field_glossary_enabled.entity_id AND (node__field_glossary_enabled.deleted = '0' AND node__field_glossary_enabled.langcode = node_field_data.langcode)
WHERE (node_field_data.status = '1') AND (node_field_data.type IN ('page')) AND (node__field_glossary_enabled.field_glossary_enabled_value = '1')
ORDER BY node_field_data_title ASC

Now you get view rows for the original language and sort them still untranslated, because you translate them later when rendering.

You need to filter the rows for the current language to be able to sort the translated titles:


Access denied on hello world custom module Drupal 8 installed in Debian VPS server.
Some installed themes do not work, some do.
When tried to creat a simple 'Hello World' module,as described in a beginners book for drupal, installing of the module was fine; but when trying to open :              www.my***site.com/hello/world i got "Access denied" message.
After installing drupal i treated permissions using this and its comments through the command : chown -R www-data:www-data drupal/

The hello World module creation:
in drupal/module created custom/ and contrib/ folder as well as custom/hello_world/. Within hello_world/ created three files hello_world.info.yml, hello_worl.module, hello_world.routing.ymland hello_world/src/Controller/HelloWorldController.php

hello_world.info.yml

name: Hello World
type: module
description: 'A basic Drupal 8 Hello World Module.'
package: Custom Modules
version: 1.0
core: 8.x

hello_world.routing.yml

hello_world_settings:
  path: '/hello/world'
defaults:
  _controller: '\Drupal\hello_world\Controller\HelloWorldController::
myCallbackMethod'
  _title: 'Hello World'
requirements:
  _permission: 'access content'

hello_world/src/Controller/HelloWorldController.php

<?php
/**
* @file
* Contains \Drupal\hello_world\HelloWorldController.
*/
namespace Drupal\hello_world\Controller;
/**
 * Provides route responses for the hello world page example.
 */
class HelloWorldController {
  /**
  * Returns a simple hello world page.
  *
  * @return array
  * A very simple renderable array is returned.
  */
  public function myCallbackMethod() {
    $element = array(
      '#markup' => '
Saying Hello World in Drupal 8 is cool!
',
    );
    return $element;
  }
}

upon  opening www.my****website.com/admin/hello/world i got Access Denied. Looking further into My**website.com/admin/reports/dblog/event/***5 i got just that it is an Access Denied and Warning in the security field.
Can anyone please explain what is going on?

The issue is with the indentation of the hello_world.routing.yml file. Simply change the indentation of it to:

hello_world_settings:
  path: '/hello/world'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::myCallbackMethod'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

And the Access denied issue should be solved. The indentation of YAML file is  important, in Drupal 8. It should be as follow:

path, defaults, and requirements should be indented by 2 spaces
_controller, _title, and _permission should be indented by 4 spaces


Delete/Edit selected record from rendered tabular form results I have made a form and retrive form submissions into a tabular format. I put 2 links ahead every single submission - Edit/Delete

Now, when I click "edit", its corresponding edit form should open. Similarly, when I click "delete", that particular entry should get delete from database.

I know it's pretty simple doing in php, but don't know how should i do in Drupal.
Please help.

Some code that I practiced: first I created a menu to show results of my form.

$items[MID_MENU_PARENT . '/component/show'] = array(
    'title' => 'Component List',
    'description' => t('Records'),
    'page callback' => 'component_list',
    'access arguments' => array('administer site configuration'),
    'file'=>'component_list.inc',
  );

/**
   * My callback function
**/
  function component_list(){
       $query = db_select('mid_components', 'n')
               ->fields('n')
               ->execute();
       $rows = array();
       while($data = $query->fetchAssoc()){
      // Fill the table rows
       $data['operation'] = l(t('Delete'), 'admin/mid-modules/component' . $data['cid'] . '/delete');
       $data['operation'] .= "|";
       $data['operation'] .= l(t('Edit'), 'admin/mid-modules/component' . $data['cid'] . '/edit');
       $rows[] = array('data' => $data, 'style' => 'word-break:break-all;',);
  }

 // Prepare table header
  $header = array( t('S.No'),t('Component Name'));
  // Output of table with the paging
   $output = theme_table(
     array(
           "header" => $header,
           "rows" => $rows,
           "attributes" => array(),
           "sticky" => true, // Table header will be sticky
           "caption" => "",
           "colgroups" => array(),
           "empty" => t("Table has no row!") // The message to be displayed if table is empty
         )
      );
  return $output;
}

 /**
   * Menu href to edir particular entry
 **/
    $items[MID_MENU_PARENT . '/component/%show/edit'] = array(
          'title' => 'Edit Component item',
          'page callback' => 'component_list_edit',
          'page arguments' => array(3),
          'access arguments' => array('administer users'),
          'type' => MENU_CALLBACK,
     );

Not sure what your real question is (there is no "question" in your question ...), so consider editing your question to make that clear.

But I would give it a try to add a / in front of the 2 (similar) lines containing admin/mid-modules/component (so that they are changed to /admin/mid-modules/component). So both for the "delete" and the "edit".


Where do I fetch myself complete definition for a bundle? I can fetch entity-type definition...

$entityType = \Drupal::entityTypeManager()
  ->getDefinition($this->entityType);

and I can fetch myself some of the bundle specific information...

if ($bundleName !== null) {
    $bundleConfig = $entityType->getBundleConfigDependency($bundleName);
    $config = HelperConfiguration::instance($bundleConfig["name"]);
    $configValues = $config->getConfigValue();
}

$configValues carries properties like description, preview_mode, display_submitted, even langcode, but what I cannot find, is how to find translatability status for a bundle.

On /admin/config/regional/content-language I can wonderfully manipulate translatability bulk-wise, from entity-coarseness, up to specific fields.

So, while there is an isTranslatable() method on EntityTypeInterface (and also onFieldDefinitionInterface), where is the bundle equivalent? Where is the rest of bundle's metadata hidden?

To get the language specific configuration of a bundle use ContentLanguageSettings::loadByEntityTypeBundle.

For the translatability of the bundle, you'd use:

$settings = ContentLanguageSettings::loadByEntityTypeBundle($entity_type_id, $bundle_name);
$isBundleTranslatable = $settings->getThirdPartySetting("content_translation", "enabled");

You could also use ContentTranslationManager:

/** @var ContentTranslationManager $contentTranslationManager */
$contentTranslationManager = \Drupal::service('content_translation.manager');
$isBundleTranslatable = $contentTranslationManager->isEnabled($entity_type_id, $bundle_name);


Drupal.behaviors js code executes mutiple times (depends on active modules) I have two almost similar websites (one was a test project) and second one is more like final version. On both of them i have quite simple custom module with js and on first web site it works fine, but on the second one - problem is that code in js executs many times (6-10 times), it depends on active modules - i uninstaled some modules and amount of times that js is execute drops down... js file is simple like alert("hi");   and it gets printed like 10 times... i gues that one module couse this issue but i dont know whitch one. maybe someone had such issues? or some advice on how to find out whats wrong.

once() may work in many cases. I've also used a flag like:

(function ($, Drupal) {
  let flag = false;

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      if (flag === false) {
        flag = true;
        console.log('This should only display one time.');
      }
    }
  };

})(jQuery, Drupal);

Please note that I only wrote this in this comment box from memory and didn't actually test this code.

Also FYI, the Drupal.behaviors is correctly running many times, since it is supposed to update every time some kind of state changes that would require it to update (like an AJAX call). So you do have to take extra steps on your side to ensure that certain code only runs once.


Avoid duplicate product while using variations I am new to drupal and fetching Drupal commerce variations from Views and the products are getting duplicated what would be the best way to avoid duplicate when using product variations. Here are the screenshots from views
http://puu.sh/vn1Po/75e158f5c5.png
Any help is really appreciated.

It sounds like you reference multiple products per display node, so adding that relationship results in multiple rows. A real easy solution is to filter by the delta value from your product reference field so that only the first referenced product results in a row being shown. Ideally we'd add another filter that let you filter by the default delta value, as that can differ from 0 if altered via code.

The filter you're looking for should read something like: Content: Product (field_product:delta) and you should set the filter value to 0. No need to expose it.


How do I use the GTranslate module? I have installed the GTranslate module, and I am searching for how to use it. In the module page, the language selection drop-down box is there, but when I installed this module the drop-down list didn't appear. How do I use the GTranslate module?

Google Translate changed their policy, this module does not work anymore according to the issue queue.

There seems to be a newer version on an external website, which also offers a paid Pro version that seems to require ioncube encoder which means that it is encrypted, which sounds like a violation of the GPL to me.


Show weight on the content screen Is is possible to show the weight select box on admin/content, rather than having to go into the node to edit it?

Weight Module Provides it : Read Documentation

  On the Content administration page (Administration » Content), there will be a "Weight"
  column containing a selector box to set the weight of any node with a content type that has been weight enabled.

And Here is a Comparison of Node/Entity Ordering Modules

To enable Weight for a content type, go to Administration » Structure » Content
types and select the content type you want to enable Weight for. Select the Weight
vertical tab, choose your desired settings, and click the Save button.

Now in admin/content you could see weight column


Unable to update content or enable / disable module via Drupal Admin once migrate to live server I have moved my website from local machine to live server, but after migration I can not save or update contents. After clicking on 'Save' button page refreshes without any changes. Also I can not enable or disable the drupal modules, and there aren't any errors displayed. Please help me out in this and do let me know solution in isolating this issue.

problem was server firewall called mod_security. It's purpose is to stop hackers from inserting mysql_query type commands into your website. So, I solved this problem by disabling the mod_security service.


D7 Related Nodes within a Content Type Please forgive me if this is a total noob question, but here it is anyway.

I have a content type 'person'. One of the fields I want to add to the 'person' is a relatives field and I want it to either be an autocomplete or a drop down list. I'm pretty sure I can figure that part out. The question is, how can I populate the drop down list (or the autocomplete) with the names of all 'person' content that is already created?

Also, I am using the persons full name for my title field.

I'm also running drupal 7 and I've installed the CTools and Views modules.

EDIT:

After some more thought on this, what I'm really trying to do is have a field that links to a related content node. That way if a person is ever deleted they would also be removed from those who claim to be related to them.

Does drupal have a way to do this? I have so many ideas on how to use drupal, but most of them involve relating nodes to one another in a heirarchal format.

I would look at the references module, this will allow you to manually set relationships between your "people".


How to efficiently check if taxonomy has children I am checking if a taxonomy term has children using taxonomy_get_children and I wonder if this is the most efficient way of doing it.
Since the function returns all the term objects, I believe it is not very efficient.

As arpitr says taxonomy_get_children() loads the child terms, so you are better of with a fork of this function.

I wanted to know whether a term a) is connected to any nodes and b) has any child terms.

/**
 * Helper function to check whether a term has no child terms and is not
 * connected to any node.
 *
 * @see taxonomy_get_children()
 */
function YOURMODULE_is_term_empty($tid, $vid) {
  $children = &drupal_static(__FUNCTION__, array());

  // Is term connected to node?
  if (!isset($children[$tid])) {
    // Get id's of connected nodes. Make query lighter by using no pager,
    // setting limit to 1 and sending an empty array with fields to order on.
    $node_ids = taxonomy_select_nodes($tid, FALSE, 1, array());

    if (!empty($node_ids)) {
      $children[$tid] = false;
    }
  }

  // Does term have child terms?
  if (!isset($children[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
    $query->condition('t.vid', $vid);
    $query->addTag('term_access');
    $query_result = $query->execute()->fetchCol();

    $children[$tid] = empty($query_result);
  }

  return $children[$tid];
}

NB: I did not make this work recursively.


Add/Fix composer in an ongoing project We are having an ongoing project on OpenSocial, which is a profile based on Drupal 8. The project was installed using composer. However, later several modules were installed and updated via Drush.

Due to this, the composer file and the actual application is not in sync. What would be the best way to get out of this situation? Is there any way to fix composer?

Try the Drush Composer Generate project. If you have your composer.json committed to a vcs, you can run composer-generate and then compare the results and fix up anything that it might mis-apply.


How do I choose a default theme if the theme gives a white screen? I tried to make a folder templates for all tpl files but after that now I can not load my theme anymore on Xamp? Now when I try to load theme in drupal there was only white screen.What can I do?
I am tired of that so if you just make one mistake in Drupal, you are need to install again and again.
I choose a different theme and I close the browser, but the theme is not working. How can I load a different theme if I don't have access anymore to Drupal?

You can update in database.

Change the active theme in the database

The default theme setting is stored in Drupal's database, and thus can be changed by manipulating the database from the command line or an administration overlay or client like PHPMyAdmin or MySQL Workbench for MySQL.

Always make a backup of your database before changing values in it directly, as it is possible to destroy data and render your site unrecoverable at the database level. You have been warned.

In Drupal 6 and 7, the setting is stored in the system table:

activate a trusted theme

UPDATE system SET status=1 WHERE name = 'garland';

change the default setting

UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';

clear the cache tables

TRUNCATE cache;
TRUNCATE cache_bootstrap;
TRUNCATE cache_block;

Another way

sites/default/settings.php:
$conf['theme_default'] = 'bartik';


Use CAPTCHA module on a custom HTML form? (no use of Drupal Form API) Is it possible to use the CAPTCHA module on a custom HTML form created in a content page of a Drupal 7 site?  I am not using the Drupal Form API or webform modules.  The form has the following code:

<form id="signup_form" action="[form action]" method="post" enctype="application/x-www-form-urlencoded">

<input id="firstName" tabindex="1" type="text" name="firstName" placeholder="First Name" value="" required />
First Name*

<input id="lastName" tabindex="2" type="text" name="lastName" placeholder="Last Name" value="" required />
Last Name*

<input id="email" tabindex="3" type="text" name="email" placeholder="Email" />
Email*

<input type="hidden" name="form_id" value="signup_form" />

<input id="btn-submit" tabindex="6" class="submit" type="submit" name="submitButton" value="SIGN UP" />

</form>

I'm trying to have reCAPTCHA displayed at the bottom of the page when there has been an X number of form submissions from the same IP address in a given amount of time.   I was hoping CAPTCHA After could work for my custom form -- I tested it on our site's Admin Login page (/user) and it worked great, of course.

I can't seem to get any CAPTCHA displaying on my custom HTML form page.  In the General Settings, I selected "Add CAPTCHA administration links to forms" and a drop-down with "CAPTCHA: CHALLENGE "RECAPTCHA" ENABLED" displayed in the content page where the form is coded.

Since the HTML id has nothing to do with $form_id... I referenced this Drupal Stack Exchange page, and haven't been able to generate the form ID...I'm wondering maybe my custom HTML form doesn't have a $form_id because it doesn't use any drupal form modules?  If that's the case, then I probably can't use the CAPTCHA module.  Could someone please confirm?

Perhaps I can't use any Drupal modules and may need to:

grab the user's IP address from the header via PHP:

$ip_address = $_SERVER["REMOTE_ADDR"];
store this IP address in some sort of database and add a timestamp
delete any IP address entities in that are over an hour old
count the number of data store entities via loop and if the same IP address appears a certain # of times in a given amount of time, then display reCAPTCHA

Any guidance would be great.  Thank you!

I'm wondering maybe my custom HTML form doesn't have a $form_id because it doesn't use any drupal form modules? If that's the case, then I probably can't use the CAPTCHA module. Could someone please confirm?

Correct - the Captcha module has been written exclusively for integration with forms built by the core form API. Without a lot of changes, it's not possible to use any of its functionality on a form that hasn't been built by Drupal.


How to pass a variable $ _ GET in a page? I will wish to create a privileged space for some users.

I create a role 'Candidate'. I assigned permission 'access user profiles' has this role.
I create a user that uses this role. (eg, foo)

Secondly, I create a menu (see below)

$items['candidate/%candidate'] = array(
  'title'            => t('My candidate space'),
  'description'      => '',
  'page callback'    => 'cel_configuration_custom_page',
  'page arguments'   => array(1),
  'access arguments' => array('access user profiles'),
  'access callback' => TRUE,
);

Then a linked function

function cel_configuration_custom_page($args){
  return 'custom';
}

Finally, I have emptied the cache.

When I go on the candidate/1 page with my account 'toto' or account 'admin', I have not found page.

Why?

Try the following code:

    $items['candidate/%user'] = array(
      'title'            => t('My candidate space'),
      'page callback'    => 'cel_configuration_custom_page',
      'page arguments'   => array(1),
      'access arguments' => array('access user profiles'),
    );

    function cel_configuration_custom_page($account){
      return 'Custom page for ' . $account->name;
    }

You can't use %candidate as an argument for user accounts. Also, if you want to restrict access by a particular permission, don't set access callback to TRUE as that will grant access to everyone.


Filter by postal code as location within user defined radius I have to make a filter in which user will add postal code and select a radius.
Suppose, user entered postal code = 12345 (which results into city 'XYZ') and the radius of 200 miles. So all nodes containing the location within the radius of 200 miles of the city 'XYZ' will be the output.

Can anyone suggest some solutions?

geofield should have what you're after.  It includes proximity handling and an exposable views filter.


Set Views page title based on content being viewed via contextual filter I have a view page that shows a single node based on a contextual filter that looks at an aliased path version of the title. For example my URL might be
http://www.tacoland.com/resources/npr-story-about-tacos
and I want to set the page title to be NPR Story About Tacos (the node title).
I see how I can change the title with the value from the URL within the contextual filter settings, but I want it to be the proper node title.
My issue is basically like this one, but for D8: Views Page Title Based on URL

Add Title as field

☑ Checkmark exclude from display

For view title, put {{ title }}


read new menu link id (mlid) before new menu item is saved I'd like to do something with menu links when they are saved.

I can use hook_menu_link_alter():

function my_module_menu_link_alter($item) {
  my_module_do_something($item);
}

This seems like the best and only hook I can use here. Only, the my_module_do_something function requires $item to have the mlid propety (menu link ID) set, and when a new item is being saved, the property doesn't exist yet.

I can fake it by querying the database for the most recent mlid value and incrementing 1:

$item['mlid'] = db_query('SELECT mlid FROM {menu_links} ORDER BY mlid DESC LIMIT 1')->fetchField() + 1;

(I'm not sure if I can use MAX() here, I don't know enough about dbs that aren't MySQL or Postgres)

And I think this will work fine for my specific use case, but I'm curious to know if there is a better, more generic solution. It seems to me that this one will break down if content is being imported rapidly while users are active on the site, for example.

What is the best way to pass the future value of the item's mlid property to my function?

As Clive points out, the best way to do pass a menu link ID (mlid) when a menu item is created or updated is to use hook_menu_link_insert(), hook_menu_link_update() and hook_menu_link_delete() instead of hook_menu_link_alter().


How can I know that node is created or updated? I had configured Drupal 7. I'm going to run cron when a node is saved/updated/deleted. How  I know that node is changed?

Thanks.

Modules that need to execute code during cron tasks, and for nodes that have been created/updated/delete already implement code to do that. If you need something similar for your own module, you could use the following code.

function mymodule_node_insert($node) {
  $queue = DrupalQueue::get('mymodule_cron_queue');
  $queue->createQueue();
  $queue->createItem($node);
}

function mymodule_cron_queue_info() {
  $queues['mymodule_cron_queue'] = array(
    'worker callback' => 'mymodule_cron_worker',
    'time' => 10,
  );

  return $queues;
}

function mymodule_cron_worker($node) {
  // Code that uses $node.
}

With this code, mymodule_cron_worker() is called during cron tasks for every node that has been created; if you need to execute code during cron tasks for updated nodes, or deleted nodes, then you need to implement hook_node_update(), or hook_node_delete(). The code I shown for hook_node_insert() is the same code you would use for the other node hooks.

References

Queue operations
Example: Cron


programmatically enable and disable theme from update hook I need to programmatically update my default theme and disable bartik on a live site. I know I need to update the config. In Drupal 7 I would have used theme_enable(), but I am not sure how to do this in Drupal 8.
Below my function sets 'mycustomtheme' by default but it does not enable the theme. Thanks in advance.

  function mysite_deploy_update_8001() {
      \Drupal::configFactory()
      ->getEditable('system.theme')
      ->set('default', 'mycustomtheme')
      ->save();
    }

Use the theme installer service to enable and disable themes .

Install a list of themes:

\Drupal::service('theme_installer')->install(['mytheme']);

Uninstall a list of themes:

\Drupal::service('theme_installer')->uninstall(['mytheme']);

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ThemeInstaller.php/function/ThemeInstaller%3A%3Ainstall/8.2.x

Instead of writing to the config you can use the theme handler to set a default theme:

\Drupal::service('theme_handler')->setDefault('mytheme');


View Mode not showing up under Manage Display I created a view mode let's call as my_node_view for content type under display type settings, I was expecting it to show along with default and teaser tabs as default|teaser|my_node_view in manage display section, but it did not show up. I have ensured my_node_view is checked under custom display settings for Use custom display settings for the following modes. Am I missing anything?

Writing out my comment as an answer.

This apparently needs a manual cache clear right now to work.


Export block that exists in two or more regions Does anyone know how to export block that exists in two or more regions into yaml file?

This is the scenario I'm facing. A 'sitebranding' block is placed onto header and footer regions. When I go to admin/config/development/configuration/single/export I can find proper configuration, however when the code is being generated I can see there is a region property and the value is 'header' although in Drupal UI it's placed in footer and header. Is there a was to include both of regions for particular block?

The short answer is no.

The simplest way to get what you need is to create two unique blocks and simply export both YAML files. This method will make adding any styling or configuration differences down the line much easier anyway.

Per question #9677 there were some problems with doing this in Drupal 7 but thankfully the block system is pretty robust in Drupal 8.


Send notification e-mail after new content was added Some people refuse to learn about RSS and wish they could give me (e.g., via some form) e-mail (without registration) and they would be automatically notified about new content.

Could you help me how to achieve this functionality in Drupal 7? I heard about three modules that could help : Rules, Subscriptions and Notify. Only the first works under Drupal 7. Could you configure this functionality with some suitable module?

Rules is best for this, it depends on Entity API.

Simple download and enable them from Admin -> Modules
Now follow Admin -> Configuration -> Workflow -> Rules
Click on Add new rule
Define name e.g. "New content email notification" , select 'After Saving new content' from React on event select box and hit the Save
On the next page, event is already defined, No condition is required to define here, Head on to Action section and hit Add action
Enter recipient email address in the To field box
Populate Subject and Message, From fields. (A number of Replacement pattern are available to include in the text)

e.g. New content [node:title] added by [node:author] of type [node:type] on [node:created].

Hit the save
On the settings fieldset, make sure to check Active check box.


Changed Comment Module and database table - how to revert changes? Yesterday, I posted this thread which was subsequently locked for being too localized. I think this is much more searchable (and I still need help!) but I'm sorry for the bad thread.

Like mentioned in that thread, I changed different files in the comments module folder and added columns to the database table. This sort of disabled comments, both the settings in page content settings and their appearance on the page normally.

I tried to fix this by: uploading a completely new 'comments' folder (I have a back up if that was a bad idea) from a new copy of the core, and deleted those table fields. Still no sign of fixing any of the problems I created.

How do I return the comments to their normal setting so I can approach the altering I was planning on doing the right way this time?

First: Do not hack core!

To restore your site to a stable state, revert to the default theme, back-up your database and the sites/ sub-directory and anything below it.  Then download a fresh copy of the core and install it. Finally, restore the sites/ sub-directory, your database, and the theme.

Having extra tables in the database that Drupal does not know about does not do any harm, but you may drop those tables that you created yourself before backing up the database.


drush make: Specify subdir for make-files provided by contrib modules Recently I started using drush make to pull in Drupal Core, all the required contrib-modules, themes and libraries.

One of the modules I use is the geshifilter-module. This module comes with it's own make-files, so when I run drush make to build my entire site, drush sees this make-file and also builds that to pull in all the dependencies for the geshifilter-module.

While this is really convenient, I have one small problem with this: I prefer to have all the contrib-modules in sites/all/modules/contrib, so I define my modules like this:

projects[geshifilter][subdir] = "contrib"

However, the make-file inside geshifilter doesn't specify this subdir, so as a result, drush downloads the dependencies to just sites/all/modules instead of sites/all/modules/contrib.

For the moment I have added some commands in my wrapper-script around drush make to move those dependencies to the contrib-folder after drush make has finished, but I'm wondering if it is somehow possible to override the subdir-property for make-files which are provided by modules (obviously without manually modifying those make-files). I'm using drush 4.5 (default one from Ubuntu 12.04)

You can specify a default subdir for all projects this way:

core = "7.x"
api = 2
defaults[projects][subdir] = contrib
projects[] = views
projects[] = ctools

it is a very recent addition to drush 5, only available in the dev release.


Example Hook form validate, get all node information after save news field In a custom module, I do some operations on several content node (add field_collections and save)
After that, I need to get all field_collections of my content nodes.
But when I get, I have the old field_collections and not the new field_collections I just save.

Exemple :

//I have this node in my submit hook
node0
    ->field0
    ->filed1

//I save a new field (via entity_metadata_wrapper and save() ), and I get this node after
//I Have
node0
    ->field0
    ->filed1

//But I would like have
node0
    ->field0
    ->filed1
    ->field2 //the new field I just save

Are there a Hook I can use after a validate form ? But I would like keep the information about who nodes has been save...for get only them
Or an other way I don't know ?

I don't think I can clear the cache because my operations "save" and after "get" are in a heavy foreach

To grab your information before the node is saved you can use hook_node_presave, then if you want to gather information after its successfully saved simply use hook_node_update.

Also if you are saving it via the entity_metadata_wrapper you should still have access to the data after its saved.

$entity_wrapper->field_name->value(); //Should have field0, field1

//Add your value here

$entity_wrapper->save();

$entity_wrapper->field_name->value(); // Should have field0, field1, field2


How to effectively manage a site with Drush make? What things are important to consider when managing a site using Drush make?

"Make files", in the Drush and Drupal context, define a set of modules, themes and libraries that make up a site. While one could stick the entire sites/all/modules directory into git, the make file is a lot faster to handle, both for git and the developers. Below is a make file from an actual project of mine. I've cut out a lot as the whole file is hundreds of lines, but I've retained enough to show all of the functionality I've used.

; API
api = 2

; Core
core = 7.x
projects[drupal][version] = 7.14

; Contrib modules
projects[date][version] = 2.0-alpha4
projects[email][version] = 1.0

; Media and file_entity go hand in hand - please make sure they work together.
projects[media][version] = 2.0-unstable5
projects[file_entity][version] = 2.0-unstable5

; Cron modules
projects[ultimate_cron][version] = 1.6
projects[background_process][version] = 1.12

; Performance modules
projects[expire][version] = 1.0-alpha2
projects[cache_actions][version] = 2.0-alpha3

; Unstable modules
projects[menu_node_views][type] = module
projects[menu_node_views][download][type] = git
projects[menu_node_views][download][url] = http://git.drupal.org/project/menu_node_views.git
projects[menu_node_views][download][revision] = f46dd41eb8c4e693a6642a6c461afa57d99a6f1b

projects[filefield_sources_plupload][type] = module
projects[filefield_sources_plupload][download][type] = git
projects[filefield_sources_plupload][download][url] = http://git.drupal.org/project/filefield_sources_plupload.git
projects[filefield_sources_plupload][download][revision] = da374770b80fcbc0dab17158d38c8436ef29caca

projects[menu_token][type] = module
projects[menu_token][download][type] = git
projects[menu_token][download][url] = http://git.drupal.org/project/menu_token.git
projects[menu_token][download][revision] = 8c18fbb

; Libraries
libraries[mediaelement][download][type] = "file"
libraries[mediaelement][download][url] = "https://github.com/johndyer/mediaelement/zipball/2.7.0"

; Patches

; #1491150: node_load in menu_node_menu_link_insert is not safe - http://drupal.org/node/1491150
projects[menu_node][patch][] = http://drupal.org/files/menu_node-node_load-in-menu_node_menu_link_insert-1491150-1.patch

; Fix rendering of relation endpoints
projects[relation][patch][] = http://drupal.org/files/relation_table_endpoints_break.patch
projects[relation][patch][] = http://drupal.org/files/relation_bundle_permissions.patch

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"

The api line defines which Drush make API to use for the rest of the file. One important thing to notice about the file, is that all modules either have a specific version, or point to a specific git commmit. We never have -dev versions in our files. When we show up at a client meeting, or hand over the make file to the Jenkins server, there must never be any surprises. The exact version included in the file should be tested and expected to pass all types of tests. This is important to be able to delivery something of high quality.

In my company, the general agreement is that every team provides a shell-script called "build", in the root of the repository, which is responsible for setting up the site, so that automated tests can be run by the same cross-team CI setup.

Module updates can be done quickly directly on sites for testing, but officially by updating the make file, and rebuilding the site.

My team currently uses this set of build-scripts. I'm working towards moving much of the functionality into a drush extension that will heavily use provision though. A CLI version of Aegir if you will.


file downloads based on user My Goal
 * User Request for a customize version of a file
 * admin uploads the file for that user.
 * User Downloads Files.

I am stuck at how to assign a certain file to certain user. How do i accomplish this with views . My idea was to create a node with file upload field and assign certain user to it , I dont know how to do this assign part and filter things with views

Note : i am using drupal 7

With Drupal 7 you should be able to add a file field to a user.

Another solution would be a content type with a file filed. After creating the node of this new type make sure the receiving user is set as the owner. Finally make sure the user hass access to all files he owns.


Probem with formatting fields Two questions that I guess are both a part of one bigger idea. When creating a content type, I've been trying to figure out how to both indent a field and create a line break after a field both by default. For indenting I have tried adding spaces before the field name, but because it's empty space they are disregarded and displayed as normal. For the line break, I've tried adding a custom code field with br or p, and simply adding a blank field, but in both situations as there is no text to display, the field is not displayed at all. Any suggestions?

The safest thing to do is to use the #attributes Form Control Attribute. You can specify a CSS class to target this element to then supply some css rules to indent these elements in your sites theme.

Similarly, you can add a class to add a line break somewhere within the widget markup to create your linebreak. Be sure to notice that the class example in the linked documentation takes a PHP array of class(es) (not a string label for the class) ... that messed me up last week for like 20 minutes.


field_attach_form with user picture and user mail? I'm trying to build a custom "edit profile" page and use a lot the field_attach_form function in order to build it :

field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_firstname'));
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_lastname'));
field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'field_user_organisation'));

I'm trying to insert input for user mail and user picture, but as they are properties and not fields, the following snippet is not working.

field_attach_form('user', $user_entity, $form, $form_state, NULL, array('field_name' => 'mail'));

Is it possible to insert user's properties form with this function ? or is there another way ?

I was working on a similar task; my task was to put the address field into the popup and I used the following code to accomplish it. I looked at modules/user/user.page.inc for it.

    function MYMODULE_init() {
         //To avoid user_profile_form_validate function not found
         module_load_include('inc', 'user', 'user.pages');
         } //end init function

        //Custom form for fields
        function MYMODULE_form($form, &$form_state) {

        $form = array();
        global $user;
        $account = user_load($user->uid);

        if (!isset($form_state['user'])) {
            $form_state['user'] = $account;
          }
          else {
            $account = $form_state['user'];
          }

        $form['#user'] = $account;
        user_account_form($form, $form_state);
        // Attach field widgets.
            $langcode = entity_language('user', $account);
            field_attach_form('user', $account, $form, $form_state, $langcode);
        //All fields get attached so removing unnecessary fields.
            unset($form['account']['pass']);
            unset($form['account']['roles']);
 $key = array_search('user_validate_current_pass', form['#validate']);
    if ($key !== FALSE) {
      unset($form['#validate'][$key]);
    }
    // hide the current password fields
    $form['account']['current_pass_required_value']['#access'] = FALSE;
    $form['account']['current_pass']['#access'] = FALSE;

            $form['actions'] = array('#type' => 'actions');
            $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save'),
           );

          $form['actions']['cancel'] = array(
            '#type' => 'submit',
            '#value' => t('Cancel'),
            '#submit' => array('MYMODULE_form_cancel'),
            '#limit_validation_errors' => array(),
          );
          $form['#validate'][] = 'user_profile_form_validate';
          // Add the final user profile form submit handler.
          $form['#submit'][] = 'user_profile_form_submit';

          return $form;
        }

        // Add function for CANCEL button.
        function MYMODULE_form_cancel(&$form_state) {
        $url = $_GET['destination'] ? $_GET['destination'] : 'choose/your/path';
          drupal_goto($url);
        }


Rendered Entity not apearing under Show I created a new index and I've created a view with it but it only has the options to show as Search Results & Fields. Is there something that has to be done when configuring the index to get Rendered Entity to show up on views?

It does show up with the Default Content Index made with the module but whenever I make a new index and create a view with it isn't an option.

Pictures:
What appears when creating a view with the default index(1) vs an index that I created(2).

Just figured it out. I found this. All I needed was to flush all caches.


display node inside colorbox Is it possible to display a node content (without sidebar etc.) inside colorbox in Drupal 6.
I know there is module for that in drupal 7 - colorbox-node. But I could not find any thread bout same functionality for drupal 6. Can anybody help? Thank you

Try the Popup module. There is a version for Drupal 6.

  The popup suite allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and php-generated content.


How to prevent other roles from publishing content I am new to Drupal. I am working on a website where I have 2 user roles: Site admin and editor.

The site admin has all permissions. I want the editor to only have the permission to edit content but not to publish or edit them. He can view his edited content but cannot publish them.

Different people suggested me different options, like use this module, use that module, but no body is showing me a neat and proper solution.

Override Node Options overrides this functionality and it's pretty straight forward.

The Override Node Options module allows permissions to be set to each
field within the Authoring information and Publishing options field
sets on the node form.


How to Disable Profile2 Field Elements I would like to disable some form elements within a Profile2 form in Drupal 7 (ie still visible but not editable). I figured using hook_form_alter would be the way to go but I can't figure out where I need to set the ['disabled'] field to true.

Here is the code that I have:

$fields = field_info_instances('profile2', 'student')
if ($fields) {
  foreach($fields as $field) {
    $field['#disabled'] = true; <- don't know what attribute to set here
  }
}

In Drupal 6 this seemed pretty straight forward but using dsm($field) is not helping me determine what field attributes need to be set. I have Googled this and looked at the Drupal 7 API and I am still lost.

I am hoping someone can help me out here.

Thanks.

In drupal 7. You can use the "field permissions" module + profile2 module.
In order to disable some fields for anonymous user, you just edit the fields with custom permissions.
You can see the demo of configuration page from here :

Currently to disable some fields from profile2 for register form, I just set permissions that don't allow the anonymous user to see that fields.


Hide Alt and Title for image field How to hide Alt and Title fields for anonymus users when they upload images? I use tokens for these field that's why I need to hide them.

Here a solution for hide the alt and title fields:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
    // If this is an image field type
    if ('image' === $context['field']['type'] && 'MY_FIELD' === $context['instance']['bundle']) {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
        // Add the new process function to the element
        $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
    }
}

function MYMODULE_image_field_widget_process($element, &$form_state, $form) {
    $element['title']['#access'] = FALSE;
    $element['alt']['#access'] = FALSE;

    // Return the altered element
    return $element;
}

Et voila :)


Convert db_query to db_select or EntityFieldQuery Can anyone help me converting this query using db_query to db_select or EntityFieldQuery? I already tried a lot of things but always getting error. I am new with Drupal, my query works well but I think it's better converting this to db_select or EntityFieldQuery, what you think?

UPDATE

My query:

function get_recent_videos($uid) {
  $query = db_query('SELECT * FROM {node} n, {field_data_field_video} v
         WHERE n.uid = :uid
         AND n.nid = v.entity_id
         AND v.field_video_value IS NOT NULL
         ORDER BY created DESC
         LIMIT 0, 4', array(':uid' => $uid));

  $result = $query->fetchAll();

  return $result;
}

How can I use a placeholder in the limit? I tried the same approach that I have used in :uid but didn't work.

Thanks a lot.

Yes, if you're querying entity/field data you should pretty much always use an EntityFieldQuery in place of raw SQL. If you're not querying entity/field data, and need to build up a dynamic query, then db_select() is probably the way to go.

I'd also recommend reading the DB API docs and making sure you understand how to use db_query() properly - currently your code is likely to be susceptible to an SQL injection attack, as you're not using parameterized queries.


What are Ctools plugin (content type, access, etc), and how does one create them? What are Ctools plugins, and how does one create them?

Every now and then when working with Ctools Page manager, and Panels, it is useful to add custom Ctools plugins.

Ctools plugins comes in a large number of forms, and other modules, such as Feeds, Addressfield and Openlayers all make use of Ctools to provide plugins extensible by other modules. The most common forms of plugin though, are probably "content type", and "access". The first must not be confused with the entity "content" and its bundles, also called content types.

First, the boilerplate:

For any module to provide ctools plugins, they should first tell Ctools where to look for them. The hook below, says that we provide plugins for ctools, of the types "content_types", and "access". The function could be made simpler, but this way we ensure that only the right module gets told about the plugins, as well as only having it scan the disk for files when we actually provide the type of plugin being asked for.

function HOOK_ctools_plugin_directory($owner, $plugin_type) {
  // We'll be nice and limit scandir() calls.
  if ($owner == 'ctools' && ($plugin_type == 'content_types' || $plugin_type == 'access')) {
    return 'plugins/' . $plugin_type;
  }
}

Below is an example directory structure for a module providing two plugins. One content type and one access plugin.

module/
module/module.info
module/module.module
module/plugins/
module/plugins/content_types/
module/plugins/content_types/two_views_in_one.inc
module/plugins/access/
module/plugins/access/term_depth.inc

Content type plugin

A content type in the Ctools vocabulary, is more often known as a "Pane", as provided by for example Views. In this question: Is there a way to intercept a list of NID's created by a view and use them as a filter for another view?, the author asks about programmatically feeding arguments to a view. While that in it self it not very hard, the follow up question quickly becomes, "How do I display the results?".

One answer, will be to create a new "content type".

Now, the actual content type plugin, again using the Views question from above, could look like this:

$plugin = array(
  'title' => t('Render a View with arguments from another'),
  'single' => TRUE,
  'category' => array(t('My custom category'), -9),
  // Despite having no "settings" we need this function to pass back a form, or we'll loose the context and title settings.
  'edit form' => 'module_content_type_edit_form',
  'render callback' => 'module_content_type_render',
);

function module_content_type_render($subtype, $conf, $args, $context = NULL) {
  $block = new stdClass;
  $block->title = 'My View';

  $view = views_get_view('get_nids');
  $view->preview('display_machine_name', array($arg1, $arg2));

  $nids = '';
  foreach($view->result as $node) {
    $nids += $node->nid . ',';
  }
  $nids = rtrim($nids, ',');
  $view = views_get_view('get_related');
  $view->execute_display('display_machine_name', array($nids));
  $block->content = $view->render();

  return $block;
}

/**
 * 'Edit form' callback for the content type.
 */
function module_content_type_edit_form($form, &$form_state) {
  // No settings beyond context, which has already been handled.
  return $form;
}

With this module enabled, there should now be a new category in Panels, 'My custom category', where in one should find a single pane, rendering the code from above.

Access plugin

The access plugin below will provide the ability to filer out variants and/or panes based on the depth of a term as measured from the root of the vocabulary.

<?php
/**
 * @file
 * Plugin to provide access control based upon a parent term.
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Taxonomy: term depth"),
  'description' => t('Control access by the depth of a term.'),
  'callback' => 'term_depth_term_depth_ctools_access_check',
  'default' => array('vid' => array(), 'depth' => 0),
  'settings form' => 'term_depth_term_depth_ctools_access_settings',
  'settings form validation' => 'term_depth_term_depth_ctools_access_settings_validate',
  'settings form submit' => 'term_depth_term_depth_ctools_access_settings_submit',
  'summary' => 'term_depth_term_depth_ctools_access_summary',
  'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);

/**
 * Settings form for the 'term depth' access plugin.
 */
function term_depth_term_depth_ctools_access_settings($form, &$form_state, $conf) {
  // If no configuration was saved before, set some defaults.
  if (empty($conf)) {
    $conf = array(
      'vid' => 0,
    );
  }
  if (!isset($conf['vid'])) {
    $conf['vid'] = 0;
  }

  // Loop over each of the configured vocabularies.
  foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
    $options[$vid] = $vocabulary->name;
  }

  $form['settings']['vid'] = array(
    '#title' => t('Vocabulary'),
    '#type' => 'select',
    '#options' => $options,
    '#description' => t('Select the vocabulary for this form. If there exists a parent term in that vocabulary, this access check will succeed.'),
    '#id' => 'ctools-select-vid',
    '#default_value' => $conf['vid'],
    '#required' => TRUE,
  );

  $form['settings']['depth'] = array(
    '#title' => t('Depth'),
    '#type' => 'textfield',
    '#description' => t('Set the required depth of the term. If the term exists at the right depth, this access check will succeed.'),
    '#default_value' => $conf['depth'],
    '#required' => TRUE,
  );

  return $form;
}

/**
 * Submit function for the access plugins settings.
 *
 * We cast all settings to numbers to ensure they can be safely handled.
 */
function term_depth_term_depth_ctools_access_settings_submit($form, $form_state) {
  foreach (array('depth', 'vid') as $key) {
    $form_state['conf'][$key] = (integer) $form_state['values']['settings'][$key];
  }
}

/**
 * Check for access.
 */
function term_depth_term_depth_ctools_access_check($conf, $context) {
  // As far as I know there should always be a context at this point, but this
  // is safe.
  if (empty($context) || empty($context->data) || empty($context->data->vid) || empty($context->data->tid)) {
    return FALSE;
  }

  // Get the $vid.
  if (!isset($conf['vid'])) {
    return FALSE;
  }
  $depth = _term_depth($context->data->tid);

  return ($depth == $conf['depth']);
}

/**
 * Provide a summary description based upon the checked terms.
 */
function term_depth_term_depth_ctools_access_summary($conf, $context) {
  $vocab = taxonomy_vocabulary_load($conf['vid']);

  return t('"@term" has parent in vocabulary "@vocab" at @depth', array(
    '@term' => $context->identifier,
    '@vocab' => $vocab->name,
    '@depth' => $conf['depth'],
  ));
}

/**
 * Find the depth of a term.
 */
function _term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + _term_depth($parent);
    }
  }

  return $depths[$tid];
}


How to check the value of a field within the current node? In order to display a block only above certain nodes of Article content type,
I created a boolean field with two values : On / Off

The goal is to display the block only above the articles that have the Off value

After enabling the PHP filter module, the block gives me this option : "Pages on which this PHP code returns TRUE (experts only)" but i haven't been able to figure out the php code that returns TRUE

( Can the context module achieve this without PHP ? )

Any help is help

I think you should be able to do this with the (https://www.drupal.org/project/rules_block_visibility) module.


Handle database connection exception via custom handler I want to catch the database connection exceptions with a custom handler. I have already built an handler which is overriding the default logger factory, but now I want to use that custom handler to log database exceptions, without hacking the core.

I can see the connection driver uses the following code in open().

try {
  $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
}
catch (\PDOException $e) {
  if ($e->getCode() == static::DATABASE_NOT_FOUND) {
    throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
  }
  if ($e->getCode() == static::ACCESS_DENIED) {
    throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
  }
  throw $e;
}

I am not sure how I can catch the exception and log it using the handler. How can I achieve this?

To handle the logging for a specific exception implement an exception subscriber with a priority higher than 50, so that it runs before Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber:

src/EventSubscriber/ExampleExceptionSubscriber

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Database\DatabaseAccessDeniedException;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Example for catching a DatabaseAccessDeniedException
 */
class ExampleExceptionSubscriber implements EventSubscriberInterface {

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof DatabaseAccessDeniedException) {
      $this->logger->get('php')->error('Custom logging message');
      $response = new Response('Custom error message', 500);
      $event->setResponse($response);
    }
  }

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

mymodule.services.yml

services:
  mymodule.exception.subscriber:
    class: Drupal\mymodule\EventSubscriber\ExampleExceptionSubscriber
    arguments: ['@logger.factory']
    tags:
      - { name: event_subscriber }

If you don't set a response this subscriber only logs the error and the response is set by a subscriber with a lower priority. In this case you get two log entries, one from your subscriber and one from ExceptionLoggingSubscriber, because the dispatcher runs the event subscribers until one returns a response. Logging does not stop this.

Another option would be to extend ExceptionLoggingSubscriber, put the custom code in ExceptionLoggingSubscriber::onException and call the parent method to run standard logging when your custom code doesn't apply. Instead of putting the service in mymodule.services.yml you need to swap the existing service in the container then, see https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

You find more infos about exception handling here How do handle exceptions?


How can I make a link from user account page to its content profile node? I could make a link from content profile to its user page by this method.

But how can I do the other way round from user account page to content profile?

Probably content_profile_load is the way to go.

The relevant issue here : http://drupal.org/node/680356


Pseudo "subdirectory subsite" While a real subdirectory subsite has a URL of example.com/site1, and shares codebase with example.com, I was wondering if it's possible to create a separate Drupal installation (in a separate docroot) for site1 and still use the URL example.com/site1. In my case, they are two completely different Drupal installations with nothing to share, well, except the somehow 'related' URL part.

I know I can just use a sub domain and make the whole thing a lot easier but am wondering if the pseudo 'subdirectory subsite' is an option.

I think you could use an alias in your apache virtual host, something like this

Alias /site1 /path/to/your/site1
<Directory /path/to/your/site1>
  Options +Indexes
  AllowOverride All
</Directory>

Like it is suggested here https://stackoverflow.com/questions/19055372/redirect-to-a-subfolder-in-apache-virtual-host-file#19055573


Content Type Field value in variable I've created a content type with some fields like link , address. And I did content-type node theming with name node--machine-name.tpl.php and all fields are printed by this code

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

or individual fields like this

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

But I want to save the link field in a variable, which will be used in various ways.

I just want this field_link_url field to not be printed but to be stored in a variable

What I Tried

echo $link =  $field_link_url['und'][0]['value'];
echo $link = $content['field_link_url']['und'][0]['value'];

Apart from that I got the message with all the array fields with this

`drupal_set_message("<pre>". print_r($node,true) . "</pre>");`

which gave me this..

stdClass Object
(
[vid] => 51
[uid] => 1
[title] => Run Tests on the Cloud. No Software or Hardware Required!
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[nid] => 51
[type] => landing_pages
[language] => und
[created] => 1392994690
[changed] => 1393072611
[tnid] => 0
[translate] => 0
[revision_timestamp] => 1393072611
[revision_uid] => 1
[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] =>
                            No software or hardware to buy or maintain.
                        [summary] =>
                        [format] => full_html
                        [safe_value] =>
                            No software or hardware to buy or maintain.

                        [safe_summary] =>
                    )

            )

    )

[field_link_title] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => START A FREE TRAIL
                        [format] =>
                        [safe_value] => START A FREE TRAIL
                    )

            )

    )

[field_link_url] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => http://xyz.displaybox.in/why-xyz/easy-to-manage-your-tests
                        [format] =>
                        [safe_value] =>  http://xyz.displaybox.in/why-xyz/easy-to-manage-your-tests
                    )

            )

    )

echo $link = $content['field_link_url']['und'][0]['value'];

This way must be correct!
Check *field_link_url* key in content variable with dsm or kpr fucntion.

And try to get *field_link_url* value from this key.


Menu setting not visibile for other roles on Node Form In Drupal 8 I am creating Editor role with limited access, but the Editor cannot see "Menu Settings" while creating or editing content, this would be helpful when Editor add the node to the menu while creating node. I checked the permission and I can't see any option to turn on Menu Settings for the Editor role or for other roles.

Go to /admin/people/permissions and make sure the 'administer menu settings' are set for the Editor role.
But I think it is better to install the Menu Admin per Menu module. With this module you make sure the Editor only gets access to certain menu's.

Menu Admin per Menu allows to give roles per menu admin permissions without giving them full admin permission.

For instance, you may let certain users manage the items of the Main or Navigation menus but not those of the Management menu.


How can I theme the Bootstrap base theme search block? I've created a sub-theme of the Drupal 8 Bootstrap base theme. My problem is that I'm using a customized version of the Bootstrap CSS Framework that does not include Glyphicons. Instead of Glyphicons, my project is using fontAwesome icons.  What I've realized though, is that the Bootstrap theme uses a Glyphicon Search Icon for the Search Form. Since I'm not using glyphicons and the CSS files are not included, I get a search form button that looks like this.

It should appear like this.

If i inspect the HTML markup using my browser, my theory is correct.

<button type="submit" value="Search" class="button js-form-submit form-submit btn-primary btn icon-only" name="">Search</button>

if I change the following markup, the button shows up correctly because it can find the icon.

  to

What I want to do is to be able to change the icon or the code in the base theme that generates this snippet of code.

My assumption is that I should use a preprocess function to alter the form block and output/replace the Glyphicon span with the Fontawesome span.

I believe that the input--button.html.twig in the bootstrap base theme is responsible for outputting the icon classes because of this code.

{% block input %}
    {% if icon_only %}
      <button{{ attributes.addClass(classes, 'icon-only') }}>
        {{ label }}
        {{ icon }}
      </button>
    {% else %}
      {% if icon_position == 'after' %}
        <button{{ attributes.addClass(classes) }}>{{ label }}{{ icon }}</button>{{ children }}
      {% else %}
        <button{{ attributes.addClass(classes) }}>{{ icon }}{{ label }}</button>{{ children }}
      {% endif %}
    {% endif %}
    {{ children }}
  {% endblock %}

Apparently, it is used to alter the button of many elements instead of only the search form.

Bootstrap theme is deeply bundled with glyphicons .. it guesses the icon from the button text.

You would need to override Bootstrap::glyphiconFromString() or Bootstrap::glyphicons(). I cannot tell you how to do this in your subtheme ...

If you removed the glyphicons, probably Theme::hasGlyphicons() will return FALSE and won't show any icon.

Workaround

You could replace the icon variable in template_preprocess_input, like:

function MY_TEME_preprocess_input(&$variables) {
  if ($variables['icon']) {
    if (array_key_exists('glyphicon-search', $variables['icon']['#attributes']['class'])) {
     foreach($variables['icon']['#attributes']['class'] as &$sValue)
     {
       if ($sValue == 'glyphicon') {
         $sValue = 'fa';
       }
       if ($sValue == 'glyphicon-search') {
         $sValue = 'fa-search';
       }
     }
    }
  }
}

or, I guess you have asked this question on do: https://www.drupal.org/node/2757463. There is a suggestion of overwriting the Input element:

Create a file at bootstrapsubtheme/src/Plugin/Preprocess/Input.php and add the following:

/**
 * @file
 * Contains \Drupal\bootstrapsubtheme\Plugin\Preprocess\Input.
 */

namespace Drupal\bootstrapsubtheme\Plugin\Preprocess;

use Drupal\bootstrap\Annotation\BootstrapPreprocess;
use Drupal\bootstrap\Utility\Variables;

/**
 * Pre-processes variables for the "input" theme hook.
 *
 * @ingroup theme_preprocess
 *
 * @BootstrapPreprocess("input")
 */
class Input extends \Drupal\bootstrap\Plugin\Preprocess\Input {

  /**
   * {@inheritdoc}
   */
  public function preprocessElement(Variables $variables, $hook, array $info) {
    $element = $variables->element;

    if ($element->icon) {
      $element->icon->replaceClass('glyphicon', 'fa');
      $element->icon->replaceClass('glyphicon-search', 'fa-search');
    }

    // Let bootstrap base theme preprocess the element normally now.
    parent::preprocessElement($variables, $hook, $info);
  }

}


Order groups in grid layout When I create a grid view, I can create groups of elements. However I have no control over the order of these groups. I can sort on the grouping variable, but that is not what I want. I want to specify the order, not sort alphabetically. The default is the order the groups were created which suggests reordering the database rows might work as a kludge. Anyone know how to do this?

The module Draggableviews could be a solution here. It adds a table drag handler and a order field that is saved after you have rearranged the view. The same order field can then be used in another display if you want.


Control access to buy products We would like to be able to restrict access to buy products.

A product could be members-only
Users who are already members should be prevented from buying membership again until near expiry.

If there is no access to buy, the "add to cart" button should not be shown.  There also needs to be a check during checkout, for example in case the a member added a membership to the cart as anonymous then logged in, they still should not be able to buy membership.

We don't want to restrict access to view products.  Non-members should be able to see the benefits of membership, and what extra things they could buy.  The price should still be visible for products that cannot be bought (so we can't hide the entire "Add to Cart" form as that's where the price comes from).

Please can someone explain how to achieve this?

I believe that good start is to implement EventSubscriber listening on ProductEvents::FILTER_VARIATIONS event. It was introduced to filter out some product variations based on different aspects, such as stock, date, etc.


How do I create a View filter by a parent taxonomy term? I've got a taxonomy that is set up as such, which I am using with Taxonomy Term Templates:

Manufacturer>>Model>>Colour

Eg:

Honda>>Accord>>Red

I'd like to create a View that displays all siblings of a Taxonomy, eg if I am on the Accord page I'd like the view to return other Honda models (eg: Civic, CR-X, HR-V, Odyssey).

I've tried using the %term:parent as a contextual filter, but have had no luck - no results display.

Would anyone know how I might go about this?

Please follow such steps for getting your result (Child Items)

1)Add Taxonomy term: Term ID in CONTEXTUAL FILTERS.
2)Add Taxonomy term: Parent term in RELATIONSHIPS. (leave Require this relationship unchecked.)
3)Add Taxonomy term: Parent term in filter section. select great than 0.
4)Do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= airports).
5)Add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to parent , check the Exclude from display.
6)In setting, under FORMAT section. In grouping field 1, select (Parent) Taxonomy term: Rendered Taxonomy term.

You should good to go. you can use view tpl to add more class base on the group.
 I have enclose my screenshot for references.


Similar Products don´t get grouped on review Page When adding multiply quantities of the same product they don´t get grouped but splitted to each line on the overview checkout pane.

-Example-

Instead of:

  Product: PLAYSTATION QTY 3

It shows:

  Product: PLAYSTATION QTY 1

  Product: PLAYSTATION QTY 1

  Product: PLAYSTATION QTY 1

I know this is a view, I tried to configure it to grouping, but with no change.
Even this module did not help:
https://www.drupal.org/project/views_aggregator

What can I do to have all similar products grouped and sum quantity?

You have to go to admin/structure/types/manage/YOUR_DISPLAY_TYPE/display, search for the product field / add_to_cart form
and set it to combine like items : enabled

That's it.


Access the row level field of a image field with multiple values I'm having issues when trying to get the image URL of an image field, which allows multiple values.

I have a view which has context to a node.

I have two templates, one for the row level of the view, and one for the field level of the view:

views-view--my-view.html.twig:

{% if rows %}
  {{ rows }}
{% endif %}

views-view-fields--my-view.html.twig:

{{ kint(get_image_path(row._entity.field_header_images)) }}

get_image_path():

public function get_image_path(\Twig_Environment $env, array $context, $image, $style=false) {
  // Check if $image is present
  if(is_null($image)) {
    return false;
  }

  kint($image);

  // Object structure different, depending on if node.field_name, content.field_name or row._entity.field_name is passed
  if(isset($image['#items'])) {
    $image = $image['#items'];
  }
  elseif(isset($image['#item'])) {
    $image = $image['#item'];
  }

  // Check $image->entity is set
  if(!isset($image->entity)) {
    return false;
  }

  if(!$style) {
    return $image->entity->url();
  }
  else {
    $image_style = ImageStyle::load($style);
    return $image_style->buildUrl($image->entity->getFileUri());
  }
}

get_image_path() is a function provided by the starter module. It allows you to easily pull out URLs for images (with size support), without having to do the horrible relationship file URI business.

I can't use get_image_path() on fields.field_header_images.content due to its structure, so I have to access the row.

Now what happens is only the first image is returned. So if I had 3 different images, I'd get the URL for the first image 3 times.

If I just use fields.field_header_images.content, I am able to see the 3 different images without issue.

Hopefully I'm not being too unclear/broad!

Thanks in advance.

I'm the author of the Starter module you reference. I've made a change to the get_image_path() twig extension, in order to support images in passed by these means.

In order for this to work as required, you need to change your view - under Multiple Field Settings for your field, tick 'Display all values in the same row'. This will ensure that the fields aren't output as a multiple of the total number.

Then, in your view fields template, use:

{% for item in row._entity.field_header_images %}
  {{ get_image_path(item.getValue()) }}
{% endfor %}

Hope this helps.


Can’t login after FF browser update My Firefox has just updated to version 17.1. When I try and login I get this message:

  Access denied
  You are not authorized to access this page.

The URL does however recognize my account as it contains /users/myusername

I can log in fine in older versions of Firefox, and Internet Explorer. I however get the same problem in Safari version 4 Public Beta (528.16).

Does anyone know a fix for this? I have tried rebuilding permissions but it didn't help.

I am running Drupal 6.

A similar situation was encountered by a user who reported that clearing his browser cookies solved the problem.


Are there any hooks for the event when an user navigates the verification URL? I'm looking for a way to modify an event (from my own module) when an user navigates to the account activation URL that they get in their mails. Are there any such hooks ready for me to use?

Also I would potentially need the $account-> mail variable if it's passed as an argument by any chance.

I've used this but it doesn't work as intended -

function my_module_form_alter(&$form, &$form_state, $form_id)
{
    // Trigger when at password reset form
    if ($form_id == 'user_pass_reset') {}
}

But the problem is I cannot seem to access the $account variable that way. What should I do?

Finally figured it out.

function my_module_lists_form_alter(&$form, &$form_state, $form_id)
{
    // Trigger when at password reset form
    if ($form_id == 'user_pass_reset')
    {
        // If $account has not been defined, define it from $user
        if (empty($account))
        {
            // Loads the user using the user id argument
            $account = user_load($form_state['build_info']['args'][0]);
        }

        // Log something
        watchdog('DEBUG MESSAGE:', 'We are there, user : ('.$account->mail.')!');
    }
}

If anybody has a better method, please do share.


How do I translate view's page path alias? I'm able to translate views titles and menus thanks to config_translation core module. I would like to have path aliases translated as well but it seems to lack this feature. Any other way to do it?

On my multilingual Drupal 8 sites, I go to /admin/config/search/path/add for adding URL alias, which asks you to select a language for this alias.

Is this what you were looking for?


Webform multiple files with descriptions D7: I am looking at building a competition section on a site I'm working on. Originally I started looking at Webforms to do this, but there are requirements I have that Webform doesn't solve (as far as I can tell).

What I need is to allow entrants to submit images. There must be at least 5 and no more than 12. Each image submitted should have a title, a caption and a date (dd/mm/yyyy). This is a big problem because I can only find two modules that allow for multiple file uploads in Webforms, neither allow specifying a minimum number of files and neither allow text fields and a date to be entered with each image.

Does anyone know a way I can solve this in Webform or do I need to look at building something custom? It's a pain that I can meet 80% of the requirements out of the box (kinda).

You can allow node submission for users. Create a content type, go to permissions tab and allow content type to be submitted by particular user role. Under content type go to manage fields and create an image field by allowing multiple images to be uploaded. Now use Form block module to display node form on front end for users. This will be easy for you as well as you can get the submitted content easily in views to display them as per your requirement.