Drupal 7 Override Image Alt and Title attributes In Drupal 6 I used the Imagefield Tokens module to set ALT and TITLE tags to default values if not specified (generally the node title).

I'm looking for applying this in Drupal 7, but I am having troubles. I found this thread, but it's a bit inconclusive.

Would it be possible to do this using a template preprocess or a field.tpl.php override?

I think a template preprocess would be fine for this, specifically hook_preprocess_image():

function MYTHEME_preprocess_image(&$vars) {
  // alt
  if (empty($vars['attributes']['alt'])) {
    $vars['attributes']['alt'] = DEFAULT_IMAGE_ALT;
  }

  // title
  if (empty($vars['attributes']['title'])) {
    $vars['attributes']['title'] = DEFAULT_IMAGE_TITLE;
  }
}

Pretty much all images (including those provided by a field) run through theme_image() so this is pretty much the best place for your code.


Is there a way to limit where a block displays based on a query in the URL? I have a page with a pager that displays a certain block at the top. I only want that block to be display on the first page but right now it display when I go to Page 2, 3, etc.

You can implement a condition plugin that does just that and then configure your block to use that condition, we did something similar once:

/**
 * Condition on the page query param.
 *
 * @Condition(
 *   id = "yourproject__first_page",
 *   label = @Translation("First page (by url query param)")
 * )
 */
class FirstPage extends ConditionPluginBase {

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    $match = !\Drupal::request()->query->get('page');
    return $this->configuration['negate'] ? !$match : $match;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    return $this->t($this->configuration['negate'] ? 'The %param parameter is not %value' : 'The %param parameter is %value or empty', ['%param' => 'page', '%value' => 0]);
  }

}


How to exclude nodes from a view if they appear on another view? I have two views called 'slider' and 'latest news'.
The slider view lists 5 nodes with content type news, article and blog post and if a custom field is selected on this nodes.
The latest news list the 5 latest nodes with content type news.

What I want to do is to exclude nodes from latest news view if they appear on the slider view.
If the slider view has only the news content type, it would be easy to exclude nodes by using the offset feature but because the slider view could have nodes from all these three content types and it's uncertain how many nodes come from each content type I couldn't solve my problem.
How to exclude nodes from latest news view if they appear on the slider view?

Try the Views Excluded Previous module:

  The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.

  This is very useful when you have pages with several embedded views, and you want to make sure that a given node only appears once in the page.


How to grant access to specific nodes to anonymous users? My site has a front page, an 'about us' and 'T&C' pages which are all created as 'basic page' types, and I want to allow anonymous users to access them. I have tried this hook below, but it does not seem to work because I am always redirected to the login page (using LoginToboggan if that matters).

function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'basic page' && $op == 'view') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}

If you need content access to roles by content types, you can try using Content Access module.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


embedding a block inside a views template file This question could be asked in numerous ways, so I'm just going to explain my situation.

I currently have a block that works fine listing any child nodes (node reference is used between the nodes). This works as it uses an Argument for the Node ID so it can list all the children in a nice list.

However, I wish to have this very list of child nodes - displayed in a sort of "Teaser List" from a seperate view. The reason this "new" view wont work - is because there is currently no Node ID to reference the children - as the block doesn't sit on the parent page anymore.

So my initial solution was to embed a view using views_embed_view with something like:

print views_embed_view('show_units_display', 'block_1', $node->nid);

And I would have this in my views template file for each result row. But seeing as the view itself sits on an entirely seperate page - no Node ID is passed here and there no results are displayed!

My overall outcome would look like this:

Node 1 - title
Node 1 - body

-- display list of children of node 1 here --

Node 2 - title
Node 2 - body

-- display list of children of node 2 here --

And so on...

Any help would be brilliant!
Cheers,
Garry.

A Computed Field on the node itself can also pass the NID to a view, regardless of the page it's displayed on.

Add a Computed Field to the node type.

in Computed Code:

$node_field[0]['value'] = $node->nid;

in Display Format:

$display = views_embed_view('VIEWNAME','DISPLAY', $node_field_item['value']);

If you store it in the database, then the field can be called in via Views.


Views Slideshow, show alternating content types Does anyone have an idea how i might display a slideshow with alternating data (odd even style) of content type?

Currently the view is loading the fields, and i guess it could be one step closer to load the rendered node, but how can one alternate it, and limit it?

So like :
Slide 1: Article
Slide 2: blog
Slide 3: Article
Slide 4: blog
etc..

In broad strokes, you could use Views' views_pre_render() hook to reorder the result of the View, eg...

function YOURMODULE_views_pre_render(&$view) {

   switch ($view->name) {

      case 'NAME_OF_YOUR_SLIDESHOW_VIEW':

        // to figure out what you have to work with, take out when done debugging
        drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

        // and here are the broad strokes... cycle through $view->result and
        // grab all the "rows" and re-order them by whatever business logic
        // you need, in this case even or them by content type instead of whatever
        // logic it is sorted in originally.  it you then set $view->result to this
        // new order, it will then be rendered by the Slideshow in that order

        break;

      // other Views might go here

   }

   // other code might go here, too...

}


How do I add comments to a YAML webform? I would like to add comments to the Sourcecode of my webforms in YAML.
# comment (without quotes).
But when I save this, it automatically gets removed.
20_e_mailadres:
  '#type': email
  '#title': E-mailadres
# write a comment here
21_werkmail:
  '#type': email
  '#title': werk E-mailadres

How do I add comments to a YAML webform so they are kept when I save?

Context

Drupal 8.x
Webform module
YAML comments

Use-case

developer KoenC wishes to add comments to a YAML file and have those comments retained upon save

Problem

Per the YAML specification, comments are specified as "throwaway" artifacts.
This means that YAML commments are not required to be preserved by parsers that implement the YAML specification

Workaround

Metadata and comments can be added as separate YAML nodes (see e.g., https://stackoverflow.com/a/8565238/42223)


How can I filter the entire contents of a site by region? I have a classifieds site that I created at http://www.gastonia.com.  I've introduced the location module, and I am using views to search by proximity after someone types in a zipcode and distance. Everything is working fine.

I now want to experiment with filtering the entire site's displayed contents - all pages, all blocks, all views, all menus, etc. When someone types in their zip code and hits submit, every item of content is filtered for them within 25 miles of their region.

I can easily do this with Views and filters, even for blocks where arguments don't work.  I also want to do this for all 770 towns in my state, which means creating views programatically.  Each would have its own page / url title like Gastonia-NC and Shelby-NC and show items accordingly.

I  have created the script to do that - loop through all 770, and everything actually works, except it's slow, to say the least. Maybe there is a better way to do this?  Note the production site does not have the location / filter implemented, just my dev.

You can still use views then just use the views global filter module. This way they only enter their location only once then every other view on the site inherits this filter.


How do I add JavaScript to a site? How can I add JavaScript and CSS to my site?

The Managing JavaScript in Drupal 7 guide provides the information to add JavaScript to Drupal. The techniques presented there apply to both themes and (custom) modules:

Add a scripts[] = somescript.js to your module or theme's .info
file
Use drupal_add_js() in your module or theme's code
Use the #attached['js'] property in a Form API or renderable array.

Note that Drupal already include jQuery, jQuery UI and a bunch of other libraries so you don't, and shouldn't, add them yourself. Instead you should use drupal_add_library() or the #attached['library'] property.

The Working with CSS guide provides the information to add CSS to Drupal. Again, the techniques presented there apply to both themes and (custom) modules. With an exception: addition of style sheets from an .info files only works for a theme and not a module.

Add stylesheets[all][] = somestylesheet.css to a theme's .info file.
Use drupal_add_css() from module or theme's code.
Use #attached[css] property in a From API or renderable array.


Printing a map using ViewsPDF I am using drupal 7 and the ViewsPDF module to generate PDF's from my content. One of my content types has a map that I have done using a geofield. While trying to export the node as a PDF everything gets printed except the map. I've done a bit of asking around before posting this.
Anyone with a solution to this?

The real problem with such maps is that, the PDF gets generated before the map appears.
I'm assuming your map provider is JavaScript based - that means the map appears on the user browser and your server just sets the javascript parameters.

I had to do a similar thing a long time ago, and the only solution that seemed easier was to use Google Maps with static maps. You can embed an image with parameters such as pointer options and geocodes and the maps server will return a static image. Worked in dompdf.


Add a hidden field on form submit I am working on a login form (information sent via https to a remote system), that by default contains a username field, a password field and a static hidden field (necessary in order to validate with the remote system).

There is one additional hidden field necessary, which should be built from the value of the username and the value of the existing hidden validation field, separated by an underscore, like this: username_hidden_id

Is it possible to achieve that after the form has been submitted? I tried to add the field using the form submit function, but that doesn't seem to work.

I could add this the mentioned field and generate it's value via JavaScript/jQuery, but I wouldn't like to have this field visible/public.

I have the following code:

function custom_login_form($form, $form_state) {

    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => t('Username'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#size' => 15,
      '#required' => TRUE,
    );
    $form['password'] = array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#size' => 15,
      '#required' => TRUE,
    );
    // Hidden validation field
    $form['hidden_id'] = array(
      '#type' => 'hidden',
      '#value' => '1234',
    );
    // Submit button
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Log in'),
    );

    return $form;
}

function custom_login_form_validate(&$form, &$form_state) {

  if (empty($form_state['values']['username'])) {
    form_set_error('username', 'Please enter a username.');
    $form_state['rebuild'] = TRUE;
  }
  if (empty($form_state['values']['password'])) {
    form_set_error('password', 'Please enter a password.');
    $form_state['rebuild'] = TRUE;
  }

}

function custom_login_form_submit(&$form, &$form_state) {

  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $form['username_hidden_id'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'],
    );
  }

}

You don't want to modify the $form array in the _submit function. Rather, you should modify the $form_state['values'] array, as that's where all submitted values are stored. So:

function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $form_state['values']['username_hidden_id'] = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
}

Note that you can also do all of the above in the _validate function, and $form_state['values']['username_hidden_id'] will then be available in the _submit function.

Why do you need it to act like a submitted field, though? I would just save it as a variable and use it as needed, like so:

function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $username_hidden_id = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
  // Do something with $username_hidden_id here.
}


Can't get Ajax data sent to my PHP function I recently took over an existing Drupal project and I tried to add a new PHP function (which works regularly) and link it with an Ajax query. There were already some in place that worked, and I wanted to add one that when you press a link, it sends the ID in the link to a PHP function which generates an info field. By copying the working code I got to this:

In my module, I added a menu hook referring to the PHP function in the module and the Ajax link:

$items['api/feedback'] = array(
  'page callback' => 'admin_user_feedback',
  'access arguments' => array('access feedback'),
  'access callback' => TRUE
);

return $items;

This is my Ajax code:

function getFeedback(id){
    $.ajax({
        type: "POST",
        url: 'api/feedback',
        dataType: 'json',
        data: {
            'id': id,
        },
        success: function(data){

            alert("success");
        },
        error: function(){

            alert("error");
        },
    });
}

I know the function gets called on, but the console gives this error:

  POST http://localhost:8080/site/api/feedback 404 (Not Found)

The URL is correct, the other APIs with similar URLs do work, so somehow he doesn't recognise this API, I must have missed something. Does anybody know?

Check your URL again...  should it have /site/ ?   I am guessing not, unless you have something going on it should be:   http://localhost:8080/api/feedback

url: '/api/feedback',


Automatically insert images to translated page I have a bilingual D7 website. It seems odd to insert all images twice, one for the original and one for the translated version, so my question is: Is there a way to automatically insert the image I upload for my orignal site into its translation?

You should use Entity Translation module instead of core Content Translation to provide multilingual functionality into your site, then define which fields are translatable and which are not.
You can't reach your goal with Content Translation module only.


How to send a confirmation reservation email using the Reservations module? I'm using the Reservations module to control certain resources.  I'd like to send an email to the user who reserved the resource when it is confirmed.  I also installed the Reservations email module to handle that.  I could not find a token to use to refer to the user in the email body.

Currently, when a user requests a resource, an admin receives an email.  When the admin confirms the resource I'd like to send the user an email confirmation.

Any suggestions about how this can be done with the existing module?

The Reservations: Email module is what allows you to send eMails. Some more details about it (from its project page):

  This module extends Reservations to send emails at different stages in the reservation process. Token based templates are included so the emails can be customized with any information from the Reservation node or User objects. Also included is a pseudo-token for a confirmation link that allows users to confirm reservations without the need to grant them the permission to confirm reservations.

However, looking at the module source, using tokens in the eMail body requires that the token module is enabled. So if you haven't enabled that module yet, it may explain why you "could not find a token to use to refer to the user in the email body" (as in your question).

Update:

About your extra comment like "... I had to add a new field to the reservation type to save the name of the user requesting the resource. I later used that field in the email.": that seems like a variation of what's written in the issue about "Sending emails to anonymous users". That issue contains a patch that you may want to look at also.


Validating user email ID during sign up We are making a accounting software and would like to know how we can use a open source API  or query to validate user email id by sending email to the specific email id and getting a activation response from the same using a weblink.

There's no need to use any sort of API or query. If you're goal is to validate email, it's built into Drupal's core account settings (Configuration > People > Account settings). Just make sure the Require e-mail verification... checkbox is ticked on the form page.


Submit of custom node with imagefield ends without warning after imagefield save I have a custom Drupal node type with a bunch of text fields, a taxonomy-dropdown and an imagefield. Only the title is mandatory, all other fields are optional. I have added no custom code that should interfere with the form being processed.

When I submit the filled-out form to add a node of this type, the form reloads without adding the node and without displaying any kind of error message. When I leave the title blank, the expected error is displayed.

EDIT/UPDATE

I have started reconstructing the content type and found out that the imagefield seems to be the culprit. The node will save flawlessly if the the type does not have an imagefield.

The minute I add the imagefield, saving fails. The image will even be uploaded, thumbnails will be displayed, but then the form will reappear with no further message.

The issue had something to do with duplicate translations for button labels that basically lead to only the file field being submitted when saving the node, see: http://drupal.org/node/684426 A simple update of the localization files solves the problem and makes you hate Drupal just a teensy bit.


Sending a JavaScript variable to a PHP function I am trying to send a value in JavaScript variable to Drupal. I am calling an external js file in hook_nodeapi(). I want to send a value from this external js file to Drupal, and want to use this value in Drupal in hook_block.
For example

hook_nodeapi() {
  // call(external.js)
}
external.js
var sendData =10;

hook_block
{
  case view:
  // need to access sendData value
}

I tried this using cookies, but I think that is not the best way.
How can this be done?

Let's look at what the client can do as an alternative to setting a cookie:

Make an AJAX request that lets the server store the variable.
Add the variable name and value to the query string of every internal link and to every form submission (not just the next one).

I do not see any benefits of Solution 1, that justifies the extra HTTP request. Especially, you cannot circumvent the necessity for the user to have Cookies enabled, because the value must be stored close to the user and Drupal uses Cookies exclusively to determine the session (and thus the user).

Solution 2 allows for different values within the same session. If this is not one of your requirements, I consider this solution too much of a hassle.


How to add an image(field) to a block? I want to add a block containing an image-(field) to Drupal, so it can be added to the block layout.
I can see the image gets uploaded (because it appears in my file system). But, the block 'forgets' about the image. Next time I configure the block, the image I just uploaded has disapeared.
The documentation is a bit fragmented, and I can't figure out how to:

set a default value for the image
how to create the render-array.

What I've got so far:
  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];
    $build['image']['#markup'] = '';
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

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

    return $form;
  }

  public function  blockValidate($form, FormStateInterface $form_state) {
//    File::load( $form_state->getValue('image'));
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}

How do I display an user-uploaded image?
How do I make the block remember this picture?

With help from "Ambidex" on Drupal Slack, I post here the complete plugin-file.

I could not find an example for this use case, and I believe it might benefit others:

file: [drupalroot]/modules/custom/ourcustomername_tweaks/src/Plugin/Block
/ContactBlock.php

.

<?php

namespace Drupal\ourcustomername_tweaks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

/**
 * Provides a 'Contact' Block.
 *
 * @Block(
 *   id = "contact_block",
 *   admin_label = @Translation("Image Contact block"),
 * )
 */
class ContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [

        'image' => [
          'value' => ''
        ],

        'label_display' => FALSE,
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];

    if (  isset($this->configuration['image']) && !empty( $this->configuration['image'] )  ) {

      $image_field = $this->configuration['image'];
      $image_uri = File::load($image_field[0]);

      $build['image'] = [
        '#theme' => 'image_style',
        '#style_name' => 'ourcustomername',
        '#uri' => $image_uri->uri->value
      ];
    } else {
      $build['image']['#markup'] = '['.t('Picture').']';
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}


Dynamic views for categories I'm really stuck on a problem that I'm seeking assistance on.
I have 3 categories under the same Taxonomy Vocab for a specific content type .

Taxonomy:
 - category 1
 - category 2
 - category 3

Now I need to make a view that when i click the link for category 1 it will show all content under that category . same as the other category . Im currently using D7.

I thank you much in advance for any assistance you can provide!

this is a follow up question ...

contextual filter saves me from this filter but when I try to access it in the url the layout of the page is not like the views ... it gets the views for the taxonomy

Suppose u have a content type called as Article. So simply add the fields in the view that you wish to show.

After adding the required fields add a contextual filter for the taxonomy term (Content: Has taxonomy term ID). In the contextual filter, select provide default values "Taxonomy term id from the url".

Save the view and it would serve your purpose.


Managing user accounts on remote drupal website? (Dev team all needs access) My company makes lots of Drupal websites and the biggest annoyance I've seen is having to add each other as a user to each site whenever someone else wants to work on it. We all have the same email address domains as we use google docs.

We currently use openId and login with our google accounts but we have to make everyone a user on each site and they have to activate it.

Is there some type of module that would allow us to all have access to any site if said module was installed? Or that it would allow us to create an admin account because we have and can verify our domain in our email through google apps?

Thanks!

maybe User Import and keep a running cvs file of users to add to new sites on an as needed basis (?)


How to build render array with node title linked to node for a list of nodes I have a paragraph type to output a list of content. The editor can set different options, one of them is to show the list as teasers or just node titles linked to node. The corresponding part in code looks like:

    if ($teaser_display) {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }
    else {
      $value = \Drupal::entityTypeManager()->getViewBuilder('node')->viewField($node->get('title'), ['link' => true, 'type' => 'entity_reference_label']);
    }

Is there a way to build the render array for titel field linked to the node without creating a dedicated view mode and without rendering the markup directly? I thought it should somehow work to use the method viewField() as $display_options can either be a view mode or an array with display options.

As pointed out by @4k4 I used the entity reference field formatter, which does not apply here. Theming as link, as answered in How do I theme a link? does the job:

if ($teaser_display) {
  $value = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
}
else {
  $value = [
    '#type' => 'link',
    '#title' => $node->label(),
    '#url' => $node->toUrl(),
    '#cache' => ['tags' => $node->getCacheTags()],
  ];
}


Drupal 7 Homebox module and Twitter Bootstrap theme I am using Drupal Homebox module (https://drupal.org/project/homebox, version 7.x-2.0-beta6) to create a dashboard. I've found an issue that the save function to keep the status/location of blocks on the dashboard (closing or moving) doesn't work when using Twitter bootstrap theme. But there is no problem when using Batik theme. I could not find any clues of what cause this issue.

Any help would be greatly appreciated!

Hi make this change found on sites/all/modules/homebox/hombox.js on line 16.

Drupal.homebox.$pageSave = $homebox.find('#homebox-save-form button[type=submit]');

Why?
bootstrap changes the input type in the page.tpl so you need to reflect the changed


Display comma-separated list of taxonomy terms? Drupal 7.

In my node.tpl.php, I want to print out a list of taxonomy terms (the taxonomy is called "channels.").  If I use:

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

It works, obviously, but the best I can do to get them inline is to use CSS to float them left. I would like them to be separated by commas.  Any ideas?

Thx.

You could try theming the field using field.tpl.php or theme_field().

As an example (using field.tpl.php):

Copy field.tpl.php to your theme directory from "modules/field/theme"
Make a copy of that file and rename it to field--field-channel.tpl.php
Edit the file however you like.

As a quick/dirty example for this to work, field--field-channel.tpl.php could look like:

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

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>

    <?php endforeach; ?>

There are probably multiple ways to accomplish this using the .tpl file, but this is just one option.  I recommend adding a class to the DIV instead of a style and make the changes in your stylesheet instead of using inline styles.


RULES : How to redirect user to a page after login unless they're using the one-time-login-url? I created a rule to redirect users to the front page after they login.
It works fine

The problem is when a user uses the link received on his email to choose a new password, or after clicking on the link to validate their signup, they're also forced redirected to the front page instead of heading to their user page to choose a password (in the case of a forgotten password) or finish their profile setup (after clicking on the link to validate their registration)

Any ideas on how to fix this ?

1st method:

I believe there is a module called Login toboggan which will allow you to do exactly what you want.

From the module page:

  The LoginToboggan module offers several modifications of the Drupal
  login system in an external module by offering the following features
  and usability improvements:

  Allow users to login using either their username OR their e-mail
  address.

  Allow users to login immediately.

  Provide a login form on Access Denied pages for non-logged-in
  (anonymous) users.

  The other brings the user to a separate page, but returns the user to
  their original page upon login.

  Optionally redirect the user to a specific page when using the
  'immediate login' feature.

  Optionally redirect the user to a specific page upon validation of
  their e-mail address.

  Optionally display a user message indicating a successful login. ...

2nd method:
I believe when someone request a password, the format of the link will be similar to this one:

https://www.drupal.org/user/reset/...

If so, you can create a rule to redirect the user upon login to a specific page. However, add one condition which will be:

Data comparison: the link should not contain the word reset

Hope it helps,


Field with type 'Term Reference' (only if I use View as data source) display N/A as first value I have a field with type 'Term reference' and widget 'Check boxes/radio buttons'.
As a first value I have a N/A and I've no clue why it appears there.

Term reference works fine if I do not use View.
It's not required to be filled.

Is it possible to remove it in proper way?

Thanks.

A very late answer, but hopefully it will still help you.
I think if you change the term reference field, you have an option if it is optional or mandatory the field. When you choose mandatory, it should be removed that option.


Can I use drush to compare the running modules on two sites on the same server? Is there a way to use drush to compare the list of running modules on two Drupal 6 sites?

I have two sites running locally (with two code bases if that matters) with different modules, but a very similar odd problem (discussed about here). In trying to find the modules that might causing this problem, it would be really helpful to get a list of modules that are running on both sites.

I don't know if there is a direct way, but this should work with bash or a similar shell. No idea about how to do that with Windows :) Please comment and I'll integrate it into the answer.

First, save the enabled modules of both sites into a textfield with this command:

drush pm-list --status=enabled > enabled_modules_site_x.txt

Then, you can easily compare the output of these two files with diff.

diff first_file second_file


How do I create a full project from a sandbox project? We have created a module for Drupal 8 on drupal.org, but it is a sandbox project. How do I make it a full project?

You need to have your account elevated to be able to promote a project to full status, meaning you have to go through the project application process if you have not already.

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


In Ubercart auction final bid amount adds sell price instead of highest bid amount in the cart? In uber-cart after auction has been won, the buyer will get add-to-cart button to add and buy the product. After clicking on add-to-cart button, it adds sell price value in the cart page instead of highest bid amount.

How to make it add highest bid amount in cart page instead of sell-price.

Any suggestions? Thanks in advance.

/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your bid product

    $items[$index]->price = 100;
  }
}

For reference:

http://www.ubercart.org/docs/api/hook_uc_cart_alter


Installing a profile inherited from an existing distribution I would like to build a distribution based on the Standard profile coming with Drupal 7, by inheriting all the features of the parent distro and changing some of them with custom code.

The title of this question sounds very similar to "Is there a way to inherit a Drupal installation profile?". While the referenced post deals with building the code base, ie a .make file, here I am interested in site installation of a distro made of profilename.info, profilename.install and profilename.profile.

There is a solution proposed in [How to Write a Drupal 7 Installation Profile][2], that seems quite simple. So I tried the following code in mydistro.profile:

function mydistro_install() {
  include_once DRUPAL_ROOT . '/profiles/standard/standard.install';
  standard_install();
}

If this worked I could add custom features further down in the process.
Then I ran site-install with drush:

drush -d si mydistro -y --db-url=mysql://root:secret@localhost/mydistro_com

The process installs the database with 43 tables (out of 74 that come with the standard profile), and enables the following modules:

user, field_sql_storage, filter, node, field, text

and then throws this error message:

exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table                              [error]
'mydistro_com.block' doesn't exist' in C:\xampp\htdocs\mydistro.com\includes\database\database.inc:2171
Stack trace:
#0 C:\xampp\htdocs\mydistro.com\includes\database\database.inc(2171): PDOStatement->execute(Array)
#1 C:\xampp\htdocs\mydistro.com\includes\database\database.inc(683): DatabaseStatementBase->execute(Array, Array)
#2 C:\xampp\htdocs\mydistro.com\includes\database\mysql\query.inc(36): DatabaseConnection->query('INSERT INTO {bl...', Array, Array)

saying that the block table is missing. All other tables belonging to the modules that are listed as dependencies in standard.info are also missing:

dependencies[] = block
dependencies[] = color
dependencies[] = comment
dependencies[] = contextual
dependencies[] = dashboard
.
.
.

I have tested with Drupal 7.38 on Windows 7, php 5.6.2.

Same test and same result also with minimal profile.

Any idea about what I am doing wrong?

Are you adding those dependencies to your .info file mydistro.info?

If not, you should. It looks like the install is getting to line 196 in the standard.install file and then trying to enable all those blocks, but the blocks module was never enabled and it doesn't test for that, which is breaking the install. @VanD

Basically you should add the same modules listed as dependencies in the standard profile, also to mydistro.info and re-run the installation.


Add "n" fields when click on "Add another item" When I click on "Add another item", It should create 10 new fields.
Is there a way I can do this?

There is an open feature request for this on Drupal.org but it is not currently supported out of the box. See https://www.drupal.org/project/drupal/issues/1394184 for details


Deleting User Picture changes the password of user? I have used following code to delete the user picture on click of a form button element (using #ajax).

function delete_user_picture($form, &$form_state){
  global $user;
  $account = user_load($user->uid);
  unset($account->picture);
  $edit = (array) $account;
  user_save($user, $edit);
}

This successfully deletes the picture but also changes the password. How can I prevent it from doing so?

UPDATE:
Based on Molot's Suggestion, I made the following change to code and now it works perfectly:

function profile_delete_user_picture($form, &$form_state){
  global $user;
  $account = user_load($user->uid);
  $file = file_load($account->picture->fid);
  unset($account->picture);
  $edit = array();
  //add just the picture info and not the whole account info and password won't be changed
  $edit['picture'] = $account->picture;
  user_save($user, $edit);
  if ($file != NULL) {
    file_delete($file);
  }
}

Also added code to delete the file from database as per SlakeFistcrunch's Suggestion.

Yes it does. This works as designed, but you made mistake. When you obtain user object, it does not contain a password. It contains a password field, but it's not populated with actual password as it is impossible by design to know it. So you are feeding all fields to user_save, including field for password, but without password in it.


How use strongarm with domain access? Lets say I have 2 domains, A (Site A) and B (Site B). I achieved this with domain access module. Then with features and strongarm I would like to export site_name variable from both domains. How can I do it?

What you want is the Domain Conf module which is a sub-module of Domain Access and provides you per-domain configuration.

  The Domain Access: Site Configuration module (called Domain Conf), is
  an optional extension of the Domain Access module.  Domain Conf
  provides options for configuring basic settings of your affiliate
  sites to be different.


how to attach existing images(image field) to node in drupal 7? I use the following code to upload images

$node  = node_load($nid);
$file  = (object) array(
  'uid' => $v['uid'],//@todo from query
  'uri' => 'public://'.$v['filename'],//@todo from query
  'filemime' => $v['filemime'],//@todo from query
  'status'   => $v['status'],//@todo from query
  'fid' => $v['fid'],
  'filesize' => $v['filesize'],
  'timestamp' => $v['timestamp'],
  'type' =>'image',
  'metadata' => array('height' =>1200,'width'=>1099),
  'height' => 1200,
  'width'  => 1099,
);
$node->field_image[LANGUAGE_NONE][0] = (array) $file;
node_save($node);

This does not work, I am not able to figure out the error in the code which prevents from image upload

can u provide me an example of how to upload image programmatically
  provided I have an image url on the public path in D7

This should do the trick

$node  = node_load($nid);
$image = file_get_contents('public://images/folder_name/image_name.jpg');
$file  = file_save_data($image, 'public://images/folder_name/image_name.jpg', FILE_EXISTS_REPLACE);
$node->field_image[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);


Language switcher shows me same node on switch I am using Locale and Content Translation modules. First I created node and translated it. On content listing both have proper alias urls, everything seems to be ok.

As a guest user I see content in first language when I want to switch to translated version of current node, language switcher block gives me node in the same language (previuosly selected) and url of this node is just raw node url (node/ID). So everything is f up.

Could somebody give me any advice?

More info:

current lang is en:

language switcher links: pl (node/154) and en (en/sample)

en/sample is alias of node/154 :/

But I am sure that I have translated to "pl" node of id 154.

Lanuage codes (admin/config/regional/language):
en, pl

Detections (admin/config/regional/language/configure)
- URL

I try to solve it again and it's was Global Redirect module fault. Please use Redirect intead


Reset a form element value through AjaxResponse I have an AjaxCallback which returns AjaxResponse(). I need to change some form element properties like (disabled to true, remove some css class etc which works). But I'm unable to reset the particular form input element value to null.

Something like this -

public function calbackfunc(array &$form, FormStateInterface $form_state) : AjaxResponse {

  $response = new AjaxResponse();

  $element = $form_state->getTriggeringElement();

  $element_value = $element['#value'];

  if ($element_value === 'hit') {
    $response->addCommand(new InvokeCommand('.hit-container input', 'attr', ['disabled', FALSE]));
    $response->addCommand(new InvokeCommand('.hit-container div', 'removeClass', ['form-disabled']));
    $response->addCommand(new InvokeCommand('.hit-container input', 'removeClass', ['error']));
    //apart from these steps I also want to set the input value to null.
   }

   return $response;
 }
}

This question is a follow up to the earlier question I've posted Form element replaced via Ajax callback doesn't seem to be submitting or the values are not appearing in buildForm .

I tried like this -

$response->addCommand(new InvokeCommand('.hit-container input', 'setValue', ['myfield', '']));

But no luck. Any help would be great.
Thanks.

You can try the code below

$response->addCommand(new InvokeCommand('#field_id','val',['']));

The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js.

Please see InvokeCommand


Pantheon Site to Local Environment I have recently inherited a Drupal 7 site running on Pantheon.io
I have set up a local Drupal 7 server for a dev/test environment that is working flawlessly as a fresh install.
However, once I put the code, files, and database backups in place, my content appears, but there is no theme or CSS present, none of my links work, etc.

I have a feeling there is a simple fix for this, but I have exhausted my limited knowledge of this platform.

Clone the code
Import database
Configure your settings.php file
Get public files; copy them to sites/default/files
Compile CSS and JavaScript in the theme, if it is required
Clear the cache

Those step should works.

If Backup and Migrate module installed in Pantheon.io
you can get the database and public files from https://pantheon.io/admin/config/system/backup_migrate.


Print Parent Menu Items of Current Page I would like to create a sidebar in node.tpl.php that prints the parent menu items of the current page with a depth that follows the current page's depth by one level.

So if I have a menu structure like:

A
B
C
--C1
--C2
--C3
D

... and I am on page B, I would see in the sidebar:

A
B
C
D

... or if I am on page C2 I would see in the sidebar:

C1
C2
C3

Answering my own question:

In a custom module (or in your template.php):

1) Create a helper function:

// Helper function used to return the children of a specific menu item
function MODULENAME_menu_subtree_data($item, $tree) {
    foreach ($tree as $cid => $data) {
        if ($item['mlid'] == $data['link']['mlid']) {
            return array($cid => $data);
        }
        if ($data['below']) {
            $return = MODULENAME_menu_subtree_data($item, $data['below']);
            if ($return) {
                return $return;
            }
        }
    }
    return FALSE;
}

2) Create a reusable output function:

// Return all the menu items for the parent of the given page.
// $menuParent = menu_get_active_trail(); Needs to be called on the requesting page
function MODULENAME_parent_menu($menuParent) {
    // Get active trail to current page
    $menuParent = menu_get_active_trail();
    // Pop off last item of trail as that is the current page
    $menuParentPop = array_pop($menuParent);
    // Store the new last item in the trail as this is the parent menu item
    $menuParent = end($menuParent);
    // Set the depth to which we want to return the parent menu tree
    $max_depth = $menuParent['depth'] +1;
    $mlid = $menuParent['mlid'];
    $menu_item = menu_link_load($mlid);
    $tree = MODULENAME_menu_subtree_data($menu_item, menu_tree_all_data($menu_item['menu_name'], $link = NULL, $max_depth));
    $tree = array_shift($tree);
    $tree_array = menu_tree_output($tree['below']);
    return drupal_render($tree_array);
}

3) Place this code in your node.tpl.php file wherever you want the menu to be rendered:

<?php
// Print all the menu items for the parent of the current page.
print MODULENAME_parent_menu($menuParent = menu_get_active_trail());
?>

Notes:
- Replace MODULENAME with your custom module name or theme name if in template.php
- You can adjust the "depth" of what's returned by adjusting the $max_depth variable to suite your needs. 0 = show everything.

Totally welcome any way to improve this!


Broken formatting while displaying both start and end date I added Event content type in D7 and I have there Event Start date. I setup this field to collect an End day + it is collecting time and have option to check "All Day Event".

What I have in the exit when I created new Event is something like:

Frida2013, 20-Sunda2013, 22, Frida2013, 20-Sunda2013, 22eptember Frida2013, 20-Sunda2013, 22, 2013 - h:ia(All day)-(All day)

When I go to Manage Display tab, I can set there for Event Date to display only Start Day for example and then this broken formatting disappears. But I need to be able to display both Start and End date.

Any suggestions appreciated.
Thanks.

Juts found a solution. Please create custom formatting like this:

D, F d, Y (h:ia)

Key here is to wrap time in parentheses

  (h:ia)

after that trick formatting is fixed and looks something like:

  Sat, September 21, 2013 (All day) to Mon, September 30, 2013 (All day)


Can Entity Translate work on the node body? Problem

I'm using Entity Translate for the multi-lingual parts of my site, this allows me to use the language switcher. (I've enabled it for content, and then on the content type I've enabled field translation).

However the node body is not translatable.

Do I need to create a field and use that as the body, or have I set-up entity translation badly?

Ah turns out you have to enable translation for the field once you've enabled translation for the content type.

Open up your content type, edit the field you want to make translatable then head down to the bottom of the page.

You should see something like:

Field translation
Users may translate all occurrences of this field:

Body in Basic page
Body in Article
Body in Webform
Body in Test Content
Body in Upgrade & Search Token Product Display
Body in Blog post/Article
Body in Development Blog

Click on "Enable translation" and you're good to go.


Which Rules Event can be used with Drupal Commerce when a cart is updated? I have created a rule which add the shipping methods on cart page. It works fine when we add or delete the items from cart. BUT there is no event available on rules which fire when we increase the product quantity and update the cart.

I already used the event "After updating an existing commerce line item" but it is also not doing the job.

Here is my rule:

{ "rules_auto_add_shipping_service" : {
    "LABEL" : "Auto-add shipping service",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_shipping",
      "commerce_cart",
      "commerce_rules_extra"
    ],
    "ON" : {
      "commerce_cart_product_add" : [],
      "commerce_cart_product_remove" : [],
      "commerce_rules_extra_line_item_quantity_changed" : []
    },
    "IF" : [
      { "commerce_order_compare_total_product_quantity" : {
          "commerce_order" : [ "commerce_order" ],
          "operator" : "\u003E=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_method_collect_rates" : {
          "shipping_method_name" : "flat_rate",
          "commerce_order" : [ "commerce-order" ]
        }
      },
      { "commerce_shipping_rate_apply" : {
          "commerce_order" : [ "commerce-order" ],
          "shipping_service_name" : [ "" ]
        }
      }
    ]
  }
}

Make sure you have the Commerce rules extra module installed. This module will provide, among other things, the extra Rules Event "Quantity of line item has changed" (as described on its project page):

  Line item quantity has changed (occurs when adding or removing a product to cart and when an amount has been modified in the cart form).

That should help to achieve your goal.


How do I remove the blank space that remains after removing "logo" and "site name" and "site slogan"? I have removed the "logo", "site name", and "site slogan" from the Theme Settings menu:

Home > Administration > Appearance > Settings > MyTheme

Unchecked: [Logo], [Site Name], and [Site Slogan] under "Toggle Display".

For some reason, these things appear above the header and not in the header, so I am disabling them.  But, there is still a small space left.  It appears to be coming from a small div containing an anchor tag:

    Jump to Navigation

Can someone help me to remove this the "right way".. or advise me if I'm doing something wrong?

If it helps, I'm using the Zen Theme.

You could do it in the CSS, {display:none;} or {visibility:none;}. As far as screen readers are concerned, I am not sure how they would work. I googled and found this Link.


What does the embed display type do? I've been trying to find an answer but any search for views embed display brings up a bunch of unrelated modules and questions.

There is a Views Display Type/Mode/Whatever called "Embed" that you select when creating different views in your view:

For what can I use this display type?

This is a display which can be embedded via views_embed_view() or drupal_view() of Twig Tweak.

You can embed other display types, too, for example Page or Block, but the first one generates a route and the second one a block derivate you see when adding blocks to the block layout. So Embed is basically a display type which does nothing until you embed it in code.

The only explanation you can find in Views UI is in the general settings, where there is this checkbox:

  [x] Allow embedded displays

  Embedded displays can be used in code via views_embed_view().

Which by the way is without function and there is an open issue to remove it.


Drupal 8 does not create path alias' valid for all languages I have a Drupal 8 multi lingual site setup using the module Pathauto to generate path alias for taxonomy terms. The alias are created form the name of the tags, which are not translated but rather are in all languages the same. So I want all those alias be valid  for all languages.
The settings page of the module Pathauto lets me either leaving all languages unselected or choose specific languages for which the created path should be valid for. But unfortunately the pathes are created only for English and do not work if a user has a different language selected.

Is that a bug, or am I not doing it correctly?

That's currently not supported.

Partially blocked by core, which also doesn't allow to create language-neutral aliases while editing nodes and then also wouldn't show them anymore. See https://www.drupal.org/node/2511968 and https://www.drupal.org/node/2689459. Once those are resolved, pathauto could follow those definitions.


Increase the panel pane title length There is a module for increasing the node title, but how to increase the maximum length of a panel pane title?
I have a view pane which title must be overwritten in its panel pane settings. This works fine, but while appending extra tokens and styling to the title I bumped into the maximum length available.
How can this be changed?

Do not put styling in pane title, move html/css in a template file, you can override next templates for that: panels-pane.tpl.php or views-view.tpl.php


Why is the --uri option needed to return absolute URLs? I want to execute a View and export the JSON file to the files directory. I am using Views Data Export and VDE drush add-on modules. My view has a file/PDF field and I want to provide a direct link to the PDF file. So I added a Views relation for the field and a file URI formatter field. When I go to see the output the View creates at the Path. The URL is an absolute link directly to the PDF file. The URL includes the domain name when viewing it on development or production instances. And this is what I want. This is the correct URL path in the JSON:

href=\u0022http:\/\/mysite.com\/files\/Allergens.pdf

But when I use this Drush command below provided by views_data_export or vde_drush

drush vde myview myviewid myfile.json

the domain name is stripped out like this:

href=\u0022http:\/\/default\/files\/Allergens.pdf

Why is this happening only when using the Drush command? I found I can fix it by adding this at the end of the command

--uri=mysite.com

So my new drush command looks like this:

drush vde myview myviewid myfile.json --uri=mysite.com

But doing this will hardcode the domain name into the URL. I want the URL to work on development, production and on my local. Thank you for any help you can provide.

You can set the default uri by adding the following file. Then if you don't provide --uri it'll use the default.

sites/all/drush/drush.yml

options:
  uri: "https://your-site.domain"


Can Drupal 8 Form #states API be used to expand/collapse Given a checkbox field with two options:

"Closed" (selected by default)
"Open"

I'd like to expand or collapse the <details> container of a different field (in our specific case an Address field). In HTML terms, this means adding the open HTML5 attribute to the <details> tag and adding aria-expanded=true to the <summary> tag when the "Open" radio button value is clicked, and ensure it is removed when that radio option is not selected (which means by default at page load time as well).

I've found a few older semi-related issues and the documentation page for Drupal 8's drupal_process_states, but it's looking like this isn't possible with the Form #states API in Drupal 8. The docs do not include "open" in the list of valid states that may be applied to an element.

The valid states are:

enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed

One would think that maybe the expanded and collapsed options could work, however this does not seem to be the case with my sample code below:

function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['#states'] = [
    // Expand address field container when the Trigger field is 'Open'.
    'expanded' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
  ];
}

Replacing 'expanded' state with 'open' in the above does not work, nor does the inverse logic using 'collapsed' state work:

function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['#states'] = [
    // Collapse address field container when the Trigger field is 'Closed'.
    'collapsed' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];
}

Unfortunately, I'm going to answer my own question:  expanded and collapsed states do work for the <details> type.

My problem was operator error.  I was adding the #states array at the level of the '#type' => 'container' but the container has a widget inside of it that holds the '#type' => 'details'.   Fun times with Form API!

The working code is this:

<?php
// In mymodule.module
use \Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['widget'][0]['#states'] = [
    // Expand location field when the Type is 'On-site'.
    'expanded' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
    // Collapse location field when the Type is 'Online'.
    'collapsed' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];

  // Load edit form with Location field either open or closed, based
  // on the value of the Trigger field.
  $form['field_address']['widget'][0]['#open'] = ($form['field_trigger']['widget']['#default_value'] == 'open') ? 1 : 0;
}


How to play a video via drupal video ftp? I've installed the Video module (Drupal 6.2), and everything works fine. I also enabled the uploading of the video via FTP. I edited the video content type with the FTP CCK field.  The FTP field uploaded file is listed in the drop-down, and as I select it provides a file link to it. I need it to be displayed in a video player.

In other words, the video file is linked as an HTTP link, and it is not being played using the video player.

Do you have any suggestions?

You just need a player frontend for the CCK field in question to display the video. This is actually quite easy.

You'll first need a video player frontend of some sort. I would recommend the VideoJS module ,personally, but I'm sure there are others worth looking into as well.

On your video content type, go over to Display, and change the display widget of that cck field to a video player frontend of your choice after enabling the video module.


Rules data comparison: compare node field with a group How to use rules to compare a field from the node with a specific Organic Group?

I am using rules event after saving new content of type X. Now I need to specify if in the field field_group the value is a specific group.

I am able to get the field of the node, but have no clue how to be able to compare it with a group I want.

Ok, lets assume that your group name is called "Pokemon"

1) Under Conditions, click on Add Condition.

2) In the drop down, select TEXT COMPARISON

3) Click on the Blue Link that says (DATA SELECTORS)

4) Look for your field, if you named it "group", then look for node:field-group

then highlight it, copy and paste it under Data Selector*

7) Under Matching Text put Pokemon

8) click SAVE

Note: obviously, replace Pokemon with your actual group name.


Change values of user input in hook_field_validate? I have setup a custom field and have a validater setup for it. I would like to be able to adjust and actually change the user input from within my validator. so say this is a multi value field, each set of values shows up in $item. I have adjusted and changed the values in this function, but how I can I save them and make sure the rest of the form processes using the changed values?

mycustomfield_field_validate($obj_type, $object, $field, $instance,$langcode,   &$items, &$errors){

  foreach($items as $item){
  // validation check is here
  }
}

Perhaps hook_field_attach_submit can be used in your case?


Override user register default URL to set up password in order to create a sign in/sign up workflow on a decoupled Drupal(React on front).
I've used the core provided rest resource /user/register with Rest ui, and after giving the permission Access POST on User registration resource to anonymous users , i was able to register users via the resouce /user/register?_format=hal_json without any authentication

I wonder if there is a way to override the link that is by default sent to the newly users via mail to setup his password ?

I don't want the users to setup their passwords on a Drupal page with a Drupal form.

I think no need to override the default register url.

To prevent Anonymous from register users, Just go Administration >> Configuration  People http://example.com/admin/config/people/accounts.
and check Administrators only in REGISTRATION AND CANCELLATION fieldset like the following:

If you have another raison to change the default url follow this tutorial just change route name from user.login to user.register.


Within Panels, get node ids that contain taxonomy term I have a panel with a content pane that shows a node based on the Taxonomy Term Name in the URL of the panel.
This is working using  "(Content) Content: Has taxonomy term ID" as a contextual filter, and "From panel argument" within the content pane.

I am also wanting to add the add comments form to the panel. Which could be done using the nid of the node displayed in the above mentioned panel.

So, from within panels, how can I get the nid of a node that has the taxonomy term as a field, where the taxonomy term is within the URL?

Can taxonomy_select_nodes($array_with_tids); be used within panels?

Using Drupal 7, Panels 7.x-3.3

Thanks

Rather than getting the nid from within Panels, I just used taxonomy_select_nodes and passed the result to panels as a second argument in the URL eg panels-view/%tid/%nid.

This solved my problem.

Thanks


modifying data in a node I have created a node with a cck select box which comes with a few possible values. How would I code a module to change the value from one value to another? For example, the default value of field_model is Oldsmobile, and I want to write code which will change it to Toyota?

This depends ... D6 or D7 ... is the field a reference to something else (term, node, entity)?

Generally you have to write something that looks up the value of the item in the list, for example for a node reference:

  $modelcode='Toyota';

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->fieldCondition('field_models_code', 'value', $modelcode, '=');
  $result = $query->execute();
  $model_nid=array_shift(array_keys($result['node']));

  unset($result);
  unset($query);

Then you would take the $model_nid and update your field in the form state:

$form_state['values']['field_model'][LANGUAGE_NONE][0]['value'] = $model_nid;

This example assumes D7 and a field set to node reference.


Multiple entity quickedit problem I am utilising the basic page content type. When viewing my basic page the layout consists of:

A view that outputs a block in the form of a header. Using the basic page fields "title" and "short description"
A block that outputs the body of the page.

When I view my page, the node/articles markup is rendered as follows:

...

...

Analysing the markup we can gather that:

They both have the same node id
The latter can be differentiated by the data-quickedit-entity-instance-id="1" tag
Only the 'quick-edit' button appears for the first article
On quick-edit click, both of the articles are trying to be manipulated by some form of js - there could be conflict here.

So the question is. How come the quick edit feature does not work for a node that is rendered twice on one page?

Has anyone got any reason why it is not working or can provide a solution for this?

Thanks in advance

According to #15 of this Drupal issue

having a duplicate node on the screen is enough to disable the contextual menu functionality. It's a bug.


How to send HTML/Rich text email from /contact I want to allow other text formats on the /contact form than just plain text.  I haven't been able to find a module that does this.  Is it possible to do this in D7?

You have two solutions one is

https://www.drupal.org/project/htmlmail - html mail module especially for html mails
you have to customize the drupal_mail function to accept html

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

https://www.drupal.org/node/224333#email-html

below is the sample:

Since Drupal 7 automatically converts all HTML emails to plain text before sending them (http://drupal.org/node/224333#email-html), you must now write your own implementation of MailSystemInterface and set a variable telling Drupal to use it in order to send HTML emails. Here is the class which needs to go in your module:

<?php
/**
 * Modify the drupal mail system to send HTML emails.
 */
class ExampleMailSystem implements MailSystemInterface {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }

  /**
   * Send an e-mail message, using Drupal variables and default settings.
   *
   * @see http://php.net/manual/en/function.mail.php
   * @see drupal_mail()
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   * @return
   *   TRUE if the mail was successfully accepted, otherwise FALSE.
   */
  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}
?>

Rename the class for your module (i.e. ForwardMailSystem). Then, you need to set the mail_system variable:

<?php
variable_set('mail_system', array('default-system' => 'ExampleMailSystem'));
?>

If you wish to have only emails from your module be sent in HTML but leave all others untouched, use this code:

<?php
variable_set('mail_system', array('default-system' => 'DefaultMailSystem', 'example' => 'ExampleMailSystem'));
?>

That code can go in your module's install file in hook_install to set that variable as soon as your module is enabled. Make sure to also set the variable back to the default in hook_uninstall.


How can I make a fieldgroup visible only to admin users? I'm using the Field Group module to group fields on my user profile page.  I have a number of fields that are only visible to admin users, so I would like to group them together to keep everything organized.  I use the Field Permissions module to limit access to the fields to admin users only; however, this module does not restrict permissions for the field groups.

As a result, authenticated non-admin users see an empty fieldgroup.  How I deny non-admin users access to a field group that should be shown only to admins?

You are probably using 1.x version of field_group module (which is the recommended version).

This problem has been solved (for most cases) in this issue. You could try the 2.x-dev version or use a simple JQuery script to remove the empty elements.


Populate a hierarchical select field programmatically I have to create a user, and one of the fields (Profession) is a hierarchical select based on a two level taxonomy, where the first level is "profession", and each profession has different specialities.

I can create a user and save the profession field, but the speciality is not saved, and that's what I want to do. Here is how I save the profession :

$fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => $password,
    ...
    'field_profession' => array('und' => array(array('tid' => $tid_profession))),
);
user_save('', $fields);

Here, $tid_profession is the id of the profession term. However, when I use the id of the speciality term, the field is not saved.

Any idea how to make this work ? Any help would be greatly appreciated.

I have saved user with custom hirerarical select field named "field_register_state" like below: it's working very well.

$account = new stdClass;
$account->is_new = TRUE;
$account->name = $username;
$account->pass = user_hash_password($form_state['values']['pass']);
$account->mail = $form_state['values']['mail'];
$account->init = $form_state['values']['mail'];
$account->status = TRUE;

$account->field_user_code = array(LANGUAGE_NONE => array(array('value'=>$userCode)));
$account->field_full_name = array(LANGUAGE_NONE => array(array('value'=>$form_state['values']['field_full_name']['und'][0]['value'])));
$account->roles = array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',$form_state['values']['roles']=>getRoleNameById($form_state['values']['roles'],$form));

$account->field_user_area_name = array(LANGUAGE_NONE => array(array('value'=>$areaName)));
$account->field_created_by = array(LANGUAGE_NONE => array(array('value'=>0)));
$account->field_register_state = array(LANGUAGE_NONE => array(array('tid'=>$statecode)));
$account->timezone = variable_get('date_default_timezone');
user_save($account);
drupal_set_message(t('User Created Successfully'), 'status');

Hope this help's you..


Is there any way to count the number of items in cache? In Drupal 6, I used to be able to look up the number of items via {cache_MODULENAME} table direct in SQL. Is there any way to look it up via the cache API?

Given the interface provided for cache backends (CacheBackendInterface), you cannot.

It doesn't expose a method that returns the number of items in the case, which would have made things easier for your use case. There could be a cache backend with a method to count the number of items in the cache, but since it is not part of CacheBackendInterface, that would not be a method you find in every cache backend.
Since CacheBackendInterface doesn't expose any method to know the database table used for cache bins, you should assume some implementation details, and that those details are never changed. If you make assumptions about those implementation details, you can use a SQL query to count the number of items contained in a cache bin. Keep in mind that a cache backend could not use a database table at all, such as in the case of the ApcuBackend class.


Get user Account form I am trying the user account form(the one that comes in user/%/edit) of the logged in user, I have tried:

drupal_get_form('user_profile_form');

&

drupal_get_form('user_profile_form',1);

Though the form is loaded, on calling render() the div is empty.

The second example won't work because user_profile_form() takes a user object as it's argument, not an id. I suspect your form is not being outputted because you're not actually calling print on it...render() just prepares the string it doesn't actually output it.

Try this code:

$account = user_load(1);
print render(drupal_get_form('user_profile_form', $account));

EDIT

You'll also need to include the user.pages.inc file where the function itself lives:

module_load_include('inc', 'user', 'user.pages');


How can I send an e-mail whenever user registration fails? I am a bit concerned that my user registration is too complicated.  I have done some basic usability testing, but I'm still not confident, so what I'd like to do is send an e-mail to myself every time a user makes a mistake on the registration form that requires a correction before registration can be processed (Mollom validation fails, no input in a required field, etc.)

Is there an easy "catch-all" way to do this for all possible mistakes users can make?

Not sure how deep you want to go, but here's what I would do.

Create a custom module, "mysite_utils" (I always make at least one
custom module to do some custom tweaks.)
Create a mysite_utils_form_alter(&$form, &$form_state, $form_id)
function.
In that form_alter function, look for the user registration form_id.
Add a custom validation handler mysite_utils_user_register_validate().
Put your validation checks in that function. If the validation fails,
send yourself an email.

This process will require a lot of custom coding, not sure what your Drupal level is.


Theme hook not found on custom module I'm trying to create a module which adds a page, the controller works but I cannot render a twig template for it.

The page layout is displayed without the page I created and this warning is reported in the logs:

"Theme hook eu_calendar not found."

but I do have the hook defined

This is the controller:

class EuCalendarController extends ControllerBase {

    public function index() {
        return [
            '#title' => 'my title',
            '#theme' => 'eu_calendar',
            '#description' => 'description test',
        ];
    }
}

Module file:

function eu_calendar_theme($existing, $type, $theme, $path) {
    return [
        'eu_calendar' => [
            'template' => 'index',
        ],
    ];
}

I also tried adding variables like

function eu_calendar_theme($existing, $type, $theme, $path) {
    return [
        'eu_calendar' => [
            'variables' => [
                'test_var' => NULL,
            ],
            'template' => 'index',
        ],
    ];
}

What am I missing here?

And do I need to configure anything with the regions, I want my module to be displayed in the content region by default...

Any documentation or tutorial is also welcome, I read a bunch of them none of them is explaining the options and details.

myModule.module

function myModule_theme($existing, $type, $theme, $path) {
return array(
 'pagina_3' => array(
   'variables' => array(
     'titulo' => 'title',
     'descripcion' => 'description',
     'formulario'   => NULL
      ),
    'template' => 'pagina_3'
   )
  );

}

mymodule/templates/pagina_3.html.twig

{{ titulo }}

{{ descripcion }}

        {{ formulario }}

myModuleController.php

public function verPagina3() {

    $form = $this->formBuilder()->getForm('Drupal\myModule\Form\InsertarGastoForm');

    // Le pasamos el formulario y demás a la vista (tema configurado en el module)
        return [
            '#theme' => 'pagina_3',
            '#titulo' => $this->t('Formulario crear empresa'),
            '#descripcion' => 'Formulario para crear una nueva empresa en Drupal 8',
            '#formulario' => $form
        ];

   }


How to setup drupal multisite in cpanel? I want to setup a drupal multisite but without success. I have followed this tutorials (and search in drupal answer):
- 2 minutes multisite
- 5 minutes multisite
- Setting up a multisite
I have tried with subdomains and with alias. My first question is when I create the alias or subdomain in cPanel, should I create a redirec? Now, I've left it blank, but I'm not sure if I have to create a redirect.

I always get:

  The website encountered an unexpected error. Please try again later.

or

  CGI-Error. Sorry. The page you request is not available.

I don't know what else I could do. Could some one detail me the steps? Thanks.

I have found the problem. My settings.php file had redis configuration, and that was the problem. I found it because I added this line to settings.php file:

$config['system.logging']['error_level'] = 'verbose';


Drupal 8 update.php/selection - access denied I wanted to update d8 from 8.0.1 to 8.0.2, but i couldn't run the update.php due to the error "Access Denied". Am logged in as user1 which should have all required privileges.Following the drupal 8 update guide I deleted core and vendor folders with all the files in the drupal root from the the 8.0.1 install, and replaced the same files and folders from the newly downloaded 8.0.2 version.

What could be the solution to this problem?

My Environment:
OSX El Captain, nginx 1.8 using the latest config from nginx/drupal, PHP 7.0.2,

See window capture below:

Many Thanks

After several frustrating days I figured the problem was from my configuration.
The conf file has
     "fastcgi_param SCRIPT_FILENAME $request_filename;"
instead of
     "fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;"

Making this correction solved the problem.

Am grateful for all the support.


Product Inquiry form in ubercart? Can we provide an inquiry form for products in ubercart ? I want to provide a form to each product so that the user can send his/her requirement to site owner. Site owner can later on check who has contacted him and why. I do not want to provide add to cart option.

Create a form in a block with a hidden field the captures the product name or information and then place the block wherever you want it.

Either store the information or just email it directly.


Custom remote video thumbnail I'm using the media entity from Drupal core together with the media library, to handle media on my site.

I have Remote Video and Image with crop media types. I'm using the crop and image_widget_crop modules to manually crop images on my site.

Remote video supports YouTube and Vimeo.

Right now the thumbnail is automatically generated, but I want to be able to upload a custom thumbnail. If no custom thumbnail is provided, it will just use the auto generated one.

I found this guide, but it is for Drupal 7.

Has anyone done something similar to this in Drupal 8?

I solved the problem by adding an image field on the remote video media entity and then altering the media entity on presave, like this:

/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'media' && isset($entity->custom_thumbnail->entity)) {
    $entity->thumbnail->target_id = $entity->field_media_image->target_id;
  }
}

The image field is called field_media_image.


Procedure to import a site to Acquia Dev Desktop So, I'm looking for a painless procedure to import a site into Acquia's Dev Destkop on Windows

Theoretically, the procedure should be

Install clean drupal site (clean db and codebase)
Create Database and user for site to be migrated with phpmyadmin
Copy sites folder to new drupal root
Configure settings.php file to match new server environment.
Run Update.php script

The problem is I get a PDOException: SQLSTATE[HY000] [1045] Access denied for user 'psr_admin'@'localhost' (using password: YES) in drupal_get_installed_schema_version() (line 155 of C:\Users\Nick\Sites\devdesktop\psr_final\includes\install.inc).

This is the procedure I've followed on a number of installations, and I am wondering what I am doing wrong, or which aspect of the configuration is incorrect. I've even gone into phpmyadmin and re-created the database user and password to make sure that all the settings are correct. So, can someone tell me what I did wrong, or point me to the correct way to import a site into Acquia's dev desktop?

Dev desktop hides the settings file on local sites, so it's a little difficult to see what the settings actually are.

Looks like you're on windows. Hopefully you can find the directory your local settings are stored in by looking at where they are on my mac:

~/.acquia/DevDesktop/DrupalSettings/

The local settings file name has the pattern:

cld_prod_<site_name>_<dev_test_prod>_default.inc

Don't change this file. But you can see if it's accessing the psr_admin user you set up. By default my settings file shows the user 'drupaluser' with '' (an empty string) for a pw.


How can I use node_load with a module created page that requires an argument? I would like to load the contents of a page like how node_load() works, although what I am trying to load isn't a node but a page created using a module. The entry in hook_menu uses an argument which needs to be passed in the URL. This is for a popup (jquery overlay) that I want to reuse where the code is already done for the standalone version.

Any idea how this can be done? (Drupal 6)

The code executed from Drupal, in index.php, contains the following code.

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

menu_execute_active_handler() accepts an argument: the path being shown. If that argument is not passed to the function, then menu_get_item(), the function called by menu_execute_active_handler() uses the content of $_GET['q'].
In your case, you would pass to the path you are interested to. Your function should use code similar to the following one:

function mymodule_get_page($path = NULL) {
  $return = menu_execute_active_handler($path);

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return −1;
}

The calling function would need to check the returned value: If it is a string, then it the what returned from theme('page'); if it −1, then the menu callback didn't return any value (but could have printed the page content; if it is an integer different than −1, then it's a Drupal error code, i.e. the one reporting the site is off-line, the user is trying to access a page without to have any permission, or the user is trying to access a non existing page.

The only "problem" with this code is that sometimes a menu callback doesn't return any content, but it prints the content directly; this is normally done for content that doesn't need to appear together the rest of the page output Drupal normally adds (e.g. the content for the blocks associated to a page), such as when a module returns XML content that should not mixed up with the HTML output generated from Drupal.
In this case, the function should intercept the output directly printed, with ob_start() and ob_get_flush().

function mymodule_get_page($path = NULL) {
  ob_start();
  $return = menu_execute_active_handler($path);
  $output = ob_get_flush();

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return $output;
}


Can i add a Slide show to my website in a block. Is it possible for my Theme I would like to add  slide show to my website. How can i do that. And i would like to add it as a block in all the pages. What is the easy way to do that.

Please suggest.

You could do this with the Fields slideshow module https://drupal.org/project/field_slideshow and optionally the Colorbox module.

Create a content type with an image field. Configure it so that you can load infinite images. Set the formatter of the image field as "slideshow". Then create a block with views and display the block in your sidebar.

Here is a good screencast to set it up: http://vimeo.com/26411524


How to add contact us form in to front-page? I need to add contact form in the front page but I don't know how. there are some modules like Contact Form On Node that inserts this form in the node page but I only want it to be in the front page. how do I can do this ?

thanks

You can use Contact Form Blocks module, in case if you want
to use the core contact form.
Alternatively, you can create your contact form using Webform module which supports embedding the form
in a block, which you can then display wherever you want.
Also, you can display your existing contact form in a custom block,
writing a custom module. In that case, you need to implement 2 hooks:

hook_block_info
hook_block_view

and then use the function drupal_get_form to retrieve the form for
rendering. (See this for some more info)


Create a rent product I'm using the Drupal Commerce module to build a Website to manage two Flats to be rented by days.

The visitor select one of the two flats and then select a date (let's say it the day: 15 January 2012) and make the payment for it.

After the payment the date of 15 January 2012 will not be available to be sold again until this day has passed (the 16 january).

I first thought of creating a product type called: Day to rent with a field called: date and then creating 365 'Day to rent' products, each one for each one of the days of the year, setting the field 'date' to the corresponding date.

Then, using the calendar module and views I would show the products in the calendar allowing the visitor to click in the 'add to cart' for the day they choose.

I'm a Newbie with the module, and I now see that I cannot get 'products' inside a view. Then, my idea fails.

Now I think that I should add the field called: date to the 'Product display' instead of the product itself, but I am not sure.

Before wasting hours, I just need to know if is there any way I can accomplish this with the commerce module.
Do I need an affiliated module? Do I need to develop a new module?
What is the best approach to do it?

Drupal Rooms module is a perfect solution to this. It is a booking and room management solution for hotels, vacation rentals and B&Bs. It integrates directly with Drupal 7 Commerce.


filedownloading is making the file to view instead of download in drupal7 Hi i have followed Working with files in Drupal 7 and created the content type for file download.Everything is working fine i can upload a file and displaying it in the front page.But when i click on particular file for downloading it is just viewing the file in another tab in the browser with url like this

drupal7.22/sites/default/files/file.txt

I can view the file but not able to download it.Can you just say me where i did the mistake.

Read Force Files to Download Instead of Showing Up in the Browser as the page suggests you can achieve this by adding these lines to  .htaccess file

<FilesMatch "\.(?i:doc|odf|pdf|rtf|txt)$">
  Header set Content-Disposition attachment
</FilesMatch>

Or alter mime type


Listing and Loading Nodes with AJAX In Drupal 7
I want to make a view of

/------------------------
--------- Header --------
List of links to nodes

/-------------
Node content

When the links of nodes in Header clicked, the node content should be loaded by ajax.
Is there anyway to do this by Views? or do I need some custom PHP?

First off if the content is only text and its size is not very big I recommend you strongly not to use Ajax , unless you can do it using views in the following way:

Be sure to enable the Ajax in views:

now this code will load the view.

$("links_click").click(function(){
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name='+your_view&'view_display_id='+view_display_id,
                success: function(response) {
                  var output = response[1].data;
                  $(".your_container").html(output);
                },
                error: function(data) {
                    alert('An error occured!');
                }
              });
        });

for more detail visit this link.


Menus items appear twice in admin menu The menus menu items appear twice as shown in the image below. I have tried to disable menu items in the Management menu which had no effect. How can I solve this issue?

That is the cause of admin_menu.module.  Upgrade it to the the most current version; it will be fixed.  That problem was fixed one or two versions ago.


determine value differences between form submissions I have an entity form that user can submit multiple times. What i would like to do is during validation get current values in the database and compare with the once that user just entered. I'm using

$form['#validate'][] = 'my_function';.

So really the questions is how do I get 'current values' that are already stored in the database to one array and 'about to be submitted values' (just updated by user) to the other array. The reason why I want those to be saved, temporary only, in the array is to do comparison.

If you're looking for a non-SQL way to get data out of the database the db_select() function (which returns an SelectQuery) is the way to go. For obvious reasons there's no implicit API implemented for your custom data tables (you'd need to create that yourself).

Without knowing your schema this can't be totally accurate, but the basics are:

$query = db_select('my_table', 't')
  ->fields('t', array('field1', 'field2'))
  ->condition('some_column', 'some_value');

$results = $query->execute();
foreach ($results as $result) {
  // $result is an object, use it...
}

SelectQuery has a bunch of helper methods to get specifically formatted data out of the database, so chances are you won't need to loop over the data. You can find a list of those helper functions (and info on the alternative, SQL based approach that still uses the API) here


Defining a varibale Node Expire date by custom PHP code in Rules module I have a content type, Job Offer, and this node type is able to expire thanks to Node Expire module.

When editing a Job Offer, I want to change the expire date by the value of the Duration field that I added to this node.

In order to do this, I made a rule with the help of Rules Module and I am using the custom PHP code below as an action in the light of this post, but it did not work with my field:

$node->expire = date('Y-m-d', strtotime("+[node:field-duration:field-value] days"));
return array("node" => $node);

node:field-duration:field-value is an integer field of a taxonomy term

Any help would be appreciated.
Thanks

Thanks to @undersound, the code below worked!

$duration = [node:field-duration:field-value];
$node->expire = date('Y-m-d', strtotime("+" . $duration . " days"));
return array("node" => $node);


Drupal_add_js is not working inside hook submit I have alter and hook submit for webform. I would like to pop a modal if form is successfully submitted. But drupal_add_js seemed to be not working inside the hook submit.

function myModule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'webform_client_form_9') {
        $form['#submit'][] = 'myForm_submit';
    }

}

function myForm_submit($form, &$form_state) {
    drupal_add_js(drupal_get_path('module', 'myModule') . '/misc/custom.js');
}

You should do this with #attached.

Like,

if (!empty($form_state['values'])) {
  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
  );
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
  );
}


Cannot create custom config entity fails because ID is blank I have created the following custom config entity. When I try to create a new one, I get the following error:

Drupal\Core\Entity\EntityMalformedException: The entity does not have an ID. in Drupal\Core\Config\Entity\ConfigEntityStorage->save() (line 248 of core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php).
Drupal\Core\Entity\Entity->save() (Line: 637)
Drupal\Core\Config\Entity\ConfigEntityBase->save() (Line: 151)

My understanding is that the entity system will create an ID for this entity, but it doesn't seem to be working in my case. I'm struggling to figure out what I need to change to get this work:

<?php

namespace Drupal\example\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\example\Entity\ExampleConfigInterface;

/**
 * Defines the ExampleConfig entity.
 *
 * ExampleConfig config entities define a configuration for a specific
 * entity/bundle. Per entity settings are then saved as ExampleContent
 * entities.
 *
 * @ConfigEntityType(
 *   id = "example_config",
 *   label = @Translation("Example configuration"),
 *   fieldable = FALSE,
 *   handlers = {
 *     "list_builder" = "Drupal\example\ExampleConfigListBuilder",
 *     "form" = {
 *       "add" = "Drupal\example\Form\ExampleConfigForm",
 *       "edit" = "Drupal\example\Form\ExampleConfigForm",
 *       "delete" = "Drupal\example\Form\ExampleDeleteForm",
 *     }
 *   },
 *   config_prefix = "example",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "example_entity_type" = "example_entity_type",
 *     "example_bundle" = "example_bundle",
 *   },
 *   links = {
 *     "edit-form" = "/admin/config/content/example/{example_config}",
 *     "delete-form" = "/admin/config/content/example/{example_config}/delete",
 *   }
 * )
 */
class ExampleConfig extends ConfigEntityBase implements ExampleConfigInterface {

  /**
   * The ID of the block.
   *
   * @var string
   */
  protected $id;

  protected $exampleEntityType;
  protected $exampleBundle;
  protected $exampleExpiry;
  protected $exampleDefaultStatus;

  /**
   * Get the bundle
   */
  public function getExampleBundle() {
    return $this->exampleBundle;
  }

  /**
   * Get the entity type.
   */
  public function getExampleEntityType() {
    return $this->exampleEntityType;
  }

  /**
   * Get the expiry time for this configuration.
   */
  public function getExampleExpiry() {
    if (!$this->exampleExpiry) {
      return example_expiry_default();
    }
    return $this->exampleExpiry;
  }

  /**
   * Get status for this configuration.
   */
  public function getExampleStatus() {
    return $this->exampleDefaultStatus;
  }

}

I have ended up prefixing all the custom properties to try to make sure I wasn't overriding something on accident. Even when the custom entity is blank, it still won't add.

My understanding is that the entity system will create an ID for this entity, but it doesn't seem to be working in my case. I'm struggling to figure out what I need to change to get this work:

That understanding is wrong. Config entities have machine names as ID's, you have to provide that. Most UI's generate one from the label, but that's form/UI code, the API has no such thing.


Node access by role or user, what module(s) should I use? I'm trying to limit the access to certain nodes in certain content types by role. So far I wasn't able to find any suitable module that would do just that.

Please take into consideration that content type access by role is not enough (but surely, I'll look into any suggested module that does this too), it must go to the node level.
Are you aware of any module that might do it?

This might be another question but since it's so closely related and it could solve my problem I'll put it here too:
I know about nodeaccess, however when I programmatically load nodes using $node = node_load($nid), there's no item in the $node array that suggests node access permissions were set. Everything else is there including those "pesky" CCK fields. Am I doing something wrong here?

Thanks in advance.

The Content Access module gives you role permissions at the content type and (optionally) node level. By default, node level permissions are disabled but you can enable it on a type-by-type basis.

If you install ACL module, Content Access can give you per user permissions at the content type and node level.


How do I add a condition to a query? $acl_ids = array(1,2,3);
$database = \Drupal::database();

$result = $database
  ->query("SELECT {nid} FROM {acl_node} WHERE grant_update = :grant",
    ['grant' => 1,])
  ->condition('acl_id', $acl_ids, 'in')
  ->fetchField();

Unfortunately the ->condition part does not work, since I get the following error:

  Call to undefined method Drupal\Core\Database\Statement::condition()

What method should I instead use?

Conditions are only used in dynamic queries; the query() method is for running static SQL.

The dynamic version would be something like:

$result = $database
  ->select('acl_node', 'n')
  ->fields('n', ['nid'])
  ->condition('grant_update', 1)
  ->condition('acl_id', $acl_ids, 'IN')
  ->execute()
  ->fetchField();

And the static:

$result = $database
  ->query("SELECT nid FROM {acl_node} WHERE grant_update = :grant AND acl_id IN (:acl_ids[])", [':grant' => 1, ':acl_ids[]' => $acl_ids])
  ->fetchField();


How can I load a JavaScript file only when a page has an element whose class is "test"? In my develop process, I meet a scenario: I only want to load a JavaScript file when a page has an element whose class is test, so what can I do? How to know a page whether has this element?

Well one way would be to just add the script always and check for the existence of test class there.
(function ($, Drupal) {
    Drupal.behaviors.tester = {

        attach: function (context) {
           if (context.querySelector('.test')) {
               // Do something
               // Or maybe load another JS file dynamically
           }
        }

})(jQuery, Drupal);