Write a File Locally I am trying to write files and read from them.  The following code works great on my local Kalabox server, but when I push to Pantheon, the files don't get written.

Could it be because all files are under sub versioning on Pantheon?

$csv_text = array2csv($db_result);
save_csv_file($csv_text);

if($_GET[save_to_email] == 'true'){
    save_defaults();
}

function save_csv_file( $csv_text){
    //$file = './inventory.csv';
    $file = 'public://inventory.csv';
    file_put_contents($file, $csv_text);
}

function save_defaults(){
    $default_vals = get_inventory_defaults();
    $default_vals[sort_direction] = $_GET[sort_direction];
    $default_vals[threshold] = $_GET[threshold];
    $default_vals[hide_zero_inventory] = $_GET[hide_zero_inventory];
    $default_vals[email] = $_GET[email];

    save_inventory_defaults($default_vals);
}

function get_inventory_defaults(){
    $file = './inventory_defaults.txt';
    //$file = 'public://inventory_defaults.txt';
    $content = unserialize(file_get_contents($file));
    return $content;
}

function save_inventory_defaults($my_variable){
    //$file = './inventory_defaults.txt';
    $file = 'public://inventory_defaults.txt';
    $content = serialize($my_variable);
    file_put_contents($file, $content);
    //file_save_data($content, $file, FILE_EXISTS_RENAME );
}

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

I am not sure when to go from here... A million thanks!!

From Pantheon docs: "Pantheon cannot be used to host files over 256MB, no matter how the file is uploaded"

http://helpdesk.getpantheon.com/customer/portal/articles/745361-known-limitations

It could be that your file is too large and therefore Pantheon will not host it.


Show Content And Webform Same Page I Am Making A Contact Page In Drupal 7 In Which I Have To Show Office Address And A Contact Form Made With Webform Show Together So Can Anyone Suggest Any Idea How To Show A Content And Webform In Same Page

In webform, you can go to form settings, and in the advanced tab at the bottom, there is an option expose your form as a block.

Then go to structure > blocks and place the webform block on the page/region that you want.


Use an image instead of a menu link in Drupal 7 I have a menu in my page that I have created. I have a link called 'Home', and I want an image to be there for only this link. I saw many modules for Drupal 6. Is there any hook or module in Drupal 7 to do this?

I am answering my own question, as I googled and found something, mixed it and carved my own way to do it.

function mytheme_menu_link(array $variables) {
  global $base_path;
  $element = $variables['element'];
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  if($element['#title'] == 'Home') {
    $element['#localized_options']['html'] = TRUE;
    $get = '';
    $output1 = l($get,$element['#href'], $element['#localized_options']);
    return '
' .$output1    . "
\n";
  } else {
    return '
' . $output . "
\n";
  }
}


drupal 8 tablesorting not working I am using the code below in a custom drupal 8 module to produce a table but the table does not sort when I click on the header, although the little arrow changes direction and the url indicates the sort order is different.

$headers = array(
      array('data' => t('Name'), 'field' => 'name', 'sort' => 'desc'),
      array('data' => t('Date'), 'field' => 'changed_date')

      );
$order = tablesort_get_order($headers);
         $sort = tablesort_get_sort($headers);
         $rows = array();
         foreach ($directoryData as $entry) {
          $rows[] = array(

             array('data' => $entry['name']),
             array('data' => $entry['changed_date']),

          );
       }
       $table_element = array(
            '#theme' => 'table',
            '#header' => $headers,
            '#rows' => $rows,
            '#empty' =>t('Your table is empty'),
        );

        $html=drupal_render($table_element);

Anyone know what i can do to debug why the sorting is not working?

the reason the sorting that comes with drupal core doesnt work is that it only works for query based content.  If the content is static or otherwise not query based that you need to sort you have the use the client side tablesorting.js as explained here http://tablesorter.com/docs/


Is there a module for "mail routing" in Drupal 6? Is there a module, with D6 support, that allows one to "route" e-mails.

For example, by default, e-mails would be sent out by the regular mechanism, but for some e-mails, say based on their ID or destination domain, where tracking is interesting, they could instead be passed of to a third party service (such as MailChimp, ExactTarget, MailGun etc).

You could try: https://drupal.org/project/reroute_email
While it's mainly designed to reroute all email to predefined addresses, e.g during development, you could use it as a starting point for similar functionality.


How to change the directory of file_create_url to default for a custom domain Suppose, we have a file: /sites/default/files/picture.jpg

Drupal is installed into a subdirectory: /drupal. There are 2 domains, attached to the site:

exchange
exchange-test (uses different DB)

 | domain        | settings.php path     |
 |---------------+-----------------------+
 | exchange      | /sites/default/       |
 | exchange-test | /sites/exchange-test/ |

When we call

print file_create_url('public://picture.jpg');

we get:

| site          | result                                        |
|---------------+-----------------------------------------------|
| exchange      | /drupal/sites/default/files/picture.jpg       |
| exchange-test | /drupal/sites/exchange-test/files/picture.jpg |

But the file is stored in default directory even for exchange-test domain.

As far as I could find, the path is being generated, using function conf_path. It scans the config directory to find a subdir with current domain name:

 $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
  for ($i = count($uri) - 1; $i > 0; $i--) {
    for ($j = count($server); $j > 0; $j--) {
      $dir = implode('.', array_slice($server, -$j)) .
             implode('.', array_slice($uri, 0, $i));
      if (isset($sites[$dir]) &&
          file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
            $dir = $sites[$dir];
      }
      if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') ||
         (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
            $conf = "$confdir/$dir";
            return $conf;
      }
    }
  }

If found, it uses this directory as files path.

So, one way is to temporarily change $_SERVER['HTTP_HOST']:

$_SERVER['HTTP_HOST'] = 'exchange';
print file_create_url('public://picture.jpg');
$_SERVER['HTTP_HOST'] = 'exchange-test';

Will give the correct result. But this trick seems clumsy to me. Is there any way to get the default directory without such hacks?

try setting the public file system path in your -test site to match that of the other in /admin/config/media/file-system


How to use og_is_member() API? Possible Duplicate:
  OG groups: How to check if user is a member or not?

I don't know how to use this: http://api.drupalize.me/api/drupal/function/calls/og_is_member/7

I want to check if user is a member of group or not.

Can someone help me?

Thank you!

I'm not sure what difficulty you're having using the function or what Drupal version you're on, but according to drupalize.me, in Drupal 7 og_is_member() takes parameters $gid (ID of group), $entity_type (defaults to 'user'), $entity (defaults to current user), and $states (optional, defaults to all), and returns TRUE if the entity (e.g. current user by default) belongs to the group.

For example, to find out if the current user is a member of group 4, I would use something like,

$current_user = global $user;
if (og_is_member(4, 'user', $current_user)) {
  // show the user some stuff from group 4
}

The above code is not tested but should get you started.


Have To Recreate Feature After Rollback - Features Module I have strange issue. I have several node instances included part of the packaged feature XXX that service as test pages. These node instances have two fields - the default body and extra text field 'description'. When I install this feature for the first time on new Drupal site, everything works. If I roll back via Migrate_backup or physically dropping all tables, the second time installing the same feature all body fields is coming up empty and the extra field 'description' is not installed at all

There is no messages in the watchdog log. My current versions:

Feature 7.x-2.0
uuid_features 7.x-1.0-alpha3
fe_block 7.x-1.0-beta1
strongarm 7.x-2.0

I also tried this with newest dev versions of uuid_features, fe_block, strongarm, but the same issue

My solution is recreating feature with different name but its unnecessary extra work and time. Have you ever experienced this issue? How would you troubleshoot? Can i enable some kind debug mode for feature installation or any module for that matter? I may be just doing it wrong as this my first experience with Features module. Thank You

It turns out the feature is in 'overridden' state

drush fl name_on_feature

If I did revert

drush fr name_on_feature

Then that solved my problem but i am still puzzled. If I drop tables, then how is it detecting 'overridden' state. Does Features module has some local file cache used for handling states?..just thinking loud. To my understanding revert updates database according to the code of the feature.


How can I add a cancel button to the content add form for a single content type? I have several content types on a site and most of them are user-editable but not user-creatable.  However, one content type, Image, allows users to upload a picture.  Sometimes, however, users upload the wrong picture and they panic because they don't want that picture to be submitted to the site.

Of course they could always hit the browser's back button, but I'd like to add a Cancel button for additional assurance.

I found this thread that gives various solutions for adding cancel buttons on Drupal.org as well as this feature request for adding a cancel button to D8.  However, there are several different general approaches and I don't know how to limit one to a given content type (in this case, my_image).

I would use the following code.

function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

Notes

markup is the default form element type; there is no need to use #type = 'markup'.
In the node edit form, all the buttons are inside $form['actions']. The weights used from the buttons that form is using are 5 (Save), 10 (Preview), and 15 (Delete). I used 20 to show the link after those buttons, but you can change its weight to show it in a different position.

// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);
$form['actions']['preview'] = array(
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
  '#type' => 'submit',
  '#value' => t('Preview'),
  '#weight' => 10,
  '#submit' => array('node_form_build_preview'),
);
if (!empty($node->nid) && node_access('delete', $node)) {
  $form['actions']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#weight' => 15,
    '#submit' => array('node_form_delete_submit'),
  );
}

There isn't the need to use arg() to understand if the form is for editing an existing node, or for creating a new one. I checked !isset($node->nid) || isset($node->is_new) is TRUE, to verify the node is being created. Drupal seems to simply check empty($node->nid), even though node_object_prepare() uses !isset($node->nid) || isset($node->is_new).
If $_GET['destination'] is set, the link added with l() will point to that path.


How to make view to group by only one field? I have a view with multiple fields and the fields have multiple values, so I get many duplicates in results.
When I try to use distinct, nothing happens, because select distinct does not affect on multiple values. I have predictable, but non desired result.

When aggregation is disabled I don't have any "groupby" directives in resulting SQL.

When I enable aggregation, I see in resulting SQL the following:

GROUP BY field_data_field_tour_short_name_node_entity_type,
field_data_field_tour_short_name_field_tour_short_name_value, node_title,
nid_1, field_data_field_arr_dates_node_entity_type,
field_data_field_arr_dates_field_arr_dates_value,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_duration_field_tour_duration_tid,
field_data_field_tour_minimal_price_node_entity_type,
field_data_field_tour_minimal_price_field_tour_minimal_price

So, as you can see, I have ALL the fields in my view.

When I disable aggregation and try to use hook_views_query alter

$query->add_field('node', 'nid', 'nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

I get the following:

GROUP BY node.nid, field_data_field_tour_short_name_node_entity_type,
field_data_field_arr_dates_node_entity_type,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_minimal_price_node_entity_type

As you can see, I get less fields, but not one.

But I need simply:

GROUP BY node.nid

How can I get grouping by only on field instead of many?

UPDATE: I found the following strings in views_plugin_query_default.inc

$groupby = array_unique(array_merge($this->groupby, $non_aggregates));
  foreach ($groupby as $field) {
    $query->groupBy($field);
  }

So views for some reason add other fields to groupby if groupby is present.
How to avoid this adding? I could change the file, but this is not proper way.

I had the same problem.
Try to implement the group by in hook_views_pre_execute, it's work for me.

function MYMODULE_views_pre_execute(&$view){
  if ($view->name == 'YOUR_VIEWS' &&  $view->current_display == 'SOME_DISPLAY') {
    $view->build_info['query']->groupBy('node.nid');
  }
}

If you are using a pager, updating $view->build_info['count_query'] with the same changes should keep the pager consistent with the query results.


How do I show an already hidden field of a custom content type to a specific authenticated user? I have a custom content type whose fields are Name, Description, and URL which is hidden by default. I want to show the latter field to the authenticated users who have flagged the node containing it. (I installed the Flag module for the flags.)
The flagging and displaying the flagged items are working fine. The only thing I am having trouble with is the hidden URL.
Can anyone guide me on how I can do this?
I looked into using the Rules and the Conditional Fields modules, but I don't think they would help and they seem to be an overkill for this particular task. I also looked into implementing hook_page_alter(), but that didn't help either.

It's possible to hide/show an entity field when an entity is rendered, but a hidden field is automatically removed from the base class used to implement an entity view, the EntityDisplayBase class. Its constructor calls EntityDisplayBase::init(), which contains the following code.
// @todo Remove handling of 'type' in https://www.drupal.org/node/2799641.
if (!isset($options['region']) && !empty($options['type']) && $options['type'] === 'hidden') {
  $options['region'] = 'hidden';
  @trigger_error("Support for using 'type' => 'hidden' in a component is deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use 'region' => 'hidden' instead. See https://www.drupal.org/node/2801513", E_USER_DEPRECATED);
}
if (!empty($options['region']) && $options['region'] === 'hidden') {
  $this
    ->removeComponent($name);
}

Since that code is executed when the entity display class is build, every hook running before the entity is rendered would not get those hidden components (which are entity fields and extra fields).
Rather than setting an entity field as hidden by default, and then show it when some conditions are met (which would not be possible), you can set the field as visible by default, and hide it when some conditions are met. Which hook to use depends also from when that field needs to be hidden.
If the entity field needs to be hidden only when specific view modes (a.k.a. entity display modes) are used, then hook_entity_view_display_alter() can be implemented.
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;

function mymodule_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
  // Leave field labels out of the search index.
  if ($context['entity_type'] == 'node' && $context['view_mode'] == 'the view module you are interested to') {
    $components = $display->getComponents();
    $name = 'The machine name of the field you want to hide.'
    if (isset($components[$name])) {
      $options = $components[$name];
      // Verify the conditions to hide the field are met.
      $options['region'] = 'hidden';
      $display->setComponent($name, $options);
      }
    }
  }
}

The code I shown assumes you are using at least Drupal 8.3; otherwise, it needs to be changed. (Instead of $options['region'], it needs set $options['type'] to 'hidden'`.)
If you need to hide the field independently from the view mode used to render the node, then the hook to implement is hook_entity_field_access().
use \Drupal\Core\Field\FieldDefinitionInterface;
use \Drupal\Core\Field\FieldItemListInterface;
use \Drupal\Core\Session\AccountInterface;

function mymodule_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  if ($field_definition->getName() == 'the field you are interested to' && $operation == 'view') {
    // Verify the conditions to hide the field are met.
    // Return AccessResult::forbidden() if the conditions are met.
    return AccessResult::forbidden();
  }
  // Otherwise, return AccessResult::neutral(), which lets Drupal core
  // or third-party modules decide.
  return AccessResult::neutral();
}

I used AccessResult::forbidden() just as example. You could also verify the account passed to the hook has a specific permission with AccessResult::allowedIfHasPermission($account, 'permission to check'), or verify the account has one or more permissions with AccessResult::allowedIfHasPermissions($account, ['list', 'of', 'permissions'], 'OR').
Keep in mind that, implementing hook_entity_field_access(), you would also avoid the field is indexed by the Search module. If you want the field to be indexed by the Search module, you need to implement hook_entity_view_display_alter() and leave the field visible when $context['view_mode'] is equal to 'search_index'.
As alternative, you could create a view mode that is similar to the view mode used to show the node, but where the hidden field is visible. Implementing hook_entity_view_mode_alter() you can alter the view mode to use the one you created.
use Drupal\Core\Entity\EntityInterface;

function mymodule_entity_view_mode_alter(&$view_mode, EntityInterface $entity, $context) {
  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && ($view_mode == 'full' || $view_mode == 'teaser')) {
    // Verify the conditions are met.
    $view_mode = 'my_custom_view_mode';
  }
}


Populating Webform Tables I am new to Drupal and have been working with Webform module to generate a custom form. One of the requirements for the form is to show a table where a user can add upload documents like this:

I created a new webform and started adding fields. As I added the 'table' field, it had option to set table Header (th) but not rows (td). I am not very familiar with the idea of hooks. Can someone please tell me how I can add rows? And if it is not possible to be done via the UI, then in what files the code must be added?

I am using Drupal 8.

Composite elements do not support file uploads. If there is a finite amount of documents you could manually build a table. The Table element was recently hidden because it was impossible to document. Here is an example of table layout within a Webform.


Global variable, visible only inside the module I have several modules, that implement very close functionality. And the SQL requests are almost the same, except for the table name. So I wanted to create a global variable, inside each module:

$GLOBALS['module_name'] = __FILE__;
$regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
$GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);

$GLOBALS['module_name'] will contain the current file name, which is the same as name of the table.

And then use it in the requests:

$query = db_select($GLOBALS['module_name']);

But global variables are shared among the modules, and the definition from a different module rewrites the correct value.

I tried to use hook_init

function my_module_init()
{
   $GLOBALS['module_name'] = __FILE__;
   $regexp = "/.*" . "\\" . DIRECTORY_SEPARATOR. '(.*)\.module/';
   $GLOBALS['module_name'] = preg_replace($regexp, '$1', $GLOBALS['module_name']);
}

But without success.

Is it possible to have global variables with the same name in many modules, but each will be visible only inside the appropriate module?

If you use the same global variable, its value is shared between all the enabled modules because global variables are globals by definition. Every PHP file that is loaded will see the same global variables, such as the global $user that is used from Drupal for the account of the currently logged-in user.

The same is true if you use constants defined with define(); they are global, and two modules cannot define the same constants. Try defining the REQUEST_TIME in Drupal 7, with define('REQUEST_TIME, 'test'): You will get an error, as the same constant is already defined from Drupal (see REQUEST_TIME).

The same is true for Drupal variables defined with variable_set(). Every module that is using variable_set($name, $value) (where $name has the same value for all the modules) is setting the same variable.

Even if you would be using &drupal_static($name, $value) in different modules, the modules will be altering the same static variable.

I would rather use a constant defined with define(), but every module needs to use a different constant.
See the Drupal coding standards about naming conventions.


Chrome makes images in Views smaller I made Views page in table format.
2 columns. In the left - image in format 220x220 (resizing by Drupal). Right column consists from text.
When I see page from Chrome, I noticed that images in first comn are extremely small.

What can be the problem?

Try setting width:220px to the left td elements in the table.

In css:
table tr td:first-child {width: 220px;}


Core update installs 8.6.0-beta1 instead of 8.5.6 Using composer I tried to update Drupal 8 to 8.5.6. The update wasn't working, so I changed the dependencies to explicitly require 8.5.6. The update began, but it installed Drupal 8.6.0-beta1. The command I used was composer update drupal/core --with-dependencies -v.

The updates page still says Drupal 8.5.6 is required. I'm not sure where to go from here.

Should I try to roll it back? I tried requiring Drupal 8.6.0-beta2 and Drupal 8.6.0-rc1, but an error suggested not to update to these versions. I want the site live ASAP, and updated to Drupal 8.5.6.

Solution for me was start from 8.5.0, upgrade to 8.5.5 then run:

composer update drupal/core symfony/* --with-dependencies

I'm now on 8.6.0 ! :)


Automatic adding of the subject to the contact form I have the block that is shown in every node of one content type. The block contains the link (the anchor tag) which leads to the page with contact form.

Is it possible to add subject automatically to the contact form depending on which page the user clicked on the link and came to contact form page? The subject would be the title of that page.

I use Webform module for the contact form.

I have created a custom module, but the form_alter can just as well be placed in the theme template file.

function MYMODULE_block_info() {
  $blocks['contact_at_webform_block'] = array(
    'info' => t('Contact Us'),
  );

  return $blocks;
}

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

  switch ($delta) {
    case 'contact_at_webform_block':
      if (user_access('access content')) {
        $block['subject'] = t('Contact Us');
        $block['content'] = l('Contact Us', 'contact', array('query' => array('subject' => drupal_get_title())));
      }
      break;
  }
  return $block;
}

function MYMODULE_form_alter( &$form, &$form_state,$form_id ){
  //dpm($form); dpm($form_id);
  if ($form_id == 'webform_client_form_5') {
    $qp = drupal_get_query_parameters();
    $subject = isset($qp['subject']) ? $qp['subject'] : '';
    $form['submitted']['subject']['#default_value'] = $subject;
  }
}

So the important part of the link in the block is to add the page title as a query parameter, so the href of the anchor will look like this contact?subject=PAGE_TITLE. If you use a block from views or created from the block UI then make sure to output the link in similar fashion.

The form alter code picks up the query parameter and inserts it into the webform subject text field. You will have to adapt the code here as your form id and text field will be different. Install devel module, then uncomment the dpm statement that is relevant. First dpm the value of your $form_id and replace mine (webform_client_form_5) with yours. Then dpm $form and inspect $form['submitted']. Look for your subject field.


Using Docker4Drupal in Production vs. its commercial Wodby solution I've been playing with https://github.com/wodby/docker4drupal on a DigitalOcean droplet and am utterly amazed at how it all works.

However, it recommends that people use https://wodby.com/ for production and I'm wondering if I have to; it seems like an unnecessary step when my testing has four sites running perfectly in "production mode".

Does anybody know in what way Docker4Drupal is designed to be run in a local environment when it seems so well on a regular server?

This isn't a question of money.. Just effort. I'm a one man show and don't need dev/staging/production for what I'm working on right now.

Disclosure: I'm a Docker4Drupal maintainer and Wodby co-founder.

We do not limit usage of our images, it's MIT licensed, so if you want - go ahead and deploy the images in production. However, you'll have to do some work before that, e.g. set up a router, certificates, cron, etc. Configuring usual stuff with containers is not always obvious especially if you're not proficient with containers. Since we already handle all of this in our platform we've added this recommendation (people asked us about production). Also, stability requirements are higher for production (including freezing the docker version).

Originally, we created docker4drupal just to provide a local environment for our customers (instead of connecting Vagrant) but later it became obvious that it is valuable for many drupalers including those who do not use Wodby. In other words, historically, it was prod > local transition, not the other way around.


Calculate webform total from select list fields Like e.g. there are two select options type components that has various amounts of $ to select from. So if user selects in one field $100 and $200 then the next field below it would generate the total which would be $300 in this example.

I did research, and the module Webform Calculation Components does the exact thing I want, but it does that only with numeric fields where user has to type amounts manually. So it's a no-go. In my case user has to select from drop-down list already given amounts.

Cheers

You can use Webform Calculator module for your purpose.

This module provides a formula webform component for computed values, where you can enter a mathematical calculation based on the other fields. E.g. Create a formula field with value formkey1 * 0.1 * formkey2.

Let us know incase of any concern/query regarding this.

Thanks!


Filtering on a field from field collection in a view I have several node types (merchandise vendor, food vendor, festival vendor) which all have an embedded field collection called equipment, which can contain multiple values. The field collection has a taxonomy field called event and some others.

For example, a merchandise vendor can have equipment for event 1 (a taxonomy term), and different equipment for event 2 (a different taxonomy term).

My view can sort out the vendors for event 1 just fine. I can include the equipment for the events in the view, but I can't seem to filter it to just event 1.

I want to be able to visit the view page for event 1, and have it show all the vendors for event 1, and the equipment each vendor needs for event 1. Right now, it shows all the equipment for the vendor for all the events.

Is there a way to filter a field collection in a view?

You can create a Relationship to the field collection, and then you'll have access to all the field collection's fields within the collection from both "Fields" and "Filters".


How to set image style for particular image in node creation or edit? I want to add some image style to the particular image, preferably the first image for adding some badge like "Agent Face Image".

My idea is when creating the node, there is an option for check box. If the user selected the check box, a particular style need to be applied to that image only, if unchecked then vice-versa. I'm using Drupal 6.

How can I achieve this?

If you are asking "How can I theme the first image in a multi-value field differently from the remaining images in that field?" you can use a custom field template.

First, copy content-field.tpl.php from the CCK module (found in modules/cck/theme/content-field.tpl.php) to your theme's directory.

Then copy it to content-field-field_NAME_OF_FIELD.tpl.php eg something along the lines of content-field-field_pictures.tpl.php.

NOTE:  You must have both content-field.tpl.php and content-field-field_whatever.tpl.php in the same directory in your theme or it won't work.

Inside, it looks basically like this:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php print $item['view'] ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

and you will be wanting to change the <?php print $item['view'] ?> line in the middle.

Dull ax approach, this would do it:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php
            if ($count==1) {
              $first=str_replace('100x100','228x228', $item['view']);
              print $first;
            } else {
              print $item['view'];
            }
          ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

where, if in your CCK configuration you have 100x100 as the imagecache style for this field as the default, it is changed to 228x228 for the first image.

Obviously, if 100x100 appears anywhere else this fails so I am sure something more eloquent could be created.  But in either case, clear caches/theme registry and you should be on your way.

Also, I've left out any logic based upon toggling this on another field's value, but all the information is available in that template to do so.


Attach PDF file to Drupal Commerce Order Notification How do I attach a views_pdf file to the commerce email?

I have views_pdf, commerce_coupon.

As Sally I would like to buy a coupon and have a copy emailed to me.

I am stumped on how to get the pdf view into a File object.

function yhivecoupons_mail_alter(&$message) {
  global $user;

  if (!empty($message['id']) && ('message_notify_commerce_order_order_confirmation' ==  $message['id'])) {
$pdf_coupon = views_embed_view('commerce_gc_user_giftcards', $display_id = 'pdf_1');

  $my_attachment = array(
    'filecontent' => $pdf_coupon,
    'filemime' => $pdf_coupon->filemime,
    'filename' => $pdf_coupon->filename,
    'filepath' => NULL,
  );
  $message['params']['attachments'][] = $my_attachment;
 }
}

Problem #1. Getting a copy of the PDF.

The function views_pdf_rules_action_save() almost did it. I changed

$display->handler->execute('', 'F')

to

$display->handler->execute('', 'E')

As TCPDF has an option to generate the PDF as an email format. I don't need to save the file with the resulting security and overwriting challenges.

Problem #2. Stripping the email and base64decode

The email format added the HTML already has the headers. I didn't dig enough to bypass the Drupal mail array processing. Instead the heading was stripped. You could use more of the provided mail headers.

$email_attachment = _yhivecoupons_views_pdf_rules_action_save('commerce_gc_user_giftcards:pdf_1', null, '');
$email_attachment_parts = explode("\n", $email_attachment);
$content_type = array_shift($email_attachment_parts);
$name = array_shift($email_attachment_parts);
$encoding = array_shift($email_attachment_parts);
$disposition = array_shift($email_attachment_parts);
$filename = array_shift($email_attachment_parts);

$clean_email_attachment = implode("\n", $email_attachment_parts);
$clean_email_nobase64 = base64_decode($clean_email_attachment);

      $my_attachment = array(
    'filecontent' => $clean_email_nobase64,
    'filemime' => 'application/pdf',
    'filename' => "tester.pdf",
    'filepath' => NULL,
  );
  $message['params']['attachments'][] = $my_attachment;

Problem #3 Permissions

This process is still executed in a context where the user was not logged in. I am printing out a person's coupons so need their login details.

I don't think this is the best way to do this, as the process is not checking unique email addresses yet.

global $user;
$user_obj = user_load_by_mail($message['to']);
$user = user_load($user_obj->uid);

Log out user at end.

Instead I am using commerce_immediate_login which does the same thing but in a rule using the ui generated by 'create login for anonymous users'. The order of the rules is specific.

This is my views PDF call function with the 1 character change from views_pdf_rules_action_save(). A tested way of getting PDF content from views_pdf.

function _yhivecoupons_views_pdf_rules_action_save($views_pdf, $arguments, $path) {
  $splits = explode(':', $views_pdf);
  $view_id = $splits[0];
  $display_id = $splits[1];

  if (!empty($view_id)) {
    $view = views_get_view($view_id);

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

    // Try to get pdf display
    if (!$view->set_display($display_id)) {
       // Try the display type
       if (!$view->set_display('pdf_1')) {
        // There is definitly no pdf display
        return;
       }
    }

    $view->pre_execute();
    foreach ($view->display as $id => $display) {
      if ($display->display_plugin == 'pdf' && isset($display->handler)) {
        // arguments '' and I
        return $display->handler->execute('', 'E');
       }
     }
  }
}


theme_field() render array I hoped the documentation for theme_field() would tell me how to create a render array that may be parsed by that function.

Based on that, I thought something like this would work.

return array(
    'test' => array(
        '#theme' => 'field',
        '#label_hidden' =>  false,
        '#title_attributes' => 'class="test123"',
        '#label' => 'test',
        '#content_attributes' => 'class="test456"',
        '#items' => array()
    )
);

It prints a &nbsp;.

what am I doing wrong?

The ultimate goal is of course printing some field_items, but I can find no documentation on how the render array for #items should look; nothing I tried outputs anything.

A pointer to better documentation might answer my questions.

If you absolutely need to piggyback on theme_field() rather than implement your own theme function (which would be preferable IMHO), then you'll have to jump through a few more hoops.

The key place to look is template_preprocess_field(), which will show you all of the elements that are expected to be in the array. Specifically for the label, the #title property is used. So this

return array(
  'test' => array(
    '#theme'                => 'field',
    '#label_hidden'         =>  false,
    '#title_attributes'     => 'class="test123"',
    '#label'                => 'test',
    '#title' => 'test',  // Required
    '#label_display' => 'visible',  // Required
    '#content_attributes'   => 'class="test456"',
    '#items'    => array()
  )
);

will return what you're looking for (with a bunch of notices about undefined indicies).

Eventually you'll also need to provide #field_name, #field_type, #bundle and #entity_type for each of your 'field' items.


Unable to change #markup I'm using Drupal 8, and I want to change the markup of more_links from more to something like more. I have tried with mytheme_preprocess_container(&$vars) with the help of kint debug to analysis the $vars array. $vars['element']['#markup'] returns more. However, setting it to a value does not applied.
function saidbakr_preprocess_container(&$vars){
 $vars['element']['#markup'] = 'HHHHHHHH';
}

I tried to use the #children but it has a protected property of markup and I don't know to how use the create method?
$vars['element']['#children']->create('HHHHH')

What's the problem here?

Update:
I just have gotten a semi solution, I regard it semi because it depends on a direct echo from template_preprocess_container like the follwoing:
function saidbakr_preprocess_container(&$vars){
  $elem = $vars['element'];
  if ($elem['#type'] == 'more_link'){
    $vars['children'] ='';
    echo str_replace('<a','<a class="btn btn-primary" ', $vars['element']['#children']);
  }
}

I used echo because setting HTML tags string to $vars['children'] leads them to be printed as entities on the page. i.e you see the HTML tag of the link instead of the actual link. Is there any concerns about using direct echo from the preprocess functions?

You should be able to change the more variable in template_preprocess_views_view, like:

function YOUR_THEME_preprocess_views_view(&$variables) {
  $variables['more'] = \Drupal\Core\Render\Markup::create('HHH');
}


Simple: How do I add data into custom field while creating new user with user_save With each user I create when my form is submitted, I want to insert an id into a field/column I've added to the users table. Trouble is, the column isn't receiving the value. I've tried a few variations of user_save() to coax it into inserting the value, but at this point I think I'm missing something fundamental of drupal 7.  Later I also need to retrieve this value from the current user.

I'd appreciate any help. Thanks.

<?php
//Func called in form submit. Values passed from there
function fsa_create_sponsor_admin($sponsor_id, $a_fname, $a_lname, $a_email){

//Misc. code. . . .

//create a new user
$account = new stdClass();
$account->is_new = TRUE;
$account->name = $user_name;
$account->mail = $a_email;
$account->init = $a_email;
//$account->sponsor_id = $sponsor_id; (no error, but not working here)
$account->status = TRUE;
$account->roles = $new_user_roles;
$account->timezone = variable_get('date_default_timezone', '');

//First variation of user_save()
user_save($account, array('pass' => $sp_password, 'sponsor_id' => $sponsor_id));

//Second variation of user_save()
user_save($account, array('pass' => $sp_password, 'field_other' => array(LANGUAGE_NONE => array(array('sponsor_id' => $sponsor_id)))/*end 2nd array*/));
}
?>

Column added in hook_install()

db_add_field('users', 'sponsor_id', array('type' => 'int', 'size' => 'big', 'not null' => FALSE, 'description' => 'Sponsor to which user belongs',));

I had the a similar problem. This code helped me.
I put this code in myform_submit.

$fieldvalue = $form_state['values']['fieldname'];

//Loading the user object

$account = user_load($GLOBALS['user']->uid);

//Gettin the user data

$edit['data']['fieldname'] = $fieldvalue;

//saving the achieved data

user_save($account, $edit);

//Retrieving the user value

global $user;
$whatever = $user->data['fieldname'];


Views: How to list nodes that are referencing to nodes, pointing to the current node I have 3 contenttypes where 2 of them have reference entity fields. Each their own entityfield.

Contenttype C is the parent. Type B points to type C. Type A points to B.

On every Node of type C i want to display a view that lists the nodes of type A pointing to B, that points to C. Is this possible?

Help appreciated.

Create a view that filters C nodes. Go to view advanced options and add a relationship with the field in B which references A and choose Referencing entity. Give a name name "children" to this relationship. Then create another relationship based on the field in A that references B. For this relationship use the previous relationship. Name this one grandchildren. Last add fields you need from the A nodes and dont forget to use relationship grandchildren for each one.

Alternatively use node A as base table and use the referring entity relationship type. Now you want to check require relationship to emulate an inner sql join and thus filter out B and C nodes with no references


installing twitter and oauth on drupal I have just been trying to get twitter going on my drupal 7.21 website.  i followed the tutorial at http://drupal.org/node/1346824
Everything was fine until the last step of authorising a twitter account, when i got a blank page back from the twitter app and a message saying "unauthorised oauth request".  I've tried re-installing, messing with callback URL's etc but cannot get anything to work. Has anyone else solved this problem?
Thanks
Andy

After the new Twitter API upgrade, I would recommend using the Twitter Pull sandbox project. It works beautifully.


Date field with selection back more than 20 years I have a date field:

the year selection is possible 20 years back from now:

But I need it to be 25 years. Is this a fix Drupal setting or can I change that?

The default is actually -10 years

Since yours is longer, scroll own and select "Other" and type -25

Save settings
Now when you edit again, you should see


Change value of a button in a form I'm using an eCommerce module. In a 'view cart' node, there is a 'remove' button so users can remove items they no longer wish to purchase, however, instead of the 'remove' value on each button, I'd like to have a simple icon and no text, how would I go about making this change? I understand it would probably be a form alter function in the template.php file, but I'm not sure how to set it up.

Yes, you can done it in form_alter . first need to know what is your button name in $form in form_alter, I suggest you print_r or var_dump $form and found your button (buttons usually are in #actions) . after it I suggest you handle your job with add a css class or id to your button and with css style it .

function yourcustom_form_alter(&$form,$form_state) {
  $form['actions]['yourbuttonname']['#value'] ='';
   $form['actions]['yourbuttonname']['#attributes'] =array('class'=>array('yourcssclass'));
}


How to include multiple taxes to a product's price? I am using Drupal commerce and have multiple taxes and tax types.

The product price in my site includes 2 types of taxes already added to them (inclusive of both the 2 taxes).

In the product edit page, I get an option to add one of the taxes to be included in the product price.

My doubt is that, how can I select multiple taxes to be included in the product price?

Any help is much appreciated. Thanks.

This is not supported unfortunately; it would require custom code for both the price field widget and the tax module's saving routine. If that's beyond your capabilities, you'll simply have to reverse calculate the price and enter it, accepting that the rounding may not always work out to nice round product prices like you want.


Use custom HTML file for page created by Views? I use Views to create new content and a new page for the content, but how am I supposed to customize the HTML layout of the page? I can style elements of the page via CSS, but what if I wanted to have my own CSS3 (animated sprite) elements? For example, most CSS3 sprites require you to have divs contained in a specific manner, but those divs are not present in a Views created page and I see no viable way to manually add them? How would I go about doing this?

When you edit the View, under the Advanced settings on the right-hand side you should see "Theme information". If you click that it will give you the content of the theme templates for the View, which you can then override by copying into your theme, in a file with a corresponding name.


Devel Krumo not updating I have the following code in my module in a hook_form_alter...

if($form_id == "privatemsg_new") {
        dsm($form);
        $form['recipient']['#type'] = 'select';
        $form['recipient']['#title'] = 'Choose Recipient';
        unset($form['recipient']['#autocomplete_path']);
    }

The code works just fine, the title is changed, the form field turns into a select list

However in Krumo, the fields are not being updated. I guess its not the end of the world, but its annoying to not be able to see my changes!

Type, Title and #autocomplete_path should all have changed.

I've run cron, flushed caches etc. Anything else I can try?

Put dsm() to the end of code...

if ($form_id == "privatemsg_new") {
  $form['recipient']['#type'] = 'select';
  $form['recipient']['#title'] = 'Choose Recipient';
  unset($form['recipient']['#autocomplete_path']);
  dsm($form);
}


What is the difference between t() and @Translation()? When writing a (translatable) plugin in Drupal 8, you have to use Drupal\Core\Annotation\Translation;, and then wrap your value in @Translation("value"), however when implementing the FormInterface, you can use t() freely as you would in Drupal 7.

I found Annotation-based plugins on Drupal.org, but it just mentions the fact that you should use it, and the Doctrine reference doesn't seem to include @Translation

I assume it is because the plugin system is part of doctrine, and not part of core, whereas t() is  -is this the correct assumption?

Basically, what is the difference between @Translation(); and t() - is it just because plugins are Doctrine based?

In short, @Translation() is a string used in annotations, meta data written in PHP comments and pertinent to a Drupal 8 class.

For example, this is the annotation for the PathItem entity field class.

/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = @Translation("Path field item"),
 *   description = @Translation("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */

When Drupal loads the class annotations from a file, and it finds @Translation("Content") in the annotation, it creates an instance of the Translation class whose constructor receives the "Content" string; the instance is then used to get the value of t("Content").

As for the differences, they are the following ones:

@Translation() is a string used in class annotations: plain text that follows a specific format and it is written in PHP comments before the class that is being annotated. You cannot use it in code similar to the following one, except in the case a module defines a Translation() function. In that case, the @ before it would be understood from PHP as the error control operator.

$form['salary'] = array(
  '#type' => 'textfield',
  '#title' => @Translation('Salary'),
  '#size' => 10,
  '#maxlength' => 10,
  '#description' => @Translation('Please enter a valid number'),
);

t() is a Drupal function. It cannot be used inside class annotations like the following one, since it doesn't follow the syntax annotations follow. If it were used in an annotation as in the following, it would not cause Drupal to call t() and use its return value.

/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = t("Path field item"),
 *   description = t("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */


How to create a payment form / pane directly from order_id Study case : customers already have the ability to pay only a deposit. So they 'll have to come back and pay the order balance later.

How can I create a payment form ?

where they will be able to directly submit a payment form and proceed to off-site payment to pay order balance
without coming from cart/checkout process, (as it has already be done in deposit payment another day)

This will be linked from the user/%/orders/% page.

Is there any commerce API function that could fit that issue ?
I had a look at commerce_payment_order_transaction_add_form($form, &$form_state, $order but I could not find any doc to implement it, .

Thank you

PS : related issue: Commerce partial payment

I got it doing the following :

with a link in user/%/orders/% page like go_to_checkout/$order_id

/**
 * Implements hook_menu();
 * Callback to pass order_id to checkout fn
 */
function commerce_partial_payment_menu() {

  $items['go_to_checkout'] = array(
    'title' => 'balance',
    'description' => 'Pay order balance',
    'page callback' => 'commerce_partial_payment_redirect_to_checkout',
    'page arguments' => array(1),
    'access arguments' =>  TRUE,//still have to change that, maybe see own orders permission
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/*
 * Prepare checkout process and redirects to checkout/%/review
 */
function commerce_partial_payment_redirect_to_checkout($order_id) {

  $order = commerce_order_load($order_id);
  commerce_order_status_update($order, 'checkout_review', $skip_save = FALSE, $revision = TRUE, $log = '');

  drupal_goto('checkout/' . $order->order_id. '/review');
}


How do I allow editors to select a template with CkEditor? I am using CkEeditor to edit the node body field. I want to add a Select template option in CkEditor.

I suggest you have a closer look at the widget API / the widget plugin for CKEditor. The widget API enables you to have something like 'templates' meaning predefined groups of elements inside the editor window.

"Widgets are special rich content units in that they are groups of elements which are treated as a single entity inside the editor."

http://docs.ckeditor.com/#!/guide/dev_widgets
At the end of that page there are links to further info about the Widget SDK and a step-by-step tutorial for creating your own widget ('mini-template').
I use the widgets plugin myself together with the SCALD module family and I must say I am still quite excited how very well these two play together.
If you 'just' want to add content templates however, you should probably download and install the Content Templates plugin for CKEditor.
From the download dialog window:

Extract the downloaded plugin .zip into the plugins folder of your CKEditor installation. Example:
http://example.com/ckeditor/plugins/templates
Enable the plugin by using the extraPlugins configuration setting. Example:
config.extraPlugins = 'templates';
Download and configure all its dependencies, too.
Add-on Dependencies: Dialog

The configuration setting can be found/added in config.js inside the ckeditor directory.


Non-breaking space in menu link name How to put non-breaking space into a menu link name in Drupal 8? I tried &nbsp; but it got displayed   literally.

Use this in your theme so menu items can be processed as html

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 * processes 1 nested level of menu items
 */
function THEMENAME_preprocess_menu(&$vars){
  if($vars['menu_name'] == "main"){
    foreach($vars['items'] as &$link){
      $link['title'] = Markup::create($link['title']);
      foreach($link['below'] as &$nestedlink){
        $nestedlink['title'] = Markup::create($nestedlink['title']);
      }
    }
  }
}

Alternatively you can use css to make regular white space not wrap

.menu li a {
    white-space: nowrap;
}

Of course you have to adjust css for your particular menu class


What module might make all my links redirect the current window with target="_blank"? I'm at a loss. None of my own JS is doing it. When I set a link to target="_blank" it opens a new window to that location, but also redirects the original window. Does anyone have a clue what module may be involved?

I had the same problem before and it was because of Google analytics module. This link may help you http://drupal.org/node/1091932


Filter module won't let me add nested values to my configuration I'm working on the D8 port of my xbbcode module; my latest sources are here.

The module is supposed to let administrators enable individual BBCode tags either in the global default settings or in an individual text format that overrides those defaults.

The settings structure for both is basically (in YAML):

tags:
  abbr:
    module: xbbcode
    enabled: 0
  b:
    module: xbbcode_basic
    enabled: 1
  [...]

The default configuration (set in the annotation comment of my filter plugin class) is

/**
 * Provides a filter that converts BBCode to HTML.
 *
 * @Filter(
 *   id = "xbbcode",
 *   title = @Translation("Convert BBCode into HTML."),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 *   settings = {
 *     "autoclose" = FALSE,
 *     "override" = FALSE,
 *     "tags" = {}
 *   }
 * )
 */

However, when I try to create a new text format, I get the following error:

InvalidArgumentException: The configuration property filters.xbbcode.settings.tags.abbr
doesn't exist.
in Drupal\Core\Config\Schema\ArrayElement->get()
(line 97 of core/lib/Drupal/Core/Config/Schema/ArrayElement.php).

Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags.abbr', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings.tags', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode.settings', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters.xbbcode', Array)
Drupal\Core\Config\StorableConfigBase->castValue('filters', Array)
Drupal\Core\Config\Config->save()
Drupal\Core\Config\Entity\ConfigEntityStorage->doSave('bb2', Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\filter\FilterFormatFormBase->submitForm(Array, Object)
Drupal\filter\FilterFormatAddForm->submitForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object)
Drupal\Core\Form\FormBuilder->processForm('filter_format_add_form', Array, Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\Core\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

Some examination of the StorableConfigBase class reveal that it seems to insist on merging my configuration values with the existing ones, down to the bottom level, and when it doesn't find the "abbr" key it shuts down. This seems pretty silly, because obviously an array can gain or lose entries when you save it.

The weird thing is that the global defaults have absolutely no problem when I change them with $this->config('xbbcode.settings')->set('tags', [...])->save() in my own ConfigFormBase settings form.

Edit: filter.format.* has a config schema, while my module doesn't. I'm not sure how to tell this schema "this array may have a number of keys, each of which has the form {enabled: ..., module: ... }

I figured out how to declare the filter settings schema by comparing with modules/filter/config/schema/filter.schema.yml and using the Schema docs.

Apparently my schema file simply needs to declare

filter_settings.xbbcode:
  type: filter
  label: 'XBBCode filter'
  mapping:
    [...]


Add custom jQuery to form as a module I'd like to get the following jQuery code to run on any forms on my site:

(function($) {
  // Hide any N/A radio buttons
  $('.form-radio[value=_none]').parent().hide();

  // Uncheck a radio button on double-click
  $('.form-radio').dblclick(function(){
    $(this).prop('checked', false);
  });
})(jQuery);

I've read that I can probably just add it to my template.php file, but I'd like to put it in a module. How would I do that?

UPDATE:

Thanks for the suggestions! So I went with option 3 because it seemed to make the most sense to me for my use-case. I still wasn't getting my jQuery to actually work though. I've updated it to this now:

(function($){
  Drupal.behaviors.doubleClickNA = {
    attach: function (context) {
      // Hide the N/A radio button
      $('.form-radio[value=_none]').parent().hide();

      // Enable the double-click unchecker function
      $('.form-radio').dblclick(function(){
        $(this).prop('checked', false);
        $(this).parent().parent().$('.form-radio[value=_none]').prop('checked', true);
      });
    }
  };
})(jQuery);

That seems to get the N/A radio button to disappear, but the second function still doesn't work. The $('document').ready part was the key for the first function (duh, right?), but I believe I need to use a behavior to get the double click action to work after the page as finished rendering. What more am I missing here?

You have different ways/options to add custom javascript/jQuery file with your module.

Option 1: Add myscript.js in module info file (mymodule.info).

scripts[] = js/myscript.js

Option 2: Add myscript.js using hook_init and drupal_add_js

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'MODULE_NAME') .'/js/myscript.js', 'file');
}

Option 3: Add myscript.js to any Drupal form or any callback that contains Drupal form

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'MODULE_NAME') . '/js/myscript.js',
    'type' => 'file',
  );
}


How can I hide search results until the user submits the exposed form? I have a fairly straightforward view, which exposes a simple keyword filter to the user.

Currently, when I first land on the page containing this view, all records are displayed (i.e., the search results are unfiltered).

How can I alter this behavior, so that no search results are displayed until the user has entered a keyword and submitted the form?

(I'm converting an old Drupal 7 site to Drupal 8. On the D7 site, the view does not show search results when I first land on the page. Is this a difference in behavior between the Views implementation in D7 and D8? I can't find anything in the D7 site to suggest that this difference in behavior is caused by a module.)

You can change that under Advanced Views options (third column): Exposed form style:

After you choose Input required, you can adjust further options, including the text to display before any filters are active:

If you're using Better Exposed Filters module it has an option for it too:

  Input required
  Only display results after the user has selected a
  filter option.

It hasn't changed since D7, it works the same in D8 as it did in D7.


Getting a taxonomy-term-name as plain-text in computed field In an entity-type with term-reference i want to add a computed field, which grabs the term and sanitizes it for further use with the drupal_clean_css_identifier for example. My code doesn't work, because field_get_items gives back a full link to the term instead the term name as plaintext:

$entity_field[0]['value'] = drupal_clean_css_identifier(array_pop(field_get_items($entity_type, $entity, 'field_myterms'))));

Can someone help me out?

calling field_get_items() on a term reference field returns an array like this

Array(
  0 => Array(
    'tid' => 10,
  ),
)

to get the term name from the term id (tid) you should load the taxonomy term:

$field_myterms = field_get_items($entity_type, $entity, 'field_myterms');
if (!empty($field_myterms)) {
  $term = taxonomy_term_load($field_myterms[0]['tid']);
}

$term is an stdClass object:

stdClass Object
(
    [tid] => 1
    [vid] => 1
    [name] => test
    [description] =>
    [format] => filtered_html
    [weight] => 0
    [vocabulary_machine_name] => tags
    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => skos:Concept
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => rdfs:label
                            [1] => skos:prefLabel
                        )

                )

            [description] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:definition
                        )

                )

            [vid] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:inScheme
                        )

                    [type] => rel
                )

            [parent] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:broader
                        )

                    [type] => rel
                )

        )

)

to set the computed field value:

$entity_field[0]['value'] = drupal_clean_css_identifier($term->name);


Breadcrumb/block settings Should Views (that are setup as a Page) be able to inherit breadcrumbs/block visibility settings? When I create a Views page, set a path, add it to the menu (then adjust it to be a sub-menu of another parent item), when I am on the actual Views page, it looses (in this case) any block settings that should be shown on this page. From the screen shot below, you can see the menu block disappear (as well as the LEAD logo on the lower left side). More odd than that, is whenever I set the View to be added to a menu (as I have done in the Views settings), it doesn't show up (which is why I had to add it to the menu manually). I've gotten it to work with another Views page (the menu link showing up), but the blocks still disappear.

Also, once you click on an individual node, they also loose any type of breadcrumb/block visibility (even though I've set the URL to be the correct breadcrumb /about/faculty-staff/directory/USER_ID). Any help would be greatly appreciated. Thanks!

Current setup:
Drupal 7.5
Views: 3.0-rc1
Menu Block: 2.2

Screenshot Explanation:

Directory page (Views page - blocks missing from this page)

Main Faculty & Staff page (parent page)

User Profile view

Views config

Menu list

Menu config

To your first problem, the menu disappearing on about/faculty-staff/directory:

Check how the menu block is configured.
Check if there is another menu item in another menu that links to this page. It could be that Drupal picks this up and thinks we are in another menu.

(There is a more general solution that I am going to post in another answer)


Get the public path directory I want to save file programmatically in public path, and I want to know how can I get Public Directory path in Drupal 8. In Drupal 7, I would use the following code.

drupal_realpath(file_default_scheme() . '://')

What is the equivalent in Drupal 8?

According to realpath API, you can Get it with :

\Drupal::service('file_system')->realpath(file_default_scheme() . "://");


Hide contextual filter parameter from view url I'm using Views to create a view which shows list of contents. The requirements of the view is something like this:

The page display url must be /mycontents
The contents must be filtered by current user(The content's author must be current user).

And what I did:

Set Page settings > Path to /mycontents
In Advanced > Contextual Filters , add Authored by
In the contextual filter's When the default value is not in the url section, checked Provide default value and selected User ID from logged in user.

The problem is that after saving the view, the actual url of the view becomes /mycontens/{uid}. Is there any way to remove the {uid} from the path?

I don't think this is possible if you show the view as a page, but you might be able to solve the problem by creating a custom route and rendering the view on that page, where you fetch the uid programatically.

You must do something like this in your Controller:

$user_id = 1;
$args = [$user_id];
$view = Drupal\views\Views::getView('my_view_id');
if (is_object($view)) {
  $view->setArguments($args);
  $view->setDisplay('page');
  $view->preExecute();
  $view->execute();
  return $view->buildRenderable('page', $args);
}


View with paged output - how to alter number of pages? I use Views 7.x-3.8.
I have view "taxonomy_term". It has Paged output, full pager. Number of pages (the total number of pages) is set to 100, Items per page = 10.
Now I want to show all pages for users with proper permission.

I tried to set pager option 'total_pages' to empty string in hook_views_pre_execute():

function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'taxonomy_term') {
    if (user_access('view all pages')) {
      $view->query->pager->options['total_pages'] = '';
    }
  }
}

It actually works with pager: users with permission 'view all pages' can view page #101, #102 and so on, but nodes on these pages (more than #100) are the same as on page #100. It means that query has not changed, and query limit is still 1000 (10 items x 100 pages).
I tried

$view->query->set_limit(0);

in hook_views_pre_execute() and

$view->query->set_limit(0);
$query->set_limit(0);

in hook_views_query_alter(), but it's not working.

I also tried to set $view->query->offset and $view->offset manually:

$view->query->offset = $view->offset = $view->query->pager->current_page * $view->query->limit;

with no effect.

What am I missing? How to change number of view' total pages AND query results programmatically?

I did it:

function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'taxonomy_term') {
    if (user_access('view all pages')) {
      $view->query->pager->options['total_pages'] = NULL;
      $query = $view->build_info['query'];
      $offset = $view->query->pager->current_page * $view->query->limit;
      $query->range($offset, $view->query->limit);
    }
  }
}


Views No results Behaviour Show All I have a proximity search on views using Gmap and Location API, I've imported all the UK post codes into my zipcodes table in my database, and it all works great. The only thing I would like to change is the no results behaviour.

If a user enters a postcode, and there isn't a venue nearby, the map disappears, and I can show a no results message in its place.

What I would like to happen, is for the map to stay where it is, but showing all venues, with a message underneath saying "Please widen your search area".

Anyone know if this is possible? I've been searching for a similar post on Google, but can't find anything, as I'm not having any errors, just wondering if its possible, and can't seem to figure it out myself!

You can embed a different View under "No results behaviour"

e.g a View that lists all venues.


How to remove fee from order I have added a fee with rules using commerce_fee module.
I need to remove the fee but i can´t find a way.
How can this be done?

Commerce Fees creates a line item of a particular type. You can loop through each of the line items on an order and remove the line item that has a particular type by looking at it's type value. I believe you can remove it by setting the quantity of the line item to 0.


Using date and rules to publish and unpublish content I have two scenarios:

I have a meditation content type that need to show in a view when the date field = today's date. I want a view to show a meditation every year on the same date.
I need to create a new node of a certain content type every week where the date field has a start date of today's date and a relative end date of + 13 days.

How to create those two scenarios using rules? I am trying to understand rules scheduler. I think it can solve both scenarios.

Create a new node of a certain content type using rules

Use rules action "Create entity" to create a node, whereas "node" is a type of entity.

For the fields that you want to provide some value for (as part of your rules action), make sure to add a Rules conditions - "Entity has field" (with the field corresponding to each such field). Doing so will ensure they are available in the Rules action (to set a value for it).

Repeat the creation of such new node

Use the rules scheduler as explained in the video about "Repeating scheduled events". The "clue" here is:

as the last action of your rule, you reschedule the same rule to be executed again after +13 days from today on. Or maybe execute the rule again "weekly" (as per your details in "2.").
the very first time (today + 13 days) you need to trigger the execution of this rule manually (from the rules UI). Since there doesn't seem to be any event in your question that you can use to trigger this rule.

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

PS: Your question seems to contain 2 questions, of which "1." is not clear to me (something about creating a view?). After you enhance your question (as suggested by Shawn also), I might enhance my answer also.


Are node title & body instances update-able through the field API? I'm guessing it's not possible, since what works on other instances won't for the title & body. (Trying to adjust widget weight.)

  $core_instances = array(
    // array(
    //   'field_name' => 'title',
    //   'entity_type' => 'node',
    //   'bundle' => 'article',
    //   'weight' => 1,
    // ),
    // array(
    //   'field_name' => 'body',
    //   'entity_type' => 'node',
    //   'bundle' => 'article',
    //   'weight' => 4,
    // ),
    array(
      'field_name' => 'field_tags',
      'entity_type' => 'node',
      'bundle' => 'article',
      'weight' => 7,
    ),
    array(
      'field_name' => 'field_image',
      'entity_type' => 'node',
      'bundle' => 'article',
      'weight' => 6,
    ),
  );

  foreach ($core_instances as $instance) {
  $instance_info = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
  $instance_info['widget']['weight'] = $instance['weight'];
  field_update_instance($instance_info);
  }

If I uncomment the title & body instances, I get the following error:

  FieldException: Attempt to update an instance of a nonexistent field . in         [error]
  field_update_instance()

The Title is not a field unless you're using the Title module.
That's why your first call doesn't work.

Body should work, unless you've deleted the field (can you see it on admin/structure/types/manage/article/fields?)


Remove node_view rendered node's title link I am using the code below to add a form to my node. This renders a page with the node and form on it. Apparently, the node is rendered with its title as a link. I would like to have the node's title without a link. So I tried to change $node->content, but there seems to be no value that determines that the node title is a link. how do I change this with code?

$form = array();
$node = node_load(24)
$form['offer_form'] = array(
  '#value' => drupal_get_form('dt_offer_entry_form', $node),
  '#weight' => 10
);
$node->content = $form;
return node_view($node);

Quoting from this comment, this code worked for the OP.

$node_view = node_view($node, FALSE, TRUE);
return '
Voorstel indienen
' . $node_view;


How can we override view field template in drupal 8 How can we override single field from Views template files 'views-view-field.html.twig' from location themes/theme-name/templates/views/views-view-field.html.twig.

There is a detailed answer in this Q: Overriding views-view-field.html.twig for specific fields.

You can simply use views-view-field--fieldname.html.twig. Of course, don't forget to clear your cache after creating the new template.


Does the tmp directory have to be shared between servers? I am having a problem with multi file uploads and I suspect the issue lies in the fact the tmp directory is not not shared between servers.

Does it have to be shared between servers? I have 2 webheads (server boxes) and both have a local tmp directory (not shared between them).

Yes, if you have multiple servers serving the same domain, then you need to ensure that the two Drupal server instances share the same filesystem. Best is to use NFS mount, so it is physically only one folder. You may get by with rsync in a cron depending on how the filesystem is used in your application.


How do I add an additional submit handler in commerce checkout form? How do I add an additional submit handler? I have tried this but it did not work.

function c_coupon_form_alter(&$form, $form_state, $form_id) {
  drupal_set_message($form_id);
  switch($form_id) {
     case 'commerce_checkout_form_review':
      drupal_set_message($form_id . '_form submit');
      $form['#submit'][] = 'c_coupon_review_submit';
  }
}

function c_coupon_review_submit($form, &$form_state) {
  drupal_set_message('submitted');
}

What you are doing is correct.

The problem is that Drupal Commerce has defined the submit action on the buttons that is clicked, which will be used instead of the submit handlers defined on the form itself. So you need to add your submit handlers to the buttons (Cancel, Continue) that you want to use your submit function.

$form['buttons']['continue']['#submit'][]='c_coupon_review_submit';


how to use user profile field information as biodata list I have created a website where users can create their own account expanded by the profile2 module. By using it, users can enter all their information in created fields field like:

name
father's name
mother's name
education information
etc

I want to display this information publically in table view where it's possible to search, sort and filter. How would it be possible to create something like that?

I know about content types and use content type in Views module.

While creating the View,

  create View (Show:User)
  add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type', in my
  case 'Main profile';
  add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for
  'Profile type', in my case 'Education profile';
  add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct relationship;


Making title unique using hook_entity_bundle_field_info_alter() hook_node_validate() is replaced by hook_entity_bundle_field_info_alter() in Drupal 8.

I need to validate the node title whether the same title is used in any other node. Title field should be unique for me.

How can I define that in hook_entity_bundle_field_info_alter()? When I print something in this hook. It didn't called when I save the node.

function my_module_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node') {
    dpm($entity_type);
  }
}

What am I doing wrong?

This hook only runs with a cold cache.
In Drupal 8 validation is done with plugins.

When this hook runs for the node entity type, you will have an array of fields, one of which is title. You need to define a new validation constraint plugin. Model it on the unique feed title or unique username one and that way you'll only have to write one method and a property or two.
Take note of your plugin's ID. When you're in that hook, call addConstraint on the title field, passing your plugin ID.

I have a feeling there's another hook too, maybe hook_entity_base_field_info_alter, but I could be wrong there. If you don't see title in the field list, check the api docs for a hook with base field in the name


Factors regarding menu visibility (menu is missing on access denied) I've built a theme based on Zen starterkit, and recently noticed that my main menu is not rendering on any access denied pages (non-admin role obviously), however, the remaining content is rendered as expected. What are the likely causes & recommended solutions? Is this a Zen thing?

So if you're ever missing something in your site, consider these factors when diagnosing:

check the raw markup itself (HTML) ensure it's not a CSS issue.
a permissions problem, does the role have access?
can you narrow the problem to the theme... this will determine further courses of action


Overriding Class Div Form-API Objective:
To override the default classes and divs that are spit out from the Form-API from my custom addressfield implementation in a Drupal Commerce checkout pane. I need to make the classes/divs predictable based on the number of seperate address forms their are. I dynamically create (x) addressfields based on the number of gift subscriptions (x) so that I can combine address information for subscriptions.

Note:
The addressfield form is a patch from the addressfield module which creates a form element type. This looks like this:

          $form['address'] = array(
          '#type' => 'addressfield',
          '#required' => TRUE,
          '#title' => t('Recipient\'s Address'),
          '#context' => array('countries' => array('AT', 'AS', 'BE', 'BG', 'CA', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'GU', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PR', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'GB', 'UM', 'US', 'VI'), ''),
          '#default_value' => array('country' => 'US'),
          '#description' => "Please enter the address you want to mail this gift to.",
          '#maxlength' => 60,
          );

However the problem arises when you load the page with the form. Drupal is dynamically creating numbers in the classes/divs that appears to be random. I would like to specify that number so that it conincedes with the number of subscriptions. So when i test i select (2) gift subscriptions and get  and .

As opposed to the current way it does things (screenshot)

See line 398 of plugins/address.inc ? $format['#wrapper_id'] = drupal_html_id('addressfield-wrapper'); That's the root of the seemingly arbitrary field identifier stuff. The code gets there from line 460 of addressfield.module $element += addressfield_generate($address, $settings['format_handlers'], $context);

Make a custom module, set the weight higher than that of addressfield so it runs after the addressfield module's hooks, and alter the form. There aren't hooks inviting you to alter those IDs unique to addressfield, and altering them in this case is no different than any other, so long as the module weight is adjusted.


How to use Views Excel Export or Views data export to export a filtered table? A while back I asked a question about how to pass a list of columns to display in a views table and a solution closest to what I wanted to do was a module:

Views Dynamic Fields

I was positively shocked that the description of the project mentioned the second part of what I need to do here. Export that view to an Excel spreadsheet.

  This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.

I need to let the user choose the columns, then render the view with those columns and expose filters for all chosen columns, apply them, then download the result in an excel file. Unfortunately I was not able to find  a description how do I actually do that. Using the xls feed option I don't get any fields from the view itself (seems like I need to add the fields manually again) which I can't imagine works with the filters from the view itself. Exporting the file works, but it only shows the default "Title" field (without adding fields to the feed manually).

I had the same problems with Views data export, creating a new data export started with a default "Title" field and I don't think you're supposed to add the same filters again.

Let me know if you have any experience with those modules or ever had to export a view to a spreadsheet.

I just used Views Data Export module for a Drupal 7 project.

Create a view with the configuration you require (exposed filters, etc.).
Add a new display to your view of the type "data export". (As you duplicate your display the filters should inherit, but otherwise, you just want the "main" view and the "data export" view configured the same.)
In the "Page Settings" of the "data export" view display, give it a unique path (This is true even for tabbed items like admin views linked in admin menus).
In the "Page Settings" of the "main" view display, attach the "data export" display (This will provide a little CSV link at the bottom of your view).
Under the "Format" settings for your view, make sure you select CSV. Then edit settings and check the box for "download as file" or whatever it is.

Now, clicking on that CSV icon that appears at the bottom of your view page/block will export a CSV file that will inherit the filtered table. Just ensure the exposed filters match in each display.


EntityFieldQuery: Load all revisions I have a self-defined entity with revisions called command. The instance with id=1 has 3 revisions. Now I want to load all these revisions. Tried this:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'command')
  ->propertyCondition('id', 1)
  ->age(FIELD_LOAD_REVISION)
  ;
$result = $query->execute();

but it gives me still only one revision, the current one. There's no difference to calling it without ->age(FIELD_LOAD_REVISION).

What am I doing wrong?

Solution: Use a regular query instead of a EntityFieldQuery to load all entity revisions.

Explanation:

In the age function on entity.inc there's this comment:

  Blockquote
     * Note that this only affects field conditions. Property conditions always
     * apply to the current revision.

So as long as you provide a property condition, you will get only the last revision id. If you query with fieldCondition, you will get the revisions, as the age method is actually querying the field revision table and not the node revision one (field_sql_storage.module):

  else {
    $tablename_function = '_field_sql_storage_revision_tablename';
    $id_key = 'revision_id';
  }

Otherwise, the entity table is queried so it will always return the entities and not the revisions.

You could do a addTag and modify the query object there but at this point the modifications will be so big that it's actually better to do a regular query instead.

Example using generic info for the entity and entity api entity_revision_load.

  $entity_type = 'command';
  $value = 1;
  $entity_info = entity_get_info($entity_type);

  $query = db_select($entity_info['revision table'], 'revision');
  $query->fields('revision', array($entity_info['entity keys']['id'], $entity_info['entity keys']['revision']))
    ->condition('revision.' . $entity_info['entity keys']['id'], $value);
  $revisions = $query
    ->execute()
    ->fetchAllAssoc($entity_info['entity keys']['revision']);

  $entities = array();
  foreach ($revisions as $key => $revision) {
    $entities[] = entity_revision_load($entity_type, $key);
  }


Displaying grouped view of node comments in a view listing nodes I've created a view that lists a number of nodes.  I've added the relationship of "comments on node" and then added the comments as a field in the view. The problem I'm having is that if there are multiple comments on the node, the view lists the node multiple times. For instance currently the view displays likes this

Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 1

Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 2

I would like it to be displayed like this;

Node Title: Title 1
Nid: 1
Node Image: Image
Comment: Comment 1
Comment: Comment 2

I know it has something to do with grouping, and that other similar posts have simply recommended grouping by the title field, but this does not achieve the desired results. Am I missing something?

So far I've only found a couple way of doing this, non of them seem very elegant.
If you choose the group by option, it does indeed duplicate all of the fields with the exception of the one you are grouping by. If you omit all the fields form the display, then click on the the grouped field and "rewrite the output" you can use tokens to output all of the fields, and they only display once. Unfortunately, this  kinds defeats the purpose of using fields in the first place. The other option is to use the node or teaser view, and make alterations to node.tpl.php and comment.tpl.php as needed ....


How do you make a Image View of a specific page? I have a problem.
The thing is that I know that you can have a [Content Type] with an image [Field], and then you can create a [View] to display the image [Field] in each of the pages that are of the selected [Content Type].
However, (if I have a [Content Type] that is an image gallery), how can I create a view that only displays the gallery of one specific page? I mean, just one entry of a [Content Type].
For example, a services_list page of basic_page [Content Type].
The end goal I want to reach is a Slideshow of a gallery, and clicking that slideshow must send me to a specific page.
So if it was possible to assign a specific link to a slideshow, instead of using the option [Link to: Content] that would work too.

In the block's options there's a paginator setion that lets you include a "more" link, so it isn't exactly what I wanted, but I just put the page's link there, and it does work so I think I'll just leave it there.


Jquery.on method returns undefined is not a function My goal was to create a simple button which once clicked would hide/show a navigational menu, and change the footer's padding alternatively, I'd have used toggle if not for the latter condition. Before I inserted .on() I just had the .click() method with a if/else, which only worked for the first click, so I added .on to solve the problem. Unfortunately it doesn't work, each time the console prints 'Uncaught TypeError: undefined is not a function'. Any help, suggestions, or alternatives, will be much appreciated.

(function ($, Drupal){
Drupal.behaviors.footerCollapse = {
    attach : function() {
        function collapseOrCondense(event){
            if($('#block-panels-mini-footer-nice-menu:visible')){
            $('#footer').css({'padding-bottom':'2.5%'});
            $('#block-panels-mini-footer-nice-menu').hide();
         }
          else{
            $('#footer').css({'padding-bottom':'5.5%'});
            $('#block-panels-mini-footer-nice-menu').show();
          }
        };
        $('#footer').append('<button type=button class=cbutton>*</button>');
        $('#footer .cbutton').css({'position':'absolute', 'left':'1%', 'top':'1%', 'width':'2%','height':'1.5%'});
PROBLEM: $('#footer .cbutton').on('click',collapseOrCondense);
  }
 }
})(jQuery, Drupal);

depending on the version of Drupal you are running, it is likely a jquery version issue. Drupal 7 for example defaults with jQuery 1.4 if memory serves, and .on() was added to jQuery in version 1.7.

You could try jQuery Update module:

Upgrades the version of jQuery in Drupal core to a newer version of jQuery.

Drupal 5 to jQuery 1.2.6

Drupal 6 to jQuery 1.3.2

Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2

Drupal 8: TBD


Output the term title on page--custom.html.twig I'm pulling my hair out trying to create a custom page--custom.html.twig for a content type and getting taxonomy terms to display.

I'm currently using the following piece of code:

{% if node.field_work__services.0 %}

      {% for key, item in node.field_work__services %}

{{ item.title }}

      {% endfor %}

{% endif %}

The if statement resolves, so I get a UL with an equivalent number of LIs to the number of taxonomy terms for that node... however, I can't get it to output the actual taxonomy term.

Anyone have any idea how to do this?

Try with:

{% if node.field_work__services|length %}

        {% for item in node.field_work__services %}

{{ item.entity.label }}

        {% endfor %}

{% endif %}


Programmatically change view path without views_alter I have a PHP script in which I want to set the path to a view.
For example on site1 I want the news to be at /news/index.html and on site2 I want the news to be at /blog/news/page/1.
The sites are sharing the modules folder so I cannot do this from the modules files. So I have a script in which I'm doing my initial setup for each website. Everything works perfect but the view path is not saved.

1. $view = views_get_view('news');
2. $view->display['page']->handler->options['options']['path'] = $my_path;
3. $view->save();

I also tried to use $view->override_path instead of line 2 but it's still not working.

I managed to find the right way. The following code works great for me.

$view = views_get_view($view_name, TRUE);
$view->display['page']->display_options['path'] = $new_path;
views_save_view($view);


how to return a db_query as an option list and display it <?php

/**
 * Define callbacks that can be used as custom select list options.
 */
function webform_contacts_webform_select_options_info() {
  $items = array();

  if (function_exists('webform_options_contacts')) {
    $items['contacts'] = array(
      'title' => t('Contact List'),
      'options callback' => 'webform_options_contacts',
    );
  }

  return $items;
}

/**
 * Option list containing Contacts.
 * Pull a list of users where status=active and rid=5 from database.
 */
function webform_options_contacts() {
  $items = array();

  $query = db_query("SELECT realname.realname AS realname_realname, realname.uid AS realname_uid, users.uid AS uid, 'user' AS field_data_field_gal_phone_user_entity_type FROM {users} users INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid LEFT JOIN {realname} realname ON users.uid = realname.uid WHERE (( (users.status <> '0') AND (users_roles.rid = '5') )) ORDER BY realname_realname ASC");

  $results = $query->execute();
}

I created a custom module for displaying an extra option list. The example provided by Drupal 7 Webform Cookbook I used worked; using a hard coded list and it displays fine.

I want to use a db_query to populate the list. I have this code (shown above) but am unable to see anything displayed. Help! I am sure I am missing the command to properly get this to display as a list.

You can make use of DatabaseStatementInterface::fetchAllKeyed(), but as you only need 2 columns it would be wise to change your query slightly. Essentially you want to select just one for the identifier, and one for the label. Something like this:

$sql = '
    SELECT realname.uid, realname.realname
    FROM {users} users
    INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid
    LEFT JOIN {realname} realname ON users.uid = realname.uid
    WHERE users.status <> :status AND users_roles.rid = :rid
    ORDER BY realname.realname';

$args = array(':status' => 0, ':rid' => 5);

return db_query($sql, $args)->fetchAllKeyed();

That will return an array with the 1st column (uid) as keys and the 2nd column (realname) as values, which you can use verbatim as options for a form element.

You don't have to return just 2 columns from the query, as fetchAllKeyed() allows you to specify the index for both key and value; but as you're not using the data for anything else, it makes sense to avoid the overhead of the extra columns.

Slightly unrelated: you shouldn't call exceute() on the return from db_query(), as the query has already been executed by that point. You can either use one of the helper methods like fetchAllKeyed(), or iterate directly over the values, e.g.

foreach (db_query($sql) as $row) {
  // ...


referenced entity not showing up in the node view page or in any view I create I have a custom module which defines a custom entity. On a content type, I have an 'Entity reference' field that let's me select a custom entity. The value is saved in the database (I looked directly to the database) but is missing when the node is viewed.

if I dump the $node in hook_node_update($node) I can see the referenced value is there. But on hook_node_view($nodes, $types) the value is gone.

The funny part is that in a view, if I create a relation based on this field, I can see the entity's fields, but not the entity reference field value :))

Other types of entities are displayed correctly though, the problem is only with my custom entity

Any help would be very appreciated :)
Thanks

I just Googled the same issue and was led to this page.

You need to implement an access callback in hook_entity_info(), else the entity reference field won't load the entity.


breadcrumb not working with taxonomy Im using the zen theme to create a subtheme. I cannot display the breadcrumb properly. My url is using taxonomy as its parents so something along the lines of http://example.com/link1/title-article. I want the breadcrumb to be "Home > Link1 > title article.

Unfortunately I only have Home / title-article as the breadcrumb.
How can I resolve this? I havent changed the zen_breadcrumb function in the zen template..

The Crumbs module will do what you are looking for. It allows you to set the pattern for crumb generation. In your case the pattern for an article would be something along the lines of

[node:field_tags]

Home is automatically generated so this will give you a crumb path of: Home >> Taxonomy Term

If you want to include the article title, then you would just add [node:title] to the crumb pattern.

[node:field_tags]/[node:title]

Which would produce: Home >> Taxonomy Term >> Title


Tooltip issue with tipsy and views tooltips I have a table of images, which link to their content, and because some of the content titles vary in length, it's difficult to align each image neatly if the titles are displayed above them, as long titles push their image to the side.
So rather than restrict title length, I'd like to remove the titles, and have them display inside a tooltip when hovering over each image in the table/gallery. Similar to imgur.com, which even shows the number of views for each node. I wouldn't mind showing creation dates too, if possible. But I'll be happy if I can just get the titles to show.

I've installed Tipsy and Views Tooltips, which for the most part seem great, but they aren't quite behaving as I'd like.

Views Tooltip provides the correct content title in the html, but it's div is outside of the Selector used to trigger Tipsy, so Tipsy isn't picking up the correct tip content. It just shows, 'null'.

The html looks something like(inspecting in chrome):

and the list goes on..

So if I set the Tipsy selector to, '.field-content a', it triggers on hover over the images, but doesn't have anything to return. And if I set it to, '.views-tooltip' and 'tooltip content', the tooltip won't trigger when hovering over the images.

So the way I see it, is that I need to somehow set the 'a' selector's original-title to the same as tooltip-content. Does anyone know how I might go about doing that, or perhaps have another solution?
Any help would be appreciated, as I've been stuck on this for almost 3 days now.

Cheers,

Matt

I got around this with some CSS and custom field HTML for the title and other info that I wanted to display in the tooltip, so there's no need for tipsy anymore


How to consume RESTful web services in a custom module? I have an API which I would like to consume to do specific actions on my Drupal 7 website after getting data from the user via a webform form. I plan to write my own custom module to do that but don't know how where I should start from.

Is there any hook that could help me add supplementary action after getting data from my webform ? How am I supposed to proceed to consume my web services ? Any code snippet, advice, will be appreciated.

Module RESTClient is for this purpose.

It provides 4 APIs:

restclient_get()
restclient_post()
restclient_put()
restclient_delete()