drupal_add_js() issues I am facing some problems while using drupal_add_js() along with drupal_goto().

I am using hook_nodeapi() to capture a node prepare condition; inside the "prepare" case, I am adding the following JavaScript code, which I need to close a Lightbox window):

drupal_add_js('$(document).ready(function() {
  window.parent.location = "'.$base_url.'";
  window.parent.Shadowbox.close();
})', 'inline');

The problem is that if I add a drupal_goto() before or after drupal_add_js(), then the JavaScript is not included in my page source.

I hope I am able to explain my problem. Can anyone please point me towards why this happens?

I know I can use JavaScript to implement drupal_goto() functionality, but in some cases the drupal_goto() comes from the drupal module itself and thus cannot be removed.

drupal_goto() alters the header of the page, then calls exit(). So if it's placed before the drupal_add_js(), the function will never be called, and if it's placed after, the header says "Go some place else," and you will be redirected as soon as possible, not waiting for jQuery to execute.

Why do you need to close the shadowbox in the first place if you are going to redirect the user somewhere else? It sounds like there's a fundamental problem to what you want to do.


Creating N fields with N 'subfields' I'd like to create a content type "Enterprise" where user can define N services and, for every service, N tasks. I have already created the other fields for this content-type (name, description, ..., easy fields) but I don't know how to start with the services and tasks.

I'd like to be able to create services and tasks in the same form. What would be the best way to do it?

In case of use d6, you can use Flexifield, then after you install you should create a content type that should represent your subfields, and in your main content type you should create a new field, with Flexifield type, and then, define the it's a number of values of the field, and then, in the creation node form of your main content type, you`ll have a field (kind of group), that will have multiple subfields, and depending of the number of fields defined, you should have multiple "groups of subfields".


file field on form in view is ajax-enabled ONLY if rendered as part of page, not retrieved through ajax We are using the popup module to render views within a page.

One of the views has a file field for uploading. The popup module can render the popup as part of the page and then display the popup or pull the data in through an ajax call.

If the views is pulled in as part of the rendering of the page, the field has ajax enabled and works correctly.

However, when the view is pulled in through ajax, the field does not have ajax enabled and fails to function.

There are dozens of such popups on the page and it is simply not practical to have all the popups pre-rendered (not to mention the inefficiency of it).

I have tried pulling in just one popup to check whether its just some missing javascript files but while the solitary popup works as expected, the other ones still fail to function.

Digging into the popup module, the bit of code to retrieve the view is exactly the same regardless of whether it's being pulled in as part of the page, or separately through ajax.

from popup.api.inc

function _popup_view($attributes, $return = FALSE){

  $title = FALSE;
  $body = FALSE;

  if (module_exists('views')){

    $view = views_get_view($attributes['view']);

    $display = $attributes['display'] ? $attributes['display'] : 'default';
    $args = isset($attributes['args'])
      ? explode(',', $attributes['args'])
      : array();

    if ($view){
      $view->set_arguments($args);
      $view->set_display($display);
      $body = $view->preview();

      $computed_title = $view->get_title();
      $title = $attributes['title']
        ? $attributes['title']
        : ($computed_title
            ? $computed_title
            : @$view->display[$display]->display_options['title']
          );

    }

  } else {
    $body = false;
  }

  $title = $title ? $title : 'View';
  if ($return == 'title'){
    return $title;
  }

  if ($return == 'body'){
    return $body;
  }

  return
    popup_element(
      $title,
      $body,
      $attributes
    );

}

The relevant javascript section:

  var placeContent = function(data, destination){

    thisObject.body.unbind('showing', fetchContent);
    var close = $('.popup-close-button', destination);

    if (close.length){
      close.siblings().remove();
      destination.append(data);
    } else {
      destination.html(data);
    }

    Drupal.attachBehaviors(destination);
  }

The popup module has a mechanism for rendering drupal forms view a popup and load that via ajax as well. This too does not work.

I should state that regular forms do work without any issues. I have views being rendered via ajax popup that have other controls (submit buttons just now) which work without any issues.

However, if I add a file form field into any of those forms, it breaks even the original controls. I believe this may be related to the form changing to a multipart mime form.

This leads me to the conclusion that there is something specific about the file form field that fails when being retrieved through ajax.

Manually adding the file.js has had not impact (I was thinking that attachBehaviours may not be working correctly)

Any help to resolve this will be greatly appreciated.

Turns out it was a bug in the popup module.


Change Profile2 Profile Type after registration I am trying to get Profile2 module to work with Simple_FB_Connect but the flow of Simple_FB_Connect requires that the user signs up first and then i need to be able to set the Profile2 user type afterwards.

After returning from FB i want the user to be able to click "Consumer" for example and their Profile gets set. Something like this...

function MYMODULE_set_user_type() {
  global $user;
  //dsm($user);
  $uid = $user->uid;

  $type = $_GET['type'];
  if (isset($type)) {
    profile2_load_by_user($uid, $type_name = 'main');
    // Unsure what to put here.
    profile2_save($profile);
  }
}

It's not currently possible with this module. The project page advertises a hook_simple_fb_connect_register_alter() hook to take action on registration, but looking at the current 7.1.15 version & the 7.2.x branch reveals only a placeholder hook. You'll have to wait for the maintainer to implement it, or to use another module that allows hooks following FB authentication.


Access denied or format unknown on field in Services Views Installed the following modules in Drupal 7

Services
Services Views

When creating new services view, I am facing the following issue.

nid and title fields shown correctly, but other fields including body and custom fields showing the following error. "Access denied or format unknown on field."

The preview shows as below:

array (
  0 =>
  stdClass::__set_state(array(
     'nid' => '47',
     'title' => 'World Cup Stadiums',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  1 =>
  stdClass::__set_state(array(
     'nid' => '49',
     'title' => 'Ladies Fencing Tournament 2014',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  2 =>
  stdClass::__set_state(array(
     'nid' => '48',
     'title' => 'FIfa World Cup',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
  3 =>
  stdClass::__set_state(array(
     'nid' => '46',
     'title' => 'Fifa World Cup Title',
     'publish_date' =>
    array (
      'error' => 'Access denied or format unknown on field.',
    ),
  )),
)

You just need to uncheck the "Use field template" inside the "STYLE SETTINGS" of your 'publish_date' field.


Is it possible/ feasible to convert ordinary nodes to Ubercart nodes? I have a site that imports content from several XML and CSV feeds, which creates nodes for each item (the items are products, but the site does not directly sell each product).

I'm just wondering if it's i) possible and ii) feasible to convert these nodes to be usable with Ubercart? Although the site doesn't directly sell the products (each product links to the supplier's site), there are features in Ubercart that are attractive to use - in particular, an Ubercart theme that I would like to use on the site.

I'm not sure how the ubercart theme you're interested in works, but you can declare any content type as an ubercart 'product' type. This would eliminate the need to convert exsiting/imported nodes, but I'm not sure if the theme you're looking at is only set up for the default Product type that ubercart creates for itself.


How do I programatically add a field to a node? I'm trying to create custom Drupal 7 module. In the form setting for the module I have checkboxes where the admin can select multiple content types:

After installing the module I need to automatically create two fields (Price of type decimal (4,2), and currency of type text) only in the 'content types' the admin has selected from the list above.

And this is how I set the content type to the checkboxes list in the mymodule_payment_admin_settings_form hook in mymodule.module:

 $form['test_content_types'] = array(
      '#type' => 'checkboxes',
      '#options' => drupal_map_assoc(node_type_get_names()),
      '#default_value' => variable_get('test_content_types'),
      '#required' => TRUE
    );

You need your own form ideally, right now you have a system_settings_form. That's typically for only setting variables and really simple stuff like that. see the documentation on system_settings_forms.

Instead you probably want to create and use a custom menu callback (you've already done that) which has a callback to a custom form you've defined. See the general drupal FAPI guide.

With your own form you create a submit callback. In that callback you take the selected node types and just create and assign instances of drupal fields to them. So you have to do 2 things: 1) create the fields, 2) assign them to the content types (entity bundles).

The form submit callback could look like this (not 100% tested code, fill in the blanks, add validation, etc):

function mymodule_form_submit($form, &$form_state) {
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field = array('field_name' => 'field_price', 'type' => 'number_decimal',);
    $field = field_create_field($field);
  }
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field2 = array('field_name' => 'field_type_of_currency', 'type' => 'option',);
    $field2 = field_create_field($field2);
  }

  foreach ($form_state['values']['content_type'] as $machine_id => $machine_name) {
    # Create instance on bundle.
    $instance['field_price'] = array(
      'field_name' => $field['field_name'],
      'entity_type' => 'node',
      'bundle' => $machine_id,
      'label' => 'Price',
      'description' => 'The price of an item.',
      'required' => FALSE,
      'settings' => array(),
      'widget' => array(
        'type' => 'textfield',
      ),
      'display' => array(
        'default' => array('label' => 'hidden'),
      ),
    );
    // ... same instance code for currancy type field instance.
    // $instance['field_currency_type'] = ...;

    foreach ($instance as $instance_field){
      field_create_instance($instance_field);
    }
  }
}


Bootstrap progress bar missing style option Drupal 8 using Bootstrap theme. I am trying to create a progress bar on my form. I have done it in a block with no problem but in the form it loses the "style" option and displays a blank progress bar.

I put in this:

    $form['pr_bar'] = [
        '#markup' => '

            40% Complete (success)

',
    ];

and get a blank bar. When i inspect element:

40% Complete (success)

Why is the style option missing and is this causing the blank bar?

#markup filters the style option because of the xss filter.

Use an inline template instead:

$form['pr_bar'] = [
  '#type' => 'inline_template',
  '#template' => '

        {{ complete }}% Complete (success)

',
  '#context' => [
    'complete' => '40',
  ],
];

You can pass the percentage value as twig variable.


How can I save the configuration value in a custom submit form method I've been wondering if it was possible to use the configuration system instead of playing directly with the database. Here's a simplified version of what I'm trying to achieve:

public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $form['action'] = array(
        '#type' => 'submit',
        '#submit' => [[$this, 'myMethod']],
        '#value' => $this->t('Test')
    );
    return $form;
}

public function myMethod($form, FormStateInterface $form_state) {
    $this->setConfigurationValue('my_config', 'my test value!');
    $this->saveConfiguration(); // <---- Is that 'kind of' possible?
}

So, I was wondering if it was possible to get the real "config class" by some way and call $config->save(). I started to look at the source and I think it's probably possible using the configuration engine.

Any help would be appreciated.

Thanks

The blockForm is used to configure a block. The configuration is then used to build the block.

If you want to use the configuration system to store data in the database use one of these methods:

Simple Configuration Form
Creating a configuration entity
type


Disclose billing cycle information on order page to customers When customer clicks on a recurring order page he can see:

  Billing information:
  Name Lastname
  Some Address
  Some City, State 11111 United States

and then immediately after that:

  Billing cycle:
  - Restricted access -

I looked high and low, tried all the different permissions for products, orders, licenses, but can't figure out how to get billing cycle information displayed on order page. I don't know why billing cycle should be restricted for the customers.

Make sure that in your roles/permissions that users have permissions to view licenses:


theme('table'...) function doesn't print the table header I need to generate a table using theme('table',array('headers'=>$header,'rows'=>$rows));

The table is printed but with no header. This is the code: I don't see any error nor missing part for the theme function

    $header = array(
    // creating array that contains data from first cell
    array('data' => t('Header cell1')),
    // second cell
    array('data' => t('Header cell2')),
    // and third cell
    array('data' => t('Header cell3'))
  );
  // creating first row
  $rows[] = array(
    // output of first cell in 1 row
    array('data' => t('Row 1 – Cell 1')),
    // second cell
    array('data' => t('Row 1 – Cell 2')),
    // third cell
    array('data' => t('Row 1 – Cell 3'))
  );
  //second row output
  $rows[] = array(
    array('data' => t('Row 2 – Cell 1')),
    array('data' => t('Row 2 – Cell 2')),
    array('data' => t('Row 2 – Cell 3'))
  );

  echo theme('table',array('headers'=>$header,'rows'=>$rows));

You are using theme('table',array('headers' => $header,'rows' => $rows)), while you should be using theme('table',array('header' => $header,'rows' => $rows)). theme_table() looks for a property called header, not headers.

  Parameters

  $variables: An associative array containing:

  header: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:

  "data": The localized title of the table column.
  "field": The database field represented in the table column (required if user is to be able to sort on this column).
  "sort": A default sort order for this column ("asc" or "desc").
  Any HTML attributes, such as "colspan", to apply to the column header cell.

  rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

  "data": an array of cells
  Any HTML attributes, such as "class", to apply to the table row.
  "no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

  Each cell can be either a string or an associative array with the following keys:

  "data": The string to display in the table cell.
  "header": Indicates this cell is a header.
  Any HTML attributes, such as "colspan", to apply to the table cell.


How do I delete content (nodes) that a user no longer has the right to create? Suppose a user of my site has had the right (the correct role with sufficient permissions) to create content of a certain type.

If the right (role) is taken away from them, how could I make the users content automatically be deleted? (the deletion doesn't have to be instant, eg. once a day is fine) i.e the content will be deleted from the moment they no longer have permissions to edit it or create such content.

This code gives you the basic idea:

$nodes = node_load_multiple(array(), array('type' => 'my_type'));// load node by certain type
foreach ($nodes as $node){
    $uid= $node->uid;//get the node author id
    $nid = $node->nid;// get the node id
    $author = user_load($uid);//load the author of the node
    if (!in_array('your_role', $author->roles)) { //the author has not your_role role
        node_delete($nid);
    }
}

if you copy this code in the theme_preprocess_html of your template.php, for every page it checks the nodes and its author roles and delete the node id its author has not the role.

If you need to run this code once a user role is updated, you can use Rules module :

I am not able to run this code right now, but it should work correctly. You can use devel module to correctly get the $node properties ($nid and $uid).


Add focus to user login I'm trying to add:

drupal_add_js('jQuery(document).ready(function () { jQuery("input#edit-name").focus(); });', 'inline');

to the user login page when the user is not logged in. This lack of login form focus is one of my worst web annoyances.

What would be the most efficient way to do this?

I can add the code to every page by adding it to my theme's js, but this is inefficient.

In the theme's template.php I can use theme_preprocess_page() and check for $variables['logged_in'] but how do I test for only the /user page?

You can use the drupal_match_path() function:

$path = drupal_get_path_alias();
$pattern = 'user';

    if (drupal_match_path($path, $pattern)) {
      drupal_add_js('jQuery(document).ready(function () { jQuery("input#edit-name").focus(); });', 'inline');
    }


How to display physical dimension fields on node--product.tpl.php? I am using the Drupal Commerce module and I want to print the physical dimension fields(machine name: field_width) value on product detail page.

How can I print physical dimension fields value in node--product.tpl.php file?

My file code is like so:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>"
<?php print $attributes; ?> >

<?php print $user_picture; ?>

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>

<?php if ($display_submitted): ?>
<?php print $submitted ?>
<?php endif; ?>

<div class="content clearfix"<?php print $content_attributes; ?>>

<?php
if ($view_mode == 'teaser')
else
print render($content['field_image1']);
print render($content['field_width']);
print render($content['product:commerce_price']);
?>

Have you set the field to be displayed under display settings for the content type?

Above is how the Field UI looks, maybe your product dimension field is hidden?

There is a guide here, on how to customize the Drupal commerce product display.

If you want to print the field in node--product.tpl.php you should first drag it so it is visible in the field UI.

Then you need to add render($content['product:field_width']);


Getting error rendering same node in different view mode Unsupported operand types in /node/node.module on line 1419

On my site users have the ability to flag a content type (node) as being featured on the right rail.  I then have a view that renders a view mode called card_view of that specific node.  This works great but if you attempt to render that card_view view mode on the same page as the full content view mode you get an error above.  Debugging the error occurs when rendering the full content and not the card_view.  This also occurs when attempting to render it programmatically:

// Error occurs here (snippet from node.module line 1419)
  $node->content += field_attach_view('node', $node, $view_mode, $langcode);

// Error occurs viewing full content and attempting to render same node in a different view mode
$node = node_load($nid);
$node_view = node_view($node, $view_mode = 'card_view', $langcode = NULL);
echo drupal_render($node_view);

If I remove the attempt to render this node in this view mode it works fine, and also if I attempt to render a separate node it works fine as well, it ONLY occurs when rendering the node view mode on that same node full content page.

I found the solution but do not know the actual cause.  Apparently I have to clone the current node to avoid conflicts:

$node = clone menu_get_object();
$node_view = node_view($node, $view_mode = 'card_view', $langcode = NULL);
echo drupal_render($node_view);

If anyone has any detail feel free to edit or add a comment.


How to show a block on a set of subpages except one of them? I have a block which is shown on all subpages under "mypagename", using the following bmock visibility settings:

Only the listed pages --> mypagename/*

Except I now need to exclude one page under "mypagename" for showing this block. Is there a way to easily exclude this page using the standard settings of Drupal 7?

There's nothing in the core UI, no.
hook_block_list_alter() exists for exactly this sort of scenario, though:

Act on blocks prior to rendering.
This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

e.g.
function MYMODULE_block_list_alter(&$blocks) {
  if ($some_condition) {
    // Remove the block from the list.
    unset($blocks[$some_key]);
  }
}


db_query unknown column on where clause? I am getting this error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Weddings' in 'where clause': SELECT id from galleries_types WHERE name="Weddings"; Array ( ) in catering_gallery_add_image_submit() (line 195

Why does it think 'weddings' is a column? It clearly is where name='Weddings'. What's up with the blank array on the end?

This is the code I am using.

$a = db_query('SELECT id from galleries_types WHERE name="'.$form_state['values']['id'].'"');

If you're new to Drupal or PHP coding, you've created a nice example of how not to write an sql query. What you've written is open to SQL-Injection.

Please review the Database API Examples Documentation page.

A "correct" way to write this query using the API could look like (adapting 1 of the top examples to your code) the following.

$result = db_query("SELECT id from {galleries_types} WHERE name = :name", array(':name' => $form_state['values']['id']));

You will want to make use of placeholders in PDO to write your queries.


Really confusing composer error output relating to working composer.json/.lock files Warning: this may come across a little ranty! Up until version 8.3.0, I thought I had solved all my drupal + composer related issues.
With the following in composer.json:

"require": {
    "drupal/core": "~8.3"
}

I ran composer update. I got v8.3.0-rc2. After some playing around, I changed the above to:

"require": {
    "drupal/core": ">8.0"
},

which updates to the latest stable 8.x release. What is going on! Why would the first example not work?

Additionally, downloading Drupal in .zip form, the line reads:

"replace": {
    "drupal/core": "~8.3"
},

Why, when nearly every guide recommends putting this line in the 'require' array if you intend on updating via composer?

Furthermore, the widely recommended Drupal Composer Project has the following - perhaps crucial - line:

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

I realised early on that without this line, many of my update attempts would fail in some way. Why would this line not be absorbed into the main Drupal distribution?

So many questions, and yet most Drupal + Composer pages across the internet forward us to the general composer website. It seems clear that Drupal is not fully compatible the 'general' composer methodology

Someone else recently reported not being able to update from RC2:

Updating core with Composer doesn't work

There are two different things, drupal/drupal and drupal/core. You can't mix the two, that's why when you download drupal from drupal.org by hand, you have drupal/drupal and it contains the replace line, as it says that it replaces that.

As suggested there, I'd recommend to use the drupal-project template, I've upgraded many drupal installations to 8.3 with that without a problem.

Note that that has quite a different file structure, specifically it has a web folder that contains the public files.


Need Separator image for views ticker content? I am using Views Ticker module for display the news in my site. It's perfectly worked for me. I want separator image for one content to another content.

If you wants the separator between two content you have to write css for that.This is a css query.Please check the css.Have a great day.


User Login with Email Address - Services Drupal login form allows users to enter their username or email to login into the site.

I need to achieve the same thing with services. But services allows users to login with username (not working with email).

JSON format for User Login (works).

{"username":'myusername', "password":"mypassword"}

But how can we do login using "email" as username? I've tried the following JSON formats

Input:

{"username":'myusername@gmail.com', "password":"mypassword"}

Response:

["Wrong username or password."]

Input:

{"mail":'myusername@gmail.com', "password":"mypassword"}

Response:

["Missing required argument username"]

According to this link, I need to tweak the services modules to achieve this requirement.

Is there any way to achieve this?

You can do this in a custom module:

/**
 * Implements hook_services_resources_alter().
 */
function my_module_services_resources_alter(&$resources, &$endpoint) {
  // Override the normal user login callback.
  if (isset($resources['user']['actions']['login']['callback'])) {
    $resources['user']['actions']['login']['callback'] = 'my_module_services_login';
  }
}

/**
 * Replacement callback for the Services user login resource. Optionally use the email address to login.
 *
 * @see _user_resource_login().
 * @see https://drupal.org/node/1431724
 */
function my_module_services_login($username, $password) {
  $result = db_query(
    "SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:username)",
    array(':username' => $username)
  )->fetch();
  if (!empty($result->name)) { $username = $result->name; }
  return _user_resource_login($username, $password);
}

Using this technique, you don't need to patch the Services module.

This solution is borrowed from DrupalGap:

http://cgit.drupalcode.org/drupalgap/tree/modules/drupalgap_logintoboggan/drupalgap_logintoboggan.module


How do I attach a single-use block through a field? I am working on a project that has a lot of custom block types (about 35). They are complex and have a lot of fields. They are being used with Layout Builder so all the blocks that get created are mostly single-use and hidden. The block plugin that is applicable here is the InlineBlock class provided by Layout Builder.
I want to re-use some of these block types in a node field. This usage is identical to how paragraphs are used on a field. The main module I would turn to in this sort of situation is block_field. Unfortunately it does not work with InlineBlocks, I've created an issue about this.
Is there a solution for this problem? Are there other patterns or techniques I'm missing? At this stage my only obvious solution is to convert these types to paragraphs which I know how to use in Layout Builder.

The block_field module is designed to reference block plugins rather than block content. I think what you want here is an entity reference field with an inline entity form or entity browser.
It's likely block field has never been tested with layout_builder enabled (where the InlineBlock plugin comes from) so that's where this confusion is coming from!


Add "email" to /admin/people overlay view I have been browsing around trying to find the answer to this but I am not having any luck. I want to add the users email to the table so that we can identify them easier. I have tried to create a new page and use "/admin/people" as the path but I get the error that it can not be overridden. I am relatively new to Drupal so if it sounds like a noob question that is why.

Have you tried using Views for this? This will work well if you want to make a new page that lists all of the users. It won't work out of the box if you want to add the email information to the existing admin/people overlay.

To use Views, enable the module and go to admin/structure/views/add
Give the View a name, and then for the 'Show:' option from the
dropdown select 'Users'
To create a new page, leave the 'create a new page' item checked, give the new page a title and path, and under Display Format select 'Fields' Hit Continue and Edit
On the next screen under Fields hit the Add button, and select User:email

There are tons of options to configure with Views - check out the Views Documentation for more information if you're new to Views.


Drupal Gardens like website I actually would like to start a website in which users can register and each registered user will get a subdomain. Each subdomain will be a drupal installation. I can share the files between installations and keep different databases for each of them (or table prefixes). I checked Drupal multisite, but it is mostly for the administrator who is maintaining the website. I need this functionality for the users as it is there in drupal gardens. I also checked Aegir and seems like its also for admin only. Basically I need the kind of functionality that Wordpress multiste plugin has have. Anyone know any drupal module which will allow the creation of multiple sudomain based websites on the fly ?

BTW, I am new to Drupal so my assumptions may not correct. It will be helpful if someone can guide me in right direction.

You can use Domain access module.

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

    example.com
    one.example.com
    two.example.com
    my.example.com


What is InstallerException and can it be thrown from a hook_install() implementation? The documentation for this Exception class is this:

  Base class for exceptions thrown by installer.

By "installer" does it mean any hook_install implementation? Which is what I assume, a counterpart to UpdateException? The hook_install documentation makes no mention of this, so my best guess is that it is a part of some plugin ecosystem.

No, this is not for hook_install(), this exception is for errors during installation of a new drupal site:

install.core.inc:

function install_drupal($class_loader, $settings = []) {
  ...
  try {
    // Begin the page request. This adds information about the current state of
    // the Drupal installation to the passed-in array.
    install_begin_request($class_loader, $install_state);
    // Based on the installation state, run the remaining tasks for this page
    // request, and collect any output.
    $output = install_run_tasks($install_state);
  }
  catch (InstallerException $e) {
    ...
  }
}


Permissions for new role do not work i have a certain problem regarding a content type and a "supervisor" role for it.

For the content type (which unfortunately did not create it myself but found it on an ongoing project), i have created a certain role (lets say "Supervisor" ) which shall give access to each user to "editing own content". Since all the content in this content type are created by the admin, for test purposes, i changed the author of a node from "Admin" to "user_1", and then later loged-in as "user_1" to edit the node, but no luck.

I tried several other alternatives, such as "content access" module, "create new content" permission, flexi-acces module, but nothing worked.

Whenever i try ../node/xxx/edit, it displays the node and not the edit screen.

Any ideas why this happens?

** i gave the "edit all content" permissions to the role, and the user could edit all the profiles (obviously) - i just wanted to check if everything works ok with the roles **

Make sure the "user_1" has a role as "Supervisor".And also check "content type: Edit own content" permission in people->permissions has assigned to "Supervisor" Role.Finally clear the performance.


Different row tpl for every row in a view? Can I create a different row template for every row in a view? Something like views-view-fields--foobar--0.tpl.php, views-view-fields--foobar--1.tpl.php and so on?
My goal is to create a slideshow width different template for every frame.

Out of the box with views? No. The row templates apply to all the rows in a given view.

You could do something like this with a custom module though...

You can use hook_views_pre_render to step through your view, like so:

function mymod_views_pre_render(&$view){
    if($view->name == "yourviewname"){
      $count = 0;
      foreach($view->result as &$row){
          $row->template = dostuffhere($row, $count);
          $count ++;
      }
    }
}

In this example, you would step through each of the result rows and and create printable content. The dostuffhere() function would be a routing function that would load in the appropriate template files, which you could define using hook_theme (example on how to call with a template file is in the comments). The custom .tpl.php files from hook_theme could be called like with the theme() function.

The routing function would then look something like this:

function dostuffhere($data, $row){
switch ($row) {
    case 0:
        return theme('mymodule_template1', array('$row'=>data));
        break;
    case 1:
        return theme('mymodule_template2', array('$row'=>data));
        break;
    //etc...
}

Because, in this example, we're using reference variables in hook_views_pre_render, the "template" variable will become available in the row output for the view. So all you really need to do in your row view is to just print out the $template var.


Commerce billy mail: how to attach multiple files to an email I have module commerce billy mail working. Additionally to the invoice PDF that is attached to the mail, I would like to send two more files (terms & conditions and a price list).

Here's the function _commerce_billy_mail_get_attachments from the file commerce_billy_mail.module, it seems to be the appropriate function (?), but I don't know how to add the additional files:

function _commerce_billy_mail_get_attachments($order) {
  $attachments = array();

  list($html, $filename) = commerce_billy_mail_pdf_prepare($order);
  $pdf_filecontent = commerce_billy_mail_pdf_create($html, $filename);
  $filemime = 'application/pdf';
  $attachments[] = array(
    'filecontent' => $pdf_filecontent, // we use a dynamically created file.
    'filename' => $filename, // can use any alias name here
    'name' => $filename, // required for mandril and other libraries.
    'filemime' => $filemime, // mime file type
    'type' => $filemime, // required for mandril and other libraries
    'list' => TRUE,
  );

  return $attachments;
}

Hope someone can help out!

I found out, how to attach multiple Attachments:

  $attachments[] = array(
    'filename' => 'MyDoc.pdf', // can use any alias name here
    'name' => 'MyDoc.pdf', // required for mandril and other libraries.
    'filemime' => 'application/pdf', // mime file type
    'type' => 'application/pdf', // required for mandril and other libraries
    'list' => TRUE,
    'filepath' => 'sites/default/files/mail_attachments/MyDoc.pdf',
  );


Found user with uid of 0 (zero) in users table... huh? Is it normal to have a user with uid of 0 in users table?

It is normal, as Drupal creates that entry when it is installed, for the anonymous user.  That is done from user_install() (Drupal 7), or system_install(), which contain the following code.

  // Drupal 7.
  // Insert a row for the anonymous user.
  db_insert('users')
    ->fields(array(
    'uid' => 0,
    'name' => '',
    'mail' => '',
  ))
    ->execute();

  // Drupal 6.
  // Inserting uid 0 here confuses MySQL -- the next user might be created as
  // uid 2 which is not what we want. So we insert the first user here, the
  // anonymous user. uid is 1 here for now, but very soon it will be changed
  // to 0.
  db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  // …
  // This sets the above two users uid 0 (anonymous). We avoid an explicit 0
  // otherwise MySQL might insert the next auto_increment value.
  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

That entry is normally used when joining the data contained in the "node" table with the data contained in the "users" table.

Not having that entry would cause Drupal not to work correctly in some circumstances.

If you need to restore the anonymous user data in the database, I would execute code similar to the one executed from Drupal. In particular, for Drupal 6, I would execute the following code.

If the data for the anonymous users already exists in the database, but the user ID is not 0:

db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

If the data for the anonymous user don't exist, even with the wrong user ID:

db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');

If you want to automatically restore the anonymous user data, you could implement hook_cron() in a custom module, and execute code similar to the following one. (The code is for Drupal 6.)

function mymodule_cron() {
  $uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", ''));

  if ($uid === FALSE) {
    // The data has not been found in the database; re-create the row.
    db_query("INSERT INTO {users} (name, mail) VALUES('%s', '%s')", '', '');
  }

  db_query("UPDATE {users} SET uid = uid - uid WHERE name = '%s'", '');
}

If you give to the module a lower weight, its implementation of hook_cron() will be executed before the other implementations, and this would avoid they will fail because the missing row in the database.


Views not showing Pager I created a Views out of some nodes and displaying it. And I've done views theming of type Row style output and saved the file in following format views-view-fields--[views machine name].tpl.php. All is working great except the views pager/navigation. It's simply not showing up, I tried all type of combinations : full pager, mini pager, Display a specified number of items and display all items, but of no use.

One important thing: I'm also using using CCK pager which might be overriding the views pager. For this issue, I tried changing views pager id, but that too failed.

I figured it out that i used multi-field selector which has its own set of min-max fields limits, which were by default set to display all. There was no conflicts between the CCK pager and the view pager nor with the pager id.


Installling fails with no error messages I installed Drupal 7 on linuxMint 17.1 localhost using the install wizard. Submitting the database configuration page leads to a white screen and nothing else happens.

Looking at the database I could see some data though.

Can anyone help me to fix it?

This is a typical white screen of death issue, ways to debug it are described here on drupal.org


Attach drupal ajax events to links that were loaded via ajax So I have links that are created when a page first loads that use a render array that is something like this:

array(
    '#type' => 'link',
    '#title' => html_entity_decode(t($title)),
    '#href' => $href,
    '#post_render' => array('_dva_post_render_ajax_link'),
    '#attributes' => array(
        'class' => array('ajax-link'),
        'rel' => url($href),
    ),
    '#ajax' => array(
        'path' => 'dva/ajax/'. $href,
        'wrapper' => 'content',
        'effect' => 'fade',
        'prevent' => 'mousedown',
        'progress' => array(
        'type' => 'none',
        'message' => '',
        ),
    )
);

These all work as expected and properly run the ajax and change the page content, etc.

However, when the page content also includes one of these links, the links included in the ajax response are just normal links and have no ajax functionality. The links are created using this same render array and they render correctly (that is, their markup appears the same as the links that work)

How can I tell Drupal to attach the ajax event handlers to the new links that have just been added to the DOM?

Try using the "use-ajax" class on the link

  In addition to using Form API for doing in-form modification, Ajax may
  be enabled by adding classes to buttons and links.

  By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call.

  When using this method, the href of the link can contain '/nojs/' as
  part of the path. When the Ajax framework makes the request, it will
  convert this to '/ajax/'.

  The server is then able to easily tell if
  this request was made through an actual Ajax request or in a degraded
  state, and respond appropriately.

  Source: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax/7

e.g:

array(
    '#type' => 'link',
    '#title' => t($title),
    '#href' => $href,
    '#attributes' => array(
        'class' => array('use-ajax'),
        'rel' => url($href),
    ),
);


Why isn't media respecting my allowed file type settings In my field settings for a media based image field, I have this:

When I upload an image and click next I get the following:

both of those types allow image files, but this particular field should only allow items to be classified as images.  Why is the setting not being respected?

My guess based on my own experience is that the uploaded file shares the same mime type as the publication files configuration, and the system is asking the user which file type to designate. Example, if both types allow for PNGs, it won't be able to determine the file type for you. Try uploading a file who's mimetype isn't shared by others; you won't get that dialog.


Image style URL does not work I have an issue related to drupal image styles, and I am not able to fix it since last two days. Have searched and tried everything on google, but of not help.

I have a drupal instance on production where all the images are stored at imgs/<entity_type>/<entity_id>/<filename>.  All these files have three different styles: thumbnail, entity_image, and slide. All the styles were working initially. Now suddenly most of the times styles do not work. If I change the image, most of the time styles show old images, even if at the URL location no image is present. Sometimes, thumbnails are not getting created.

To resolve this, the following are the things I already tried:

drush image-flush: Did not help
Changed permissions of styles to 777:  Did not help
Cleared all caches several times: Did not help
Disabled and re-enabled clean URLs: Did not help
Created another instance and tested: Issue persists
Tried to create style forcefully using image_style_url: Did not help
Changed +FollowSymLinks to +SymLinksIfOwnerMatch in .htaccess: Did not help.
Commented Options None and Options +FollowSymLinks in .htaccess: Did not help

Initially it looked like a permission issue but after all this, I am not getting what could be wrong. It could be some issue with inode creation, but not sure. So, please let me know your suggestions, what should be done in this case.

EDIT: I disabled clean URLs and everything worked fine. Enabling clean URLs again gives the same issue. SO it has to do something with the menu I guess, but not sure about the fix. Need a permanent solution as I can not afford to keep clean URLs disabled.

I added following lines in modules/image/image.module, on line 1056 and it started working.

// Create derivated image if it doesn't exist.
  if (!file_exists($file_url) && !file_exists($uri)) {
    if (file_exists($path)) {
      $current_style = image_style_load($style_name);
      image_style_create_derivative($current_style, $path, $uri);
    }
  }

FYI: This change comes with a risk of when Drupal core updates, this will get removed. Also, I found it affected the performance of search in our platform. So, need a permanent solution.


I want to create a custom Rule? I have to create a custom rule . Basically its a site for faculty.Before a faculty is added to site an authentication is done by there ldap server on first time login.After user is authenticated it redirects to site.Each faulty has there own vsite.So issue is that a faculty who has been removed from ldap then his/her vsite must be disabled.
Now is it possible to do it through Rule ??

Rules are very important and most common using thing in Drupal. We can create custom rules programmatically using the hook_rules_action_info. There is a useful hook hook_rules_action_info() provided by rules api to create custom rules programmatically. Using this We can use our custom functions to perform the actions that we require.

Following is a sample of the hook_rules_action_info implementation

function sample_custom_rules_action_info() {
  return array(
    'sample_custom_action' => array(
      'label' => t('Custom Rule Action'),
      'parameter' => array(
        'param1' => array(
          'type' => 'int',
          'label' => t('Sample Label'),
        ),
        'param2' => array(
          'type' => 'commerce_order',
          'label' => t('Sample Label2'),
        ),
      ),
      'configurable' => FALSE,
      'group' => t('sample Custom module action'),
      'callbacks' => array(
        'execute' => 'sample_custom_action',
      ),
    ),
  );

Label for the rule action appears in the Rules interface.
Parameter that needs to be passed to the custom action function
A group for this element, used for grouping the actions in the
interface.
callbacks are array of custom functions that to be used for this
action's functioning.

This function has more parameters, but the above are most required ones to create a custom action.

Video tutorial

Creating a Rules Action


How to disable specific message displayed by contrib/core? I am using the Disable Messages module to disable one of the message which is being displayed to the end user. The message is:

  Anonymous (not verified) has requested to be your Friend. View your
  pending friend requests to approve or decline.

To achieve this I have configured the module and written a regular expression to match a word from the message, But it seems to not be working.

Here is the code:

str.matches("(?i)(^|\\s+)(Anonymous (not verified))(\\s+|[.?!]$)");

Once a user has been deleted, The User relationships module have to delete all relationships associated to deleted user but it doesn't work correctly. I implemented hook_user_delete() in a custom module and delete non-approved relationships associated to the deleted user. like this:

/**
 * Implements hook_user_delete().
 */

function YOUR_MODULE_NAME_user_delete($account) {
  //user_relationships_delete_relationship($relationship, $user);
  db_delete('user_relationships')->condition('approved', 0 , '=')->condition(db_or()->condition('requester_id', $account->uid)->condition('requestee_id', $account->uid))->execute();
}


Local Task Menu - Add a Page link I am trying to figure out the best way to add a panel page navigation item to the local task menu set.

I want to create a Panel Page with QuickTabs to build a simple UX for a non-drupal admin to updated and edit users for there events.

I can add the quick tabs etc. to the panel page, however, I am not sure how to add the menu item to the local task menu tabs.

So, when you edit an event here is what I want the menu to look like...

View | Edit | Panel Page

So, Panel Page  is the new local task menu item for my panel page. I have been searching for a way and change not find it.

So, it took a while to figure what I needed was to add a custom local task navigation tab. To handle adding local task you need to learn the hook_menu() function, right after you learn to build your first hello world module. P.S. having the Test 1 and 2 menu items is what tells Drupal to create the outcomes tab.

/**
* Implementation of hook_menu().
*/
function outcomes_menu() {
  $items['node/%node/outcomes'] = array(
        'title' => 'Outcomes',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
  );
  $items['node/%node/outcomes/test1'] = array(
        'title' => 'Outcomes Test1',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );
  $items['node/%node/outcomes/test2'] = array(
        'title' => 'Outcomes Test2',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );

  return $items;
}

Hopefully, this helps someone else.


import local drupal site with database already exist i create a local website in my laptop and now i want to work on the project from an other laptop, after installing the module backup and migrate and active it , i download the public files settings and default database, after that in aquia dev desktop i choose import local drupal site then i choose the folder (public files downloaded) as my local code base folder and for database i choose start with Mysqldatabase dump file, at the end, after i click on the link: my local site, it shows me this :

Not Found

The requested URL / was not found on this server.

You can use Backup & Migrate Module for importing and exporting DB's.

  Backup/Restore multiple MySQL databases and code
  Backup of files
  directory is built into this version
  Add a note to backup files
  Smart delete options make it easier to manage backup files  Backup to
  FTP/S3/Email or NodeSquirrel.com  Drush integration  Multiple backup
  schedules  AES encryption for backups


How to give anonymous users access to only certain nodes? I am trying to implement the following:
Anonymous users are not allowed to view all nodes but only certain nodes.

I am using tac lite (https://www.drupal.org/project/tac_lite) to make this happen.

However, the only way I am currently able to control permissions to view nodes is the following:

not giving anonymous user the role 'View published content' and
   configuring tac_lite or other content access module to allow access
   to anonymous user to certain pages => doesn't work, access denied
   when testing nodes that user should has access to see

giving anonymous user the role 'View published content' => doesn't work, now anonymous users will see all the nodes regardless of settings of any other content access modules

Problem is not related to tac_lite. It also happens with for example node view permissions -module  https://www.drupal.org/project/node_view_permissions.

Also, when trying to solve the problem this page caught my eye:
https://www.drupal.org/node/270000
It says: "Only users who have 'access content'/'view published content' and not 'administer nodes'/'bypass node access' are eligible for the wild world of node access module control.."

I have understood that access control with Drupal is additive. Thus I should not give the anonynomous user the permission to 'view published content'. Yet, the text from https://www.drupal.org/node/270000 seems to contradict with this approach.

This is what devel node access shows when

I have set 'view published content' permission off for anonymous user
I have configured tac lite to show that page to anonymous user
I visit the page as anonymous user

You can use the Rules module for this.

Here is a prototype of a rule (in Rules export format) to get you going:

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "some\/path1",
                  "some\/path2"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed for Anonymous users.",
          "type" : "warning"
        }
      }
    ]
  }
}

Adapt the paths in it to fit your own needs, to reflect all the paths that anonymous users should not be able access. And for any access module you have enabled, allow access for anonymous users also (any paths that fit in the Rules Conditions will be blocked by the above rule, while any path that does not fit can be accessed by anonymous users). Obviously, using the "negate" facilities or Rules, you could also rework this prototype rule so that you only specify the paths allowed for anonymous users.


How do I see if it's improving my response time? I installed memcached for a Drupal 6 site. The status report shows it's properly installed.

How do I check if it's working as expected, and speeding up my site?

You can check the status at /admin/reports/memcache.


Add properties to an entity hook_schema_alter I need to implement a custom module that adds fields and properties to an entity defined in another module. I felt the best way to do this was using hook_schema_alter and hook_update_n to achieve the data structure updates. However, I do not see these new fields on my entity. Is there another step to take to attach these to the entity via code?

Using the third-party Entity API module, you can:

Implement hook_schema_alter().
Use something like db_add_field() to actually make the change to the DB in YOURMODULE_install() or updateN(). hook_schema_alter() does not actually create the field in the database. It just tells other modules at the code level that the field exists in the schema.
Implement hook_entity_property_info_alter(). This tells the Entity API module that this field exists as a property of some entity, where it lives in the database table, and how to access it.

Clear the cache to have the new properties showing up.

An example property in the $info array is basically the following one:

  $properties['survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make business logic easier.',
    // This is the schema field you made.
    'schema field' => 'survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );


Can I create a node that acts as a pointer to another node of the same type? For example:

There are two types, "contest" and "recipe".  A recipe can reference any number of contests, and a contest can be referenced by any number of recipes.  There is a recipe View that lists all the details of each recipe matching the criteria.  I want to filter the recipes listed only to those in the most recent contest.  I can add the contest relationship.  The problem is that I have to choose from one of the existing contests.  Can I create a contest called "mostrecent" that will refer to a different contest depending on which of all contests was created most recently?

You can create a view that lists contests in newest/descending order and limit it to 1 item, and use that to return the nid of the lastest contest, or if you are comfortable with SQL, do something like select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1 to get it.

You can then use that as an argument to another view that returns recipes based upon what contest they reference, eg, all recipes with a contest node reference of nid.

You can do that all inside the views UI with default arguments and so forth, or create a module to do it.

MORE SPECIFICS--the easy part:

create a view, filter it on published recipes
put in the fields area whatever you want to see, eg, the title linked to the recipe, a node teaser, etc.

MORE SPECIFICS--the hard part:

add an argument to the view:

a. select the field in recipe that is the node reference to contest

b. in action to be taken if argument is not present, select php code and enter:

$nid=db_result(db_query('select nid from {node} where type="contest" and status=1 ORDER BY created DESC limit 1'));
  return $nid;
save everything :)
Preview the view.  What should be happening now is the view will be returning all recipes that have the latest contest nid (aka node reference) in the field you entered in the argument above.


Sort by taxonomy weight I have a content type 'Member' with a field referring to taxonomy term called 'Member role' which is a multi value field. Each member may have up to 3 member roles.

I have created a view to display members which sorted by taxonomy term weight with reference to taxonomy field. But the problem is each member repeats 3 times in the view result page.

My question is how to remove duplicates and only sort by last value in the multi value field(Member role).

Below are a couple of things you can try to reduce duplicates caused by a multi-value field. Results will vary depending on your particular view.

1. Use aggregation

Under "Other" in Advanced options, enable Use aggregation.

Locate the offending field under "Sort criteria". Click on Aggregration settings, then select Aggregation type: Maximum.

2. Filter by delta

Under "Filter criteria", add the delta equivalent of your multi-value field; e.g. if your field is "field_artist_bio", there should be another field available called "field_artist_bio:delta".

Add the field. Set Operator: is equal to, Value: 0.


Panel Layout Designer I came across this video showing how to setup custom home page using Panels. I installed the Chaos tool suite, and Panels modules, but I don't see the Layout designer interface anywhere as it is shown in the video.

Have a look at Administer › Site building › Pages for the page you are wanting to design.

Click on the Content link in the left column and you should see a button for 'Show Layout Designer'.


How can I disable meta tags provided by the Metatag module for a custom route? I have created a custom module for displaying the players information. Module will create dynamic pages and each page will display players stats. With the help of the following links, I was able to add meta tags to my module.

How to add meta tag in head
Adding meta tags

Since each of the page generated by my module for separate meta information, I was not able to use page_attachement_hooks. Using the above links, I was able to add meta information in my controller itself.

But, I am using Meta tag drupal module for generating meta information for other pages. Now I am getting multiple meta tags with same property name. Global configurations of meta tag module is displaying along with my meta tags.

I read in some blog that if multiple meta tags found with same property, few crawlers will ignore them. How do I keep only my meta tags?

I saw this post which says how to override the meta tags. But there the code has to be placed in the module and it will be static. I wanted dynamic meta tags for each page. How will I achieve it?

Here is my code.

PlayerController.php

<?php

namespace Drupal\player\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal;

class PlayerController extends ControllerBase {

  public function content($player) {
    $result = [];
    /* --------------
     code logic here
    ------------------ */
    return [
      '#type' => 'markup',
      '#markup' => $result,
      '#attached' => [
        'html_head' => [
        [
         [
          '#tag' => 'meta',
          '#attributes' => [
            'property' => 'og:description',
            'content' => $result->player_details,
          ],
        ],
        'player',
      ],
    ],
  ],
    ];
  }

}

For reference, I am adding link to my old question regarding how to add meta tags in dynamic module. It have more codes in case you need.

Edit – @AlfredArmstrong pointed me to the hooks provided by the Metatag module itself. And there's hook_metatags_alter() you can implement to completely disable all meta tags added by the Metatag module. Much shorter than my original answer.

/**
 * Implements hook_metatags_alter().
 */
function MYMODULE_metatags_alter(array &$metatags, array &$context) {

  // Exclude meta tags on 'player' route.
  if (\Drupal::routeMatch()->getRouteName() === 'player') {
    $metatags = NULL;
  }
}

Original answer – I've had similar problems before. You can override or unset meta tags added by the Metatag module implementing hook_page_attachments_alter() like in the following example.

/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &$attachments) {

  // Check for the route you want to override.
  if (\Drupal::routeMatch()->getRouteName() === 'player') {

    // An array of tags you want to unset.
    $unset = [
      'description' => 1,
      'abstract' => 1,
      'keywords' => 1,
    ];

    $meta_tags = $attachments['#attached']['html_head'];
    foreach ($meta_tags as $key => $meta_tag) {

      // And now unset them.
      if (isset($unset[$meta_tag[1]])) {

        unset($attachments['#attached']['html_head'][$key]);
      }
    }
  }
}


How to hide homepage link from menu once logged in? I have a "home" link on my primary navigation menu. Once the user is logged in, the home link is irrelevant and I don't wish to show it.

I've set the access control permissions for the "home" page to only show for "anonymous user", but it's still visible in the menu once logged in. I'm guessing that authenticated users can see everything anonymous ones can, even if they don't have the box ticked. Is there some way around this?

I'm aware of "menu per role", but I read that it's better to set the permission of your content directly and let Drupal hide/show where appropriate, so I'd like to avoid using menu per role if possible.

Try with this code

function THEME_menu_item_link($link) {
  global $user;
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ( ($link['href'] == '<front>') && ($user->uid == 0) ){
       return '';
  } else {
      return l($link['title'], $link['href'], $link['localized_options']);
  }
}


Retrieve / call facet blocks from non search page I am trying to load full facet blocks on non search page to put them in cache.

What I am doing is looping through items with taxonomy $tid, then

$params = array('fq' => 'tid:' . $tid);
$current_query = apachesolr_drupal_query('apachesolr', $params, '', 'search/site');
$response = apachesolr_do_query($current_query);
$facet_block = module_invoke('facetapi', 'block_view', $block_id);

When I dsm $response->request, on each iteration I always see the first $tid in the query string ("q.alt=tid..."). The result I get is the same block for every terms, on each apachesolr_do_query requests.

Anyone got a clue on what is going on there ? The purpose of this is to generate cached facet blocks from non search pages, for several tid as the apache solr search parameter.

The problem is, apachesolr_do_query checks if a query has already been made:

apachesolr.module line 1470 :

  // Verify if this query was already executed in the same page load
  if ($response = apachesolr_static_response_cache($searcher)) {
    // Return cached query object
    return array($query, $response);
  }

So, all you have to do to process multiple ApacheSolr queries is to reset the Drupal static variable like so:

drupal_static_reset('apachesolr_static_response_cache');


Views: alter data of a View of another module I wanted  to add a relationship to data in a View of an existing module, so I've hacked the code (the function modulename_views_data) and it works.

Now I want to create a new  module to do this extension, leaving clean the original one. I guess I should use the function views_data_alter(&$data) but I don't understand how to bind it to the other module.

You would create a module.  It only needs a simple modulename.info file and modulename.module file.

If you called your module 'mymodule', then in mymodule.module add the function:

mymodule_views_data_alter(&$data) {
  \\custom code
}

Clear the caches and you should be good to go.

The hook system allows modules to interact with other modules code. By naming your function MODULENAME_views_data_alter you are telling Drupal that you want to take advantage of the hook HOOK_views_data_alter.


Millions of entities when logging I know there is a lot written on Drupal and tables that have tens of thousands and even millions of records but everyone has a different solution and I want to bring up a specific case.

I am using the log module (https://www.drupal.org/project/log) for Drupal 7 to save detailed custom log messages about a process that I have created for an internal system running on a small ubuntu VM in the Azure cloud. My bundle for the log entity has three custom fields. At 1.5 Million records with 4 custom fields that is 6 Million Records and we are growing every time the process iterates.

As you can imagine the site is slowed down to a near stop when making queries against the log table.

I am thinking of writing a little module to put the entities into a table that is not part of Drupal or exporting the data into a CSV file.

Is there a better way?

Thanks,
Josh

First thing I would look at is creating indices for your tables.  Look at the queries you are making and see if you can't optimize them with an SQL index. E.g. if you are querying against node id and user id with joins, try creating three indices, one for nid, one for id, one for nid and id.

Having the right indices can make a long running query fly.


Image upload broken when editing content Sorry if I'm using incorrect terms here. What's going on is, when I edit any content, as the the types of content under 'Content Management > Content Type', there's the Image: field, which I think is provided by the CCK Imagefield module or Imagecache. (I'm on 6.x-3.10 of Imagefield)

When I choose a file and click upload, I get a thumbnail image (http:/mysite.com/sites/mysite.com/files/imagefield_thumbs/image.jpg?1357151034). When I click 'Preview', I get a preview with the image I uploaded (http://mysite.com/sites/mysite.com/files/imagecache/product/image.jpg). When I save, the image is gone, and going back to the edit form, it doesn't show up as an attached image. One possible clue; this content type isn't 'product', but it's in sites/mysite.com/files/imagecache/product/.

This all worked until a couple of weeks ago, when I updated a bunch of modules. I did a whole site backup before I ran the updates, and a development version of the site on my local computer doesn't have this problem on up to date modules. The only way I can replicate it on my local machine is to use a backup of the database from after this error occurred.

Make sure the file directory exists at sites/default/files and make sure it is writeable by the web server. For this you need to go to the file directory if you are familiar with terminal and type chmod -R 775 files when in the directory that contains the file directory. otherwise in an FTP client like Filezilla right click the file and click file permissions and change the permissions there.  You may also need to check that this folder files/imagecache/product exists and is writeable.


What is wrong with this schema definition and db query? Hello and thank you for your time to help me in this weird case.
I have a schema API function that returns few database table information, and everything seem to work fine... except the most simple table.

$schema['quotes_key'] = array(
  'description' => 'Auth keys for quotes',
  'fields' => array(
      'qid' => array(
        'description' => 'The {quotes} this key belongs to.',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'key' => array(
        'description' => 'Key of the qid to be accessed anonymously.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('qid'),
    'indexes' => array(
      'qid'        => array('qid'),
    ),
  );

Then, I use drupal_write_record to write a new object to the database.

$key = new stdClass();
$key->qid = 789;
$key->key = md5(uniqid());
drupal_write_record('quotes_key', $key);

Whenever I run this code, I'm getting a mysql error:

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES (789, '02ab38a849e02744f532cdf3137df146')' at line 1 query: INSERT INTO quotes_key (qid, key) VALUES (1, '02ab38a849e02744f532cdf3137df146') in .../includes/common.inc on line 3576.

Can anyone kindly help me to figure out the problem ? I tried db_query to do the same database INSERT but getting same error. So I guess the problem is with my schema.
the qid is stored in a {quote} table.

I tried reinstalling schema by drupal_uninstall_schema() and drupal_install_schema()

Thank you.

I believe key is a reserved word. I'd stray away from using the key instead of trying to get MySQL to accept it. But here's some examples on how to get around it (which might not be possible via Drupal's db api).

https://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table


EntityFieldQuery not returning Bundle data I've defined an entity in hook_entity_info as follows:

function foo_entity_info() {
  return array(
    'Foo' => array(
      'label' => t('foo'),
      'base table' => 'foo',
      'entity keys' => array(
        'id' => 'bar',
        'label' => 'bar',
      ),
      'module' => 'foo',
      'fieldable' => TRUE,
      'bundles' => array(
        'Foo' => array(
          'label' => t('Foo'),
          'admin' => array(
              'path' => 'admin/config/foo/fields',
              'access arguments' => array('access content'),
          ),
        ),
      ),
      'views controller class' => 'EntityDefaultViewsController',
    ),
  );
}

When I run the following code:

$info = entity_get_info('Foo'); it all looks OK

When I run the following code:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo');
  $result = $query->execute();

it all looks OK

But when I run the following code:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type','Foo')
    ->entityCondition('bundle','Foo');
  $result = $query->execute();

I get an empty array in $result. This seems wrong.

What should I expect to see in $result and why aren't I seeing it?

Many thanks,

MB

What should I expect to see in $result

You should expect to see an array of data that represents the entities that match your query. This array will contain a key for each entity type it returns, and an array within each of those keyed by the individual entity IDs. The inner-most array will contain bundle key data for the entity. You will need to run the ID(s) through entity_load() or equivalent if you want access to general field/property data for the entities.

  why aren't I seeing it?

Not really possible to say without more information. If you know that you have existing entities that match the criteria, and they're not showing up in an EFQ, that's potentially the sign of a deeper problem with your installation (or it might not be, it depends).

If that's the case, clear your caches and try again. If that doesn't fix it, reinstall your entity module. After that, you're left with step-debugging to find out what DB query is being produced, you can run that against MySQL proper to see what's going on, and so on.


Change name to menu link dinamically I have a menu:

Parent-1
 - Child-1-1
 - Child-1-2
 - Child-1-3
 - another_child
Parent-2
 - Child-2-1
 - Child-2-2
 - another_child

I needed change the name of Parent-2 item (Parent-2 text is unique), I did it with hook_link_alter() hook:

/**
 * Implements hook_link_alter().
 */
function MY_MODULE_link_alter(&$variables) {
  if ($variables['text'] == 'Parent-2') {
     $variables['text'] = t('New name');
  }
}

I need too to change the names of all child of Parent-2 dynamically. I can't do it with hook_link_alter() hook because in my example there is two elements(another_child) with the same name. Those changes must not be saved in database.

How can I do this?

I can do it implementing hook_preprocess_HOOK hook, specifically hook_preprocess_superfish:

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_NAME_preprocess_superfish(&$variables) {
  if ($variables['id'] == 'superfish-main-menu') {
    $menu = ($variables['element']['#tree']);
    // ...
  }
}


How to make blob file downloadable? I have created a Module to make blob file available for Download in Drupal 7 .

Below my code for .module file

<?php

function blobfile_block_info() {
  $blocks = array();
  $blocks['blobfile_block'] = array(
    'info' => t('Blob Files Download'),
  );

  return $blocks;
}

function blobfile_block_view($delta) {

      $query = db_select('health_policy_document_upload_dtl', h)->fields('h');
      $result = $query->execute();

      $content ='';
      while($record = $result->fetchAssoc()) {

          $filename = $record['Document_Name'];
          $file     = $record['Document'];
          $type     = $record['Document_Type'];
          $size     = filesize($file);

          header("Content-length: $size");
          header("Content-type: $type");
          header("Content-Disposition: attachment; filename=$filename");

          $content .= "".$filename."";
          $content .= "
";
      }

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );

}

Please guide me where I went wrong.

I'm assuming you have already come up with a solution to upload the files and put them in the database, and that you have a good reason not to use Drupal's built-in file handling (I question that second assumption particularly given the reference to health policy but I'll grant it).

The block you created needs to just provide the list of links, but you should not set the headers there, just generate the links.  The link should probably be in the form of something like:  /custom_files/[filename]  (or something clearer based on your complete context.

First you need a hook_menu() to define the menu router to get your files. Something like:

function mymodule_menu() {
  $items['custom_files/%mymodule_filename'] = array(
    'page callback' => 'mymodule_filedownload',
    'page arguments' => array(1),
    'delivery callback' => 'mymodule_file_delivery',
  );
}

You should also add some permissions handling here, the documentation on hook_menu() explains how that works.  Also read the section on deliver callbacks because those also have security implications I'm glossing over.

Next you need the page callback function to actually send the file:

function mymodule_filedownload($mymodule_filename) {
   // Validate permissions
...
   // Validate filename
...
   // Load file object from database
   $query = db_select('health_policy_document_upload_dtl', h)->fields('h')->condition('filename', $mymodule_filename,'=');
  $result = $query->execute();

   // Prep an array to hand data off to the delivery callback. It might just be the results, but often you want to tweak details...
...
  return $file_data_array;

}

function mymodule_file_deliver($file_data) {
   // Check $file_data to see if this is a valid file or an error of some kind.
...
  // Process and errors found and send proper error response.
...

  // Send file
  drupal_add_http_header("Content-length: ".$file_data['size']);
  drupal_add_http_header("Content-type: " .$file_data['type']);
  drupal_add_http_header("Content-Disposition: attachment; filename=".$file_data['filename']);

   print($file_data['data']);

   drupal_page_footer();
}

Obviously lots of details are glossed over here. In addition to hook_menu()'s documentation you likely will also want to read drupal_deliver_html_page().  Note the use of drupal_add_http_header() instead of PHP's header(), for most basic tasks Drupal has internal functions that provide some clean up and standardization to avoid basic mistakes and conflicts with other module; you should use them whenever possible.


Drupal 8 route not found I keep having a 404 error no matter what I change on my routing file.

I've created a module in modules\custom which have :

An info file in modules\custom\first_module\first_module.info.yml:

name: First module
core: 8.x
type: module
package: Training modules
description: First Module created to learn coding in D8

A Routing file in  modules\custom\first_module\first_module.routing.yml:

first_module_hello_world:
  path: '/hello-world'
  defaults:
    _controller: '\Drupal\first_module\src\Controller\TrainingModule:helloWorld'
  requirements:
    _permission: 'access content'

A controller in modules\custom\first_module\first_module.routing.yml:

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloWorldController.
 */

namespace Drupal\first_module\src\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class TrainingModuleController extends ControllerBase {

 /**
  * Return the 'Hello World' page.
  *
  * @return string
  *   A render array containing our 'Hello World' page content.
  */
 public function helloWorld() {
  $output = array();

  $output['hello_world'] = array(
    '#markup' => $this->t('Hello World!'),
  );
  return $output;
 }
}

Any help would be greatly appreciated !

Edit: The Module is activated and I cleared the cache several times.

In first_module.routing.yml, controller there is no src and you use 2:  ::

first_module_hello_world:
    path: '/hello-world'
    defaults:
        _controller: '\Drupal\first_module\Controller\TrainingModule::helloWorld'
        _title: 'hello world'
    requirements:
        _permission: 'access content'

Also without src in drupal 8 there si no need to use  return $output;
Alsi class is not good. Class is TrainingModule not TrainingModuleControlle and file need to cole the some TrainingModule

namespace Drupal\first_module\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for hello_world module routes.
 */
class TrainingModule extends ControllerBase {

 /**
  * Return the 'Hello World' page.
  *
  * @return string
  *   A render array containing our 'Hello World' page content.
  */
 public function helloWorld() {

  return array(
    '#type' => 'markup',
        '#markup' => $this->t('Hello World!'),
  );
 }
}

change first_module_hello_world: to first_module_hello_world.help:

make the file first_module_hello_world.module and write this code

function first_module_hello_world_help($route_name, $route_match) {
 switch ($route_name) {
  case 'first_module_hello_world.help':
    $output = '';
    return $output;
 }
}


How to get the id of a group when using the Group module? I'm using the Group module.

How can I get the id of a group whose a user is a member (I have the user id)?

I would just start with creating a view (using Views) of all "Group memberships", and include all available colums of that specific base table. It should include things like "user id" and "group id".

If you then add a contextual filter to limit it to some selected user id, you'll get 1 views result (row) for each group that the selected user is member of, or is invited for, revoked from, etc (membership status for each group is one of the available columns to include in your view). For each group you'll have its group id available also, so if needed you can add a relationship to the group itself to have access to additional data about the group itself (eg: the group title, or any of its custom fields you added).

After you have such view created, you have a prototype of anything else you want to do with that, e.g use whatever you want in your custom module to invoke the Group's API functions.

PS: refer to my answer to "How to add a column to the list of group members or create a Views equivalent of it?" for getting started with creating such view (even though it's for D7, for D8 you can use a similar one).


Add a page to nodes with comment form I'm using Drupal 7.

I would want to add a page to my nodes, with the comment form (only), and a link in the tab menu to reach it :

I tried with views but I did not arrive there.

Do you know the simplest way to reach there?

I believe Display Suite module will do the trick.


How to show comments in teaser? As the title says, I'm looking for a way to show the node comments in teaser. Anybody knows how to do?

You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the teaser.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.


Drupal System cron temporary file/folder error I have very specific problem which I can't resolve. Thing is, I've created few files with function that creates temporary files and then system cron after running should delete them. Problem that I have is that I have manually deleted (temporary) file named "user-upload" and then created folder which has exact same name. Now when system cron runs it gives me two errors:

  Could not delete temporary file "public:///user-upload" during garbage
  collection public:///user-upload is a directory and cannot be removed
  using file_unmanaged_delete().

I think I should somehow clear something in database but not exactly sure where to look at. Running drush cc all isn't helping in this case.

Thank you

EDIT:
Eh, it takes you to ask question so you can get better idea. For the reference, solving this issue is locating particular file under database table "file_managed" column "filename" and then manually deleting it.
Maybe it will help someone...


No content type problem When I go to node/add. I see the message showing there is no content type:

But, when I go to admin/structure/types. I see three content types I have :

What could that be the problem ?
I'm using Drupal 7.14.

Try these.

1) You may have changed the Navigation block settings:(Administration -> Structure -> Blocks -> 'Navigation'). Configure the 'Navigation' block under 'Content types'.

2) Configure :structure>menus>navigation>listlinks (if you are using Bartik theme).

Reference: http://drupal.org/node/1166416, http://drupal.org/node/1094238


How to align views pager url with real page number? When creating pager in views (D7) you get urls with query parameter like page=X by default. But this X does not match actual page number.

page=1 is generated for 2 link in the paginator and so on.

Is there any way to make them the same without too much of code kung-fu or did I miss some checkbox?

As 4k4 mentioned in the comment there is an issue for this you should check out.

In the meantime you might implement a workaround (outside of Views)

with the help of the Query Parameters To URL,
or outside of Drupal through your server configuration and redirects.


How come Drupal Console is not downloading all commands? When adding Drupal Console using Composer, we are finding that the list of commands is not complete. How can I resolve the issue?

Installation steps:

change to root directory (/local/path/drupal-site)
run composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader
run composer update drupal/console --with-dependencies

Steps to reproduce:

Change to either Change to drupal-site/vendor/bin/ or drupal-site/vendor/drupal/console/bin directory
run drupal generate:form
error message below is returned.
change to root directory (/local/path/drupal-site)
run vendor/bin/drupal generate:form
error message below is returned again.

  [ERROR] Command "generate:form", is not a valid command name.

Versions:

Drupal core v8.5.5
Composer 1.6.3
Drupal console 1.8.0

output of drupal list

After spending hours on chasing this same issue, i quit and now use drush to create boilerplate stuff such as module, plugins etc.
After you install drupal site via composer with --dev try the following.

./vendor/drush/drush/drush generate module-standard # other generate commands there as well


Save a node from another site I have a newspaper web based management system that allow users to manage articles and news and photo album using J2EE (Internal system to the newspaper)

I need to make a website using drupal 7 to this newspaper

I need to make a button in the J2EE system that will save a node in my site(plain text,Full html test,files like images and pdf)

So I need to make a webservice in my drupal site and call it from the J2EE

Is there any module that help me in this issue,if not how to customize it.

The Services module will definitely help you with that

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It has CRUD operations for nodes, files, users and plenty more. There's a video presentation available that introduces it properly, and there are loads of code samples on the web to get you started.


Clean field value handling inside views_handler_field subclass? I am writing a few views_handler_field subclasses that render fields of my entity depending on other values of the entity. The examples I see use a very awkward way of accessing the other field data, eg.

function render($values) {
  if (isset($values->field_name[0])) {
    $my_stuff = $values->field_name[0]['raw']['value'];
  }
  ...
}

Is there a clean way of accessing other fields in the entity, like EntityMetadataWrapper? I would just load the entity and create a EMW instance but that seems expensive to do for each cell in a big table.

field_get_items() and field_view_value() are as clean as it gets without Entity API.


Update Mysql table row I'm new to Drupal and its SQL API, and I am trying to update a row in a table I created.

// Admin form
function admin_Form($form, &$form_state) {
  $dbval = getVals();
  $form = array();

  $form['firstname'] = array(
    '#type' => 'textfield',
    '#title' => 'Fornavn',
    '#id' => 'fornavn',
    '#value' =>  $dbval['firstname'],
  );

  $form['lastname'] = array(
    '#type' => 'textfield',
    '#title' => 'Efternavn',
    '#id' => 'efternavn',
    '#value' =>  $dbval['lastname'],
  );

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

  return $form;
}

function admin_Form_submit($form, &$form_state) {
  $update_zoho = db_update('zoho')
    ->fields(array(
      'firstname' => $form_state['values']['firstname'],
      'lastname' => $form_state['values']['lastname'],
    ))
    ->condition('lastname', 'lastname', '=')
    ->execute();
}

Everything gets executed and the message gets displayed, but the row is not updated.

Can anyone point a newbie in the right direction?
These are the table structure and the values is contains.

    title, firstname, lastname,  city, ... lots of colums
    ------------------------------------------------------
          - Bolli    - lastname - KBH  ....
          -          -          -
          -          -          -
          -          -          -

You need a condition() so that it knows which record to update.  When you don't give a condition, it just doesn't update anything.  More Info on db_update()

The following says, "Update firstname to formvalue, lastname to formvalue WHERE the last name as stored in database is 'Bolli'".  To avoid conflicts, your table should have a field that contains a unique value for each entry, such as an auto-increment primary key.  That way, you can say "UPDATE ... WHERE id = unique_id".

$update_zoho = db_update('zoho')
  ->fields(array(
     //'title' => $form_state['values']['title'],
     'firstname' => $form_state['values']['firstname'],
     'lastname' => $form_state['values']['lastname'],
  ))
  ->condition('lastname', 'Bolli', '=')
  ->execute();


How can I send a coupon to visitors? I need something which could seems a little strange, but it's a client request...

I have a site selling products using the Commerce module. All is working fine.

I need to allow the visitor to request a Discount Coupon in the following way:

The buyer see the full display for the product.
The product has a price of: 10,00 $
Bellow the price there is a form to allow the visitor to request a Discount Coupon
This form has 2 fields: one is email and the other one is called: 'I want to pay'. The visitor enter the price he/she wants to pay: 8,00 $ and the email.
The form is sent and some calculation are done based in: if the value of 'I want to pay' is >= than the price of the product (10,00 $). Then the condition is true and the visitor receive an email with a Discount Coupon
The buyer enters this Discount Coupon and pay 8,00 $ for the product.

Can I do this with Rules and Commerce Coupon. Do I need some other module?

I think this can be done via Rules and the Commerce Coupon Module. But you may need to write custom Rules condition and event. But first, from your question it is not clear that the form of email and price that you are saying is line items? I am assuming that those are line items and displayed in the Product display. So in that case in a custom module,

We will use the action "When an order is first paid in full" and create a new custom condition to check if the line items are set or not for the payment made. This can be done via creating a new file as "custom_module.rules.inc". In that file create a new hook as hook_rules_condition_info()

/**
 * Implements hook_rules_condition_info()
 * @return array $conditions
 */
function custom_module_rules_condition_info() {
  $conditions = array();
  $conditions['agree_to_mail_coupon'] = array(
    'label' => t('Check if user paid for Coupon Code'),
    'group' => t('Coupon'),
  );

  return $conditions;
}

function agree_to_mail_coupon() {
  //This conditions only return TRUE or FALSE.
  if(your line item check condition) { // Add logic to check for the line items. you will get API from api.drupalcommerce.org
    return TRUE;
  } else {
    return FALSE;
  }
}

Then create a new Event to send the mail. But you need a function to create the coupon code. So via commerce_coupon.module API list you will get commerce_coupon_create or other functions to use. So to create a custom event that will get the email address and the coupon code and send the mail you need the following,

/**
 * Implements hook_rules_action_info()
 * @return array $actions
 */
function armory_commerce_commission_rules_action_info() {
  $actions = array();
  $actions['send_coupon_code'] = array(
    'label' => t('Send Coupon code'),
    //Add your parameters in the parameter array. Given are some demo below
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
      'component_name' => array(
        'type' => 'text',
        'label' => t('Price component type'),
        'description' => t('Price components track changes to prices made during the price calculation process, and they are carried over from the unit price to the total price of a line item. When an order total is calculated, it combines all the components of every line item on the order. When the unit price is altered by this action, the selected type of price component will be added to its data array and reflected in the order total display when it is formatted with components showing. Defaults to base price, which displays as the order Subtotal.'),
        'options list' => 'commerce_line_item_price_component_options_list',
        'default value' => 'base_price',
      ),
      'round_mode' => array(
        'type' => 'integer',
        'label' => t('Price rounding mode'),
        'description' => t('Round the resulting price amount after performing this operation.'),
        'options list' => 'commerce_round_mode_options_list',
        'default value' => COMMERCE_ROUND_HALF_UP,
      ),
    ),
    'group' => t('Coupon Discount'),
  );

  return $actions;
}
function send_coupon_code($line_item, $component_name, $round_mode) {
     //Add your coupon generation code
     //Use Drupal_mail to send email to the user
}

I haven't tested this one as it's a unique type of requirement. But this will be a basic logic to solve the issue. You may need to do a fair bit of R&D to get it working. I appreciate if you ask if you found some questions & queries.


Book navigation pager is moved under the comments For some reason, if I change the display order of any field in Manage display for the Article content type, the Book navigation pager is moved to the far bottom under the comments.

If I check the template output, it is showing under the comments, which was not the case when everything was right. Even reordering the fields in Manage display to where they were before fixes this.

Is there any reason for what happens? Is it a bug?

I am using the Bootstrap theme, if this makes any difference.

This sounds like a weight issue.

First: Try actually setting the field display weights.

1) Click the "Show row weights" button.

2) This will replace the drag and drop interface with an integer weight field. Set the weights to be lower (more negative) for all of your field items. Hopefully, this will allow them to float above the comments field.

Second: If the above doesn't work, then you might have to manually set the weight of the elements by altering the form.

You will need to place your code in a custom module. And then using hook_ENTITY_TYPE_view() alter the weight of the comments form.

Your code would look something like this:

// This part would go at the top of your mymodule.module file.
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

This is where you actually set the  weight of the comment form.

function mymodule_node_view(&$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  // This probably isn't exactly what it will look like for you, but it's close-ish.
  if ($entity->getType() == 'book' && $view_mode == 'full') {
    // Not exact, but this should be pretty close as well.
    $build['comments']['#weight'] = 30;
  }
}

Hope this helps!


Access User Data from external script inside a custom module The method mentioned at Php Access User Data from external script works for me but only if the script is at the document root. If I move the file into my custom module the user returned is the anonymous user.

So, is there something else to do in order to keep all my files in my module and avoid starting to add custom scripts in the Drupal root folder?

Thanks!

The code snippet is bootstrapping Drupal by assuming it's in Drupal's root path (i.e. require_once 'autoload.php';) To have it runnable from the module dir, you'll have to alter the relative path to make it work from wherever your script is at (e.g. is your module is in DRUPAL_ROOT . 'modules/custom/my_module/scripts/my_script.php' you would have use the path ../../../../includes/autoload.php to reach it).

Depending on what you're doing, you might want to consider a custom Drupal Console/Drush command as a part of your module instead of a PHP script that has to assume/find the location for bootstapping Drupal.


Drupal7 - User/Registration customizing Please any one help me to how I can do customizing User/Registration page in Drupal 7. For example I have a select option for user group, suppose if I choose 'others' option ’ then user is allowed to create new group in separate text box.

I'm new to Drupal. Please anyone help me

In Drupal 7 you can use Select (or other) module for your requirement

  Select (or other) module : Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When
  'other' is selected a textfield appears for the user to provide a
  custom value.


Create a form without creating a page It seems simple enough to create a form in Drupal 7 with the Form API, however, everything I find shows that you have to use hook_menu() to add a page and then generate the form that way.

I would like to create a standalone form, then just display the form using drupal_get_form() and drupal_render() to render the form.

How do I create a custom form without creating it's own page?

It's very simple...add a function to your module:

function MYMODULE_some_form($form, &$form_state) {
  // Build and return your form.
}

Call drupal_get_form() from whatever context makes sense to your use case, and render the result:

$form = drupal_get_form('MYMODULE_some_form');
$rendered_form = drupal_render($form);

Then you can use $rendered_form as the output wherever it makes sense to do so (usually a template file).