Add CSS class to fields I have the following snippet.

function <themename>_preprocess_node(&$vars) {
  if ($vars['teaser'] && !$vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser';
  }
  elseif ($vars['teaser'] && $vars['is_front']) {
    $vars['theme_hook_suggestions'][] = 'node__teaser__front';
  }

  if (!$vars['teaser'] && count($vars['field_related']) > 2) {
    $vars['theme_hook_suggestions'][] = 'node__alt';
    foreach (element_children($vars['content']['field_related']) as $k) {
      $vars['content']['field_related'][$k]['#attributes']['class'][] = 'grid_1';
    }
  }
}

Basically, I have this field_related in my node that holds from 0 to 3 values. If it holds more than 2 values, I change the template suggestion (node__alt) and I'd like to attach a class (grid_1) to each of the values. I've spent the last 4 hours researching but nothing got me even near to where I want to go.

Do you have any idea?

EDIT In the template file I did like this:

<aside id="related">
  <?php foreach(element_children($content['field_related']) as $k) : ?>
    <div class="grid_1">
      <?php echo render($content['field_related'][$k]) ?>
    </div>
  <?php endforeach ?>
</aside>

It works, but it is far from being clean.

Make a copy of your_drupal_site/modules/field/theme/field.tpl.php in your theme directory and name it field--field_related.tpl.php  In this file  You can attach the class (grid_1) to each field as follows:

<?php foreach ($items as $delta => $item) : ?>

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

 <?php endforeach; ?>

All the available variables are listed in the comments of this file so you will be able to customize as you like.

On any given node you can check how many fields have been created and theme according to that. You can change the above code to count how many fields are there on any node, the revised code is as follows:

<?php foreach ($items as $delta => $item) : ?>
    <?php
    if (count($items) > 2) {
        print '
' . render($item) . '
';
    } else {
        print '
' . render($item) . '
';
    }
    ?>
<?php endforeach; ?>

This will add class "grid_1" to any node with 3 or more fields of field_related and add class "two_or_less" to the nodes with 1 and two fields.


How to fix call to undefined function libraries_get_path() in multi-site install? I am setting up a multi-site Drupal 7 install. I have the base site set up correctly and running just fine. When I create the second site (a sub domain of the first site), the install.php script ran fine but when I try to view the site I get the following error:

Fatal error: Call to undefined function libraries_get_path() in /var/www/drupalhome/d7/sites/all/themes/mytheme/template-preprocess.php on line 75

I assume that since the second site inherits everything from the first site (since it is the default install) that the second site should display just fine. However it looks like the second site doesn't know about the libraries module and is throwing the above error (at least that is my interpretation of it). My question is: how can I fix this?

Thanks.

...since the second site inherits everything from the first site..."

To the best of my knowledge that's not how a multi-site setup works; in my experience there's no inheritance involved. Core code/modules/themes/libraries etc can be shared between any number of sites, but each has their own separate database (and files structure, potential for site-specific modules/themes etc.).

When you add a new site you get a fresh Drupal install, none of the settings from any of the other sites in the setup are copied over.

An inheritance-based workflow wouldn't make sense, as multi-sites can contain any number of completely different Drupal sites - the point is that they can share the resources mentioned above, and when it comes time to upgrade core/contrib modules you only have to do it once for all the sites in the setup.

You can solve the specific problem you're currently having by enabling the libraries module on the new site; but if your custom theme relies on other contrib modules to be installed as well, those will need to be enabled before the site will work properly. Similarly, if the custom theme relies on settings/variables that were available in the default site, those will need to be restored.

I think in your case it would make more sense to clone the default site and database into the new one (bypassing the installation procedure entirely), then make the necessary adjustments to distinguish it from the default site afterwards.

Either that, or wrap the default site's functionality up in Features/Config, perhaps creating an install profile along the way, and use that to instantiate the a clone when you need one.


Drupal website only in Arabic on English installation I have installed my Drupal in English Language. But i want my all pages to be only in Arabic as of now. English launch will be later. How i do such that all wesbiste content can be only in Arabic and Admin language will be in English.

First you'll need the i18n module to enable your drupal website for a multilingual setup. It should be no affair to have Arabic as the preliminary language, though you may think about having English as the default language due to some string issues. If you want a website with right-to-left text direction, you'll need a theme which supports this.

A good start to see what's also important can be found in this comprehensive tutorial.


Create new content of a different type within the article edit screen? My editors are asking to be able to create content of different types (albums, songs) from the same screen they use to edit articles. Are there any modules that support this type of functionality?

The Inline Entity Form should help assuming the content types need to reference each other as well!

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.

It was created primarily for Drupal Commerce (Product display -> Product references on one page), but the functionality is there for other entities (out of the box it supports nodes, so it should be fine for your needs).

(Assumed) use case:

Add an entity reference for Songs onto an Album content type
Configure the entity reference to use the inline entity form (IEF) as its widget
Add an album - from here you can add songs to the album using the IEF
When you save the Album, it'll create the Album node plus all of the Song nodes and keep an Album->Song reference


Can menuTree load a menu's items including children From what I understand I should be able to retrieve all the items in a menu using menuTree. However I only get one level/depth no matter what I try.

My Menu Looks Like:

  Imported Content
  --Products
  ----A Child
  ------Grand Child
  --------Great Grandchild
  ------Grand Child 2
  ----Child 2
  --A Sibling
  Screenshot from Drupal: https://www.evernote.com/l/AAKdnwekb7BM87AFANo1z2XjCdEvR8HgDEI

This is my code:

$menu_name = 'imported-content-menu';
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $parameters->setMaxDepth(100);
  $parameters->setMinDepth(0);
  $tree = $menu_tree->load($menu_name, $parameters);

When I inspect $tree, it is an array of two items "Products" and "A Sibling".

I inspected these two items to see if there were nested items (the children) but there were not.

The "Products" item has 'hasChildren' set to TRUE. But I don't see those children.

Within the typical route context ($menu_tree->getCurrentRouteMenuTreeParameters($menu_name)), subtree elements are loaded only, if the menu item is flagged as "Show as expanded" within the menu item settings.

To load the entire tree, you have to pass in a plain MenuTreeParameters object without the current route context:

use Drupal\Core\Menu\MenuTreeParameters;

$parameters = new MenuTreeParameters();

// Optionally limit to enabled items.
$parameters->onlyEnabledLinks();

// Optionally set active trail.
$menu_active_trail = \Drupal::service('menu.active_trail')->getActiveTrailIds($menu_name);
$parameters->setActiveTrail($menu_active_trail);

// Load the tree.
$tree = \Drupal::menuTree()->load($menu_name, $parameters);


is it a security hole to verify an uploaded supposed-to-be-zip file as a zip with zip_open()? Question's subject is pretty much it.

I have an upload widget on a custom content type that is for users to provide a zip file.

I want to verify the file they provide is indeed a zip file, and take appropriate action if not. However, first I need to know if it's safe to pass an unknown file type to zip_open(), probably using the ZIP_CHECKONS flag for extra integrity checks.

edit: just realized ZIP_CHECKONS is not exposed in php. :(

Is this a safe way to verify a file is a zip file?

That seems reasonable to me. I would probably place the file in a temporary directory first and then use zip_open on it in that location.

You may also be able to use OS level commands (which come with their own risks) to verify the integrity of the file without actually unzipping it.

Are you going to store the zip files as zip files after being uploaded? Doing so presents additional issues since zips can be used to contain lots of files that may or may not be appropriate. You may want to get a list of the contents of the file to automatically include in your field so people downloading them will know if the file contents are valid. You could also integrate with something like http://drupal.org/project/clamav to scan all the files that are uploaded.


drupal 7 restful server VS seperate Restful server to access mysql. Can a restful server be on a subdomain I am trying to figure out which would be easier to setup and maintain, while keeping the speed average or better.

I have setup a Drupal 7 site on godaddy with their Deluxe 4GH hosting plan.  What I am trying to figure out now, would it be easier to setup and maintain a resful server in drupal 7 or setup a seperate restful server.  I would also like to know if I can run the seperate restful server on a subdomain.  Right now I have the restful server enabled in drugal (nothing setup tho), and I now cannot get past the firewall of the company I work for.

It really depends on what part of your Drupal site your REST service will be an interface to. The Services module provide a great and easy solution to expose parts of of Drupal core and some selected contribs data and feature as REST services. IT also provide a framework to build your own services.

By-passing Drupal in a separated service directly accessing the MySQL DB is only an option if you are accessing custom tables. Accessing nodes (ie. content) directly in the MySQL database is a bad idea. The DB schema to store the nodes is dynamically managed by Drupal (the Field API). It could change whenever you add, remove or edit fields or when updating Drupal. But the Field API is not the only one to manage node data, any module can contribute data to a loaded node or add behaviours on node CRUD operations. If you go directly to the database you loose all these added behaviours. The same is true for most data handled by Drupal.


Theme takes different css file from /default/files/css when uploaded to remote server from local I have zymphonies theme installed in my Drupal 8 website. In my localhost everything was working fine. But when I uploaded the entire files to the remote server the styling of breadcrumbs has gone (it shows as numbered list). As I inspected with the firebug the css file that is taken from default/files/css is different.

There are large number of css files in the default/files/css how does Drupal choose to select a particular css from that set of css files?

The location "default/files/css" is used to store aggregated CSS files, created by Drupal Core. CSS/JS file aggregation can be enabled/disabled by navigating to Drupal Performance settings page, using "Admin => Configure => Development => Performance" and enabling checkbox "Aggregate CSS files". You can also delete the .css files from "default/files/css" directory and Drupal will automatically create new one whenever site is visited first time after that. Check the screenshot below:

It is not advisable on production, but if you want to use original files from Theme's CSS directory directly, then uncheck "Aggregate CSS files" setting checkbox and Try clearing cache.


Creating nodes from json including image field upload I am trying to create a node programmatically from the data(JSON) sent by my front-end template.

<input id="title" name="title" type="text" >
<input id="body" name="body" type="text">
<input type="file" name="pic" id ="pic1" accept="image/*">

^^ This is my front end html

jQuery(document).ready(function(){
jQuery("#save").click(function(){
    //alert("The paragraph was clicked.");
  var postData =  [{
      "content-type" : "article",
      "title": jQuery("#title").val(),
      "body" : jQuery("#body").val(),
      "pic1" : jQuery("#pic1").val(),
  }];
        jQuery.ajax({
            type: "POST",
            dataType: "application/json; charset=utf-8",
            url: "my-module/create-artcle/", //This is the menu hook I created
            data: {'article': postData},
            success:function(data){
            //if(data.status === "success"){
              alert(data);
            //  window.location = "/user";
            //}
          }
    });
  });

});

^^^ This is my json.

This data is sent to the hook_menu I created, which triggers a callback function to create the node. here is the code for that.

function create_article(){
  global $user;

  if(isset($_POST['article'])) {
      $json = $_POST['article'];
      $decodedData = json_decode($json, true);

      $contentType = $decodedData[0]["content-type"];
      $title = $decodedData[0]["title"];
      $body= $decodedData[0]["body"];
      $image1 = $decodedData[0]["pic1"];

       //Create a article
       $node = new stdClass();

       //Set values to fields
       $node->type = $contentType;
       $node->title = $title;
       $node->body[LANGUAGE_NONE][0]['value'] = $body;

       node_object_prepare($node);
       $node->language = LANGUAGE_NONE;
       $node->uid = $user->uid;
       $node->status = 1;

       $node = node_submit($node);
       node_save($node);
  }
}

So far I am getting my code to work except saving the image, because I'm seriously confused in saving an image to my node.
The value that I get from front-end is simply the name of the image.
my question is :
can I save an image to the node I am creating with what I am getting from front-end ? If so I am confused with this reference https://www.drupal.org/node/201594

could any one guide me to extend this code to save my image..
$image1 this variable contains the image name.

Thank you.

The best way to achieve that is through Services module

In your case you have to post the image itself and use the file data in node object as a value for the field see that snippet:

  //$file_array is the result from saving the file
  //assuming you have the field name is image
  $file_array = api_save_file($_POST['image'], $title);
  $node->field_image[LANGUAGE_NONE][0]['value'] = $file_array

Note that you have to save the image base64 encoded like

//save base64 images as files
//@return object file object

 function api_save_file($file, $name, $entity_type = 'node', $entity_id = 0){
$data = base64_decode($file);

$finfo = finfo_open();
$mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
finfo_close($finfo);
// get file type png. jpg
$ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
$file_name = str_replace(' ', '-', $name);

$file = file_save_data($data, 'public://'.$entity.'/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);
file_usage_add($file, 'file', $entity_type, $entity_id);

return array(
    'fid' => $file->fid,
    'width' => 800,
    'height' => 600,
    'display' => 1,
    'alt' => $name,
    'title' => $name
);

}


How can I provide a checkbox to display name as 'anonymous'? When users register on my website, they have to fill in their name. However, not everyone wants his/her name to be displayed on his/her profile page. Therefore, I'd like to provide a checkbox "Show as anonymous" during the registration which changes the name to anonymous on the profile page. In other words, the checkbox rewrites the displayed name, as opposed to Is there a way to let every user can choose (e.g. on registration) whether their field is private or public?, where the field is hidden.

I rewrote the profile pages with user_view in the Pages section and I'm using Panels.

How can I do that?

You can add one more text field to user entity, keep it hidden.While registering the user check if show as anonymous user field is checked save the hidden field value as anonymous else copy the user name field to hidden field.

You can do the above changes in hook_user_presave().

Finally add this hidden field to your user view, instead of name field.


How do I add a cart form to the product view? With Drupal Commerce 8.x-2.0-beta5, I created some products and a view that lists all products with their variations.

I wanted to add the cart form to any variation, but I was not able to do so.

How can I achieve it?

To display an "add to cart" button on a product's display you need to:

Go to /admin/commerce/config/product-types/TYPE/edit/display
Make sure that Variations field is displayed
Select "Add to cart form"

Views display:

You simply need to add the "Product: Variations" field and set its display as "Add to cart form"

You of course you need to have the "Commerce Cart" module enabled :)

Not intuitive really. I might end up using Commerce Variation Add to Cart module.


saving JS settings in theme_settings.php file i am working on a responsive D7 theme and need some JS settings to be saved via theme settings form not a custom module. i did following codes to give what i want but it seems that Using drupal_add_js() function to add JS settings in theme_settings.php file doesn't work. could you please point out what is the problem and is there any alternative solution?
some of my codes in theme_settings.php file is as followings:

/**
* Implements hook_form_system_theme_settings_alter()
*/
function glossy_form_system_theme_settings_alter(&$form, &$form_state) {
    $theme = alpha_get_theme();

    $lib_options = false;

    /** add mobileMenu options to theme settings */
    if (isset($theme->settings['libraries']['glossy_mobileMenu'])) {
        $lib_options = true;
        $form['alpha_settings']['glossy_lib_options']['mobileMenu'] = array(
            '#type' => 'fieldset',
            '#weight' => -10,
            '#title' => t('mobileMenu options'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_selector'] = array(
            '#type' => 'textfield',
            '#description' => t('Select the CSS selector of the container that all inner menus will be responsive. e.g. %example', array('%example' => '.navigation')),
            '#title' => t('responsive menu container selector'),
            '#default_value' => theme_get_setting('mobileMenu_selector'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_title'] = array(
            '#type' => 'textfield',
            '#description' => t('e.g. Select a page'),
            '#title' => t('First option text'),
            '#default_value' => theme_get_setting('mobileMenu_title'),
        );

        $form['alpha_settings']['glossy_lib_options']['mobileMenu']['mobileMenu_indent'] = array(
            '#type' => 'textfield',
            '#description' => t('e.g. !string', array('!string' => '&nbsp;&nbsp;&nbsp;')),
            '#title' => t('string for indenting nested items'),
            '#default_value' => theme_get_setting('mobileMenu_indent'),
        );

        // add submit handler
        $form['#submit'][] = 'glossy_mobileMenu_submit';
    }

    if ($lib_options) {
        $form['alpha_settings']['glossy_lib_options']['#type'] = 'fieldset';
        $form['alpha_settings']['glossy_lib_options']['#weight'] = -10;
        $form['alpha_settings']['glossy_lib_options']['#title'] = t('Libraries options');
    }
}

function glossy_mobileMenu_submit($form, &$form_state){
    // Add the mobileMenu options variables.
    drupal_add_js(array(
        'responsive_menu_options' => array(
            'selector' => $form_state['values']['mobileMenu_selector'],
            'title' => $form_state['values']['mobileMenu_title'],
            'indent' => $form_state['values']['mobileMenu_indent'],
        ),
    ), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

thanks in advance.

I think you problem is this: drupal_add_js needs to be called at runtime. It's not some kind of registry function that adds your js file for every future page request. In other words, your code only adds the js when the form is being submitted.

Instead of calling drupal_add_js in your submit handler, store a variable using variable_set() to indicate that the js must be added. In your template.php file you can use the _preprocess_page function to retrieve the setting using variable_get() and call drupal_add_js if needed.


Retrofitting CSS media queries into an existing project I've inherited a Drupal 6 project with a custom theme based off fusion. I would like to keep the current design for screen sizes above 800. Should I wrap existing CSS in @media screen and (min-width:800px)? Or, might I be able to use a "reset" technique under another media query?

How would you retro fit media queries into an existing site?

Got it. Basically we're moving ['all'] to ['(min-width: 720px)'] in the array structure. When it's loaded back in all of the stylesheets are effectively now wrapped into a media query.

function hook_preprocess_page(&$vars) {
  // get style sheet array
  $css = $vars['css'];

  // copy over the [all] to a media query key
  $css['(min-width: 720px)'] = $css['all'];

  // Remove the all
  unset($css['all']);

  $vars['styles'] = drupal_get_css($css);
 }

This leaves us the ability to define other style sheets in theme.info for other breakpoints.

stylesheets['(max-width: 480px)'][] = phone.css

Update, I turned this into a larger structure to let my content maintainers pick where the breakpoint should be.

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook_preprocess_page to move stylesheets from [all] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook_preprocess_page to move stylesheets from [all] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

/*
 * Implemntation of hook_preprocess_page
 *
 * Takes CSS files from the $vars['css']['all'] and moves them to $vars['css'][$breakpoint]. In effect, this moves all
 * existing stylesheets into a media query that you can specifiy. By default it's 480px.
 */
function wrapcss_preprocess_page(&$vars) {

  $css          = $vars['css'];
  $pixel_break  = (int) variable_get('wrapcss_breakpoint', '480');

  // Ensure that we have a value and that value is numeric
  if (isset($pixel_break) && is_numeric($pixel_break))
  {
    $breakpoint   = '(min-width: ' . $pixel_break . 'px)';
  }
  // If not, just default to 480
  else
  {
    $breakpoint   = '(min-width: 480px)';
  }

  // copy [all] to [breakpoint]
  $css["$breakpoint"] = $css['all'];

  // Remove stylesheets from [all]
  unset($css['all']);

  // Import back in
  $vars['styles'] = drupal_get_css($css);
}


How often does drupal core need updating? How often (on average) does drupal core need updating?

There is no "rule" but update as soon as it's released.

Usually Drupal core updates (bug fixes) are released once in a month but in case of a security vulnerability, there will be an immediate release.

I usually leave Update Status module enabled and configured to check for new releases every week.

Read more about Drupal core release cycle here. (This is about major Drupal releases, eg. 6, 7 and upcoming 8)


Terms in tree view - wrong order? I wanted to list the terms that a node has in a tree view. I've gotten that far that the list, sorted by the parent, is done, but the terms is in wrong order. Some terms becomes childterms to the wrong parent.

How do I fix that?

function my_module_cmp($a, $b) {

$a = (array) $a;

$b = (array) $b;

return strcmp($a['name'], $b['name']);

}
// A block with the current nodes linked categories in a tree view

function myfunction_category_block_contents($delta) {

// get nid from URL

$nid = arg(1);

$node = node_load($nid);

// get the terms using that nid

$terms = taxonomy_node_get_terms($node);

usort($terms, "hr_torget_cmp");

// create the head

$html = '
Kategorier
';

$html .= '
';

$i = 0;

foreach ($terms as $term){

    // the tid

    $tid = $term->tid;

    // the name

    $name = $term->name;

// DEBUG    $html .= $tid.'
';

    // get terms

    $parents = taxonomy_get_tree(10,$tid,NULL);

    // if the term is a parent
    if ($parents) {
        $html .= '
'.$name.'
';
    }
    // if it isnt
    else {
        $html .= '
';
        $html .= '
'.$name.'
';
        $html .= '
';
    }

$i++;

}

$html .= '
';

$html .= '';

return $html;

}

If I only get your goal correctly, I would suggest: for each node - get attached terms - for each term - get taxonomy_get_parents_all - reverse the array to have parent-to-child chain - form a list into a tree

Forming a tree could be yet another function with logic allowing to merge terms that share branches.


custom user profile pages I am working on a directory for a membership organization.

I am trying to create two distinct user pages. One for the user themselves (and admins) and one for the public to view. I would like these formatted differently, not just show different fields (which I could do simply with permissions, right?). And these public pages need to include Profile2 profile data.

I have tried editing the user-profile.tpl.php page. For example:

<div class="profile"<?php print $attributes; ?>>

  <?php print render($user_profile['field_first_name']); ?>
  <?php print render($user_profile['field_last_name']); ?>

</div>

...but this seems to have no effect on the user page at all, even when I clear all caches. (Perhaps because I'm using Display Suite to layout the user profile page? Does that override everything else?)

I also created a View:

Contextual Filter

User:Uid
Provide default value: Type = User ID from URL
Specify validation criteria: Validator=User

Relationship

User:Profile
Profile types (all 3 custom profile types chosen)

Path: /users/%user

But I'm still just getting the Display Suite layout. Is that doing the override?

DS uses it's own templates. Go to admin/config/people/accounts/display, then scroll to the bottom and DS will show you which templates you can use to overwrite the output.

In the example below there are 2 suggestions. Hope this helps you out.


drupal_write_record() cuts off data I have some pretty straightforward code that combines some string values together and then writes them to the db using drupal_write_record(), and it seems that the values are getting cut off for some reason when actually written to the database.

$keys_string = str_replace('|', '', $product->attribute_keys);
$values_string = str_replace('|', '', $product->attribute_values);

$keys = array_filter(explode('~', $keys_string));
$values = array_filter(explode('~', $values_string));

$description = '';
foreach ($keys as $key => $data) {
    $description .= $keys[$key] . ' : ' . $values[$key] . "\n";
}

$description .= "\n" . $product->group_text;
....

// Write record to database.
$table = 'ridethis_combined';
$record = new stdClass();
$record->title = $title;
$record->description = $description;
$record->short_description = $product->group_text;
$record->upc = $product->upc;
$record->sku = $product->vendor_item_id;
$record->cost = $price;
$record->price = $price;
$record->bti_quantity = $product->available;
$record->hawley_quantity = NULL;
$record->weight = NULL;
$record->manufacturer = $product->manufacturer_name;
$record->image = $image_url;
$record->meta_description = $product->group_text;
$record->meta_keyword = $product->group_text;
$record->meta_title = $title;

drupal_write_record($table, $record);

When stepping through the code in a debugger, I can see that prior to drupal_write_record, the full concatenated value is is stored in $record->description.  However, when I view the data in MySQL, only the concatenated values from $product->attribute_keys and $product->attribute_values is there; it's as if the $product->group_text data was never there.  The size of the db field is not an issue, since it has plenty of space for the content I'm writing to it.

Do you have any thought on what could be cutting this text off?

The function drupal_write_record() uses the database schema defined from the module. Check your hook_schema(), and see if it has the right length.

Post your hook_schema() implementation too, if this doesn't help.


Stop displaying content of subpaths for invalid URLs I have views set up, with following paths:
www.example.com/news
www.example.com/projects

If a user goes to www.example.com/projects/not-a-url or www.example.com/news/not/a/real/url it displays the content of /projects or /news accordingly.

Is this a core function? I would prefer it to either 404 or preferably redirect completely.

I have disabled Paths, Pathauto, Redirect, and Global Redirect but it still shows the content for the views when it should be a 404.

This can be achieved through views contextual filter.

As per wesleymusgrove's asnwer on drupal.org support
"Under "WHEN THE FILTER VALUE IS NOT IN THE URL", tell it to "Display all results for the specified field".  This allowed me to still see the list of all articles at the views path: example.com/articles

And under "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" check "Specify validation criteria", Validator "Content", Content type "Blog post" or "Article" - whatever content type it is.  This allowed me to still see a valid post at example.com/articles/my-page, but invalid links like example.com/articles/mypage respond with 404


Display content on a node which is referenced in another node I have a content type called 'style' and another one called 'style - description'. Unfortunately, it's necessary to split the two up. 'style' will be a sort of portal page, while 'style - description' contains further information about said style.

So, 'style - description' has an entity reference field that points to one of the 'style' nodes. I want to display content from a 'style - description' node on the 'style' node that has been referenced.

I've been trying to do this through a view with a relationship and a contextual filter, though I don't seem to be getting anywhere with that. Anyone any ideas?

I think you forgot to add a relationship in your views.

If you use  References module it works.(i know it'll be deprecated soon but for now it works well and save my life few times:))

In your content type add a field node reference to the article
In your views add a contextual filter [node:id] (add some validation criteria about your content type)
After add relationship

After you can hide the fields (don't forget in the setting formatter: rendered node)

After that you'll have the result you want.


How to set related products view contextual filter to get its value from current product category id I have build a Related Products view that supposed to show latest products which in the same category of the current product being viewed.

so I set a contextual filter for the category_id field, but couldn't find anyway to get the commerce product category id.

Drupal 8 / Commerce 2

I needed a block to display related products for the current viewed product by showing products from the same category.

To do that you can use the same steps used in the 'related article' tutorial.

but first you have to add the ability to extract term id from product page (like the way it is extracted from node page), so you have to modify

core\modules\taxonomy\src\Plugin\views\argument_default\Tid.php

like this

include this namespace:

use Drupal\commerce_product\Entity\ProductInterface;

look for:

    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }

replace with:

    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  } elseif (($product = $this->routeMatch->getParameter('commerce_product')) && $product instanceof ProductInterface) {
    $taxonomy = [];
    foreach ($product->getFieldDefinitions() as $field) {
      if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'taxonomy_term') {
        $taxonomy_terms = $product->{$field->getName()}->referencedEntities();
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        foreach ($taxonomy_terms as $taxonomy_term) {
          $taxonomy[$taxonomy_term->id()] = $taxonomy_term->bundle();
        }
      }
    }
    if (!empty($this->options['limit'])) {
      $tids = [];
      // filter by vocabulary
      foreach ($taxonomy as $tid => $vocab) {
        if (!empty($this->options['vids'][$vocab])) {
          $tids[] = $tid;
        }
      }
      return implode($this->options['anyall'], $tids);
    }
    // Return all tids.
    else {
      return implode($this->options['anyall'], array_keys($taxonomy));
    }
  }


How to print id of user whose profile I visit rather than id of  logged in user? Possible Duplicate:
  How to print id of user whose profile I visit rather than id of  logged in user?

I would like to print the id of the user on his profile page? How can I do it in Drupal 7. So far I could only print logged in user id..Any advice appreciated.

If you add this to the user-profile.tpl.php template, it will show the UID of user account being viewed.

<?php echo $account->uid;?>


Why does Drupal still convert links using a non-existant url alias pattern First I created an alias for an entity type like this:

project/[project_type]/[id]

which worked fine. After a while I decided to delete all aliases and created a new pattern, and bulk generated all aliases.

[project_type]/[id]

However, drupal still converts menu links (with internal path) as well as links in views (linkto content) using the old pattern project/[project_type]/[id]

I have cleared cache of the site,
I have cleared the views cache,
I have re-saved all entities, I have checked the alias list, the
aliases pattern that drupal uses is not present in the list, the new alias patterns are present.

In some way, drupal still uses this phantom-pattern which is cached somewhere apparently. It refuses to use the new alias pattern for converting links.

The new alias patterns do work for manually created links that correspond with the new pattern. Just the automatic conversion from internal path to alias path does not work, it does use the new alias but an already deleted alias.

Home » Administration » Configuration » Search and metadata » URL aliases (settings tab)

Update action
 Do nothing. Leave the old alias intact.
 Create a new alias. Leave the existing alias functioning.
 Create a new alias. Delete the old alias.


Drupal Theming 'Add Content' Page Is there any module that can help me theming the "add content" page?

I'm also looking for a way to allow the use of the "add content" menu only to the users who paid.

When I talk about "add content" page, I'm actually talking about the template used when creating for example a new article page.

I don't want to give access to other users to the following fields, and basically change the whole look of that page.

Menu settings
Revision information
URL path settings
Comment settings
Authoring information
Publishing options

I found and article explaining how to theme the node form here (http://batayneh.me/post/theming-node-forms-drupal-7). To solve the other part of your question - Only people who pay can use the "create content" you can create a new role and specify that only users with the new role can create content.


Drupal 7 "undefined function" fatal error; from FTP error One of the guys here deleted a module folder, in error, from drupal 7 site using FTP (I know but it was a mistake).

the Commerce module was deleted. Now can not access the site at all as we are getting a fatal error
Fatal error: Call to undefined function commerce_pricing_attributes_property_info_callback() in /var/www/sites/all/modules/contrib/entity/modules/field.info.inc on line 30

Anyone know how to correct it?
line 30 is
    $callback($info, $entity_type, $field, $instance, $field_type);

The function in question is below

function entity_metadata_field_entity_property_info() {
  $info = array();
  // Loop over all field instances and add them as property.
  foreach (field_info_fields() as $field_name => $field) {
    $field += array('bundles' => array());
    if ($field_type = field_info_field_types($field['type'])) {
      // Add in our default callback as the first one.
      $field_type += array('property_callbacks' => array());
      array_unshift($field_type['property_callbacks'], 'entity_metadata_field_default_property_callback');

      foreach ($field['bundles'] as $entity_type => $bundles) {
        foreach ($bundles as $bundle) {
          $instance = field_info_instance($entity_type, $field_name, $bundle);

          if ($instance && empty($instance['deleted'])) {
            foreach ($field_type['property_callbacks'] as $callback) {
              $callback($info, $entity_type, $field, $instance, $field_type);
            }
          }
        }
      }
    }
  }
  return $info;

If you have a backup this is the time to use it.

If not you should:

Put your Site in maintenance mode from command line: https://drupal.org/node/590468 or by using Drush: drush vset maintenance_mode 1
Replace the deleted module with exactly the same version in exactly the same place.
Run update.php either from drush: drush updb or command line: https://drupal.org/upgrade/running-update-php
All should be fine.

Please report back if this works or if another solution is found


JWPlayer in Drupal has container ID starting with Numeric Character Following up this question on SO, I am looking to change the default DIV container name that JWplayer provides to JWPlayer Div. The problem is that it starts with a numeric and that creates loading problems.

Is there a way, I can customize this JWPlayer ID ?

This is how it looks btw,

jwplayer('141ef7fe77391234fc105767808cc0a5').setup({"file":"my_video.mp4",
      "width":"838","height":"383","controlbar":"none",
      "modes":[{"type":"html5"},{"type":"flash","src":"http://path/jwplayer/player.swf"}]});

While you're at it, here is a quick solution to it.

Since this is a fix for Drupal JWPlayer Module, do the following:-

Go to jw_player module folder and open theme folder.
Open jw_player.tpl.php and add the following line on top (probably where PHP declaration starts).

$html_id = "myvideo". $html_id;

It kinda does the job but I am sure you guys have better solutions than this. Please feel free to comment.

Found a better solution

Don't do upper suggestion. Paste the following code in jw_player.module instead.

Find this line $variables['html_id'] = md5(rand()); (I guess line 308) and uncomment it before pasting the following code instead.

while(1) {

      $variables['html_id'] = md5(rand());
      if (ctype_alpha(substr($variables['html_id'], 0, 1))) {
        //echo "First Digit is Alphabet";
        break;
      }

  }

Thanks.


Is it possible to create multiple submission forms for one content type? I want to allow my users to submit different type of content using different types of templates (like in tumblr.com where you get a specific template/form for each content)

At first, I was thinking about creating custom content types, but this is a workaround because I dont really want to make different content types (all nodes are blog posts). I just want to create different forms for the content submission.

What is the proper "Drupal way" of doing that?

The proper way to do this in Drupal is using multiple content types, but if you want (for whatever reason) to still stick to your solution, you can write a custom module, and modify that one before rendering.

Here's an example using the default page content type and hiding the body. Use the Devel module, and dsm() to inspect the form.

function mymodule_menu() {
  $items['mymodule/add'] = array(
    'title'=> 'mymodule add',
    'description' => 'add content',
    'page callback'=>'mymodule_form',
    'access arguments' => array('add content'),
    'type'=>MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_form() {
    global $user;
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->type = 'page';
    node_object_prepare($node);

    module_load_include('inc', 'node', 'node.pages');
    $form = drupal_get_form("page_node_form", $node);
    hide($form['body']);
    dsm($form);
    return drupal_render($form);
}


debuging drush with xdebug I'm trying to debug a segmentation fault (11) from drush.
I have xdebug installed. The command it's giving the error is the pm-disable.

$ drush dis "module" --debug --verbose:
...

Calling hook drush_pm_disable [11.17 sec, 84.08 MB]                                                                                [debug]
Segmentation fault: 11

I think the issue is when it is calculating the dependencies, as I was also getting this on features/create, but disabling the dependencies checkbox in the features settings makes the features/create work well.

If the question is how to debug drush, you could use your IDE in the commands file you've got the command in pm.inc most probably, and use xdebug with the idkey, i.e.

xdebug.idekey="PHPSTORM";

See debuging drush with xdebug for more information

Also related: Can Xdebug be triggered by Drush commands?


Override buildForm() in another module I would like to override the buildForm() method of the Comment module in my custom module.

The method is defined in core/modules/comment/src/Form/CommentAdminOverview.php.

To achieve this, I've created myModuleName/src/Form/MyModuleNameCommentAdminOverview.php, whose first lines are the following.

namespace Drupal\myModuleName\Form;

use Drupal\comment\CommentInterface;
use Drupal\comment\Form\CommentAdminOverview;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

class myModuleNameCommentAdminOverview  extends CommentAdminOverview {
  public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') {
    // ...
  }
}

In myModuleName.info.yml I have these lines.

 dependencies:
  - comment:comment

My code is not working. What am I doing wrong?

I have read the following, but I don't understand what I'm doing wrong.

Need to override single Drupal 8 plugin function
Override or extend function of a contributed module
Overriding the function of a module in another module

These are the two routes for the original form class:

comment.routing.yml:

comment.admin:
  path: '/admin/content/comment'
  defaults:
    _title: 'Comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'new'
  requirements:
    _permission: 'administer comments'

comment.admin_approval:
  path: '/admin/content/comment/approval'
  defaults:
    _title: 'Unapproved comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'approval'
  requirements:
    _permission: 'administer comments'

You have to alter both routes like this

  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('comment.admin')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyForm');
    }
  }

in a RouteSubscriber.


How should I use hook_init()? I'm trying to disable the LabJS module from running on certain pages by following the maintainers instructions at Compatibility issue with Slickgrid.

This is what I have, so far. I tried putting it directly in the page and my themes template.php with the theme's name appended to the function name, but neither work.

/**
 * Disable LabJS on certain pages
 */
function versatile_hook_init() {
  if (current_path() == "private/members/search") {
    define('LABJS_DISABLE', TRUE);
  }
}

Can you help pointing me in the right direction?

hook_init() must be implemented in a custom module. In your example, the function mymodule_init() would go into a file named mymodule.module in a custom module named mymodule. You would also supply a simple mymodule.info file and put both files in the sites/sitename/modules/mymodule directory.

The custom module must be enabled like any other. Also, when creating a hook implementation, it is usually necessary to clear the cache for Drupal to recognize it. Finally, note that mymodule needs to be a unique name different from other modules or themes.

As a minor usage point, current_path() returns the current URL which may not be the current alias (e.g., node/5). Using drupal_get_path_alias() is recommended to always return a friendly alias.


Debugging with var_dump -> where does the output go? Me and a colleague had a D7 problem to handle, $_SESSION were being lost for anonymous users.  Because this is all happening on a staging server in a corporate environnment, devel module has been ripped out in preparation for the push to production. My colleague starts inserting var_dumps() in a  forms validate function, but the results don't show to screen.

He figures the validation is not being called, but I tell him about how Drupal suppresses output during rendering, I have experienced this many times.  Adding a die in the validate function confirmed that the function was in fact being executed,  except the question remains ->  why / how is output suppressed when echoing / var_dumping in functions?

Debugging with var_dump is probably not the most recommended or effective method, I just want to know what it is that prevents ouptput.

Usually the var_dump() works but gets hidden below the theme. This is because theme rendering comes last.

I could go into it more, but basically just install Devel and use dpm() for your variable dumps. It prints them in a Drupal-style message. You'll love it.


Using Modal Forms - Relative paths don't work I'm using the Modal Forms module to provide Modal Login and Register Forms across my site. Unfortunately it only seems to work if I access the link from a page which is one deep from the host folder. i.e.

Localhost/drupal/myform - Works
Localhost/drupal/node/31 - Doesn't Work

The error that throws says that

/drupal/node/modal_forms/ajax/login can't be found. Which is correct because the login form is kept at:

/drupal/modal_forms/ajax/login

It's adding the relative path on the end of the current page path.

A. Has anyone come across or solved this before?

IF NOT:

B. I think the code path is being pulled from hook_menu:

function modal_forms_menu() {
    $items['modal_forms/%ctools_js/login'] = array(
      'title' => 'Log in',
      'page callback' => 'modal_forms_login',
      'page arguments' => array(1),

I tried changing the link to  a direct path (not relative), but this doesn't do anything. What should I be trying to change to get the path to either load from /drupal/ each time or become direct?

This was due to how I implemented the modal forms. I'd put the following path:
"modal_forms/%ctools_js/login" in my menu links.

Changing this to an absolute rather than relative path solved the problem.


How to customize a field price in Drupal Commerce? I have a field price in my grid and want to customize it.

Below are 2 pictures that will explain the situation:

My question: How can I customize that field to looks like this:

Any suggestions?

You might want to try to customize the price via either of these contributed modules that can be used in combination with Drupal Commerce (quotes are from their project pages):

Drupal Commerce Extra Price Formatters (has a stable D7 version):

  This is an add-on module for Drupal Commerce that provides additional options when displaying the formatted price in your store.

Commerce Price FlexyFormatter (DEV version only).

  ... adds more options to format your products price.

Another option is to try what is described in the (accepted) answer to the question about "Additional classes for price based on price components", which includes a template.php tweak and states:

  ... you could theme the price components to add your own classes via a theme override.


Which statistics like page visitors or most visited pages are tracked automatically, or do I need extra modules for that? I'm using Drupal 7.22. In this version are there any "default" or simple site statistics that are tracked automatically? I am looking for the following statistics:

Page visitors
Most visited pages
Most clicks

Do I have to install a module to get statistics?

Everything in Drupal is provided by a module (core, contrib or custom), so one way or another you'll need to enable one to get extra functionality.

Drupal core comes with a Statistics module, you can enable that and see if it has what you want easily. If not, just search around for the different statistics modules there are out there, and install and try them.

If you stick to stable releases, you shouldn't have any trouble removing a module that you find doesn't do what you need, so there's no downside to trying.


how do i link to pdf file in drupal 7 I have a content type in which i created flie type field and text type field.I uploaded the pdf file and wrote 'link' to text field.
I have copied the link from uploaded file and with the use of ckeditor given the link to the text 'link'. Now when i click to text 'link' then the pdf file get opened. But the problem is if we look at the url it says 'www.example.com/sites/default/files/ADMISSION_FORM.pdf'. which is not correct and secured i think. it shud be somelike 'www.example.com/node/35/ADMISSION_FORM.pdf'.
  Can anyone who knows tell me the fact....??????Thank you!

That's not a problem, Drupal stores uploaded files under sites/default/files by default. There's no reason file paths for uploaded files would be similar to the URL of the node they're attached to.

www.example.com/sites/default/files/ADMISSION_FORM.pdf is the correct path if you haven't changed any of the default settings. I'm not sure why you've mentioned security, as that really doesn't come into it.


How to access to the user info on the search page? When I was trying to resolve this question: How to display the user picture on the search page? I found that in the THEME_preprocess_search_result function I can't access to the user information (I use the user search functionality) the only information about the searched users that I can use is the follow:

function THEME_preprocess_search_result(&$variables) {
    dpm($variables);
}

I can use the username and the email, I can extract from $variables['result']['title'] the username, but I think that the best way is access directly to the uid of the searched user. The problem is that I don't know how access to this information.

So, there is another way to obtain the uid of a searched user?

EDIT: I need the info of the system users (drupal users). User is not a content type.

Did you try implementing hook_preprocess_search_results (notice the plural search results)?

I haven't tested recently and I'm on a mobile right now. But I'm pretty sure that hook somehow had node objects (should be user objects in your case). Collect the UIDs, run a user_load_multiple and then add the user objects to each result for profit in hook_preprocess_search_results.

Update

I'm no longer on my mobile, so I could actually test this. It turns out that the user module does not feed the results set with the user account. I don't think Drupal 7 will receive these features anymore, so you'd have to patch the core user.module to achieve that.

Here is a patch if you are interested in going down that path: https://gist.github.com/Ayesh/b1892942b053dc746fb5


Calender System module and webform Does "Calender System" only works with "content types " ? The date popup options does not show while adding a "date" type field in to a webform node .

https://drupal.org/project/calendar_systems
https://drupal.org/project/webform

Date Field properties in a content type .

Date field properties in a webform node .

Any clue ?
thanks :)

The module info page at https://drupal.org/project/calendar_systems claims it has webforms support. 4th last item. So I suppose it does not only work for content types.


How to remove subdir from base URL after installing site with Composer on a shared host? I've managed to install drupal 8 using composer and following script:

composer create-project drupal-composer/drupal-project:8.x-dev my_site_name_dir --stability dev --no-interaction

I decided to use composer since it seems to be the new way and you get all the dependencies with it.

But the structure is different then installing drupal by downloading it to the server. And that's my problem.

I'm using shared hosting and before composer everything landed in the folder public_html. But with composer there's a folder called web inside public_html that holds drupal itself (or at least it seems that way to me). So instead of having a url like www.mydomain.com I end up with www.mydomain.com/web to reach the site.

My question is how do I do to hide /web from the url? Or do I do something when installing via composer?

I've done a temporary solution that hides /web just from the frontpage. Had to create a new .htaccess in public_html which included following:

RewriteRule ^$ web/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /$1 [L]

But as soon as you click on a different page the /web is there again.

Any hints or of course answers are most welcome.

Thanks //Tobias

Me and my collegue managed to find a working solution.

In our public_html folder we created a .htacess file with the following lines.

RewriteRule ^$ web/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ web/$1 [L]

We edited the .htaccess file in ~user/public_html/web.

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
RewriteBase /web

In the ~/user/public_html/web/sites/default/settings.php file, we added this code at the bottom.

if (isset($GLOBALS['request']) and
'/web/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}

We also changed trusted_host_patterns setting as well.

# will allow the site to run off of all variants of example.com and
# example.org, with all the sub-domains included.

$settings['trusted_host_patterns'] = array(
  '^DOMAIN.com$',
  '^.+.DOMAIN.com$',
  '^DOMAIN.com/web$',
  '^.+.DOMAIN.com/web$',
);

As I said, this is most likely not the correct way to do it, but it worked for us.


How to measure user growth over time? I have a client that is looking to measure how their drupal user accounts grow over time.

I currently have the http://drupal.org/project/chart module with the System Charts sub module enabled and this does provide a nice pie graph of the users as the system currently stands.

Has anyone found a solution for this? Integration with the charting API would be nice too ;)

You can use select count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') as month from users group by MONTH(FROM_UNIXTIME(created));. This uses the created field of the users table.

Edit:

In your code this should look something like

$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') AS month
                    FROM {users}
                    GROUP BY MONTH(FROM_UNIXTIME(created))");

This will return all new usercreations grouped by month. You could use other Date/Time Functions like DAY. But be carfull with the groups. The example above only works correct if you track the data of one year (because it does not group by year). Here is a more complex example:

$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%d-%m-%Y') AS month
                    FROM {users}
                    GROUP BY YEAR(FROM_UNIXTIME(created)),
                             MONTH(FROM_UNIXTIME(created)),
                             DAY(FROM_UNIXTIME(created))");

I'm not entirely sure if there is a better solution to this. I can't help with the Integration into the charting API as I never used it.


How to not print a Menu Block if a Menu Block exists I've been using a whitelist/blacklist PHP script to control the display of 2 different menu blocks, and its becoming bloated.

Menu_block 1 is the primary menu.
Menu_block 2 is the supplementary menu.

I'm trying set the block visibility for Menu_block 1 via PHP - IF Menu_block 2 exists return FALSE, else return TRUE.
Print Menu_block 1 unless Menu_block 2 exists.

PHP visibility for Menu_block 1

<?php
  if(isset($block = module_exists('menu_block', 'block', '2')) {
    return FALSE;
  }
  return TRUE;
?>

I'm not even sure if this is actually possible.

I had the same issue and resolved it by removing one of the blocks by calling  template_preprocess_page() in a custom module or in your theme's template.php. What I do is check to see if both blocks exist on the page, and if so, call unset() on the block I want to remove:

function mymodule_preprocess_page(&$variables) {
//Remove secondary menu block if tertiary menu block is on the page
if(!empty($variables['page']['sidebar_first']['menu_block_tertiary']) && !empty($variables['page']['sidebar_first']['menu_block_secondary'])) {
    unset($variables['page']['sidebar_first']['menu_block_secondary']);
}

The indexes in your $variables array will most likely be different. On my site, 'sidebar_first' is the region in my theme where my menu blocks (menu_block_primary and menu_block_secondary) are placed. If you're not sure what your variables are, you can use a call to dpm($variables) to find them (Make sure you you have the devel module enabled) like so:

function mymodule_preprocess_page(&$variables) {
  dpm($variables);
}


Editing a Field Collection element in a custom module In a custom module, I'd like to to edit a Field Collection element. The element is linked to a taxonomy but I think the code would look quite similar if it was to a content type.

I've read a lot of documentation, source code, forum entries and Drupal articles, but I'm stuck.

In my hook_form() implementation, I've got:

$field_collection_item = entity_create('field_collection_item', array('field_name' => 'my_fc_field_name'));
// In a content type, use ('node', $node) instead
$field_collection_item->setHostEntity('taxonomy_term', $term);

// Not sure if those three lines are usefull
$field_node_example_values = field_get_items('taxonomy_term', $term, 'my_fc_field_name');
$field_node_example_ids = field_collection_field_item_to_ids($field_node_example_values);
$field_node_example_fc_items = field_collection_item_load_multiple($field_node_example_ids);

// Not sure if this line is correct
$form_state['field']['my_fc_field_name'] = $field_node_example_fc_items;

/* All examples below produce the same result : only one instance of the FC form appears, with no existing values and no buttons */

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

// 1/
$form = field_collection_item_form($form, $form_state, $field_collection_item);

// OR

// 2/
$form['my_form_entry'] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['my_form_entry'], $form_state);

// OR

// 3/
$output = drupal_get_form('field_collection_item_form', $field_collection_item);
$form['my_form_entry'] = $output;

So, my goal would be to get the same result as "out of the box" FC edit form, a nice fieldset with as many instances as exist, with Remove and Add buttons.

To be clear, I can see this type of form when I edit the taxonomy term, but I'd like to do it in a custom module.

I've look into the FC module, specifically the field_collection_field_attach_form and field_collection_field_widget_form functions, but I'm not sure how I could use them.

Some useful articles and forum entries:

http://www.cocomore.com/blog/field-collections-exposed
https://www.drupal.org/node/1842304
How to pre-populate multiple "field collection" fields in node form
https://stackoverflow.com/questions/13364905/need-an-example-on-attaching-a-field-collection-to-a-drupal-form-drupal-7
https://stackoverflow.com/questions/18447025/adding-drupal-field-collection-element-to-a-custom-form
https://www.drupal.org/node/1337804#comment-6326678

Strictly speaking on how to edit a field collection entity, once you have the field collection ID (you would get it from a field on your host entity, for example), you can load the collection using entity_metadata_wrapper, change it and them save it back.

$collection = entity_metadata_wrapper('field_collection_item', $collection_id);
// Do your change
// ...
$collection->save();


"Undefined index: link path in menu_link_save() (line 3113 of /includes/menu.inc)" I have a new Drupal installation; when I installed my first module, I got the following error:

  Undefined index: link path in menu_link_save() (line 3113 of /includes/menu.inc). error.

I have seen the line 3113 of menu.inc but I don't understand what happened. The error happen every time I install a custom module.

Does anybody know what the problem is?

This is the code I am using.

function froga_menu() {
  $items = array();
  $items['anunciantes'] = array(
    'title' => 'Editar perfil',
    'description' => 'Editar perfil - Anunciante',
    // 'parent' => array('anunciantes'),
    // 'page callback' => 'drupal_get_form',
    // 'page arguments' => array('form_editar_perfil'),
    'access callback' => TRUE,
    'type' => 'MENU_NORMAL_ITEM',
    'menu_name' => 'main-menu',
    'customized' => 1, // Must be 1 in order to not dispaly the link in any language
    'language'  => 'es', // language is required in order to make the item translatable
  );

  $mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
  $ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it

  return $items;
}

You are using the correct function (menu_link_save()), but you are passing it the wrong arguments, and you are calling it from the wrong hook.

The array key you can pass in &$item are described in the function documentation; the ones marked as (required) are required, and you need to pass them.

  link_path: (required) The path of the menu item, which should be normalized first by calling drupal_get_normal_path() on it.
  link_title: (required) Title to appear in menu for the link.
  menu_name: (optional) The machine name of the menu for the link. Defaults to 'navigation'.
  weight: (optional) Integer to determine position in menu. Default is 0.
  expanded: (optional) Boolean that determines if the item is expanded.
  options: (optional) An array of options, see l() for more.
  mlid: (optional) Menu link identifier, the primary integer key for each menu link. Can be set to an existing value, or to 0 or NULL to insert a new link.
  plid: (optional) The mlid of the parent.
  router_path: (optional) The path of the relevant router item.

hook_menu() is used to tell Drupal which menu paths the module is using, not for saving a menu link when the module is installed. For that there is hook_install() or, in alternative, hook_enable() which is called every time the module is enabled, even after the module is installed; in the case you use the latter, the code needs also to check the menu link is not already present. As side note, hook_enable() is not used from Drupal 8.


Performance: is preferable to use Rules or node_presave/node_save/other hook ? we know that via hook_* we can make everything, but my question is about the use of Rules vs hook_. At high level performance programming  hook_ is better that rules, but if we consider a normal level performance ?

In a site where you have installed rules (like a commerce) is better to use hook_* or I can create a rule that exec an PHP function? In the first way (hook_*) I need to remember in which module an FooBar thing happen (say does something before node's saving, hook_node_presave) but I have max performance; second way is  via Rules module where I have all rules in one path and I can crete a Rules that is "called" when "condition" "before saving new node of node type XYZ" appair.

Which is better in a normal site ? Or in a site more than normal ?

M.

PS: sorry for my bad english.

In practice, it is far easier to debug a hook than a rule that includes a PHP function.  So, not only are hooks faster, they are easier to maintain and less likely to present security risks.

You do not need to remember "in which module foo happens" if you put all your hooks in a single custom module for the site.  Unless you have an extremely large number of tweaks, using a single module (and version controlling it!) is probably the easiest way to do this.

Regardless of the size of the site, if you want to write custom PHP, you should use a custom module, not rules.


Building a Web App using Drupal I'm looking at building a Web Application on the Drupal framework. Does anyone know of an existing drupal profile installation that has this viewpoint?

For example, I've been building features for Open Atrium and I'm familiar with some of the concepts and modules this contains. However, Open Atrium does not really satisfy the concept of clients having a profile and creating projects with subscriptions.

So in essence, I'm looking for a package similar to Open Atrium, but satisfies a web application development. Think of it more as building web tools like Basecamp or Freebooks, but using a base platform to get there.

Any ideas?

Creating your own install profile doesn't need to be a big project in itself, especially for Drupal 7, that has simplified making install profiles. Features also helps a lot, making it easy to save settings, content types, views etc in a module.

All you really need to do in the install profile is to

Enable modules
Save settings
Enable blocks (maybe)
Create content (maybe)

I suggest that you build your own install profile that fits your needs, instead of trying to find one. You could start out with how it's done in Open Atrium, and just edit it to fit your needs.


Searching through nodes and outputting the details on gmap I have a gmap that is displaying all the information of real estate listings that I put in.

Now I want a text search that basically searches through the nodes and outputs the information in the same map and filter it basically.

So if I search for 2 bedroom in Boston in a simple text search. (Hopefully the search will have auto complete)

It will only show me the two bedrooms in boston I selected. (Boston is a node type) not part of gmap.

Basically I need a text search to filter the map listings which I dropped on it.

I don't want spatial searching.

Help!

Does it have to be a search box? If not, use GMAP's Views integration and create exposed filters for the fields you want to filter by. Instead of a search box, use a dropdown for bedrooms, city, and whatever other filterable fields you include.

Using a text input/search box may cause usability issues. You can't account for the variety of keywords a user may input, nor will you be able to filter appropriately for unknown terms. Giving the user defined filters (which they are familiar with) will be much easier for them to understand and use.

Better Exposed Filters may come in handy here depending on what type of filters you use -> http://drupal.org/project/better_exposed_filters


Static page on main domain and Drupal on subdomain In my installation, I'm utilizing Drupal's awesome capability to run on multiple subdomains using one code base. Each subdomain has its own database. So, I only need to have a static page on the main domain (root) but Drupal running on subdomains.

How do I do that? I know that I could modify the .htaccess file to make it look up for index.html first, but that would affect the subdomains.

Thanks.

You can solve this one using a RewriteRule in your .htaccess file. What you basically will do is check if the request is destined for your main domain (both with and without the www), and if so, tell Apache to go fetch the files from somewhere else. All this is done on the server-side, so the browser doesn't see a thing about this.

For the example below, I assume that Drupal is installed in /var/www. If it's installed somewhere else, update all occurrences of /var/www below.

Create a new directory /var/www/static_main_domain. This directory will contain the static content of your main domain.
Add the following lines of code to your .htaccess file (preferably immediately behind   the RewriteEngine On):

      # Check if the request is destined for www.yourdomain.com OR
      RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC,OR]
      # Check if the request is destined for yourdomain.com
      RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
      # If so, go get the requested files from the static_main_domain subdirectory.
      RewriteRule ^(.*)$ static_main_domain/$1 [L,QSA]

For more info, check this: http://httpd.apache.org/docs/current/mod/mod_rewrite.html


Recreate search api tables When use search_api, module automatic create more table:
search_api_db_article_title,search_api_db_article_body,...
But I accidentally lost these tables ==> search_api can't index. How to get back to the table?
I run cron, updatedb but nothing happen :(

Two ways are avaliable:

Recreate from nightly or hourly backup. This is preferred way to solve issues like yours.
Disable module, uninstall it, and then enable it again. Will be as good as new. To keep configuration:

Export configuration search index to Features.
Disable modules search_api, search_api_db,...
Enable modules again => tables will be recreate.


Is it required to run update.php? I have updated the require Drupal core files and folders, but I didn't run update.php.

Is it required to run update.php? If not, which types of issues I will face in future?

Running update.php is only required if there are new implementations of hook_update_N() done from a module, which the hook used when:

The schema for a database table is changed
A database table is created, deleted, or renamed
The content of a database table is altered
A persistent variable is added, removed, changed, or renamed

If the release notes for the version you installed say it is necessary to run update.php, or you check the content of every .install file and notice there are new implementations of hook_update_N(), then you need to run update.php.
If you don't do it, modules will start not to work, and you could get database error messages (for example, about a database table not existing, or a table field not being present).

If the release notes for the release you installed say it is not necessary to run update.php, or you check the content of every .install file and notice there aren't new implementations of hook_update_N(), then you don't need to run update.php.
If you don't run update.php, there isn't any issue, for this update, but it's not said you can continue avoiding to run update.php for future updates. For each update, you would need to check what the release notes say about or the code in .install files.

What I said holds true also for third-party modules, not just for Drupal core.

If you want to avoid reading the release notes for every installed modules, which could also not report if running update.php is necessary or not, or check the code in .install files, which would also require you to notice if there are new hook_update_N() implementations, you just run update.php after updating core or any third-party module.

I normally run update.php every time I update core or modules. If there are update hooks that need to run, they will run. If there isn't any update hook that needs to run, update.php will end faster and show me a page with a link to the front page and the administrative pages.


Bringing modules into project as git submodules - .info file doesn't have version info I'm adding modules into my git-enabled Drupal project as git submodules. Things seem to work fine except that when I bring in a git submodule and use the version I want, by doing a 'git checkout 6.x-1.1' for example, the resulting .info file doesn't have the following information (with this example taken from zen):

; Information added by drupal.org packaging script on 2011-04-05
version = "6.x-2.1"
core = "6.x"
project = "zen"
datestamp = "1302017816"

Whatever is added by this drupal.org packaging script is apparently added when the archive is prepared for download on drupal.org, and isn't added when the commit is tagged with a certain version in git. Now will these modules even be considered valid by Drupal when I try to enable it? And if so, I'm sure this would screw up the update process because update won't know what versions of existing modules it's comparing against.

So how can I fix this? I must have missed something, because clearly there's no way every git user can be expected to manually add in this metadata for every module every time they update.

Check out the Git deploy project.

It exposes the version information by looking at the git information. I am not 100% if it supports git submodules, but it's worth a try.


Insert date programatically in custom module I am programatically saving values from an array $customer into a content type. The below code works fine and populates the content type customer_profile except for the field date of birth. This field is of type date and date type is set as date only (not date and time). The value in $customer['dob'] is '19/12/1938'. How do I insert this value?

$node_data['type'] = 'customer_profile';
$node_data['title'] = $customer['First Name'].' '.$customer['Last Name'];
$node_data['field_customer_gender']['value'] = $customer['Gender'];
$node_data['field_date_of_birth']['value'] = $customer['dob'];
$node = Node::create($node_data);
$node->setPublished(TRUE);
$node->save();

I think correct format is 'yyyy-mm-dd', try to insert '1938-12-19'


How to translate the user profile page in commerce kickstart Hello,
I'm using commerce kicksart in my website, I use french as source language instead of english, I translated many words in the user profile page, but I can't translate or edit some titles:

-HELLO
-PRIMARY SHIPPING ADDRESS
-PRIMARY BILLING ADDRESS
-RECENT ORDERS

I didn't find them in the translate interface page admin/config/regional/translate/translate, also I didn't find any view or block to edit them.

How I can translate or edit them without touch the tpl file?

Thanks

The solution described in issue #1937982 has been used to solve an issue similar to yours. That issue includes a .PO file to handle at least these strings:

Primary billing address
Primary shipping address

If that would work in your case also, you can probably use the same solution by adding 2 similar lines for these 2 other strings (you may have to verify if it is case sensitive or not):

HELLO
RECENT ORDERS


My pager disappears when I use hook_views_pre_execute I need to modify a query of one view. So, I use the hook_views_pre_execute.
The query is modified but the pager disappears.
My question is why? Do I need to add more lines to hook to use to display the pager?

Code:

function view_format_render_views_pre_execute(&$view) {

    if ($view->name == 'view_probe' && $view->display['block_1']->display_title =='List of categories') {
        $tid = $view->args[0];
        $tids = array_keys(taxonomy_get_children($tid));
        $tids=implode(', ',$tids);

         $search = "node_data_field_formatos_colecc.field_formatos_colecc_value = %d";
            $search_new = "node_data_field_formatos_colecc.field_formatos_colecc_value IN ( ".$tids." )";

            $query = &$view->build_info['query'];
            $query = str_ireplace($search, $search_new, $query);

            $view->build_info['query'] = $query;

        if (isset($tid) && isset($arguments)) {

                $query = str_ireplace($search_new, '', $query);
                $view->build_info['query'] = $query;
        }
    }
}

if query exec is too long (for pagination views must return total count of rows at all pages and correspond it to rows per page ) pagination not returned by views.

nid of nodes returns from one table in database and this queries is very simple & fast

another fields (cck, ubercart, stock) returned from another db tables and it can be too long. for this views just returns first page to prevent timeout


How to link the parent of a Nice Menu to nowhere? In order to make a Nice Menu, I created a menu like this:

My Menu
   - First link
   - Second link
   - Third link

The menu works perfectly fine, but I also had to fill in a link for the 'My Menu' (I've set it to the frontpage). However, I'd like the parent link to be linked to nowhere. How can I do that?

This is the relevant code for the menu's parent:

    My Menu

Note: At first, I couldn't get the code from the accepted answer working, because I forgot to load my theme's MYTHEME.js file. After reading this, I learned that one can do that by adding scripts[] = MYTHEME.js to the MYTHEME.info file.

Yes you can do that using the Special menu items module:

Special menu items is a Drupal module that provides placeholder and separator menu items.
A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it


Accessing files from a local cdn I know that drupal comes along with 2 default stream-wrappers(public and private).
What I want to achieve is to have my images placed in an another server, where they can be accessed by a url similar to http://cdn.mysite.com/image/etc.png.

https://www.drupal.org/project/remote_stream_wrapper allows the use of http, and https as stream wrappers. How am I suppose to use this programmatically?

When a file is loaded "public://" is replaced by the actual public URL, how does this work with the above module? Could you provide any other info on how to tackle this issue?

I use Storage API for this sort of thing with S3 and cloudfront. I think it supports custom sub domains. It handles all the replication (copying,moving, deleting) itself. I have had a couple of minor compatibility issues with other contrib modules during upgrades.

https://www.drupal.org/project/storage_api


Create a 'universal' reusable View? Is it possible to create a View that essentially a skeleton, and can be reused over and over again (on different parts of the site) simply using different input i.e. something like different node ID's?

I want to be able to create a new Views Slideshow Gallery (The gallery is a jQuery slider) just by adding content to my custom content type, Photos. The way I have it set up now, I have to create a new Photos content type, keep it not published, and then plug that Node ID to a brand new View using the Views Slideshow formatting. As you can imagine this is quite a laborious task.

This question has applications outside my specific uses. The core question is, can you create a (dynamic?) view that will automatically take different inputs for use in a content type?

What you may be looking for is "Contextual Filters"

Here's a good tutorial I have that explains how to implement them:

http://www.youtube.com/watch?v=lJFMTDuaxy8

There's also a way to call a View directly from a template, which can be pretty useful in some cases:

views_embed_view("slideshow_gallery", "page", array() );


Multistep ajax form, rebuild form and replace contents with the current step I have a multistep form.
In the first step i have an AJAX submit callback that updates my &$step in $form_state and should return the next step of the form in the same page (replace contents of the form with the form elements in the second step) e.g.

  <?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_submit',
          ),
         '#executes_submit_callback' => TRUE,
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function form_first_submit($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';

  $form = drupal_rebuild_form('my_form_builder', $form_state, $form);
  $commands[] = ajax_command_replace('#main-content', render($content));
  // return  ajax
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

So, naturally after the first submit, i should be able to rebuild my form and return to the #main-content the form elements defined for step 2.
Why this doesn't work?I see the code passes on the right places and rebuilds and prepares the form for rendering.

I tried with drupal_build, drupal_retrieve_form and im getting nowhere.

If i drupal_get_form('another_form_id') it will work as expected.

Where is my error?

You dont' have to call drupal_get_form explicitly, instead mark form to rebuild.

In your ajax powerd element define two attributes: #submit, and #ajax.

#submit references the function that makes the action related to the submission  (in your case changing the step value to 2 in form state). Also, set $form_state['rebuild'] to TRUE.

#ajax, where you set the ajax parameters and the PHP function that will return the result form the built form (in this case, the rebuilt one). When this fucntion is called form is build (or rebuilt) and you only have to return the form part you need.

Take into account that in the #ajax attribute you can set the HTMl element that will be replaced by the answer, so you don't need to use ajax commands.

<?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_ajax_callback',
          ),
         '#executes_submit_callback' => TRUE,
         '#submit' => array('my_form_builder_callback'),
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function my_form_builder_callback($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';
     $form_state['rebuild'] = TRUE;
  }

  function form_first_ajax_callback($form, &$form_state) {

  $commands[] = ajax_command_replace('#main-content', render(form['element_to_return']));
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

Example uses the ajax commands aproach.

Check the Form API internal workflow illustration.


enable/disable node_save programmatically I created a custom module that can save nodes.

I want a checkbox that determines whether the node will be saved or not.

This is the node_save program :

     global $user;

// IF (FORM_STATE [VALUE][CHECKBOX] == Checked ! ) {

        $node = new stdClass();
        $node->type = "services";
        node_object_prepare($node);
        $node->language = 'fr'; // Or e.g. 'en' if locale is enabled
        $node->uid = $user->uid;
        $node->status = 1; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 1; // 0 = comments disabled, 1 = read only, 2 = read/write
        $node->title = $form_state['values']['produit_de_client'];

        $node->field_produit_dc['und'][0]['value'] = $produit;
          $node->field_espace_dediee_categories[LANGUAGE_NONE][0]['tid']=$form_state['values']['espace_dediee'];

        $node->body['und'][0]['value'] =$form_state['values']['text_service'];
        $node->body['und'][0]['format'] ='full_html';

        $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
     foreach($aaz as $of)
       {

       $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;

       }

        $node->field_id_prod['und'][0]['value'] = $produit;
            $file = file_load($form_state['values']['image_dc']);
            $file->status = FILE_STATUS_PERMANENT;

            $uploaded = file_save($file);
            $aaa = file_create_url($file->uri);
        $node->field_produit_dc['und'][0]['value'] = $file->fid;
        $url = $file->uri;

        $node->field_image_serv[LANGUAGE_NONE][0]['fid'] = $file->fid;

        node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().

        $node = node_submit($node); // Prepare node for saving
        node_save($node);

//ELSE NO NODE WILL BE SAVED

In a nutshell:

function mymodule_form_submit($form, &$form_state) {
  if ($form_state['values']['mycheckbox'] == 1) {
    // node code...
    node_save($node);
    drupal_set_message('Node saved.');
    $form_state['redirect'] = 'some/path';
  }
}

Or you could just require the checkbox in the form:

$form['mycheckbox'] = [
  // props
  '#required' => TRUE,
];

If the checkbox is required, the form can't be submitted, and thus the node won't be created.

I would probably require the field(s) instead of silently do nothing on submit if they did not check it. That way the form submit won't get hit and the user won't have to re-enter all of the information.


Does the Context module check block visibility settings? I am using Drupal 7.14 and the Context module (7.x-3.0-beta4).

I set block visibility settings and the Context module doesn't seems to be checking them before rendering. Only context conditions are validated before rendering a block.

I would like to use PHP code as visibility conditions to render a block, but Context module is not respecting block visibility settings.

Is it a bug? Or context module is designed to respect only Context Visibility settings but not block visibility settings that are enabled in a particular context.

Any idea ?

Context module ignores Block visibility settings

The Context module does not check (take into account) the "Block visibility settings". If you want that to be the case, then you need to also use the Context Respect module. Some details about this module, from its project page:

  Extends the Context module by making it respect default block settings.

  This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

Alternative to Context module

Have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.

By using this module as an alternative, you'd only have to create a Rules Component with Rules Conditions that could be identical to the "PHP code" as in your question. However, if you can, you should try to avoid such PHP code if you have other Rules Conditions available that could be used as an alternative to such PHP code.


Automate clear of mysql database in drush site install Is is possible to automate clearing the database when I run site install?
e.g. here is my drush command:

drush si geoslate --db-url='mysql://root:root@localhost/geo_test' --site-name=Geoslate

But the db has to be cleared first. Can I automate this process?

Chapabu is correct, but if you're using drush 5.7, this is unnecessary with site-install. If there's an existing db, drush will warn you it will drop all tables in the existing database.

For example:

drush dl drupal --drupal-project-rename=test
cd test
% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test
You are about to create a sites/default/files directory and create a sites/default/settings.php file and DROP all tables in your 'test' database. Do you want to continue? (y/n): y
No tables to drop.                                                                          [ok]
Starting Drupal installation. This takes a few seconds ...                                  [ok]
Installation complete.  User name: admin  User password: 6SkT989sPX

So let's rerun the site-install command over the now existing "test" directory

% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test         130 ↵
You are about to DROP all tables in your 'test' database. Do you want to continue? (y/n):


How to expose an entity reference field as a filter on a custom entity in Views? I have a field on a custom entity that is an entity reference to a node. However when I select this field as a filter and expose it, it just acts like a numeric field instead of a reference field (only option is less than, greater than, equal to... etc).

How can I make this field act properly? I just want a drop down of options (only 32 nodes ever) to make filtering easy.

I think there are many solutions but I resolved the same problem in the hook
hook_form_alter()
altering the form element type from textfield to select and populate the #option attribute:

  $options = _getOptions();
  $form['your_field'] = [
    '#type' => 'select',
    '#options' => $options,
  ];

Other solutions are appreciated.


Modifying contribution modules safely and conventionally I want to modify a contrib module in such a way that I don't lose my customizations whenever I update the module. Below is my git diff from the changes I want to make. I use git and drush.

What I am wondering is, how can I add something to my own custom help module that will have the same affect?

The change I had made was to disable the function in this Facebook connect module that grabs the user's picture and adds it to the profile.

+// Disable facebook profile picture integration (CH)
     // If user pictures are enabled, try to get the profile picture from FB.
-    if (variable_get('user_pictures', 0)) {
-      $fid = simple_fb_connect_get_fb_profile_pic($fb_session);
-      if ($fid) {
-        $fields['picture'] = $fid;
-      }
-    }
+//    if (variable_get('user_pictures', 0)) {
+//      $fid = simple_fb_connect_get_fb_profile_pic($fb_session);
+//      if ($fid) {
+//        $fields['picture'] = $fid;
+//      }
+//    }

You should not modify the contrib module directly and save it. You should create a patch file and use that patch file in the project. This way every time if there is any update in that module, you run drush command and your changed will be safely applied. Please refer this page to create a patch file if you don't know How to create Drupal patch with git.


Display message or block when View Page is null or empty I have a Content Type : Events and i have created 3 events they are currently published and displayed in Page ie Display as View.
If there are no published Events then it should display a custom message as "No Events" or a "block".

I am trying to work on views with null values but i could not get it. Is there any thing like this.

On your configuration Views in the right you've "Advanced" zone, if you click on it you will see more options and "No results behavior" that will let you do what you want when the view doesn't return results.


Drupal chat slowdown my application I am using Drupalchat for my application. The issue is that my application getting very much slow down after put this chat system. I think the problem will be due to Ajax, it's keep on polling to the server for frequently to check the chat messages(incoming or outgoing). How to fix this issue to fasten my application ?

Also I am curious about how the facebook and gmail chat systems are working in general?

AJAX chats are pretty resource hungry by nature when running on Apache, so there are no easy configuration switches that will instantly give you better performance, I'm afraid.

The big difference between chat implementations is that GMail and Facebook uses a different backend, more suitable for AJAX polling / push. The node.js backend for Drupalchat might be able to help you in that regard. If I were writing my own chat from scratch, I'd probably try out http://www.ape-project.org/ which seems to be pretty good featurewise.


Two 'add to cart' buttons using different attributes I am using Ubercart 3 on Drupal 7 for my website.

How am I able to have two "Add to cart" button on a product page that use two different attributes? So for example I can have:

(Buy the large version)
(Buy the small version)

Those two buttons match my attributes that I have set in the back, so customers can click on one of those and add the product to the cart directly.

A. Enable Ubercart Cart Links (part of core).
B. Add necessary attributes and make sure you have a default attribute set.

With UC cart links, you can perform the add-to-cart functionality with many different AND DYNAMIC arguments. Without making a new add-to-cart button using Form API or complicated setups.

You can,

Add any quantity of any number of products to the customer's cart, with specific attributes and options for each added product, if applicable.
Display a custom message to the user.
Track the click for display on a store report.
Empty the customer's shopping cart.
Redirect to any page on the site.

Basically you make a URL that will, when opened, adds given items with given parameters to the current user's cart.

cart/add/e-p123_a1o2

See above link. When opened, it will first empty the cart (e), adds product/node ID 123 to the cart(p123) with attribute of ID 1 (a1) and that attribute's option ID 2 (o2).

You can see a very good help instructions on help section of uc_cart_links module's admin page (admin/help/uc_cart_links) .

You can build the URLs using Drupal's url() or l() functions.

Put these snippets in your node.tpl.php file of the product node type (node--product.tpl.php) where you want to display buttons.

<?php
 print l(
      t('Buy the large version'),
      'cart/add/'.$node->id.'_a101'
    );
  ?>

<?php
 print l(
      t('Buy the small version'),
      'cart/add/'.$node->id.'_a102'
    );
?>

if you are putting this code in a block or anywhere other than node.tpl.php or variants, change $node->nid to arg(1) . This arg(1) thing will only work if the button is being displayed in full content page.
if you are placing these buttons in a View, replace $node->nid with the appropriate node ID by adding a node: ID field and tokens.
If you want to see attribute and option IDs, go to attributes page and you will see the attribute/option ID which is a numeric one.

Good luck!


How do I add a new condition in Rules 2? I can't get my new Rules' condition to work.

I wrote the (simple) code below in includes/MYMODULE.rules.inc, and nothing appears in the condition list.

/**
 * Implementation of hook_rules_condition_info().
 */
function MYMODULE_rules_condition_info() {
    return array(
        'MYMODULE_rules_condition_MYCONDITION' => array(
            'label' => t('My label'),
            'group' => 'My very own group',
        )
    );
}

/**
 * Condition
 */
function MYMODULE_rules_condition_MYCONDITION() {
    // logic
    return TRUE;
}

I have already tried to flush the Drupal cache (as it seems to me that Rules uses a cache system).

Read Rules 2.x / Drupal 7; I think you can find what you want, there.


Need to alter response headers for error pages We have Cloudflare sitting in front of our Drupal sites - and in order to take advantage of their "AlwaysOnline" feature - we need to alter the response code sent in the event of an error.

I want to cater for when the database is unavailable - as this can sometimes happen when upgrading the MySQL server.

The only way I've found so far is to hack the errors.inc file:

if ($fatal) {
    drupal_add_http_header('Status', '504 Service unavailable (with message)');
  }

Is there a more elegant way to achieve what I'm after?

You could use a template_preprocess_maintenance_page() invocation in your theme's template.php so that when you go to maintenance mode (or the DB is down) it will trigger your needed status code:

function MYTHEME_preprocess_maintenance_page(&$variables) {
  drupal_add_http_header('Status', '504 Service unavailable (with message)');
}