File Upload form issue I have been working on this code and I am having some errors, and I was wondering if anybody can find errors in this code...  I have posted my error below it...

function background_audio_form($form, &$form_state) {

$form['background_audio_file']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('File'),
  '#description' => t('Allowed extensions: mp3'),
  '#upload_location' => 'public://MP3/',
  '#default_value' => variable_get('background_audio_file'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg mp3'),
  ),
);

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

  return $form;
}

function background_audio_form_submit($form, $form_state) {

 // The file is automatically uploaded and saved in the default
 // validation process so you just need to load the file object at this point,
 // mark that you want to keep it, and save it again.
 // The file ID is contained in the $form_state['values'] array
 $file = file_load($form_state['values']['background_audio_file']);
 $file->status = FILE_STATUS_PERMANENT;
 file_save($file);

 $fid = $form_state['values']['background_audio_file'];

 $fileid = file_load($fid);

 variable_set('background_audio_upload_path', $fileid->uri);

}

Notice: Undefined index: background_audio_file in background_audio_form_submit() (line 107 of /Users/jtharpe/Overflow_Dev/sites/all/modules/background_audio/background_audio.module).
Warning: array_flip() [function.array-flip]: Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 178 of /Users/jtharpe/Overflow_Dev/includes/entity.inc).
Notice: Undefined property: stdClass::$uri in file_save() (line 573 of /Users/jtharpe/Overflow_Dev/includes/file.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => 1329961119 ) in drupal_write_record() (line 6975 of /Users/jtharpe/Overflow_Dev/includes/common.inc).

In your $form FAPI usage you called the file key file, a child element of the parent container background_audio_file. In your _submit() function you are not looking for file.

Do a Devel dpm($form_state['values']) or a print_r($form_state['values']) and you will see the key file with your content. Besides that your code looks ok.


Commerce - Views - Taxonomy - Add to cart issue I am constructing an e-shop using Drupal Commerce. I've arranged my products in Categories and Subcategories using taxonomies and taxonomy-menu. All is nice till now. I also created a view, that displays the subcategory's items, with an 'Add to cart' form as a field.

Clicking the 'Add to cart' button does adds the item to the cart.

The cart's block is is configured to link each line item to it's display path.

The issue occurs here: products added from their perspective nodes, are linked correctly (to their perspective display paths) in the cart. Products that were added via the view's 'Add to cart' button, are plain text, and their 'Display Path' field is empty.

I'm puzzled. Any help?

Instead of rendering fields including the 'add to cart' form as a field, try rendering the full node using a particular view mode which includes the 'add to cart' form. See http://drupal.org/node/1399434#comment-5450456


view content by two taxonomy terms from two vocabulary I have a content tagged by two taxonomy vocabulary ( location and category)

How can I let the user select the location then select the category, the view (or panel) will show the contents tagged with both terms

with love

In Views you can do it with Exposed filters.

Just add filtering by your two vocabularies to your view (FILTER CRITERIA) an set each filter "Expose this filter to visitors, to allow them to change it". That will show form to enter taxonomy tags to filter on views page. AND logic "show the contents tagged with both terms" works by default (set each exposed filter to "required" if you dont want to allow "all", that way user must select something).


How to display a view without using a page template - drupal 7 So on a drupal site I am working on the client has a page where they have a view without a page template applied to it, and now the client wants to change the url of that page. As soon as I change the url of the view it applies the page template to the view. Obviously this was hard-coded in by url by the person who originally built the site, however, I have no idea how they did it. So i'm hoping someone on here has had a similar experience or knows how to make a view without a page template being applied to it.

You can create a block view and display it anywhere in the code.

If your text format allow you to use PHP code you can insert a views anywhere in your website by adding something like this.

  <?php
    $block1 = "Name_Of_The_View";
    print views_embed_view($block1);
  ?>

And this will print a view inside of a node without using a page template. The beauty about this is that you can add HTML around this without using the block module.

For more information I will recommend you to read this documentation page Placing the contents of a block in any location


How do I alter the options in the add menu link checkbox in the node edit form? I am hooking the node edit form with hook_form_node_page_edit_form_alter(). How can I alter the available options when adding a menu item for that node?

I need to only show menu items of given node ids:

if (isset($form['menu'])) {
  $node_ids = array(1,2,3);
  // only show those node's menu links in the options
}

$form['menu']['link']['menu_parent'] is the form array select box for the menu selector widget. $form['menu']['link']['menu_parent']['#options'] contains the key/value pairs for the menu select box.

In your given example, you can use unset($form['menu']['link']['menu_parent']['#options']['my_uneeded_menu_id_option']); to remove your  unneeded menu items.


Implementing a callback after user registration I want to run a database query in another CRM database after a user has registered. I have the following function in my sugar_crm module eg:

function sugar_crm_user_register_submit($form, &$form_state)
{
    // some code to run a database query in SugarCRM
    ddl("User registration form submitted to CRM");

}

However, the function doesn't appear ever to be called. What am I doing wrong here?

A way is add a submit function to user_register_form submits in form alter.

yourmodule_form_alter(&$from,$form_state,$form_id) {
  if ($form_id == 'user_register_form ) {
       $form['#submit'][] = 'sugar_crm_user_register_submit';
       }
 }

but I think the better way is setup your custom function in hook_user_insert.this hook triggered when a user registered . you can implement it in your custom module.

  function yourmodule_user_insert(&$edit, $account, $category) {
   // some code to run a database query in SugarCRM
  ddl("User registration form submitted to CRM");
  }


Node preview in a POPUP I Want to open node preview in popup,

Is it possible to display Node Preview in a pop up like colourbox or light box?

If anyone has solution Please let me know

Thanks..!!

Take a look at the Colorbox node module. you could show any node or view in a colorbox.


How to safely delete relation entity endpoint revisions (field_revision_endpoints) I would like to safely clean duplicate field revision data. This field_revision_(field_name) data not associated with nodes, but the relation entities.

I'm using the relation module. I'm bumping up against the problem outlined here: https://www.drupal.org/node/1530164

I have a lot of relations on my site linking different entities. My field_revision_endpoints table is growing quite large. The issue mentions as a work around, he uses a sql script to clear out the old revisions. I did some googling on info for deleting revisions, but I'll I have come up with is results relating to deleting node revisions.

Is it safe to simply delete rows out of field_revision_endpoints?

The answer is no. I eventually had to circle back to this question and come up with a solution myself. The relation_revision table contains the relation + revision ids that match up to the field_revision_endpoints rows. Simply deleting rows from relation_revision would orphan the revision field data in field_revision_endpoint.

After poking around the relations issue queue, I found this patch which adds support for the Entity API's revision deletion mechanism.

Instead of patching the relations module, I used hook_entity_info_alter to register my own 'revision deletion callback' on the relation entity, which I based on the above patch and node_revision_delete(). I can now use the Entity API's entity_revision_delete() to cleanly remove the excess revisions in batches.


Date problem after restore I had to restore a drupal 7 site from scheduled backup using backup & migrate. Since then I seem to have problem with date/timestamp.
I have a view (3.6) filtering on node created date with options between "today" and "tomorrow".
All users are in GMT+7 timezone.
It is now 18:01pm here and the sql query generated has:
node.created BETWEEN 1375959700-25200 AND 1375959700+61200

So "today" is current time instead of today at 00:00:00

Any suggestion ?

In Drupal 7 They are not using the datetime field. instead of that you can use the int field and add your date in unixtime stamp format.

You can expose the data using hook_views_data hook. Check following URL for more help:

https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7


Disabling Wysyig profile profile for particular content type I am using CKeditor with wysiwyg profile .
I want to disable this Wysyig profile for a particular content type.
cant find a better way.
please help me out with any module if its there or any configuration setting if its possible

I was having a similar issue and did it using Better Formats module.

I created a new Input Format (for example "my input format")
Disabled WYSIWYG in that format
In the Content type settings, under "Input format settings", select that new profile as default


Twig_Sandbox_SecurityError: Calling "setOption" method on RC4 I'm porting light_skeleton to Drupal 8, and it was working fine on RC2 but I ran into this issue after updating to Drupal 8 RC4.

Twig_Sandbox_SecurityError: Calling "setOption" method on a "Drupal\Core\Url" object is not allowed in "themes/light_skeleton/template/html.html.twig" at line 55. in Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 101 of core/lib/Drupal/Core/Template/TwigSandboxPolicy.php).

After debugging I find out that it was due to this line:

{{ link(item.title, item.url.setOptions({'set_active_class' : TRUE, 'attributes' : {'class' : 'navbar-link'}})) }}

Which I stole from - Custom classes for menu links  and it was working until RC4.

My question is what I'm doing wrong in here ? All I'm doing in there is setting up a variable into the links and in addition setting up the links if the link is active.

There seem to be a similar issue with the bear skin theme. You can look at this issue Twig_Sandbox_SecurityError

Update

Here is the results after debuggin on item.url {{ kint(item.url) }}
RC4 (this is the one that does not work)

RC2 - this how it use to be and it was working.

Core recently added a default sandbox so that it's not possible to e.g. call the delete method on node objects.

See https://www.drupal.org/node/2513266, you can bring it up there and try to allow it, try to extend it yourself or call that option in preprocess. Not sure what the best option is.


Remove module dependency in multi-site D7 setup? In sites/all/modules, I have video module 7.x-2.2 installed. Within my sub-site in a single-core, multi-site setup, I have video module 7.x-2.7 installed. When I try to disable and remove the local video module (7.x-2.7) - for a lack of words, it wont' let me, nor default back to the sites/all/modules/video module. I get wsod, database errors, and funky behavior. How would I remove my subsites manual dependency on its local module? Is my last resort to go into the database? Thanks,

Try this.  Without disabling the module, remove the code for your local video module, leaving the code you want in sites/all/modules. Next, run drush registry-rebuild followed by drush updatedb.  See: http://drupal.org/project/registry_rebuild

IMPORTANT NOTE: Your globally installed video module is 7.x-2.2, but your local module is 7.x-2.7.  You can't go backwards in version numbers in Drupal, so you'll have to upgrade your global video module to 7.x-2.7 and run updatedb on all other sites that use it before following the instructions above. If you can't upgrade the global module, you'll have to keep them separate until you can.


hook function not deleting nodes when calling node_delete I have a cron job where I need to do a node_delete().

From what I can tell the delete occurs okay if I run the cron job manually from the status report page, but if I try to run the cron from inside a call to a module_cron function it looks like the delete fails.

Is there some way to give the cron the access to delete nodes with node_delete?

A scheduled cron runs as uid 0, the anonymous user, and therefore probably can't delete anything.  When you run cron from the admin menu, it uses your current session, so you can delete things.

If you google for "drupal run cron as uid 1" you will see some workarounds.  Most involve switching users inside your hook_cron and then restoring the session when you are done.

What should be possible is to invoke drush -u XXX cron from your crontab instead of the the typical wget method.  Some searching will dig up the proper way to call it (you need to get the environment and Drupal basedir set right).  I would not run as uid 1, though.  Pick (or create) a user with sufficient permissions to do what you need.

What would also be possible is to create a script that bootstraps, loads the proper user, and then does your task.  Lock this down in your .htaccess and call it from your crontab.


Ubercart need to pay depends on user role I am using drupal 6.20 and Ubercart 2.0
Like what I asked in the subject.
Is there any chance that I can customize a ordering process with or without payment?

For example:
There are 2 roles of users ( Role A and Role B)
Users of Role A need to pay all my products to complete the transaction.
Users of Role B don't need to pay any of my products to complete the transaction.

Actually I want my website to be suitable for 2 kinks of clients:
1. wholesalers (Role A) --- order online but pay through company invoicing system
2. retailers (Role B) --- order online and pay instantly

Appreciate any thoughts and helps on this!

This question has been solved and just want to put the solution here to help someone has the same interests!

Download the uc_purchase_order module, http://drupal.org/project/uc_po

And give the permission to the user role you want them to purchase through purchase order.


Drupal 8: make Taxonomy terms translatable How to translate Taxonomy terms?
I have 2 languages in my site added here: /admin/config/regional/language
I have turned the Types here /admin/structure/types marked "Show language selector on create and edit pages" in "Language settings" of each type.
But I cannot really understand what to do in Vocabulary settings?
I have terms but I cannot see button "Translate" that it was in Drupal 7.
Should I create 2 languages terms separately one from another?
Please give me manual.

To translate terms of taxonomies, you need to activate the Content Translation module.


How to assign default values for an edit form? In my form I create a field of type list (with the widget box is checked). By default, this field has no value.

In my hook_form_alter () method, I add options (via PHP) has this field.

$form['field_genric_domains']['und']['#options']= _get_domaine_options();

if($form['field_genric_domains']['und']['#default_value'] == NULL){
    $form['field_genric_domains']['und']['#default_value']  = array(_get_this_domain_id());
}

Then I set a default value. I set up a test that shows whether we are editing or creating.

When creating, it works perfectly, but when editing the table (# default_value) is empty. Normally it should contain the values previously inquire.

Why? Thank you for your help

You need to check that value returned by _get_this_domain_id() function is in the array key used to create #options for form element ['field_genric_domains'] .

Example :

If _get_domaine_options() function returns array as :

array(1=>'India',2=>'USA');

Then _get_this_domain_id() should return key either 1 or 2 .That will set the default value depending on the array key .


How to define text css style in my themes folder to work with wysiwyg editor? Bold text and Italic text are not working in ckeditor and I think it is because I have sites/all/themes/mytheme/styles/mytheme.css somehow not communicating with it.

Other text formats like strikethrough and underline are working fine for ckeditor.

So do I need to declare a property in mytheme.css to allow the editor to work?

I don't have the eric meyer reset file included or anything , just the add on css changes I made to my theme but don't see how that is stopping the strong and italic tags from not working because my changes were made for specific div ids.

i usually add a separate .css file for the editors, this is only possible via the WYSIWYG module, in the settings of that text-format.
you can even add special classes and block-formats the user can choose then.

to see what's happening, you can inspect the editor normally in your browser, and should see the problem.


Create service with argument I have class like this:

<?php

namespace Drupal\mymodule;

use Drupal\comment\CommentInterface;
use Drupal\comment\CommentManagerInterface;
use Drupal\comment\CommentStorage;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Session\AccountInterface;

class MyCommentStorage extends CommentStorage {

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $current_user, $cache, $language_manager);
  }

}

and my file service:

services:
  comment.storage:
    class: Drupal\mymodule\MyCommentStorage
    arguments: ['@xxx','@database', '@entity.manager', '@current_user', '@cache.entity', '@language_manager']

I don't know add @xxx service to pass first argument in my method construct.I don't find any service implement interface EntityTypeInterface. So what's service I need add to first argument?

An entity handler class is instantiated via EntityHandlerInterface::createInstance static method, which takes the container as the first argument and the EntityTypeInterface as the second argument.

So you would not need the service and have to use the injected container to instantiate your class.

class MyCommentStorage extends CommentStorage implements EntityHandlerInterface {

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $current_user, $cache, $language_manager);
  }

  static public function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('database'),
      // etc...
    );
  }

}


How to show a Drupal Commerce coupon system on the cart page? I am new in Drupal and working over a shopping site using Drupal Commerce. My client's requirement is that to show a coupon field in the cart page through which user can add a coupon code. I have installed the Commerce Coupon module, but did not understand how to show the coupon form on the cart page.

Basic rule of thumb using any module in Drupal is first read Documentation or Readme or Install files inside Drupal module.. That will tell you how the module works... Go through Project page for full details

For fixed amount discount use Commerce coupon fixed amount

For Example - Readme file explains how to create %off coupon

Example - Create a '10% off' coupon

1) Install modules

Install:
   - Commerce Coupon
   - Commerce Coupon UI
   - Commerce coupon percentage

2) Create a 'Percentage coupon' coupon

Go to: Home > Administration > Store > Coupons

Click 'Create Coupon'

Choose 'Create Percentage coupon'
   (if you have no other coupon types clicking 'Create Coupon' will redirect to
    the 'Create Percentage coupon' form)

Create a percentage coupon with the following:

Coupon Code: 10%OFF
Number of Uses: 1 (change as necessary)
Percentage Amount: 10
Active: Yes

Save

3) Enable the 'Coupons' area on one of your Commerce checkout panes

Go to: Home > Administration > Store > Configuration > Checkout settings

Move the 'Coupons' item into one of the checkout panes

Save

4) Test it!

Please do some basic research before posting questions like above .. Otherwise they will be put onhold :-)


How to create fields group as accordions? Hello Drupal community,

I am trying to create a group of fields with an accordion, so that it can be visible/unvisible with a simple clic on the title of the field's group.

Does anyone know how to do it ? Or know a module that does it ?

The Field Group module is great for that usage.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.


LDAP SSO - User not redirecting to user/login/sso to login the visitor I have implemented LDAP - Single Sign On (SSO) on my Drupal project. All the settings (testing, connecting with server) is working perfectly fine.

The problem is that when I visit my site, the site doesn't authenticate the user.

Upon testing every option regressively, I realized that my site is not redirecting to http://www.theurl.com/user/login/sso, which authenticates and sign in the visitor.

When I manually went to http://www.theurl.com/user/login/sso, the site authenticated and logged in the user perfectly.

Is there anything I can do to mitigate it?

Thanks a lot

You can use a rule to redirect them to the /user/login/sso. You can make a rule, if user has not logged in auto send them to /user/login/sso. If the user is already logged in send them to the home page.


How to pass dynamic file location in Form API? my requirement is to upload files to specific folders. How can I achieve this by using form api. How can I modify below code such that upload_location should be dynamic. Uploaded file should save into the Folder name provided by the user. I tried below code but not worked.

#submit element is not calling custom_document_submit function.

 $form['folder_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Folder Name'),
  );
  $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );
function custom_document_submit($form, &$form_state){
  $destination = $form_state['values']['folder_name'];
  $validators = array();
  $file = file_save_upload('document', $validators, 'public://'.$destination);
}

I would suggest using ajax to update the #upload_location on demand.

However, ajax on managed_file element is quite tricky. Because managed_file has its own ajax handling for uploading file. It only rebuilds the file element itself and returns lack of data from other fields during during file upload ajax. So it need to be fixed in some hacky way

Example code:

function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];
  $values = &$form_state['values'];

  $form['folder_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Folder Name'),
    '#submit' => array('mymodule_custom_form_folder_name_submit'),
    '#ajax' => array(
      'callback' => 'mymodule_custom_form_folder_name_ajax',
      'wrapper' => 'edit-file-ajax-wrapper',
      'event' => 'keyup',
    ),
  );

  // HACK: manually construct the folder_name value.
  // $form_state['values'] is empty for other field in file upload ajax
  // because it only rebuild the element rather then the whole form.
  if (!isset($values['folder_name']) && !empty($input['folder_name'])) {
    $values['folder_name'] = form_type_textfield_value($form['folder_name'], $input['folder_name']);
  }

  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#disabled' => empty($values['folder_name']) && empty($input['folder_name']),
    '#upload_validators' => array('file_validate_extensions' => array('jpg')),
    '#upload_location' => !empty($values['folder_name']) ? 'public://' . $values['folder_name'] : 'public://',
  );

function mymodule_custom_form_folder_name_submit(&$form, &$form_state) {
  unset($form['file']['#disabled']);
  $form_state['rebuild'] = TRUE;
}

function mymodule_custom_form_folder_name_ajax(&$form, &$form_state) {
  return $form['file'];
}


Check if user registration field is set to visible or hidden on the registration form In the user registration form, I have set a certain field say surname as hidden i.e. I have unchecked the checkbox saying "Display on user registration form." as shown below:

Now I want to disable the server side validation for this field. When I print the $form array, the surname field is still displayed. However I am not able to find any such value in the $form array which checks if the value is unchecked or not. Is there any way to figure out if the said field is not displayed on the registration form? Hope I am clear enough.

If you look at the code of user_register_form(), you will notice it uses the following code.

  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      $form[$field_name]['#access'] = FALSE;
    }
  }

If you are implementing hook_form_alter() (or other similar hooks), it's quite easier to look at the #access property. If you need that in other functions, you can use code similar to the following one.

  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      // $field_name is not supposed to be added to the account registration form.
    }
  }

Clearly, checking for the #access property in a hook_form_alter() implementation is the safer method, since it consider the field can be made accessible from third-party modules (or third-party modules can hide a field that should be visible).
The other method is more for getting a specific field setting.


Drupal do not publish more current notes to other browsers than admin logs in On my site eso-meetu.de Is a node created on  13 Juli, 2014  Drupal does not publish more current nodes to other browsers than the one i uuse to admister my site.

has someone any idea how to fix this or get closer to the error that populates this issue?

There are no errors in watchdog related to this also the server logs look fine

Even if I turn off memcache ore flush all caches the resul is the same.

I looked at your site and all I see is "File not found.". If posts aren't showing up, check the view that is creating that list of content, it might be limited by a date range.


Drupal Bootstrap THEME_menu_tree on new menu I'm using Drupal 7 and the Bootstrap theme, in template.php I am successfully theming the primary menu (main menu) to enable extra list styles with

function MYTHEME_menu_tree__primary($variables) {
return '
' . $variables['tree'] . '
';
}

I would also like to theme a new menu called "Banner" (menu-banner) but can't access it as expected at

function MYTHEME_menu_tree__menu_banner($variables) {
return '
' . $variables['tree'] . '
';
}

The new menu is successfully defined in MYTHEME_preprocess_page in template.php

$menu = menu_navigation_links('menu-banner');
$vars['banner_nav'] = theme('links__menu_banner', array('links' => $menu));

And I'm able to call it as banner_nav in my page templates.

Is there something I'm missing or is there something specific to Bootstrap that I need to do that's different from the documentation at theme_menu_tree?

This isn't related to Bootstrap. In your preprocessor you're using theme_links, which is unrelated to menus. Your "menu" isn't being output as a menu at all.

If page preprocessing is necessary, you can try:

function THEMENAME_preprocess_page(&$vars) {
  $menu = menu_tree_all_data('menu-banner');
  $vars['banner_nav'] = menu_tree_output($menu);
}

Or you can render the menu block (these are automatically generated if you have the Blocks module enabled):

function THEMENAME_preprocess_page(&$vars) {
  $block = block_load('menu', 'menu-banner');
  $vars['banner_nav'] = _block_get_renderable_array(_block_render_blocks(array($block)));
}

In page.tpl.php:

<?php print render($banner_nav); ?>

Either will work.

If you don't need to preprocess the menu, you can simply position it via the Blocks admin UI.

I hope that helps!


Solr indexing on custom tables We are implementing apache solr search in drupal 7.. after installing the module if you run the index, the apache solr is returning results from the drupal tables (nodes,users,taxonomy,content type).
But we have created custom tables (example: product table) where apache solr is not able to index those table data.. how to make it index the custom created tables

There is a patch available for this. Please refer the below link

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


Access imagefield file object during node create/update I have a content type with an imagefield. I need to get a reference to the file object during node save or update, so I can do something with it.

function foo_node_presave($node){
    if ($node->type ==='foo'){
        $filename = $node->original->field_foo_image['und'][0]['filename'];
    }

In the above code, $filename isn't populated yet when a new node is being created. It does work during a node update if there was already a file in that field.

How can I get a reference to the file object in a filefield/imagefield in a hook during node creation?

Even if the field hasn't been updated yet you should have access to the fid column (the file ID), which you can use in conjunction with the file_load() function to get the filename:

// Load a file object based on the fid column fo the field.
$file = file_load($node->field_foo_image[$node->language][0]['fid'];

// Get the filename.
$filename = $file->filename;


How do I show a basic search block on the front page that integrates with search api? I've been creating my search pages in Search API, but I want to offer a search block on the front page or other pages that can do what the core search block does. Is there a way to either integrate the search block, or a work around to have a search block on the front page while it pulls up search and displays everything on the main search page?

Search API module has the ability to integrate with views module. All you need to do is to install views module and then create Search view,expose search filter and in your views configuration choose Exposed form in block option to yes, now you will the see the search block from your search api and place it on front page, the block will take you automatically to the search page to show the search items.


How to list all fields of a content type with views? I would like to create a product comparison view. Each product has lots of features which all need to appear in the comparison view. Each feature is a separate field in the “product” content type.

Instead of manually adding all fields of the “product” content type to my view, I’d like to have all fields added automatically to the view – for example when adding a new field to the “product” content type. Is this possible?

Bonus question: can I add all fields to the view by default and later exclude only a few of them?

Edit: Further Notes

I’d like to create a comparison table where corresponding features appear in the same row with a single row/column label for the feature. Many features are optional, though. Therefore I need the feature fields of the “product” content type to be available as separate fields in the view – so that I can properly align them in the table.

According to me the best way to configure a view is to use display modes ("Show: content" and select the display mode).
So that when I add a field to a content type I just have to configure the "Manage Display" sections (1 per view mode) of the content type.

Note that sometimes I need extra fields to render, to use as token for other settings (rewrite a field, header/footer text, more link,...) or to make grouping. To achieve this I switch the "Show" option to fields and add a "Content: Rendered Node" field (that comes with Entity API module). Then the "Show complete entity" display option of this field allows you to choose a display mode (Full content, teaser, list item or any other display mode) and render the nodes.


How to add attribute to element in twig before render? I have a template for one of my forms and I want to add css class to the element before I render it but since I am printing the element as a whole I am not sure how to alter the attributes.

I was told on IRC to have a look at the merge method but so far no luck.

{% set submit_attributes = form.submit.attributes %}
{% submit_attributes.addClass('test') %}
{% form.submit.attributes|merge(submit_attributes) %}
{{ form.submit }}

or

{% form.submit.attributes.addClass('test') %}
{{ form.submit }}

Here is my solution for adding a placeholder to a custom text field being used for inputting search terms in a form.  I could not use element.attributes.setAttributes() because in my case the key for attributes is #attributes.

{% set attr = form.search_api_fulltext['#attributes']|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = form.search_api_fulltext|merge({'#attributes': attr}) %}
{{ search }}

Here is the same expanded a little for clarity:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{{ search }}

Or add a third merge and merge the field back into the form.  Then output the form as usual:

{% set search = form.search_api_fulltext %}
{% set attr = form.search_api_fulltext['#attributes'] %}
{% set attr = attr|merge({'placeholder': 'Enter search term'|t}) %}
{% set search = search|merge({'#attributes': attr}) %}

{% set form = form|merge({'search_api_fulltext': search}) %}
{{ form }}


Best way to define entity and additional custom logic (CRUD) in module I want to create a new content type, e.g. company. This company needs an additional field which is a multiple file upload field. When the full node of the content type is displayed, I want to run some code in a controller which reads the uploaded files, executes logic and sends information to the twig template. However I'm unsure how to proceed. As far as I can see there are three options (of which the first isn't really an option):

I can create an entity type through the admin interface, and create a new node.html.twig template file, however this lacks the ability to execute custom PHP logic and send the information to twig, as i only have the twig template.
I can create a content type in a module and define the fields through the admin. If i understand correctly, this can be done through drupal generate:entity:content with the Drupal Console.
I can create a module in which I define the content type, and hard-code all the fields. This is less flexible but maybe a stronger option: if something happens with the database I don't have to recreate the structure.

Both option 2 and option 3 can be viable. I've used Symfony2 before and using that I would take option 3, however it seems this option is over-complex in D8. If I understand correct in D8 fields should be defined through the admin interface. And a custom template can be created in the module eventually.

How should i tackle this issue? Which option is best? What is the best way to create a controller, which is used in displaying an entity/content type which is created via the D8 admin interface?

Given that you want to change the formatting of a file field, then I would create a FieldFormatter plugin, which could probably extend FileFormatterBase (or one of its sub classes). This would allow the formatter to be a configurable option for file fields in the Manage Display interface (or as part of a content type configuration YAML that your module provides).

By implementing FormatterInterface::viewElements, you can add to the render array that is returned.

To summarize:

Create a field formatter plugin for file fields in a custom module: drupal generate:plugin:fieldformatter --field-type=file
Create a content type: drupal generate:entity:bundle --bundle-name=company --bundle-title=Company
Add a multiple-value file field to the content type.
Configure the file field to be displayed with your custom field formatter plugin (in Manage Display).

Edit: Added drupal console commands as far as I know them


Is there any way to add comments to pages which are NOT nodes Im building a module and need to put a comments form on a page which is NOT a node. Is there a way of doing this?

I guess I will need to use:

  drupal_get_form('comment_form',
  array('nid' => $node->nid));

However this seems to have a certain dependency on the nid as it always seems to be attached to a node.

API the module that handle the pages you see at api.drupal.org, has the same problem; the documentation pages you see are not nodes, but the module allows to add comments to them.

The page callback invoked for the documentation pages is api_page_function(), which is associated to the path api/%/%/function/%api_item in its implementation of hook_menu() (see api_menu(), starting at line 125 of the linked file). The page callback uses _api_add_comments(), which contains the following code:

if (module_exists('comment') && user_access('access comments') && variable_get('comment_api', COMMENT_NODE_READ_WRITE) != COMMENT_NODE_DISABLED) {
  $output .= comment_render(node_load($documentation_object->did));
  if (user_access('post comments')) {
    $output .= comment_form_box(array('nid' => $documentation_object->did), t('Post new comment'));
  }
  // ...
}

API creates empty nodes that associate to the documentation pages; the reason of this is that the Comment module still need a node object to return any comment that is associated with that node.


How to get values of delta field from "block" table in drupal 7 from the database for the activated theme in a custom module? Can I get all the values of delta field from "block" table from the database in my custom module

I have tried with this code as clive has explained it here but it shows me an error:

 $query = db_select('module__block', 'b')
  ->condition('theme', $business)
  ->condition('status', 1)
  ->condition('region', -1, '<>');

    $query->addExpression("CONCAT('_', delta)", 'delta');
    $deltas = $query->execute()->fetchCol();
    print_r($deltas);

module__block : Is the name of the block table since I attached a prefix to it.

SELECT delta,
FROM  `module__block`
WHERE theme LIKE  'business'
LIMIT 0 , 30 ;

shows only blocks.

SELECT delta, theme
FROM  module__block
WHERE theme LIKE  'business'
LIMIT 0 , 30;

It will shows both the block names and theme name.


Add a node field to a comments view I'm using Drupal 7, Views 3, and Token.

I created a view of comments.

I would like added to this view a field of the parent node.

I thus added a header, of type "global text area", I tried of added a token corresponding to the desired field, clicked on "Use replacement tokens from the first row ", but it does not work (the token appears but not the field).

Have you a solution?

You need to add a relationship to your view on the nid. Once you do that you will have the fields from the parent node available to be added to your view.


Merging multiple feature modules It looks like I went a bit too overboard with number of features modules on my website (~50), but it really made initial development easy (for multiple people). Now the question is - what would be a safe procedure that would allow to merge them into less number of beefier features?

Is creating those new ones with "Allow conflicts to be added" option, and then disabling and UNINSTALLING the smaller ones safe? Should I firstly enable conflicting new modules? What is the order and procedures?

Sometimes the best way to merge/split features is to edit the module code directly. It's pretty straightforward where everything is laid out in a module created by Features. And it's a great way to start learning module development (if you're new to it). Just start at the *.info file - that's where Features describes all the various things it manages in the module. Then you can pretty easily find those things in the *.module file and other *.inc files. Just clone the whole module, rename it and all the files, search and replace all occurrences of the name in the code, then remove the stuff you don't want in each.


How to escape markup with check_markup in a twig template? I am getting following error in drupal 8 :

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

Twig_Error_Syntax: Unknown "check_markup" function.

Twig template line :

{% set featured_portfolio_text = check_markup(featured_portfolio_array['field_portfolio_link_text']['#items'][0]['value'],'full_html') %}

Is there any alternative to check_markup function for twig?

This seems like something you could do in a preprocess function and create that variable. At that level, you can use check_markup to check it.

Be sure to see the two notes on the docs page:

  Note: Because filters can inject JavaScript or execute PHP code,
  security is vital here. When a user supplies a text format, you should
  validate it using $format->access() before accepting/using it. This is
  normally done in the validation stage of the Form API. You should for
  example never make a preview of content in a disallowed format.

  Note: this function should only be used when filtering text for use
  elsewhere than on a rendered HTML page. If this is part of a HTML
  page, then a renderable array with a #type 'processed_text' element
  should be used instead of this, because that will allow cacheability
  metadata to be set and bubbled up and attachments to be associated
  (assets, placeholders, etc.). In other words: if you are presenting
  the filtered text in a HTML page, the only way this will be presented
  correctly, is by using the 'processed_text' element.

Here is a similar question/answer (albeit from 2014) that may still apply.


Address module PHP error due to missing interface I've installed the Address module and run Composer. I've checked the CommerceGuys/Addressing dependency is present. This was working fine, until a recent update (I'm not sure whether it was Drupal 8.2 or Address beta 4), but now the site is giving the following error.

PHP Fatal error:  Interface 'CommerceGuys\\Addressing\\Model\\AddressFormatInterface' not found in /var/www/drupal/sites8/all/modules/address/src/Entity/AddressFormatInterface.php on line 16, referer: https://www.google.com/

Can anyone halp?

James

The command Bojan offered above did the trick:

composer update drupal/address --with-dependencies

This gave the following message:

Nothing to install or update
Generating autoload files

However, the site now displays correctly and doesn't log the message posted above.

Since it didn't seem to install anything, I presume it was the Autoload files that were the problem.

Thanks!


Add user to a group after the user makes a comment in that group is this possible in Drupal Commons (Drupal 7) using Rules:

If a user makes a comment on a post in a certain group, have a rule which makes the user a member of the group automatically.

Why do I want to do this? Well, the contributors block in Drupal Commons is not showing all those who comment in a group. I found that the reason for this was that the particular user is not yet listed as an active member of the group.

Thank you!

The answer is ... yes, it is possible ... and easy to do ... with Rules.

If anyone coming across this is new to Rules or needs a refresher I highly recommend Johan Falk's free screencast series. It's excellent. http://nodeone.se/en/learn-the-rules-framework

See the screenshot for how I did it, and also the exported Rule below.

{ "rules_lambeth_comment_join_group" : {
"LABEL" : "lambeth comment join group",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "og", "comment" ],
"ON" : [ "comment_insert" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "og_group_ref" } }
],
"DO" : [
  { "og_subcribe_user" : {
      "user" : [ "comment:author" ],
      "group" : [ "comment:node:og-group-ref:0" ]
    }
  }
]
}
}


Is it possible to resize image before saving it with media module? I am building a site using Drupal 7, in which users can upload content in a form, also images. The images will be uploaded and stored with the Media module version 7.x-2.x-dev.

I want to allow users to upload any image up to 10 MB of size.

But, I don't want to have many pictures as big as 10 MB on my server. I prefer to save the image only after it has been resized to 800x600 to have more space on my server.

How can I achieve this with the Media module?

In addition, what is the difference between the field type "file" to "image" when rendering images with the Media module?

There is an option to chose "Field Type: File" and "Widget Type: Media Browser", and then chose rendered file, and then image on the Media settings (here is a great guide to the Media module). Another option is to chose "Field Type: image" and "Widget Type: Media Browser".

First off, image dimensions are not the same as image sizes. Images could have the dimensions of 800x600 but still exceed 10 MB in size.

One possible solution is to create new image styles under /admin/config/media/image-styles/ providing your desired dimensions (e.g. 800x600). See attached image:

Then under the Manager Displays section of the Content Type containing the image field, choose the Image style you just created. See attached image:

Then set the Maximum upload size for your field in the Manage Fields section of the Content Type containing the image field. See attached image:


Location Proximity Search using db_select in Custom Module I want to build a custom block which uses the nid of the node it's visible on to pull in nodes within a radius of 50 miles based on it's geolocation. I am using the location module and gmap where doing this query in views is easy but I have no idea where to even begin in building this query in db_select.

this is what views is outputting for the same query:

SELECT node.title AS node_title, node.nid AS nid, (COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) AS location_distance_sort
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (( (node.nid != '3849' OR node.nid IS NULL) )AND(( (node.status = '1') AND (node.type IN  ('weather_reports')) AND (location.latitude > '51.081897505891' AND location.latitude < '52.530604494109' AND location.longitude > '-5.3366374087818' AND location.longitude < '-2.9936745912182') AND ((COALESCE(ACOS(0.61832265427253*COS(RADIANS(location.latitude))*(0.99735883206175*COS(RADIANS(location.longitude)) + -0.072631674277943*SIN(RADIANS(location.longitude))) + 0.78592435718291*SIN(RADIANS(location.latitude))), 0.00000)*6364902.7458257) < '80467.35') )))
ORDER BY location_distance_sort ASC
LIMIT 1 OFFSET 0

How do i run a db_select query to select the nodes within 50 miles of 51.6599, -3.9215

Thanks to @joemurray for pointing me in the right direction. This is my function to grab the closest nid to my target nodes lat, long.

/**
 *
 * Load the nid we are interested in for this report taken from the page we are on.
 * [http://funkjedi.com/technology/308-search-using-geolocation-data-in-mysql/][1]
 */
function _load_proximity_nids($lat, $lon) {
  $nids = array();

  // in Miles
  $radius = 25;

  // Constants related to the surface of the Earth
  $earths_radius = 3958.9394;
  $surface_distance_coeffient = 69.174;

  // Spherical Law of Cosines
  $distance_formula = "$earths_radius * ACOS( SIN(RADIANS(latitude)) * SIN(RADIANS($lat)) + COS(RADIANS(longitude - $lon)) * COS(RADIANS(latitude)) * COS(RADIANS($lat)) )";

  // Create a bounding box to reduce the scope of our search
  $lng_b1 = $lon - $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lng_b2 = $lon + $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lat_b1 = $lat - $radius / $surface_distance_coeffient;
  $lat_b2 = $lat + $radius / $surface_distance_coeffient;

  // Construct our sql statement
  $results = db_query('SELECT node.title AS node_title, node.nid AS nid, node.status AS status, node.type AS type, (' . $distance_formula . ') AS distance
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (location.latitude BETWEEN ' . $lat_b1 . ' AND ' . $lat_b2 . ') AND (location.longitude BETWEEN ' . $lng_b1 . ' AND ' . $lng_b2 . ') HAVING distance < :radius
AND (node.status = 1)
AND node.type = :type
ORDER BY distance ASC',
  array(
    ':type' => 'weather_reports',
    ':radius' => $radius)
  );

  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  return $nids;
}


Make Admin fieldset open by default when editing comment As supplied by the core comment module when you go to edit a comment as an admin there is an Administration fieldset that lets you change the author and if the comment is published. When you load the page the fieldset is collapse and I'd like it to be open by default.

I found in the comments.module this bit of code:

// Display author information in a fieldset for comment moderators.
if ($is_admin) {
$form['author'] = array(
  '#type' => 'fieldset',
  '#title' => t('Administration'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#weight' => -2,
 );
}

Is there a hook or something I could use to manipulate this?

Use hook_form_alter(). Here's an example:

    function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'comment_node_YOUR_CONTENT_TYPE_form') {
        $form['author']['#collapsed'] = FALSE;
      }
    }

You can place this in a custom module, or in template.php of your your front end theme.


How to set the value of a Fixed amount Commerce Coupon using Rules? It is practically impossible for me to set the fixed amount of a coupon created with rules. The coupon is generated allright with a coupon code but the fixed amount value is always empty, I can only edit the generated coupon and set the fixed amount manually. I am referring to these issues which seemed to have never been resolved:

https://www.drupal.org/node/1785372
create a fixed amount coupon using rules in drupal commerce
http://www.drupalcommerce.org/comment/4433#comment-4433
http://www.drupalcommerce.org/discussions/8436/generate-coupon-using-rules

Edit: I know that Commerce GC exists but it is buggy and not production ready (breaks my site during checkout) and the bug issues havent been resolved.

Here is my exported rule:

{ "rules_send_a_gift_certificate" : {
"LABEL" : "Send A Gift Certificate",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_coupon", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product" : {
      "commerce_order" : [ "commerce_order" ],
      "product_id" : "BGC-1-8",
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : { "type" : "commerce_coupon" },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:commerce-coupon-code" ],
      "value" : "ord[commerce-order:order-id]ers"
    }
  },
  { "data_set" : { "data" : [ "entity-created:type" ], "value" : "commerce_coupon_fixed" } },
  { "data_set" : { "data" : [ "entity-created:is-active" ], "value" : 1 } },
  { "data_set" : {
      "data" : [ "entity-created:commerce-coupon-number-of-uses" ],
      "value" : "1"
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "commerce_coupon_action_create_coupon_line_item" : {
      "USING" : {
        "commerce_coupon" : [ "entity-created" ],
        "commerce_order" : [ "commerce_order" ],
        "amount" : "100.00",
        "component_name" : "commerce_coupon_fixed_ord1ers",
        "currency_code" : "NGN"
      },
      "PROVIDE" : { "commerce_coupon_line_item" : { "commerce_coupon_line_item" : "commerce coupon line item" } }
    }
  },
  { "data_set" : {
      "data" : [ "commerce-coupon-line-item:commerce-total:amount" ],
      "value" : "100"
    }
  },
  { "entity_save" : { "data" : [ "commerce-coupon-line-item" ] } },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "[list-item:field-gift-recipient-email]",
            "subject" : "[list-item:field-gift-sender-name] has sent you a Gift Certificate",
            "message" : "Hello [list-item:field-gift-recipient-name], [list-item:field-gift-sender-name] has sent you a \u20a6 [entity-created:commerce-coupon-fixed-amount] Gift Certificate to celebrate your birthday. Your Gift certificate code is: [entity-created:commerce-coupon-code]. Please note that your Gift certificate may only be used once, please spend the full amount in one purchase, any balance remaining is non-refundable. Happy birthday celebration!",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]
}
}

After much digging, i was able to resolve this using a rules component. The trick is, after generating your coupon code using rules, that is,

  event: completing the checkout process

  condition: your condition (e.g order contains a particular product
  etc)

  action: create new entity => commerce coupon action: set data value
  (do this for the coupon code, max number of uses, coupon type (human
  readable name), etc) action: save entity => (your created entity)

  action: create new entity => commerce line item => commerce coupon
  (set your values) action: save entity => (your newly created coupon
  line item)

  create component:

  component plugin: rule name: name your component here (e.g "set gift
  coupon value") data type: commerce coupon label: (give a label that
  you can identify it easily with) machine name: (give a machine name
  that you can identify easily) save component.

  Under conditions: entity has field: (identify your coupon fixed amount
  field here e.g "coupon-fixed-value-component") action: set a data
  value => (here you identify the fixed amount coupon field and then set
  the value you want)   save component

  Come back to your earlier created rule,

  add loop: (it should automatically capture that you want to loop into
  the commerce line items e.g "commerce-order:commerce-list-item"  save
  loop inside the loop, add action = > (here you'll select the component
  you created, it should automatically detect that you want to fire this
  component on your created coupon entity initially created within this
  rule e.g "entity-created" save the action.

  perform any other action if you want, like send email to referenced
  user in the gift card.

  That would do. each time you complete the checkout for the product
  referenced in the rules condition, a gift coupon will be created and
  the amount would be set based on your rules component action value.

  Limitation: You have to do this whole process for every different
  amount of gift coupon you create.

  Possible improvement: Allow a user to specify the amount at product
  creation time, then use rules to capture this amount and then set the
  coupon value based on the set amount of the product

  More improvements welcome..


Export custom module strings for translation I've developed some custom modules for a client and implemented the $this->t() method to enable translations on static strings, like table headers. Is there a way to export only the translatable strings from my custom module into a .po file that I can handoff to someone for translation? I ideally want to export each modules translations separately so each module can be self contained.

You can give Translation template extractor a spin. While there is no official release for Drupal 8 available (yet), there already is a development version that seems to work for your use case when using the GUI:

https://www.drupal.org/project/potx/releases

Using composer, just install it like

composer require drupal/potx

After enabling the module, you'll have a new menu entry Configuration > Regional and language > User interface translation > Extract (/admin/config/regional/translate/extract)

There you can extract language and module specific translation templates from your custom module's PHP files.

Disclaimer: As mentioned, this module's Drupal 8 version has not been released yet. It may contain bugs and is not feature complete/en par with the 7.x version. Better use it in your development environment only.


Unable to set Drupal environmental variables using Drush alias $aliases['opendoor_stage'] = array(
    'uri' => 'stage.opendoor.com',
    'root' => '/var/www/stage.opendoor.com',
    'db-url' => 'mysql://someurl',
    'path-aliases' => array(
      '%dump-dir' => '/var/www/database-dumps',
     ),
    'variables' => array(
        'site_name' => 'My Drupal siteSSSSSSSSSSSSSSSSSSSSSSSSSSSS',
        'file_temporary_path' => '/var/www/open_door_files/uploads',
        'file_private_path' => '/var/www/open_door_files/contentfiles',
      ),
     'command-specific' => array (
       'sql-sync' => array (
         'no-cache' => TRUE,
         'structure-tables-key' => 'skip',
       ),
     ),
    'command-specific' => array (
    'sql-sync' => array (
      'sanitize' => TRUE,
      'no-ordered-dump' => TRUE,
      'structure-tables' => array(
       // You can add more tables which contain data to be ignored by the database dump
        'skip' => array('cache', 'cache_filter', 'cache_menu', 'cache_page', 'history', 'sessions', 'watchdog'),
      ),
    ),
  ),
  );

I then do the following commands to copy into my stage environment:

drush rsync @opendoor_test @opendoor_stage

and

drush sql-sync @opendoor_test @opendoor_stage --no-cache

Everything copies over fine however the information in the variables array never gets set. What am I doing wrong? I am following the documentation verbatim.

The 'variables' entry in a Drush alias file, or in $options['variables'] in a drushrc.php file will only affect Drush code execution; it does not in any way change the variables table in the database, or affect that way that Drupal runs from the webserver at all.

If you would like to change the values in the database, after sql-sync you could run:

drush @opendoor_stage vset site_name 'My Drupal siteSSSSSSSSSSSSSSSSSSSSSSSSSSSS'

See also sync_enable.drush.inc, which will enable modules and set permissions after every sql-sync operation.  If you often needed to set variables after every sql-sync, you could extend this code to call vset based on the values of entries in the site alias.

POSTSCRIPT:

You might also want to consider using $conf['site_name'] in the destination site's settings.php file rather than change the database value.  This is what most folks do.


Conditional views exposed filters (using Search api views) I have two views exposed filters,one dropdown field and a checkbox.
I want,when the checkbox is checked the dropdown field to dissappear.When I uncheck the checkbox I want the dropdown field to appear again.

First I tried Views dependent filter,however it doesn't play well with Search api views.

Secondly I tried with javascript.I wrote this code and added it to the .js file of my theme.However it doesn't also work.How can I do this?

(function ($) {
  Drupal.behaviors.cdgi = {
    attach: function(context) {

      var $('#edit-field-level-of-telecommuting-1').prop('checked') = true;
      if ($('#edit-field-level-of-telecommuting-1').prop('checked') === true) {
        $('#edit-field-job-region-parents-all').hide();
      } else {
        $('#edit-field-job-region-parents-all').show();
      }
    }
  }
}(jQuery));`

There is a slight change in the code.May be this can help you.

(function ($) {
  Drupal.behaviors.cdgi = {
    attach: function(context) {
     $(function () {
      $('#edit-field-level-of-telecommuting-1').click(function() {
        if ($(this).prop("checked")) {
          $('#edit-field-job-region-parents-all').hide();
        } else {
          $('#edit-field-job-region-parents-all').show();
        }
      });
     });
    }
  }
}(jQuery));`

check more info how to include js file


view exposed filter ajax error coming for non administrator user I have event calendar module which is perfectly working fine. For some other users (non-admin users) I have to give permission to access events posted by them (They have permission to view the calendar and add/modify/delete events).

So far everything is good. Now I added exposed filter(event status) which is working as expected while I logged in as admin.
Only when I login as user with some other role, I'm getting:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /views/ajax
StatusText: OK

Why is this happening only to non-admin user? I thought bypassing access control can give me some hint if its permission issue so I gave 'Bypass views access control' to that particular user role, still no luck. Any help greatly appreciated.

Go to Views Ui Setting Tab on Advance and uncheck Javascript ...
it's Work for me


Entire site broken because of one custom module! No pages found anymore. How to fix? I wrote a custom module and implemented it.  Now I cannot access any pages on my drupal site.  They all say something like: Page not found.  The requested page "/" could not be found.

I removed the module by hand from the table by running:

UPDATE system SET status=0 WHERE name='MyModule';

Even with this, no pages are working anymore.  I thought it was an htaccess issue or a clean url issue, but even doing /?q=user does not get me to my login screen.  Any ideas on how implementing my one custom module broke the entire website?  My module was basically this:

function MyModule_menu() {
  $items['MyModule_views'] = array(
    'title' => 'MyModule test',
    'page callback' => 'MyModule_list',
    'access callback' => TRUE,
    'type' => 'MENU_CALLBACK',
  );
  return $items;
}

function MyModule_list() {
  return t('hello');
}

I'm not sure why your menu item above took over all paths, it should have only responded to paths that start with '/MyModule_view'. Maybe someone else can see what the problem is. However, I believe it's still causing problems because the menu registry hasn't been rebuilt. You'll need to clear that out to actually remove the menu item definition. Normally this would happen when you disable the module from 'admin/build/modules', but because you did this manually by altering the database that process didn't happen. If you use Drush (which I highly recommend) you can rebuild the menu registry with

drush cc menu

If you don't have Drush, then you can write a simple script to rebuild the menu even though you can't really access your site. The script is explained in an answer over on StackOverflow: https://stackoverflow.com/a/6912110/318158


Can anyone give me an example of a seperator used in table style in views I am not sure what seperator does. I basically want view of the
node:title, and the node body in the same column of a table. How can I acheive this?

Dunno about drupal 7 but in in 6 youd go to your View, then View Style, select table, click on the wee wheel for options,  and then select which coloum you want your fields in.


How to get the enabled manage displays per node type? I have an admin form and need to check if a node, e.g. article has a specific manage display enabled. How do I get the data?

Found out to get an array of all available displays in general and there is a difference between display views and view modes. May I am just searching with the wrong terms.

You can use this service:

EntityDisplayRepository

  Provides a repository for entity display objects (view modes and form
  modes).

Example:

$view_modes = \Drupal::service('entity_display.repository')
  ->getViewModeOptionsByBundle('node', 'article');

More info: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityDisplayRepository.php/class/EntityDisplayRepository/8.2.x


display a taxonomy terms as autocomplete using form API I am writing my own module. I want to display a taxonomy terms as a autocomplete field in my form using form API. How can I do that?

I am using Drupal7.

Hope this will help you,

In Drupal 7, it can be done in 2 ways

By using existing taxonomy field(like TAG field), for this example I'm using field_tag

$node=node_load($nid);
$tags = array();
foreach ($node->field_tags['und'] as $item) {
  $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
}
$form['tags'] = array(
  '#type' => 'textfield',
  '#default_value' => taxonomy_implode_tags($tags),
  '#title' => 'Add Tags',
  '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
  '#maxlength' => 1024,
  '#element_validate' => array('taxonomy_autocomplete_validate'),page
);

If you dont want to use any field then it can also be using custom autocomplete

//custom field
$form['taxonomy_term_field'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'get_TAXONOMY_NAME/autocomplete',
);
//menu callback for autocomplete
function HOOK_menu() {
  $items = array();
  ....
  $items['get_TAXONOMY_NAME/autocomplete/%'] = array(
    'page callback' => 'TAXONOMY_NAME_autocomplete_callback',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
  return $items;
}
//autocomplete callback function
function TAXONOMY_NAME_autocomplete_callback($str = 0) {
  $matches = array();
  //vocabulary id
  $vid = 2;
  $result = db_select('taxonomy_term_data', 't')
    -> fields('t', array('tid', 'name'))
    -> condition('vid', $vid, '=')
    -> condition('name', $str.'%%', 'LIKE')
    -> range(0, 10)
    -> execute();
  foreach ($result as $term) {
    $matches[$term -> tid] = check_plain($term -> name);
  }
  drupal_json_output($matches);
}

References : Existing taxonomy field and Custom autocomplete field


Alternation of Log in Form in drupal 7 I want to alter the User login form of drupal 7.
I want only two fields Email ID and password. I don't want a username field. Please any one have idea to how to do these changes in User login form.

In order to delete the field in a form   you have to  print the form  either using dpm($form) or print_r($form) and there you will get the field of username use that field to unset in form_alter .

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

  if (form_id=="Your_form_id"){

      unset($form['the_field_you_dont_want']);

        }
   }


How do you identify a form element? I'm still learning Drupal, and I was trying to use hook_form_alter() to resize a text field added from a module.  My problem is that I don't think I'm indentifying the element correctly.

Here's the element code:

<input type="text" class="form-text form-autocomplete" value="" size="60" id="edit-2" name="2" maxlength="128" autocomplete="OFF">

Here's my module code:

/**
 * Implements hook_form_alter().
 */
if ($form_id == 'edit-2') {
  $form['text'] = array(
    '#type' => 'text',
    '#size' => 25,
  );
}

I'm not sure what to do; any suggestions would be helpful.

Thanks!

The HTML id has nothing to do with $form_id.

$form_id is the name of the whole form. In most cases, it is the name of the function that generates the form unless hook_forms() is used.

Instead of checking the $form_id with an if condition, it is often easier to implement the more specific hook_form_FORM_ID_alter() hook. So if the form_id is BLA, you can directly create a function yourmodule_form_BLA_alter(&$form, &$form_state)and don't need to mess with $form_id at all.

There are exception when this doesn't work or isn't practically, but it most cases, it is recommended to use that hook (It's a performance improvement too, because your function will just be called for that specific form and not every single form in Drupal).

If you are not sure what $form_id is, implement hook_form_alter() and put a drupal_set_message($form_id) in there. That should then print all form ids of the page you are on, allowing you to easily pick the one you want to change.

About the name of the form element, you can't guess that from the HTML in most cases, because unless #tree is set to TRUE, the names are flattened, so it might be $form['some_fieldset']['example'] in the $form structure and just name="example" in HTML.

So, to find the element you want to change, there are two ways.

a) Look at the source code of the function that defines the form structure.

b) Use dpm($form) (requires devel.module).

I prefer the second method, and this is usually the second step after figuring out the $form_id, if I don't know exactly what I want to do. dpm() prints complex array/object structures in a very nice and browseable way. That is actually something you should get used to all the time when you work with Drupal. Don't just guess things. You're going to be wrong pretty often. Instead, if there are any variables that you want to use but don't know the exact structure of them, add a dpm($var), load the page/trigger the action and then you can exactly see what you are working with.

Edit:

The last problem is that right now, your code does completely replace that form element. Instead, you only want to override the #size property, like this:

$form['finder_form'][2]['#size'] = 25;


Basic pages are being rendered incorrectly do they differ at all to the article or custom content types in any fundamental way? I have a custom theme, all (custom) content types display as expected except basic pages. Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

The site has custom theme/child-theme, custom modules, and a heap of contrib modules so I can't really "paste the code", and as it's a development site I can't give access to it.

The problem I'm experiencing seems to be HTML markup errors, some missing closing elements etc., but I've stepped through most of the code already and can't see anything. Is it something specific to basic pages that Drupal does differently?

Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

No, content types are completely generic. Drupal core processes them identically, but of course, custom and contrib code can heavily affect how they work.

You're going to need to check your theme, templates and custom modues, and maybe even contrib modules (depending on what you have installed and how you have them configured). The problem is with one or more of them, not with the content type itself.


What is the Correct UID path whilst using Ubercart Affiliate in Custom DB I'm currently building a various user dashboard using my own custom hacked Workbench (WB) & cloned from one Master for end users (3 roles ex SU). WB chosen over Homebox as that was taking me too long and WB seems easier to integrate Views etc. FYI, I'm working on a D7.2x local Linux Ubuntu webdev box using the system localhost.

Things are going well and general path links to modules link well (Support tickets, Messages etc). However, one of the options I'm offering is the Ubercart Affiliate and whilst that module is working fine, I cannot for the life of me get a users Affiliate account path to show up correctly via a direct link from the Workbench. I require the path to be simply: site/user/affiliate linking direct the Affiliate dashboard (DB).

For my benefit, for now I created Custom Content Pane (as opposed to a Block) and simply created HTML links into it as one would do (using 'other' as the option URL settings. The other links work fine linking to the relevant modules, but the link to users main Affiliate DB overview won't work. I set "Affiliate Center" as the link to the UC Affiliate DB but am I either confused over the correct path structure or something is missing or both.

For example, user' joetest' can login and is redirected on login to his WB and all shows aok. joetest can access his UC DB via: [http://localhost/sitename/user/12/affiliate] but what I presumed was correct (...sitename/user/%/affiliate) or .../user/uid/affiliate) neither don't work and gives me an error message of what I expect, "affilate shop not found etc...".

I know it's a path issue (Redirect, Pathauto, URL-Alias) but I cannot figure it out. I checked all permissions and others.

I'm quite happy for the end result to be:  in order for the user to access their said UC Affiliate main 'home' DB even maybe using the ME module? I'm not sure.

Presume this should be a five minute setup, but a few hours later, I'm getting stumped now but simply want to user to be able to view, edit, amend their Affilate details but via either a link on their WB. Not looking to use Menu tabs as I'm wanting a very light, minimal structure.

Any advice great appreciated.

Ok, I'm a learning 'novice', but probably missing a small point on the path structure knowledge. (:
Thanks in advance.

I resolved this by using the ME Alias module which allow the insertion of the said UID into the path I required for all users.


Installing with Composer causes unit tests to fail I installed with Drupal with Composer (using drupal-scaffold) with Drupal files placed inside the web directory. When I run unit tests, two of them fail because Drupal expects to find the composer.json file inside the web directory whereas in my case composer.json is in the project root (which is obvious place for it).

Is this an issue with my configuration, or is it a problem with unit tests that make wrong assumptions?

The failing tests are
Drupal\Tests\ComposerIntegrationTest::testComposerJson and Drupal\Tests\ComposerIntegrationTest::testComposerLockHash. Both fail with the following error message.

  file_get_contents(web/composer.json): failed to open stream: No such file or directory

Drupal with Composer uses the drupal-scaffold script which you mentioned. It seems that it does not include the composer.json and composer.lock files by default.

But the files are there: http://cgit.drupalcode.org/drupal/plain/

Looking at the plugin documentation on github in the Configuration section reveals that the composer.json and composer.lock files are not on the list to be included by default.

But the plugin is configurable, and you can actually specify the name of the files that should be additionally included.

So adding this in the extra section of your composer.json:

"drupal-scaffold" : {
    "includes" : [
        "composer.json",
        "composer.lock"
    ]
}

followed by running composer drupal-scaffold OR removing web/core directory and running composer install should get you the required files and make the tests pass.x


Reference (include) php file in content summary In my content summary section I will have the same information for each node. I would like to reference an external php file so that down the road if I ever need to change the summary content I don't have to go through each one and manually change it.

I set text format to php code.

In the summary I added:

<?php include("external.php"); ?>

Problem is that I am not seeing the contents of the php file. In fact, I am not seeing any sign of it in my code.

Am I going about this the wrong way?

Edit: I basically want to be able to change some static HTML that needs to belong in the summary field of my nodes if I ever need to without having to go into each node and change it manually. The text will be the same for all my nodes.

If you have a custom module for your site, put the file in that module directory, add it to the mymodule.info file,

file[] = external.inc

and put the include statement in the mymodule.module file. Use the model here if you are unfamiliar.

Make the code a function, named for instance mymodule_standard_summary(), and then use:

<?php
print mymodule_standard_summary();
?>

in the summary of your nodes. This should get you started.

EDIT:

Rather than trying to embed your code in the page like this:

<?php
  // Embedded code
  print $result;
?>

instead you should set it up in a function in your file like this:

function mymodule_standard_summary() {
  // Your code
  return $result;
}

I hope this makes it a little clearer.


How do i change the apachesolr index environment based on node values? I have two apachesolr environment setup in my drupal instance. I want to index some nodes to one environment and some to the other, say based on some node values.

I could see that it always indexes to default the environment. I could see the possibility of indexing in two environments, but it is irrespective of the nodes value.

How can i achieve it?

UPDATE:

To give more detail, I am trying to achieve shards in apache solr in Drupal

UPDATE - 17 DEC 2012

Modules used:

Apache solr Module and not search api/search api solr

Reason on why i need node values

I have a large nodes of a particular entity type, This makes my index so large.

So Decided to go with shards with multiple indexes of the same node type.

So based on the node size and its priority of the node or proximity of the nodes location or users location , I want to split up the index to separate cloud servers and index them.
Proximity of the node also gives me power of separate out search indexes at a later stage.

I do not know if it is possible to shard Drupal nodes into different Solr indexes based on arbitrary field values, I do however know it is possible at a node type level.

From the API documentation:

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1.
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  // Never index news entities to core_2.
  if ($entity_type == 'news' && $env_id == 'core_2') {
    return TRUE;
  }
  // Default to allow.
  return FALSE;
}

So all you would need to do is allow some node types to be indexed by one core, and allow some other node types to be indexed by another core.


Disqus include causing Bad Gateway errors I've set up Disqus on my drupal site and it was previously working, but it's suddenly not working and I have no idea what changed.

This is one of my nodes with Disqus in the block at the bottom:
http://liberalgeek.com/content/republican-todd-akin-and-legitimate-rape-doesnt-cause-pregnancy

I'm getting a 502 Bad Gateway message in my javascript console on Chrome:

GET http://mediacdn.disqus.com/1345491156/uploads/themes/dsq028ee724157b05d04e7bdcf237d12e60.css?1557 502 (Bad Gateway) client.js:6
DISQUS.requireStylesheet client.js:6
Backbone.View.extend.bootstrap client.js:84
Backbone.View.extend.initialize.b client.js:81
b.Events.trigger lib.js:108
(anonymous function) client.js:16

It looks like the API was undergoing maintenance which is why it was rejecting with a 5xx error. Here is the list of meanings to the HTTP response codes that Disqus uses:

http://disqus.com/api/docs/errors/


Trying to create a new prebuilt list in webform I'm attempting to define a new prebuilt list for our site, and even though everything looks like it should be fine, based on the examples I could find, the list doesn't appear.

My module is appearing in the list of modules, under "Other", and it is  enabled.

This is the content of the AddressList_webform_select_options.module file.

<?php

/**
 * Implementation of hook_webform_select_options_info().
 * See webform/webform_hooks.php for further information on this hook in the Webform API.
 */

function AddressList_webform_select_options_info() {
  $items = array();
  $items['Address'] = array(
    'title' => t('Select Address'),
    'options callback' => 'AddressList_options_Address'
  );
  return $items;
}

?>

<?php

/**
 * Build an options list for use by webforms.
 */
function AddressList_options_Address() {
  $options = array();
    $options[] = "1|city2 - Address1 - Floor - Building Name";
    $options[] = "2|city2 - Address2 - Floor - Building Name";
    $options[] = "3|city2 - Address3 - Floor - Building Name";
    $options[] = "4|city1 - Address4 - Floor - Building Name";
  return $options;
}

?>

This is the content of the .info file.

name = Address List
description = Creates a prebuilt list that contains all current addresses.
core = 6.x
dependencies[] = webform

Please tell me I'm missing something simple.

When you are building option list in code, don't use human-readable syntax. Use machine-readable one. So instead of this:

$options[] = "1|city2 - Address1 - Floor - Building Name";

you should use this:

$options[1] = "city2 - Address1 - Floor - Building Name";

Second very bad thing you did is:

?>

<?php

It is highly discouraged to ever close php block. Everywhere except template files you should have <?php as the very first 5 bytes, and no ?> at all. What you apparently did was outputting few empty lines to the user's screen where nothing expected them.


Send node path alias to user When I create a new content, I would like to send an email that contains "node path alias".

Pathauto pattern

[title-raw]-[nid]

Rules

ON event After saving new content
IF
Created content is Les entreprises
AND
Created content is new
Add a condition
DO
Send a mail to a user

Rules email

[node:node-path]

I receive the email, but the content is 'node/16565'. I would like to receive 'les-entreprises-16565'.

If I inspect token with the Devel module, I get: node-path (String, 21 characters) les-entreprises-16565.

Why didn't I receive this node path alias? Is the Rules module sending the mail too quickly, and the path alias is not yet created?

Have you included the condition “Entity is of type … Node”? Having to specify this condition may seem redundant, since you have already established this rule is triggered by the Event “After saving new content”. However, I have experienced that without this condition a very limited amount of tokens holding data from the node will be available to the Action and any Components invoked by the rule.
 Good Luck!
Susan


How to programmatically add content to a group in the Group Module? I'm using the Group module. If I have a group type such as Project, and I have a content type such as Article, and I programmatically created a new article node using Node::create(), how can I in the same code add this article as content to a project that I choose?

Given you have the group entity and node entity, you can simply create a GroupContent entity.

$groupEntity = ... The group entity.
$node = ... The node entity.

$type = $type = $groupEntity->getGroupType()->id() . '-group_node-' . $node->getType();

$groupContentEntity = \Drupal\group\Entity\GroupContent::create([
    'gid' => $groupEntity->id(),
    'entity_id' => $node->id(),
    'type' => $type,
]);
$groupContentEntity->save();


Fatal Error after creating Custom Display Suite layout I am using Display Suite and I created a custom layout called ds_6row when I Flush Cache I get the following error

Call to undefined function ds_ds_6row() in /Users/myname/Sites/sitename/sites/all/modules/contrib/ds/includes/ds.registry.inc on line 570

I followed the method to create the layout here

My structure looks like this:

mytheme
--ds_layouts
---ds_6row
----ds_6row.css
----ds_6row.inc
----ds_6row.png
----ds-6row.tpl.php

The code for ds_6row.inc is:

<?php
function ds_6row() {
  return array(
    'label' => t('6 Row Layout'),
    'regions' => array(
    'info_data' => t('Info_data')
  ),
// Add this line if there is a default css file.
'css' => TRUE,
// Add this line if you're using DS 2.x for icon preview
'image' => TRUE,
);
}

The code for ds-6row.tpl.php is:

    <?php

/**
 * @file
 * Display Suite 6 row template.
 */
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-6row <?php print $classes;?> clearfix">

  <?php if (isset($title_suffix['contextual_links'])): ?>
  <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

  <<?php print $first_wrapper ?> class="group-first<?php print $first_classes; ?>">
    <?php print $first; ?>
  </<?php print $first_wrapper ?>>

  <<?php print $second_wrapper ?> class="group-second<?php print $second_classes; ?>">
    <?php print $second; ?>
  </<?php print $second_wrapper ?>>

  <<?php print $third_wrapper ?> class="group-third<?php print $third_classes; ?>">
    <?php print $third; ?>
  </<?php print $third_wrapper ?>>

  <<?php print $fourth_wrapper ?> class="group-fourth<?php print $fourth_classes; ?>">
    <?php print $fourth; ?>
  </<?php print $fourth_wrapper ?>>

  <<?php print $fifth_wrapper ?> class="group-fifth<?php print $fifth_classes; ?>">
    <?php print $fifth; ?>
  </<?php print $fifth_wrapper ?>>

  <<?php print $sixth_wrapper ?> class="group-sixth<?php print $sixth_classes; ?>">
    <?php print $sixth; ?>
  </<?php print $sixth_wrapper ?>>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

Have a look in the code for Display Suite, specifically the block mentioned in the error message:

function _ds_layouts_scan_theme($theme, &$layouts) {
  $theme_layouts = file_scan_directory(drupal_get_path('theme', $theme) . '/ds_layouts', '/inc$/');
  foreach ($theme_layouts as $file => $values) {
    include_once(DRUPAL_ROOT . '/' . $file);
    $function = 'ds_' . $values->name;
    $layouts[$values->name] = $function();
    $layouts[$values->name]['path'] = str_replace('/' . $values->filename, '', $file);
  }
}

Note that when it goes looking for layouts is it prepending your layout name with 'ds_'.

I imagine this is to prevent functions being included that were not intended for this purpose, a bit like using your module name in place of hook_ when you implement hooks.

That's why changing your function name worked.


How to use commerce_cart_order_product_line_item_delete? I've set up my own custom module structure, and am trying to implement commerce_cart_order_product_line_item_delete. At it's most basic level, i'm trying to delete line item 70 from order 1 in my cart with the following code in my module:

<?php
    commerce_cart_order_product_line_item_delete(1,70,FALSE);
?>

I'm getting this error on the page:

Fatal error: Call to undefined function commerce_entity_reference_delete() in /Users/[username]/Documents/Sites/[site_name]/profiles/commerce_kickstart/modules/contrib/commerce/modules/cart/commerce_cart.module on line 1268

I've tried other methods, like the code on this page:

http://dropbucket.org/node/358

but i can't seem figure out how to find a product's ID, and in the end, I want to delete a line item from a cart which could potentially have two entries of the same product. don't want to delete the whole product from the cart... hope that makes sense.

What am I missing?
thanks!

The function accepts the $commerce_order object not just the order_id. You could try

commerce_cart_order_product_line_item_delete($order, 70);

commerce_entity_reference_delete is defined in commerce.module so it should be available, if commerce is enabled and at current version.


How to send a user an email when a content is published by somebody else? I want to send an email to a user when the user's earlier unpublished content is published by somebody else (site administrator, moderator, etc).

I tried doing it with Rules but could not figure out how.

Any help?

The Workflow module can do it exactly what you want. By using this module you can trigger different action at each flow of content.

  Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state.
  You can set up the Workflow to alter states from form, page, comment and a special workflow tab.


AJAX Views arguments: how to specify quantity of results and what are other options that can be used? From this great answer I have a working jQuery implementation of a simple call to an existing view using AJAX. Which is brilliant, but I want to specify the number of results differently to as is setup in the existing view, and I want to know what other options I can use under view_args.

I can't find documentation/a full example of what's available and how to use it. Is there any?

$.ajax({
    url: url,
    type: 'post',
    data: {
        view_display_id: v_display,
        view_name: v_name,
        //   view_args: {}, // your views arguments
        view_args: v_args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
            return response[1].data; // do something with the view
        }
    }
});

I inspected the HTML of the Views admin page and saw the pager was encapsulated from the other arguments, and tried this but it carried on supplying 6 items (which is odd because the view is saved to display 10):

var data = {
    'view_name':'ajax_test',
    'view_display_id':'block',
    'pager_options': {
        'items_per_page':'1',
    }
};
$.ajax({
  url: '/views/ajax',
  type: 'post',
  data: data,
  //pager_options: {items_per_page:1},
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      document.write(response[1].data); // do something with the view
    }
  }
});

Previous experience tells me with Drupal 7 that if I don't find an answer after a day of research then people probably haven't approached it like this and I'm unlikely to find much assistance, so I'm doing the custom menu item approach instead, as people have suggested in the discussions I've read.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items['ajax/%'] = array(
        'page callback' => 'get_view_with_args_get_ajax',
        'page arguments' => array(1),
        'type' => MENU_CALLBACK,
        'delivery callback' => 'ajax_deliver',
        'access arguments' => array('access content'),
    );

    [....etc....]

function get_view_with_args_get_ajax($args) {
    views_get_view($name);
    return 'Args: ' . $args;
}


Don't show blocks on some pages I don't want to show blocks inside some pages, and I can't touch the theme files.

Is there any way to do this programmatically inside a module?

You can use hook_block_list_alter() to hide the blocks in your module code. See docs for more information on how to achieve this. This is the the alter for the function Drupal used to hide/show blocks.


Adding css classes to taxonomy terms I am trying to have all my taxonomy terms to look different from each other.

Is there  a way for me add specific CSS classes to differing taxonomy terms?

Already the page-taxonomy-term-TERM_ID is present on the body tag.

To add more classes you can use hook_preprocess_html() and add the $vars['classes_array'] to add the css classes you want for the terms.


Drupal Collaboration for beginners I am currently working on a team of four people trying to develop a simple news website. We are having a hard time figuring out the best way to collaboration. I've found other threads that suggested using Features module; however, that is outside of our scope at the moment. Can you suggest a simpler way to collaborate?

Since you specifically mention the Features module in your question, (also mentioned in the upvoted and accepted answer to: How do I manage collaborative development on a Drupal site?) I shall assume you're asking about how to share the database and code under development among team members, and not about tools for team collaboration ("groupware") in general.

First, let me say that I don't think Features is the right tool for this task, and shall propose an alternative set of tools.

A prerequisite for team collaboration is to have a staging server for testing out development versions of the project that is separate from your production server.  All development code is tested at the staging server, and only pushed to production server when it is stable and ready for deployment.  However, the developers doesn't work directly at the staging server.   Each developer work at his or her own workstation, using a revision control and source code management (SCM) to coordinate his or her work with the rest of the team.

The SCM system allow team members to work in parallel on different branches of the code without interfering with each other.  Only the master branch is deployed on the staging server for testing purposes.

To mirror the database between production, staging and workstations, there is a module named Backup and migrate that can be used if you're on shared hosting and not managing your own database. If you're managing your own database server, this is the only project on that server, and you use mysql, the following pair of commands are handy:

To dump:

mysqldump --all-databases --opt -u root -p > DUMP.sql

To restore:

mysql -u root -p < DUMP.sql

If yours is not the only database on that server, script some version of mysqldump (or equivalent if you're not using mysql) that dumps your databases only.

Make a policy that it is the database on the production server that is master.  The staging server and workstations should be a copy of the production database, not vice versa.

Note that Drupal 7 keeps all its admin setting in the database.  This means that mirroring the database between the production site, staging site and workstations will migrate admim settings without Features.

Now, for sharing the code:

The standard way for sharing code among the members of a development team is to use SCM system.  Drupal happens to be default be managed with such a system named git.

Git allows the use of local or remote repositories.  If the team members are located in the same physical space, you can set up a local repository on your staging server.  If they're spread geographically, you can set up a remote repositiory.  If you don't mind others having read access at your code under development, you can use a sandbox at Drupal.org as a remote repository. You can also use a project area on GitHub.  GitHub is not only a repository, but comes with a some tools for collaboration, and allows both public and private repositories.

Basically, a SCM system allow team members to pull source code and documentation from  the respository shared by the team members, and push it back in again after having worked on it.  The SCM keeps track of changes and if there is a conflict (i.e. somebody tries to push code that doesn't the contain the changes another team member has committed), it will tell you and also suggest a way to resolve this conflict.

Usually, with some cordial communication about how the tasks are divided among the members of the team, there will be no conflicts.  But with the SCM system keeping track of things, conflicts become manageable even if mistakes are made or communication fails.

There exists a lot of tutorials on getting started with and using git (GIYF).  Two I will recommend are: the git-scm website and Pro Git by Scott Chacon.


How to adjust the length of [node:summary] for metatags? How can I tweak the amount of characters for [node:summary], so that the description metatag never shows more than 150 characters?

On admin/config/search/metatags/config/node I can only see for description token [node:summary], which does not allow me to control the amount of characters that get displayed on the source code. I would need to trim it to max 150 characters, but I have no idea how/where this can be done.

You can do a few different things.
Assuming you are using the metatag module.

1) Prevent metatags from saving with more than 150 chars using a presave hook:

function hook_metatag_presave(&$metatags, $entity_type, $entity_id, $revision_id, $langcode) {
  dsm($metatags);//debug what the array is. You can trim the values for the metatags here.
}

2) Alter the metatag before bing cached:

/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 * @param array $options
 *   All of the options used to generate the meta tags.
 */
function hook_metatag_metatags_view_alter(&$output, $instance, $options) {
  if (isset($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'])) {
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = truncate_utf8($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'],150);
  }
}