What can cause an incorrect base_url to intermittently appear for images? I have a set of images provided by a view. They are displayed on the site home page via a panels page. JCarousel is used on display. An image cache style is applied. When previewed in the view, they appear without issue.

When displayed on the home page, the path to the images uses localhost, not the server domain name, and thus are broken. All other images on the site load fine, including other images provided by image cache.

I've tried:

Clearing the cache
Flushing the image cache style

I'm not really sure what else to check. Do I have any other options beyond settings base_url in the settings.php file?

I have had a very similar issue before.

Basically, the problem I had was that the image path was saved as  url, instead of being a relative path. If this is the case, the fix is fairly simple, simply go look at that node's attributes in the database, and change the url path to a relative paths.

If you are in doubt, a quick and dirty way to see if this is really the problem:

Do a DB dump, with mysqldump or whatever you use,
grep in that file for "http://localhost"

grep -b3 -a3 "http://localhost" yoursqlfile.sql

The b and a flag are for the number of lines returned upon a text match before and after the match it is optional and can be tweaked to higher values if wanted/needed.

Now, if there is any reference in the sql data pointing to  your http://localhost, in your node meta-data these 2 simple steps will quickly help identify where the offending nodes are.  Just note the table and field names that grep found & the nid's and go change the values to relative paths using either the commandline, a script or php-myadmin!

Of course, there are many ways to do this I just pointed out a very general way of fixing your data so it is portable.

Good-luck, happy coding.


Set a Date field with Rules? I have a form that users can fill out and it creates a node, an event node to be shown in the community calendar of my website. I'm using Rules to create the new node when the "Webform: After a webform has been submitted" event (requires Webform Rules module).

Everything is working well except for the Date field. The event node needs a date and time, that's kinda the point of a calendar!

I can select the webform data with [data:date-value] and [data:time-value] and I know that they output the correct data because if I put them into a regular text field ([entity-created:body:value]) the date and time show up just fine. And I can use PHP if I need to:

<?php
  echo $data['components']['date']['value'][0] ;
?>

I just don't know what Data Selector to choose for the date field. There's several that Rules knows about but so far I have no luck:

entity-created:field-date

if I choose this, in the resulting page to set the new value, there is no PHP Evaluation or Replacement Patterns available to use, only the Data Selector ajax dropdown, which doesn't allow for the [data:date-value].
and it says "Data types: Select data of the type List<struct>."

entity-created:field-date:0 - it goes from 0 to 3 although there's only 1 date field for the event node, and they all the same

if I choose this, in the resulting page to set the new value, there is no PHP Evaluation or Replacement Patterns available to use, only the Data Selector ajax dropdown, which doesn't allow for the [data:date-value].
and it says "Data types: Select data of the type Struct."

entity-created:field-date:0:value (Start Date)

in the resulting page to select the new value, it says: "Data types: Select data of the type Date." so I think it's a step in the right direction...
now there's a plain value field I can use (direct input mode),

instructions say: "The date in GMT. You may enter a fixed time (like 2016-06-04 16:01:07) or any other values in GMT known by the PHP strtotime() (link is external) function (like "+1 day"). Relative dates like "+1 day" or "now" relate to the evaluation time." If I put "+1 day" into the field and test it by submitting the webform, then a node is correctly created with the date field set one day into the future.

I can switch to the Data Selection mode and I have Data Selectors, PHP Evaluation and I can add an offset.

if I set the new value to [data:date-value] or [data:date-value] [data:time-value] then it doesn't say there's any errors, but when I test it but submitting the form and checking the new node that was created, the Date field was not set
if I try to set the value to <?php echo $data['components']['date']; ?> ... still no luck. And no errors are displayed or logged.

it also lists entity-created:field-date:0:value2 (End Date) and entity-created:field-date:0:duration (Duration) as possible "Set a data value" things to select

Anybody have any idea what I'm supposed to do here?? Thank you!

Re Dan Mantyla's comment, if your date field is not a Date (UNIX timestamp) or Date (ISO) field but just a normal Date field, the following code works for me:

$thedate = $data['components']['date']['value'][0].' 00:00:00';

// set the date
$entity_created->field_date[LANGUAGE_NONE][0] = array(
    'value' => $thedate,
  );


How to get a field's value for all nodes in a content type? I would like to get values of a field from all nodes of a content type. How can I do this? EntityFieldQuery seems to return only node ids, so will I need db_query? Sg similar to this In a custom module how do I get all the nodes of a certain type?

I guess I just need to lookup the table name of the field...

In your case, you can probably simply query the field data table, with a condition on the entity type and bundle.

In any case, something like:

$field_name = 'FIELD_NAME';
$result = db_select("field_data_{$field_name}", 'f')
  ->fields('f', array('entity_id', "{$field_name}_value"))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('deleted', 0)
  ->range(0,10)
  ->execute();

foreach ($result as $row) {
  // drupal_set_message($row->field_name_value); // example
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

As an aside you might want to join on the node table to only select published content, but that's the gist of it.


Programmatically created nodes don't appear unless opened and saved I've written a simple script that iterates over a CSV file and creates nodes in Drupal. All of the nodes are present in the admin interface but do not appear on the site unless I manually click 'Edit' then immediately save. This is a real problem because I do not have time to open each and every node. Funny thing is, this doesnt happen for every node.

A simplified version of my code

 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $title = $data[1];
    $address1 = $data[2];
    $address2 = $data[3];

    // Add a node
    $node = new stdClass();
    $node->type = 'store_location';
    node_object_prepare($node);
    $node->status = 1; # published or not...
    $node->promote = 0;
    $node->uid = 1; // ID of author
    $node->created = date('U', strtotime('now'));

    $node->language = LANGUAGE_NONE;
    $node->path['pathauto'] = TRUE;
    $node->title = $title;
    $node->gsl_addressfield['und'][0]['thoroughfare'] = ucwords($address1);
    $node->gsl_addressfield['und'][0]['premise'] = ucwords($address2);

    node_save($node);
}

Use hook_node_presave($node) to check whether you are getting proper values.

Also, try drupal_form_submit() instead of node_save() for edit


How to make "Time" part of a date field not required? Using the Date module, how would one make the Time part of a date field not required when the whole field is set to "Required".

Also if possible, not display the Time on the front end when there's no time specified?

I'm not sure this is possible without some re-engineering of how the date module works, or at least writing your own custom date field.

The date_field_validate() function calls DateObject::validGranularity() which checks to make sure there are sufficient date parts for the granularity you've chosen. If the field instance is set to be required, it's necessary for that check to pass before you can save the field values. Obviously this check won't pass if you haven't provided all of the relevant date parts.

A simple way around the problem might be to use a field collection, to which you can add two fields: one for the date and one for the time. There is a Timefield module out there, I recommend the dev version as the alpha version has some weird problems.

That method would also help with your display issue as the date and time are now separate fields.


Display all values in a facet block even when a value is selected I have facet block which looks like:

Categories:
[ ] Category 1
[ ] Category 2
[ ] Category 3
[ ] Category 4

Categories are represented with the ss_category field (single string field). When a category is selected, all the other categories disappear, which makes the block looks like:

Categories:
[X] Category 3

I need all the other categories to remain displayed even when there is an active category, so that the user doesn't have to unclick the active category first then click another one. In other words the block should look like:

Categories:
[ ] Category 1
[ ] Category 2
[X] Category 3
[ ] Category 4

How can I achieve this behavior in Drupal 6?

I need the same behavior, with drupal 7.

I know 2 ways :

Use a facet block
use minimal facet count
rewrite yourself the missing facets


Extract currency code from $orders I'm trying to extract the currency code for the current order, I printed the $order variable using print_r, but I'm not at all a PHP programmer and I don't really know how to extract the currency code, I can see it there, but I don't know how to extract it, can somebody point me to the right direction? I will be delighted if I will learn how to do this kind of actions.

Thanks for your time!

The currency data lives in the commerce_order_total field by default. You can extract that information easily using field_get_items(), though an entity_metadata_wrapper() is just more fun:

$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$currency_code = $order_wrapper->commerce_order_total->currency_code->value();


View mode for specific bundle Drupal 7 makes it quite easy to create a new view mode (see this tutorial for instance), but is there a way to define a view mode that is only available for a specific bundle (content type)?

No.

View modes are specified per entity type, not bundle, as hook_entity_info() shows.

It is also not possible to define extra fields which are only available for a specific bundle/view mode combination, only per bundle.


Subscribe user to list I have a forum site and I need sign up user list (on profile page). So every user should sign up for new forum posts. Basically, I need a user group which I can attach in rules and send them email with new thread details.

Is there a module for this or do I need create a custom module? If I need my own module is this a good solution - Create content type "user_list" and attach users to nodes via user reference field. Then in Rules settings I will attach this user_list and send email to all users(via user refernce) in this node. Or is there a better alternative?

Thank you for response

Have you already tried to use Organic Groups and Notifications ?
There is also Organic groups e-mail blast module I didn't try.


An illegal choice has been detected. Please contact the site administrator is given on ajax form after programmaticly adding an item to a select list I have a form in Drupal. On a select list I am using the ajax built into the form api to trigger a callback on change.

I need to be able to add an option to the select list via javascript. Set the value on the select list to be that new value and then trigger the ajax call.

I have something like:

var select_list = $('#edit-example');

select_list.append($("<option></option>")
  .attr("value", data.ObjectID)
  .text(data.Name));
select_list.val(data.ObjectID);
select_list.change();

Where data is a JSON object.

So the option is being added to the select list. The value has changed to my new option. I trigger the ajax event. However I am getting the error message:

  An illegal choice has been detected. Please contact the site administrator.

The callback is working fine except the error is displayed. What can I do to stop this message appearing?

Upon validation, the FAPI checks that the values given for any select/option/radios match what was originally available when the form was first built. This is a security check, and is built in to all form processing.

Changing the values of an existing select list with javascript means your form has been altered outside of Drupal's control (perhaps maliciously, the FAPI cannot know), and so the validation fails.

To stop the message appearing, you should use the AJAX framework to build you form, instead of manipulating it directly with jQuery.


How to add phone number field with extension to webform component Theme:
Bootstrap subtheme
Modules:
https://www.drupal.org/project/webform_bt_layout,
https://www.drupal.org/project/webform,
https://www.drupal.org/project/phone,
https://www.drupal.org/project/webform_phone.
Steps:
Enter 'Phone No' in component field.
Selected 'Phone Number' as   field type.
Clicked 'Add'
Country was selected as 'US/Canada' (I am accepting only US/Canada 10 digits)
Separator field has dash(-)
Problem:
When I visit my form, I see a one field which allows to enter more than 10 digits.
How can I make sure I can enter 10 digits numbers (separated with dashes) with upto 4 digits extension?

You could add a phone field as you described for the phone number.

And add another field of type number for the phone extension, you can limit this field to be only numeric and 4 digits.

And even to make sure that the phone number is introduced and not only the 'phone extension', you can add a Webform conditional to display the 'phone extension' field only if the 'phone' field has been filled.


How to validate the headers of a csv uploaded with cck filefield? I need my users to upload a csv, using a cck filefield. I then wish to confirm they have the correct order of columns.

My research led me to believe that writing a custom validator for the filefield, was the best option. I have used this as a resource: https://drupal.org/node/546146 for writing it...

I then used this for an example of how to open a csv and read it: http://oliverhuynh.wordpress.com/2011/06/21/drupal-batch-csv-importing-template/ ...

I'm very new to this and lack the insights to spot what i'm doing wrong... Here's my code:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'stocklist_node_form') {

    $form['field_stocklist'][0]['#upload_validators']['stocklist_validation'] = array();
    return $form;
  }

}

/**
 * The validation for the file.
 *
 */

function stocklist_validation($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field / file
  $filepath = $field->filepath;
  global $base_url;
  $fileurl = $base_url . '/' . $file_path;
 // Open the file
      if ( $handle = fopen($fileurl, 'r') ) {
        $line_count = 1 ;
        $first = TRUE ;
        if ( $line = fgetcsv($handle, 4096) ) {

        // Validate the headers

         if ( $line[0] !== 'manufacturer' ) {
            $errors[] = t('Unable to verify uploaded file !filepath. Please ensure the file has the correct file type, column names and information.', array('!filepath' => $field->filename));
         }
        }
        fclose($handle);
      }

// in case of error, add error message

          return $errors;
}

I would really appreciate any help or pointers... I feel I'm one step away from finishing it but running out of google searches... It doesn't matter whether I upload a valid or invalid file, it just throws the defined error message... Why is it doing that?

edit:

Here is a screenshot using devel whilst viewing a 'stocklist' type node. Thought it may help...

Just got this too work:

/**
 * The validation for the stocklist.
 *
 */

function stocklist_validation($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field / file
  $filepath = $field->filepath;

 // Open the file

      if ( $handle = fopen($filepath, 'r') ) {
        $line_count = 1 ;
        $first = TRUE ;
        if ( $line = fgetcsv($handle, 4096) ) {

        // Validate the headers
         if ( $line[0] !== 'something' ) {
            $errors[] = t('Please ensure the files 1st column has the something in it. Including something as the heading.');
         }

    if ( $line[1] !== 'somethingelse' ) {
            $errors[] = t('Please ensure the files 2nd column has the somethingelse in it. Including somethingelse as the heading.');
         }

        fclose($handle);
      }

           else {
        $errors[] = t('Unable to open uploaded file !filepath.', array('!filepath' => $filepath));
       }
      }
// in case of errors, return error messages

          return $errors;
}

The first function didn't need changing...

In the second function, it was the fopen() that needed changing. Secondly, like an idiot I just realised that the "valid" file was actually tab delimited... Doh! Would be nice to be able to accept those files too. As some software saves csv files in that format, such as the one I clearly used, OpenOffice.


Line breaks with theme settings textarea I'm using the following to get a form field in the theme settings page

function theme_form_system_theme_settings_alter(&$form, $form_state) {
   $form['foo_example'] = array(
   '#type'          => 'textarea',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
 );
}

The problem is when I output the result in my theme file with this:

$foo_example = theme_get_setting('foo_example');
print render($foo_example);

It doesn't respect the line break and puts it all in one p tag. I'd like it to respect the line break and put each line in a p tag if possible.

Try to use "text_format" type.

 $form['foo_example'] = array(
   '#type'          => 'text_format',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
   '#format' => null, //I think "null" saves the default text format of your website. If you want to see your changes you must put a dynamic value.
 );
}

NOTA BENE: the values saved by this type of textarea, is an array with "value" and "format" keys:

$var_saved = array(
'value'=> 'something',
'format' => 'full_html', //could be filtered_html, plain_text or any custom text format you've created.
);

//in your field definition
'#default_value' => $var_saved['value'],
'#format' => $var_saved['format'],

I didn't test it for your case, but choosing the right format, will normally output the text with respect of the rules chosen for that format type.

If I understood well your problem...


how to have a different page from the front page? In my site, all my pages are the same as the front page. For example, I have our team block and price table on the front page, but I also see them in blog posts or article pages.

Why is this happening? How do I have a different page from the front page?

When placing the block, you can set the block visibility conditions.

To get a block to show up only on the home page, you would set <front> and Show for the listed pages under the pages visibility section.


How can I control block visibility with code? In Drupal 6, I could control block visibility using PHP code in the block UI configuration like:

<?php return MYMODULE_abc() || MYMODULE_def() ; ?>

These functions looked up the current node, taxonomy, etc. to decide on whether to display the block. This PHP option is gone in Drupal 8, but there is a $visibility field in BlockBase. Can I use this to programmatically set the visibility at runtime?

A working code snippet how to use hook_block_access(). Here I retrieve the condition from a field of the current node:
use Drupal\block\Entity\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_block_access().
 */
function MYMODULE_block_access(Block $block, $operation, AccountInterface $account) {

  if ($operation === 'view' && $block->getPluginId() === 'MYBLOCK') {

    $node = \Drupal::routeMatch()->getParameter('node');

    $hero_image_exists = FALSE;

    if ($node instanceof NodeInterface) {
      if ($node->hasField('field_hero_image')) {
        if (!$node->get('field_hero_image')->isEmpty()) {
          $hero_image_exists = TRUE;
        }
      }
    }

    return AccessResult::forbiddenIf($hero_image_exists === FALSE)->addCacheableDependency($block);
  }

  return AccessResult::neutral();
}

Thanks @Insasse for sharing the following gem in the comments. For programmatically created custom blocks you can control visibility directly from inside the block class via blockAccess():

class MyBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->t('This is a simple block!'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

}

Source: How to Programmatically Create a Block in Drupal 8


wrapping menu items with span in Drupal 6 I need <span> tags around strings on my menu items. Trying to use this answer but it does not work for me. I probably just need some guidance in terms of naming things (just started on Drupal).

My theme folder name is sub_website, it is inheriting from theme called website (set by base theme = website in sub_website/sub_website.info). The menu in question is named 'Primary menu', it is selected as "source for the primary links" in the settings, and it is accessible via /admin/build/menu-customize/primary-links URI.

I tried adding the following into the sub-theme's template.php:

function sub_website_links__system_primary_links_menu($variables) {
  foreach ($variables['links'] as $link) {
    $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
  }
  return $output;
}

What am I doing wrong? Am I not clearing the cache properly? Did I not name the function correctly? Is there no such hook in Drupal 6? Documentation is very fragmented and is further complicated by two major versions existing side by side.

The answer that you found is for Drupal 7 not for Drupal 6.

In Drupal 6 you can't override theme_links() for a specific target.

You need to override theme_links() function itself to add span tag as the following code:

function sub_website_links($links, $attributes = array('class' => 'links')) {
  global $language;
  $output = '';

  if (count($links) > 0) {
    $output = '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = $key;

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class .= ' first';
      }
      if ($i == $num_links) {
        $class .= ' last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
          && (empty($link['language']) || $link['language']->language == $language->language)) {
        $class .= ' active';
      }
      $output .= '
 $class)) .'>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.

        // check if menu id attribute is set to primary-links
        if(isset($attributes['id']) && $attributes['id'] == 'primary-links') {

          // add html to link options
          $link['html'] = true;

          // wrap text with span
          $output .= l('' . $link['title'] . '', $link['href'], $link);

        } else {
          $output .= l($link['title'], $link['href'], $link);
        }

      }
      else if (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= ''. $link['title'] .'';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Then edit page.tpl.php and add id attribute for $primary_links menu

print theme('links', $primary_links, array('id' => 'primary-links', 'class' => 'links clearfix'));


What is the simplest way to transfer webform /data/ from one instance to another? I have much webform data that I want to move from a data entry instance to a testing instance, but I don't want the entire database.  What is a simple recipe for exporting and importing drupal webform data.

I know about the webform export / webform import modules, and the import module that this is possible, but I can't find the correct combination of parameters that makes it happen.

Thanks

Sometimes it is possible to export/import only selected tables on testing environments (not recommended on production sites).

A simple way is to use backup&migrate module (https://drupal.org/project/backup_migrate) and then export and import the webform tables you like. You can select this tables on the advanced options.


Any Modules to help with price caculator? Ive made a booking form using Drupal 6, where bookings are a content type and you create a node of that type to make a booking.

I now need to add a price calculator. When creating a booking node, one of the CCK fields you fill in is distance. I then need the price to be calculated from the rates below, and that value to be given to another CCK field.

Rates:
0-5 km $20/ mile
5-10 km $15/ mile
10-20 km $10/ mile
20-30 km $5/ mile

So if the distance was 11km, the price would be 11 x 15 = 165. Also, the rates table needs to be editable by the site admin.

Can any modules do or at least help with this? I could probably manage to do the calculations and change the price field value with jQuery. If the table was shown on the page then jQuery could grab the values from it, and the table could be editable by the admin so the rates could be changed. Im far from a jQuery expert though and I love Drupal's ability to do powerful stuff without writing code.
Thanks

if you need an admin interface for this your best bet is to write a small module for it in PHP, not jQuery. Unless you want your "rates table" to be handled by nodes as well..


Using variables in Drupal Would appreciate any assistance of how to handle configurable URLs for each environment.

The links need to take the user to a different URL depending on the environment the site is installed in.  In test environment, they would go to the test site, in beta test environment, beta site.  And in production, production.

Currently I am calling the test url by h ref in the body text. However, when the site is moved to beta, I would have to manually change the url to the beta url and so forth. I have about 50 of these type of URLs throughout my site so I am looking for a automated way.

I have thought about using

https://www.drupal.org/project/scanner
https://www.drupal.org/node/257026#example-use-cases

But open to any suggestions or experience.

Many thanks in advance!

Mike

If I understand your use-case properly, as far as I know everybody uses Pathalogic for this.


How to get distinct nodes for a view and its attachments? I have a view of type "block" showing 1 node and another display attached to that block showing 3 nodes, in both displays nodes are sorted randomly, the problem is that I can't find the way to add a "distinct" for both views, so sometimes both displays show the same node because of the random sorting

Is there any way to solve it?

EDIT: I've posted an image with the real view, has you can see in this case first and the third nodes are duplicated, sometimes it happends because i need them to show randomly

You can achieve you requirement by following below steps.

Under view Advance setting, click on Query settings.
Now select Distinct checkbox.


Strict warning and views - site not working I am using drupal 6 and after moving to php 5.4 or 5.5 from 5.3, I am getting error "strict warning: Declaration of views_plugin_style_default::options() should be compatible with views_object::options() in.... views_plugin_style_default.inc on line 24."
I tried updating views but does not help. It is not just about warning - Views do not work at all. What can be done in this case? Besides switching to 7.x - it is not an option for me. Thank you.

There is a patch, it can be found here: https://www.drupal.org/node/893128

I used this one: https://www.drupal.org/files/issues/893128-61.views_.strict-warnings-method-declarations-php-5-4.patch but it did not fix everything. In the end I fixed some items manually similar to what is done in the patch where I replace the function arguments that are the problem from $argument to &$argument. (or sometimes the other way around).

Did you already try the latest dev version, because a patch for the issue I mentioned was committed recently, but I don't think a new version was released since then.


Forbid the publication I created a new role for the user to write.
How do I forbid the publication to a redactor?

If I understand the question, I think you want the Workflow module.  You probably also need the Revisioning module, and potentially the Module Grants and Rules modules.

I don't recall testing this particular workflow, though.  It is also worth noting that workflows can be a pain to set up, and adding workflow to an existing site can be problematic because existing nodes will not have a workflow yet (some scripts to fix this are available if you poke around).

This question is tagged for Drupal 7, which presents a problem with this solution.  Workflow and Module Grants don't have D7 versions yet.  There are discussions about ports in the issues, but nothing has been released yet.


can't import sql dump to new database for backup i have a site on drupal. I want to make a copy of that site so as to be able to make changes to the site without the fear of loosing something.

I have problem with the database. I export it in spl format. The size is about 100 MB. When i try to import it to the newly created database it says it is in progress but nothing is happening. The import is not proceeding.

I tried to transfer each table separately but when i reach a table that it is 36 MB (locale_sources) it shows it is in progress but nothing is happening.

Everything is done through phpmyadmin.

Can anyone suggest anything?

Thank you.

You can use mysql on the command line to avoid timeouts when updating big dbs.

Example:

mysql --password=yourpw --user=name --default-character-set=utf-8 db_name <your_dump.sql

See mysql -? or the manpage for more options.


Difference between a bundle and a content type Can somebody explain to me the difference between a content type and a bundle? Is the latter just a bundle for the entity node?

Bundle is a generic term that applies to every entity Drupal or third-party modules define; content type is a specific term that applies to nodes.
Since nodes and content types were introduced a way before Drupal 7, content type was the first concept introduced, which then got expanded into the bundle concept when entities were introduced in Drupal 7.

So, yes, a content type is a bundle for the Node entity.


What does URI mean in drush site alias? I want to create drush site aliases for my sites in order to use rsync. However, I'm not sure what URI means. Is it the (sub)domain I have assigned to my site, or the sites/ folder it is in? If it's the sites/ folder and I am using sites/default , does that make the URI "default"?

$aliases['demosite.drupal7.local'] = array (
  'uri' => 'demosite.drupal7.local',
  'root' => '/var/www/drupal7',
);

Update

I found my answer in drush/examples/example.aliases.drushrc.php.

  'uri': This should always be the same as the site's folder name in the 'sites' folder.

Okay, I wrote that line you're quoting above ("uri': This should always be the same as the site's folder name in the 'sites' folder."), but unfortunately that is an oversimplification that is not always correct, especially when using a Drupal 7 site.

This is what I say about "uri" in the Definitive Guide to Drupal 7:

  The URI used on the command line should be the same as when the site
  is being accessed from a web browser. It is also possible to use the
  name of the folder that contains the settings.php file for that URI
  (e.g. --uri=default).  This works, and is, in fact, equivalent to
  [back reference to an example that runs core-status using the cwd to
  select the Drupal site] in terms of the site URI that Drush will use
  when calling in to Drupal; you can confirm this by comparing the
  output of the "Site URI" line in [back reference to same listing] with
  this output.  Having a correct site URI is not always required, but
  some modules might need it if, for example, they are generating
  absolute URLs or making HTTP requests back to the same host; it's
  therefore advisable to set a correct URI whenever possible.

This quote is 100% correct for Drupal 7, but the situation is slightly more complicated with Drupal 6.  In D6, the value of the --uri option (and correspondingly, the URI used to access the site from a browser), will sometimes be written into the database.  For example, if your settings.php file is stored at sites/mysite.org/settings.php, and your URI (from the browser) is http://mysite.org, then you might in some circumstances find paths "sites/mysite.org/files/myuploadfile.png" in the database.  The URI from the browser is converted to the name of the folder containing settings.php before being used by Drupal (for some uses), whereas the --uri option passed to Drush is always used as-is.  Because of the fact that your site folders are written to the database, it's often handy to continue to use the sites folder "mysite.org" for your dev site "http://dev.mysite.org", and of course there's always the possibility that your sites folder is called 'default' (often a good idea on D6).  So, while --uri=dev.mysite.org and --uri=mysite.org and --uri=default may will all work (presuming a site http://dev.mysite.org which is a dev copy of http://mysite.org with its settings.php file in the default folder) to select the site for Drush, there are some edge cases where --uri=default is better in that the other options will not match what your modules are seeing when the same code.  On the flip side, there are also other edge cases where --uri=mysite.org is what you need to align your runtime variables with what your module will see with the browser (c.f. above dgd7 quote).  So the truth of the matter is that there is no value that is absolutely best for D6. The simplified advice you quoted above was used in the example file because things can really go wrong if you use --uri=mysite.org instead of --uri=default, AND a path is generated and written to the database, AND you migrate your database to another instance of the site, breaking the path.

For D6, the most pragmatic thing to do would be to name your sites folder 'sites/mysite.org' instead of 'sites/default' (and make sure that it is also 'sites/mysite.org' for http://dev.mysite.org).

I changed the advice in examples/example.aliases.drushrc.php as follows:

  'uri': In Drupal 7, the value of --uri should always be the same
  as  when the site is being accessed from a web browser (e.g.
  http://mysite.org, although the http:// is optional).  In Drupal 6,
  the value of --uri should  always be the same as the site's folder
  name in the 'sites' folder (e.g. default); it is best if the site
  folder name matches the URI from the browser, and is consistent on
  every instance of the same site (e.g. also use sites/mysite.org for
  http://dev.mysite.org).


Add captcha to last step of multi-step form I have a multi_step form which contains four steps. I want to add captcha to last step of the form.

use this code in your template.php, you need to know what the ID of the last form is,

<?php
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
    if ($form_id == "YOUR_FORM_ID") {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'Math',
            );
        }
}
?>

you can also replace the Math with image


Configuring a taxonomy argument view Using Views 6.x-3.x-dev

I have a content type called Images and a Content stype called Stars.  Both Types share a Vocabulary Called Name. The vocab is tags.

Via a View, I want to display all the images associated with that Star when viewing that particular Star node.

So say I am currently viewing Brad Pitt's Node. This node is tagged the term 'Brad Pitt' in the Names Vocab.  I want all his images (too who are tagged 'Brad Pitt') to be displayed below the his node.

So I need to get NODES from type IMAGES that are tagged the same term in vocab NAMES as the currently viewed node

So in the Brad Pitt Node,
get NODES from type IMAGES tagged BRAD PITT from the vocab NAMES

If I understand you correctly:

Use Taxonomy: Term ID as argument.

Write php to get taxonomy term/terms from current node and return them.

Configure this view to display node types you want to display.


How to change path of file from absolute to relative? In my website, some of the images are having absolute path of old server .../old_directory/sites/, but now I have changed my server, I want that these images should be picked from /sites/ path of my current instance.

Anyone has any suggestion??

Install any one of the below modules.

Pathlogic
Portable path


Hiding 3rd level menu from sidebar, but displaying elsewhere. Possible? - D7 I have a 3 level menu structure in the sidebar. I would like to add a set of submenus for one of the Second level menu items, but would this time like to hide it's children from the sidebar. Instead, I would like this menu to be displayed in the main content area. Is this possible? How would I go about doing this?

So just to clarify, some 3rd level menus I would like to display in the sidebar, but other 3rd level menus I would like to hide from the sidebar, but instead display in the main content area.

The level of control you need can be achieved using Menu Block module:

So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
Pretty simple, eh?


How to translate plurals in language with multiple cases (most of European) Function format_plural is useable only if language has only one plural case (English), but I need to use it for Czech language what has (like most languages from slovenian and roman family) more cases for plural.

For example English has two cases:

1: bed
2-∞: beds

But in Czech we needs more cases for the same word:

1: postel
2-4: postele
5-∞: postelí

And the schema is usually different for different words. (Mistake, it is the same for all words in one language, but different between languages.)

Is there some API in core or in some module that can translate this (for Americans crazy :-)) cases?

format_plural() does support multiple plural versions in general.

format_plural() only has arguments for singular and plural because english only has those two and the input is always english, Drupal does not support translating interface text from another language than english.

However, it is something that defined per language and not per word, that doesn't work. I'm not aware of a workaround that can handle per-word differences.

Actually, according to https://en.wikipedia.org/wiki/Czech_declension#Plural_forms, those rules (1, 2-4, 5+) are always the same? So that should just work.

This is how it looks in the UI


OG + Exposed Filters + Views What would be the smartest way to approach filtering content by the groups that it is posted in?

I will almost certainly need custom code to do this (I think a Handler, but I need someone to point me in the right direction), especially because I want to be able to filter by content posted in "All" groups, posted in a set of groups (i.e. a user's "core groups," determined by a taxonomy term reference on all users and groups -- if they are equal, that group is a user's "Core Group"), and also by each individual group that the user belongs to (but I don't want groups that the user isn't a member of showing up in the filter).

The docs for Views aren't very good, and I just know that there's an elegant, Drupal way to do this, and I need someone to point me in the correct direction (i.e what hooks, etc.)

Thanks in advance for help!

I think you can do what you want using OG and Views with nothing custom. This is a good place to get started: https://modulesunraveled.com/organic-groups-7x-2x.


How to place a custom javascript link/button in each row of a Views table I would like to place a link or button in each row of a Views table, and have custom javascript code executed, with field content taken from that particular row as input. The Javascript code already works fine outside of a Views table. How can I add such a custom Javascript link/button? Is this possible ?

You can use a Global Text field to create the link, and, since Views wraps everything in all sorts of divs, use jQuery to grab any of the other fields there for your js


"$nid" for individual pages not working <?php
  $nid = arg(1);
  $arg0 = arg(0);
  if(isset($nid) && is_numeric($nid) && isset($arg0) && $arg0 == 'node') {
    $node = node_load($nid);
  }
  $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
  if(isset($theme_img)) {
    // print styled image
    print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
  }
?>

I am using the above code to load styled image (from node 6) in page.tpl file. This is working fine in all the pages but when I am trying to load images from individual images by using '$nid' it is not working.
I don't understand what I made mistake in code due to which I couldn't get the value of '$nid'. Please help.

As you are looking to edit/override node template, it is suggested to place your changes into node.tpl.php where you will get $nid as out of the box. page.tpl.php will not give you node variables by default.

If you still you want to get your code on page.tpl.php you can get $nid from url like arg(1).

Let me know if I miss anything!


Using ImageField to add an inline image (save thumbnail, and when clicked open with colorbox) Here is what I usually do in my websites:

Have an option for adding image in the WYSIWYG editor of my choice
User can upload the image
User can resize the image in the WYSIWYG editor
Have the Image Resize Filter enabled for the Input Format
When user resizes the image, it automatically saves the thumbnail and adds a lightbox/colorbox related attribute so that the image is opened using one of these libraries.

What the problem is now? I have come across a "not very tech-savvy" customer that is displeased with the way that the images are added right now as he cannot grasp any of the regular concepts for images.

Based on his description I reached to the conclusion that I need to implement the following workflow:

A straightforward filefield (imagefield) where he can press the "Browse" button and then the "Upload" button.
He will then write his text in the "Body" field and that's it.

My Requirements:

I don't mind if he cannot see the image when he is editing the node
Only one image will be allowed per node
I want to pre-edit the image's vspace, hspace and alignment (e.g.5px 5px
left)
I would also like if I could use the Image Resize Filter for the uploaded image so that only a thumbnail appears in the actual node (teaser and full view) and the original image appears in a colorbox
I don't mind if I will have to edit the node.tpl.php or any other theme file
It's needed that the image is added with the body of the node (e.g. at the start of the text)

What I've tried so far:

I have watched the MustardSeed video for Image Resize Filter along with ImageField Insert module (now it's called Insert) but there are some complex steps in there that my customer cannot comprehend (e.g. adding Vspace, Hspace, Alignment or even manually resizing the image). I would like to give my customer as few options as possible.

If you enable core File and Image modules you can add image upload fields to different nodes/entities and create image styles (to get thumbnails). The number of allowed image uploads can also be set. The image uri will be available in the node.tpl.php file which means you will have full control over how it appears. Here's example code showing about how it could look like in the node.tpl.php file (with colorbox module 'Colorbox load' enabled - alternatively just use javascript):

<?php if (!empty($node->field_image['und'][0]['uri'])): ?>
  <?php
  $full_img_url = file_create_url($node->field_image['und'][0]['uri']);
  $thumbnail_url = image_style_url('thumbnail_style', $node->field_image['und'][0]['uri']);
  ?>
  <a class="colorbox-load" href="<?php print $full_img_url; ?>"><img src="<?php print $thumbnail_url; ?>" alt="Image" />
<?php endif; ?>

The code is not tested so there might be mistakes, but it should still be helpful. You'll have to set the image field hidden via 'manage display' or unset/hide it in the template file otherwise you'll get a duplicate printed with $content.


Is it possible to set up preferrential IPs when in maintainance mode? I've previously worked on Prestashop and there I had the choice to set my site in offline/maintance mode and then edit one ore more IP addresses in order other people to view the sites but not the commmon users and stills no login require and no additional host file settings.

Thanks

Actually on Drupal you can create a new role and assign permission to this role to login in maintenance mode (Add permission "System > Use the site in maintenance mode").

If this is not what you want, then you can filter IP addresses on firewall /linux level. Please ask on https://serverfault.com/ if you need this kind of solution.


How do I install multiple drupal sites in a single installation? I am trying to install multiple sites in a single installation on a local server.

But I don't have any idea about how to do this.

Can anybody tell me how to create multiples site using Drupal 6?

Look at Aegir to help you, and/or look at the multisite documentation.


You are not authorized to access this page with blocks displayed I made a custom module in Drupal 7 with a simple page.

I used hook_menu to make permission :

function mymodule_menu() {
  $items = array();
  $items['prestart'] = array(
            'title'             => t('Prestart page'),
            'page callback'     => array('mymodule_show_page'),
            'access arguments'  => array('access content'),
            'access callback'   => 'mymodule_isUserAuthenticated',
            'type'              => MENU_NORMAL_ITEM,
  );
  return $items;
}

The function to check if the user is authenticated :

function mymodule_isUserAuthenticated() {
   if (!user_is_logged_in()) {
       return FALSE;
    }
     return TRUE;
  }
}

After I created block (admin/structure/block) and I added to the page.

Problem :
If I go on the page in a private navigation tab (so not connected), I can see You are not authorized to access this page but all blocks are displayed.

How can I fix it ?

You probably need to adjust the visibility settings of your blocks (see screenshot below). You can, for instance, restrict the visibility to authenticated users only.

It is also possible to do it programmatically. See this question, for some guidance.


What to do in a case of plugin ID not found? I'm fairly new to Drupal, the inside settings are quite easily to understand for me but when it gets to error fixing I'm kind getting stuck sometimes.

For a project I've installed the Open Social platform as my Drupal, which is working fine but a couple bugs and things for me to find out. I wanted a file browser as a Knowledge Base into my site so I've installed the FileBrowser module.

Now when I want to specify (open social) group rights to a file browser node, so only that group can look into this file browser, I get the following error and I cannot seem to find out where to solve it:

Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException: Plugin ID 'group_node:dir_listing' was not found.

Could anyone point me into the right direction?

It looks like the error is coming from a missing plugin provided by the group_node module, which if I recall ships with the Group module. Try re-downloading that module to your codebase, and clearing your cache. If that doesn't work, uninstall the group_node module.


Non-empty string as route parameter I'm creating a search results page using the Search API. I want to set an url like this:

    /search/{text}

How should i set up my route? It must accept any combination of characters, including non-ascii, spaces, numbers, etc, but it must not be empty.

This is my current routing rule. As you can see, there is no restriction for the text parameter:

    my.search.results:
      path: '/search/{text}'
      defaults:
        text: NULL
        _controller: '\Drupal\my\Controller\SearchController::results'
        _title: 'Search Results'
      requirements:
        _permission: 'access content'

As long as a default value isn't provided in the route definition, every route placeholder is required. Defining the route as follow is sufficient.
my.search.results:
  path: '/search/{text}'
  defaults:
    _controller: '\Drupal\my\Controller\SearchController::results'
    _title: 'Search Results'
  requirements:
    _permission: 'access content

See, for example, the definition of the dblog.event route in the dblog.routing.yml file.
dblog.event:
  path: '/admin/reports/dblog/event/{event_id}'
  defaults:
    _controller: '\Drupal\dblog\Controller\DbLogController::eventDetails'
    _title: 'Details'
  requirements:
    _permission: 'access site reports'

The controller associated to that route, DbLogController::eventDetails(), doesn't check the value of $event_id is an empty string, simply because it won't get an empty string for that parameter.
public function eventDetails($event_id) {
  $dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [
    ':id' => $event_id,
  ])
    ->fetchObject();
  if (empty($dblog)) {
    throw new NotFoundHttpException();
  }
  // …
}


HTML in QuickTab Titles I've programmatically created some quicktabs in Drupal 7, however I require html tags within the title.

For e.g:

    $tabs_project['backers'] = array(
        'title' => t('Backers').'strong'.$backers_total.'strong',
        'contents' => 'backer information..',
        'weight' => 2,
    );

But this prints out the strong tags too.. Any ideas? (couldn't work out how to put the correct html tags in the pre tags, so left it as 'strong')

Cheers in advance,

Turns out you can apply something like so:

$qt_project['content']['content']['tabs']['tablinks']['backers']['#options']['html'] = TRUE;

thanks to comment on drupal forum

cheers


Change value of user reference based on node reference Is there any way to refine the user reference field values based on node references value.
Let me explain : I have one node reference field and user reference field in one content type and another node reference is added to user profile fields. Both node reference are of same content type with different name. Is there any way to refine the view of user reference field based on node reference field value.

 Image of User Profile

 Image of Content type

If what you are asking is can you change the user reference field to something based upon a node reference field, sure, not a problem.  But what do you want to change it to?  If it's the user id of the creator of the node referenced, that's easy:

// load node in question
$node=node_load($nid);
// load node referenced in that node
$node_referenced=node_load($node->field_node_reference[$node->language][0]['nid']);
// set user referenced in node to the uid of the node referenced in it
$node->field_user_reference[$node->language][0]['uid']=$node_referenced->uid;
// save the node
node_save($node);

If you want to do this automagically, you can look at hook_node_presave() and have this done every time a node type is saved.


Why my Data Export View uses default value for an exposed Grouped Filter? I am using Views 7.x-3.8, Drupal 7.28 and Views Data Export 7.x-3.0-beta7.

From a view (page) with multiple fields and exposed filters, I created a homemade search engine with search results within a table. I have created an export view, attached to that view, with exactly the same fields and exposed filters. So users can export filtered search results.

From the search engine, after choosing a value for a field with exposed grouped filter (Any, Yes, No), the export does not consider that choice and keeps the default value for this filter. Same result if I activate the option "Remember last selection" on the export view.

Any idea why?

Thanks in advance.

It could be that the export display is not attached to the page display. Try to edit the export display (typically you can not adjust the exposed filters on this page, as visiting the page will simply download all the results for the master view without considering any exposed filters).

Instead of getting your file by visiting the path of the data export, instead attach the data export to the page display where you placed your exposed filters.

You can do this by editing your data export display and adjusting the settings in your "Attach to" settings in the data export settings column (see screenshot below).

Once you click the Attach to link you'll be able to add your data export to any display in that view. Add it to your page.

Then, load the page in your browser, adjust your exposed filters until you see the results you want, and then scroll to the bottom of your page. You should see an icon that will enable you to execute the download of whatever file type you specified for your data export. For example, below I've filtered results for a page and set it to download as CSV.

By clicking the orange button, I'll download the filtered results on the page.


Phising warnings (in gmail) when using a gmail address as the website email address. How to avoid it? I would like to use a gmail address (a simple email address. i'm not using google apps) as my website's email.

The problem is that users receiving messages from the websites (notifications etc..) have a yellow bar warning them that this might be a fishing attempt.

I thought there might be some settings or best practices to avoid this problem.

Any ideas ?

I have been using this module for a long time without problems. You need to authenticate once, and then all your site emails are sent through the google smtp server.

http://drupal.org/project/smtp


How to add / update a field collection without updating parent node/entity? I needed to to add / update field collections to node entities without updating the node entities. I tried two ways listed in https://www.drupal.org/node/1842304 and http://alexrayu.com/blog/saveupdate-field-collection-without-nodesave but none of them seems to be working exactly the way I want.

I tried as follows:

$node = node_load($nid);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_college_rating_data'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_text1['und'][0]['tid'] = $form_state['input']['field_text1']['und'];
$field_collection_item->field_text2['und'][0]['value'] = $form_state['input']['field_text2']['und'];
$field_collection_item->save();

It added a field collection but it updates the node.

I also tried to alter the field collection form submit and used custom submit handler as follows:

function own_custom_field_collection_submit($form,$form_state) {
  $field_collection_item = field_collection_item_form_submit_build_field_collection($form, $form_state);
  $field_collection_item->save(TRUE);
  drupal_set_message(t('The changes have been saved.'));
  $form_state['redirect'] = $field_collection_item->path();
}

I have copied this code from core field collection module to change the default argument to "TRUE" in the save function. It added the field collection but didn't associated with the parent node.

I need to save the field collection separately since my node entity form is very large with 50 to 60 fields and field collections and I don't want to update it as many times as I add / update any field collections to the node.

Any help?

You can make use of the Entity API

example will be

<?php
// Implements hook_entity_update().
function qmlc_mod_entity_update($entity, $type) {
  if ($type == 'node' && $entity->type == 'event') {
    $link_title = $entity->title;
    $link_url = entity_uri('node', $entity);
    $language = $entity->language;

    foreach ($entity->field_event_images[$language] as $event_images) {
      // Load field collection item.
      $field_collection = field_collection_field_get_entity($event_images);

      $num_of_images = count($field_collection->field_image[$language]);
      for ($i = 0; $i < $num_of_images; $i++) {
        $field_collection->field_image_link[$language][$i]['title'] = $link_title;
        $field_collection->field_image_link[$language][$i]['url'] = $link_url['path'];
        $field_collection->field_image_link[$language][$i]['attributes']= array();
      }

      // Save field collection item. Use TRUE since you are updating a field collection item which is already linked with a node.
      $field_collection->save(TRUE);
    }
  }
}
?>

References

Programmatically create and update field collection with Entity API
Update field collection programmatically


how long do files hang around in temporary://? I want to offer a file download to my users, and I was thinking of using temporary:// to store the data. But how temporary is it? When do files disappear from it? Of course, I want to avoid having the file not be present when my user goes to download it jsut after a form submission, and I also want it gone after a while. So when do they go?

Temporary files that are created with the managed file functions are deleted when they are older than six hours, and during cron tasks.

The description for the FILE_STATUS_PERMANENT reports the following text:

  Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs, but permanent files will not be removed during the file garbage collection process.

The value of DRUPAL_MAXIMUM_TEMP_FILE_AGE is 21600 (seconds), which means six hours.


Deprecated version of DFP (v201508) We are getting emails from google about the latest version of Double-click for Publishers' (dpf) API.

Currently our site appears to still be using a deprecated version (v201508) and need to update to v201608 by November 30.
https://developers.google.com/doubleclick-publishers/docs/deprecation

Is this dfp api change is going to affect the dfp module?

As far as I can tell the DFP module doesn't load API version specific files and so unless you are using additional custom JS or loading the DFP JS files directly from your site (instead of pulling them from Google), there is no reason the API change should effect the module itself.


Twig adds an unwanted 'row' class that doesn't appear in class array My site theme includes customised templates for 4 regions in the footer, all containing identical code:
  set classes = [
    'region',
    'region-' ~ region|clean_class,
    'col-sm-12',
    'col-md-6',
    'col-lg-3',
  ]
%}
{% if content %}

    {{ content }}

{% endif %}

However, the HTML it produces varies.
In the first two regions, the class row is being inserted - despite it not appearing in the classes array:

In the last 2 regions, the row class is missing - which is the correct code I want:

I can't figure out where it's coming from, so my workaround is to include an additional step that removes the class, in the first two region templates only:

This gives the result I want, but I'm still not sure where the row class comes from and why it was being applied inconsistently??

Those 5 classes are being added using .addClass() to a pre-existing {{ attributes }} Twig object. The 'row' class must already be in the attributes object when Drupal passes it to the Twig template.
Typically, the place where something like that would happen is in your .theme file (or the parent theme's .theme file if yours is a subtheme). Look for a function like THEMENAME_preprocess_region() and see if you can find a hard-coded "row" string being thrown in there.
Alternatively, some fancier theme systems might expose configuration options in the Drupal interface that could be setting that class. You'd find those under Admin > Appearance, then in "Settings" for your active theme.


Change links titles of PDF uploads I have been trying to find a sensible solution to this problem with no success so far.

I have a site running Drupal 7 – and have built a basic content type which allows content admins to upload their own PDF documents using a file field. The content admins now what to be able to rename the PDF title that appears in the download link to whatever they want, but I can’t find a workable solution to achieve this. I have tried File (Field) Paths, but it was a disaster – full of bugs.

Is there a module out there somewhere that can allow what should be simple functionality?

The file module has that built right in. Edit the settings for your file field, and find this bit:

Save that, and go back to your node edit form where you will see:

With both the included field formatters you should see the contents of the 'Description' field for the link text of each file.


Change autocomplete results based users selected checkbox I have a drupal 8 site that uses the paragraphs module. In one of the paragraph is a field that contains an autocomplete field. It is already set up to reference a small list of Content Types.  For example, "News, Events, Product, Image" are four referenced for the autocomplete.

On another paragraph, it includes this autocomplete but also has a field called "Select a Content Type", it lists out ALL the content types. This is used on the content type.  When someone adds a new content they are presented with a list of all the content types as a checkbox and the autocomplete field.

My goal is to only display the selected results from the "select a content type" field onto the autocomplete field.

So when a user selects a "news" / "events" / "Product" / "image" from the "Select a content type" field, the autocomplete only displays nodes of what was selected. If I select news then only news appears when I start entering data. If I select News and events, then both will show. If I select none then a custom message appears.

I have looked around and found how to overwrite getReferenceableEntities but I don't see a way to pass two variables: one from the checkbox field and the autocomplete entered value.

I suspect there will be JS involved to have the form send both checkbox and search value over but I don't know where to begin.

MYMODULE/src/EntityAutoCompleteMatcher.php:

class EntityAutocompleteMatcher extends \Drupal\Core\Entity\EntityAutocompleteMatcher {

  /**
   * Gets matched labels based on a given search string.
   */
  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {

    $matches = [];

    $options = [
      'target_type'      => $target_type,
      'handler'          => $selection_handler,
      'handler_settings' => $selection_settings,
    ];

    $handler = $this->selectionManager->getInstance($options);

    if (isset($string)) {
      // Get an array of matching entities.
      $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
      $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 10);

      // Loop through the entities and convert them into autocomplete output.
      foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {

          $entity = \Drupal::entityTypeManager()->getStorage($target_type)->load($entity_id);
          $entity = \Drupal::entityManager()->getTranslationFromContext($entity);

          // Only return bundle types we want.
          if ($entity->bundle() == 'page') {
            $matches[] = ['value' => $label, 'label' => $label];
          }
        }
      }
    }

    return $matches;
  }

}

More work would need to be done, but this shows where we can control the returned list of referenced entities.

See:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityAutocompleteMatcher.php/8.8.x


Show block only on node view page, not in node create or edit form How can I configure block visibility to show only in node view pages? (not in node edit and create pages)

What should I insert in "Show block on specific pages" > "Only the listed pages"? current config is:

video
node/*

Use this in your block configurations page "Show block on specific pages" > "Show if the following PHP code returns TRUE"

if(arg(0) == 'node' && is_numeric(arg(1)) && ((arg(2) == "" || arg(2) == 'view'))) {
  return TRUE;
}

Hope this will help.

You will need to enable the core module PHP.


hook_form_search_block_form_alter is not working with bootstrap theme? I am facing an issue where hook_form_FORM_ID_alter() code is working in bartik theme while same is not working in Bootstrap theme. Any idea what could be the reason or am I missing something? Very Thanks.

In THEMENAME.theme of bootstrap theme

<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function subtheme_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

OtherWay,

function subtheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'search_block_form'){
      $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
    }
}

In bartik.theme

<?php

/**
 * @file
 * Functions to support theming in the Bartik theme.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;

function bartik_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.');
}

You can try a bootstrap plugin:

themes/THEMENAME/src/Plugin/Form/SearchBlockForm.php

/**
 * @file
 * Contains \Drupal\THEMENAME\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\THEMENAME\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends \Drupal\bootstrap\Plugin\Form\SearchBlockForm {

  /**
   * {@inheritdoc}
   */
  public function alterForm(array &$form, FormStateInterface $form_state, $form_id = NULL) {
    // Call the parent method from the base theme, if applicable (which it is
    // in this case because Bootstrap actually implements this alter).
    parent::alterForm($form, $form_state, $form_id);

    $form['keys']['#attributes']['placeholder'] = t('Sentence for placeholder!!!.')
  }
}

Reference:

http://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8


Subscribing the new user to a mailing list as a part of registration What is the simplest way to configure Drupal in such a way, that every registering user is asked for his email and permission to send him  info about site updates?

That way I want to postpone serious site building, but have a solid user base just from the now.

The email address is already a standard user property. Using fields you can ask for permission about the mailing list.

You can use rules module (http://drupal.org/project/rules) to get notified of new registrations and find or implement the action for a mailing list registration.

Another option would be the simple news module: http://drupal.org/project/simplenews


Moving a site, links/admin do not work I moved a drupal installation from one server to another.
Steps I followed:

Copied whole directory structure from old server.
Exported database from old server.
added files to newdomain/drupal
Imported database
edited settings.php with new database information.

As of right now the home page is working (Except for some broken non-db images, but I know the reason for that and can fix it) But none of the links to any of the nodes or any of the admin paths I know seem to exist. I get a 404 File Not Found error.

I wonder if it's related to the fact that this installation is in a subdirectory and the other one was not, but is that enough to make every page except the homepage not function?

Yes, that's possible. You can try to adjust the used base URL by setting the $base_url value in your settings.php .


Migrate module: how to handle adding Redirects and rolling back? I'm writing some migrations using the Migrate module. I need to set up redirects after I migrate in an item, but I'm not sure where to perform that action.

I can do it in the complete() function for the migration, which is called after each object has successfully been inserted. At that point, I'd have enough information to programmatically add a redirect.

However, if I needed to roll back the migration, I don't see where I can put in any clean up code to remove those redirects. There are pre and post rollback functions, but those are called before the entire migration is rolled back.

I suppose one alternative would be to, in a pre rollback, query the map table for all the objects and then lookup and destroy the redirects like that. Seems ugly.

I think the best solution here is to have a pre/post rollback function available on a per-object basis.

Anyone run into this previously or have suggestions?

The redirects associated with the migrated (node) content should be automatically removed during the rollback.


How to allow direct user input links the Facebook way? Does Drupal offer the possibility to have users input a link the Facebook way? In other words, showing directly a summary kind of view of the linked page?
Thanks.

You are looking for oembed, there is a Drupal module for it as well, that offers integration to media and some other modules.

  This module will allow your Drupal site to embed content from
  oEmbed-providers as well as for the site to become an oEmbed-provider
  itself so that other oEmbed-enabled websites can easily embed your
  content.

This won't give you a facebook experience out of the box, you still have to configure quiet a lot, you might want to read up on this: #2108973 Making oEmbed module work with WYSIWYG and CKeditor, which also links #2269433: Support URLs on a line by themselves in ckeditor/WYSIWYG.


How to delete all Drupal content owned by a particular user? It seems like there should be a drush command to achieve this, but I cannot find one. I am not clever enough to fashion an SQL query that will delete all nodes owned by a user as well as clean up all the field and revision data.

Please let me know if anyone has any solutions (other than deleting the user's account).

Drupal 7

A possible alternative to achieve what you're trying to do, is to use a combination of modules Views and Views Bulk Operations (VBO). With these modules in place, you could simply create a view of all the nodes "owned" by a user, and simply use the out-of-the-box VBO action to "delete an item" (after adding a VBO field like "Bulk operations: Content"). And by creating a similar VBO view, using the VBO field "Bulk operations: Content revision", you can probably also cleanup up the revision data.

If you need more sophisticated business logic to decide about the criteria related to "owned by a user", you could add Rules to such solution also and implement a variation of the solution described in my answer to "How to bulk update select list fields?", i.e.:

Create a Rules Component with a Rules Condition to checks if the node matches the criteria you're interested in.
Create a VBO enabled view of all nodes to be checked, whereas you'll use the Rules Component as your custom VBO action.

Done ...


Drupal 8 installation (bash) script. I want the latest stable v8 version each time. But how? My Drupal 7 script utilised a make file which specified '7.x' as the Drupal version to install, drush make would fetch the correct core files.

My current Drupal 8 script uses git to clone and then checkout a version, eg. 8.1.0, and then renames the remotes as per the instructions on this page. However since this method downloads the entire Drupal project history, I end up with a huge project folder.

I work for an agency and we install Drupal for website projects, so our need is not for the latest dev builds, otherwise I image I would just use:

git clone --depth=1 [url to drupal.git]

I'm looking for a way to clone the latest stable (release) v8 branch, with no extra files. I could specify the zip on the release page, but this would mean updating the script upon each new release. I tried using Composer, but ended up with a much more complex than necessary folder structure.

Can someone help me with a way to get essentially a copy of the latest v8 .zip file via a script?

Thanks!

As mradcliffe said in the comment, if you don't want to use composer (which I would really recommend you look into), you can simply use drush. You just need this:

drush dl drupal

This defaults to the latest stable Drupal 8 version. If you want to have a git clone (which is way slower), you can tell drush to do that too:

drush dl --package-handler=git_drupalorg drupal


Comma seperated text field into a HTML ol I have created a custom content type and one of the fields will be a texfield with values separated by a comma e.g.

value 1, value 2, value 3

I want to then display this as an unordered list in the output.

Can anyone help with how this can be achieved?

Thanks

You can make use of hook_node_view like this

function hook_node_view($node, $view_mode) {
  // explode the field contents with comma
  // replace the content with your exploded value.
  $node->content['yourfield'] = 'YOUR_EXPLODED_VALUE';
}

explode


openlayers toggle visibility of layer I hope I'm not breaking any rules, but I wanted to cross-post this --- it is in the stackexchange for 'geographic information systems', but now I think the problem may be more on the Drupal side.

https://gis.stackexchange.com/questions/41223/openlayers-toggle-visibility-of-layer

I think the problem I'm having is in two things:

I'm not sure how best to get a handle on the map object in jQuery.
There seems to be a separate issue where strangely the click event is being fired twice.

EDIT: What I'm in effect trying to do is have the switchers below the map behave in the same way as the switchers in the right-hand-side grey switcher widget supplied by the openlayers library itself. See the screenshot.

I'm copying the question here, for the use of search engines etc.

I'm using OpenLayers in Drupal and am stuck while trying to make a layer toggle on and off (as it does from the right-side layer switcher).

See this map.
http://dev.lambeth.coop/map

Click on food growing projects.

EDIT: I've changed the code to show the Drupal-specific elements.

(function ($) {
  Drupal.behaviors.openlayers_switcher = {
    attach: function(context, settings) {
      $(document).ready(function() {
        $('[id^=openlayers-switcher-block--]').click(function(e) {
          $(this).toggleClass('active');
          // 27 is the length of 'openlayers-switcher-block--'
          // layername is the string following that.
          var layername = e.target.id.substring(27);
          var ol = $('.openlayers-map').data('openlayers');
          var layers = ol.openlayers.getLayersByName(layername);

          // this doesn't work
          // if (layers[0].visibility) {
            // layers[0].setVisibility(false);
          // }
          // else {
            // layers[0].setVisibility(true);
          // }
        });
      });
    }
  }
}(jQuery));

When I try to toggle visibility - the visibility doesn't change.

EDIT: So it appears that the entire click function is being called twice.

I've tried putting these lines (in various combinations) at the beginning of the function, as these have been suggested in google searches for 'click events firing twice' etc.

$('[id^=openlayers-switcher-block--]').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

... but these don't help - I still get the function called twice.

In any case, I'm new to openlayers and would be grateful for a way forward!

Thanks!

@Duncanmoo: You're quite right, the response to this was incredible. It's nice to have the opportunity to explain how I came up with the current working solution.

The solution has a number of parts and is not entirely elegant, so feedback and advice is still very welcome!

Here is my custom drupal module:

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers_switcher/openlayers_switcher.module

The default html generated by openlayers for the switchers wasn't very easily changed with css, so I have hacked the openlayers.js file to give it some structure (for example wrapping each switcher in an anchor tag).

Take a look here for the amendments I made (search for lambeth.coop):

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers_switcher/OpenLayers-2.11/OpenLayers.js

... a very important hack here was to add the click event to show/hide the layers (at time of writing this is line 2850):

// bind the click event to the aSwitcherBlock a element
OpenLayers.Event.observe(aSwitcherBlock,"click",OpenLayers.Function.bindAsEventListener(this.onInputClick,context));

... this meant I could by-pass all the horrible jQuery problems I was experiencing and made me very happy!

... I would like to do the same with the openlayers-2.12 js file but got stuck. I'd love to find a way to do this - currently I'm stuck on openlayers-2.11 which is the old version as far as the Drupal Openlayers module is concerned. So that's a bit dumb.

Finally, see here for a method of taking the entire layer-switcher out of the default right-hand-side-of-map position and assigning it to a div outside the map:

http://drupal.org/node/1475316#comment-6945728


How to set value of file field with entity_metadata_wrapper How do you set the value of a file field when using the entity_metadata_wrapper?

I've tried doing this in code:

$file = new stdClass();
$file->uid = 1;
$file->uri = $file_path;
$file->filename = basename($file_path);
$file->filemime = file_get_mimetype($file_path);
$file->filesize = filesize($file_path);
$file->status = FILE_STATUS_PERMANENT;
$file->display = '1';
file_save($file); // I also tried: $file = file_save($file);

$node = array(
  'type' => 'news_item',
  'uid' => 1,
  'status' => 1,
  'comment' => 0,
  'promote' => 0,
  'language' => 'en',
);

$entity = entity_create('node', $node);

$ewrapper = entity_metadata_wrapper('node', $entity);

$ewrapper->field_document->set((array) $file); // I also tried: $ewrapper->field_document->set($file);

$ewrapper->save(true);
entity_save('node', $entity);

But I get this exception:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of C:\wamp\www\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).

Any help is very mych appreciated.

Well I just found out a simpler and less ugly looking way to set image.

$image_file = A FILE OBJECT; //Lot of choices here : new stdClass(), file_load, etc
$wrapper->FIELD_NAME->file->set($image_file);

Just as taxonomy or node/entity reference, the file field name point on a loaded object, thats how I find out.

:: EDIT a posteriori ::

Here how I would have do it with OP question.

// Get the file
$file = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg');

// Wrap' it like one of your French girls
$wrapper = entity_metadata_wrapper('node', $node);

// And set the photo
$wrapper->field_photo->file->set($file);

// And save the node
$wrapper->save();


Link to files stored in drive In a content type I have a links fields using Link Module which has Title and URL set. This is useful to link the external files but I have a requirements also to link the files stored in Networked hard disk.

In an intranet system there is a drive eg: Z drive, which is same for all the systems in Intranet. The drive is actually an intranet server which stores all the doc files for everyone's use. When System Admins set-up new computers they set-up in such way that server drive is always Z drive in any computer (company preference).

I have a task to link to the file from Drupal site, lets say the file path is:
 z:\popular-documents\how-to-use-pc.docx

When I give the above file path to link field, it changes the whole Link completely like:
http://localhost/Z%3A%5Cpopular-documents%5Chow-to-use-pc.docx

How can I use Link Module to link to the file and display the file link as it is instead of having http:// which link module adds by default.

The reason I have to use Link Module is I also want to be able to link it to external files too, lets say Google docs.

Not a requirement but good to have, if possible when the link is clicked it would open the file (I guess this is not possible from web interface).

As I also stated in my comment, try to give a real network path. For example if the shared folder Z: is mapped to \\server\folder, the real network path of the file would be:

  file:///\\server\folder\popular-documents\how-to-use-pc.docx

UPDATE:

According to Link module page:

  Filter allowed protocols module This module allows you to change the default protocols that are set by Drupal to include new protocols like skype. The default protocols, for reference, are 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', and 'webcal'.

You can try this module to include 'file://' protocol.


How do I find available public methods? I'm finding that the biggest problem in working with Drupal 8 is I can't get the data I need.  Drupal 8 wants me to use public methods rather than manually drilling down thru an object.  The problem is, I can't figure out a consistent way for getting a list of available methods! (they magically exist, and I feel like I'm just supposed to know about them).=

For this example, let's say I have a content type with a video field.  I need to get the raw URL of the video file in that field.

So I'd start with a node id ($nid), and somehow I have to figure out how to load the node.  This isn't too bad because there's lots of examples.  So I do something like $node = \Drupal\node\Entity\Node::load($nid);.

So far so good.  Then I need to get the value of my video field (field_main_video).  This took me FOREVER to figure out because there's conflicting documentation around the 'net.  Finally I figured out I'd have to do something like this (because it is a multivalue item):

$video = \Drupal\node\Entity\Node::load($nid)->field_main_video->getValue();

...then loop thru the array etc.  Using kint didn't help me find this, either.  Because, for example, if I kint($node) and look under methods, I don't see getValue() as an item there.  Still not terrible, because there were enough examples around to figure it out.

As I go deeper, though,  what I didn't know (this is the important part) was that rather than getting the video field entity id, then loading the entity, then finding the "uri" field in the entity, etc (like I would in D7):  There was a method that lets me get the URI all in this same line of code!

$url = \Drupal\node\Entity\Node::load($nid)->field_main_video->entity->getFileUri();

But how could I possibly have known this getFileUri() existed?  I happened to stumble upon it in a blog post.  This truly DOES make getting a URI easier than in D7...but only if you know (magically) what methods exist for each 'level' of an object.

In the end, with this example I'm asking: How do you find all public methods for each level of an object in a way that's easy to read and understand?  Note that it seems there should be a drupal-centric (ie. devel module) way of doing this rather than manually searching api.drupal.org or using something IDE specific?

Content entities are different from most other things in that they often do not have methods and proper interfaces, at least not for configurable fields.

In case of content entities and fields, public methods is not really what you actually want to know, what you want is to know about fields and properties. And only when you get to an entity again through a reference then the methods matter.

For an overview, I always refer to the great Entity API Cheat Sheet.

Content entities have a fixed structure, Entity > Field (FieldItemList) > FieldItem -> Property. A property is either scalar or a reference to something else, e.g. another entity, a language object, a date object, ...

For a few specified examples, some useful snippets:

// List of fields that an entity has, the field definitions also have a lot of information like the type.
array_keys($entity->getFieldDefinitions())

// Use get() instead of the magic __get() on the entity level then you at least get some type hints.
$entity->get('field_name').

// Get the list of properties a certain field has, use array_keys() again for just the names, but the definitions also have the type and if it's computed or not.
$entity->getFieldDefinition('field_name')->getFieldStorageDefinition()->getPropertyDefinitions()

// Most field types have value property, but e.g. entity references have target_id and the computed entity. as you found. File and Image fields have additional properties like title/alt/description.
$entity->get('field_name')->value
$entity->get('field_name')->target_id
$entity->get('field_name')->entity

// Note that get('value') is not the same as ->value on the field item level, get() returns a typed data object, get('value')->getValue() is the same as ->value.

// When not specified, the delta 0 is assumed (all fields are a list internally, even something like the node id), you can use array access or the delta to access another delta, make sure it exists.
$entity->get('field_name')[1]->value
$entity->get('field_name')->get(1)->value

// When you have an entity reference, you can get the entity type and class like this:
$entity->get('field_name')->entity->getEntityTypeId()
$entity->get('field_name')->entity->getEntityType()->getClass()
// or
get_class($entity->get('field_name')->entity)

// From there you can look up the interface and type hint against that, to a) make sure you have a valid, loadable reference and get type hints in an IDE:
$file = $entity->get('field_name')->entity;
if ($file instanceof \Drupal\file\FileInterface) {
  $file->getFileUri();
}


FeedsHTTPFetcher: how to parse object to get source url? I've got several content-types based on imported RSS feeds (Feeds import, Simple Pie library).

In a Views pre render, I try to display an information stored in $row->node_feeds_item__feeds_source_config that looks like this:

a:1:{s:16:"FeedsHTTPFetcher";a:1:{s:6:"source";s:38:"http://www.as-e.be/agendas_rss/rss.xml";}}

How can I just get the http://www.as-e.be/agendas_rss/rss.xml part of that object? I have no idea how to parse that.

Ok, I found out a dirty solution to extract an URL from a random string text!

preg_match('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $row->node_feeds_item__feeds_source_config, $match);


How can I add an entity reference to a list entity refences of a node with rules? I have a node with a entity reference field with multiple values.

How can I add an entity reference to a this list with rules?

You didn't post your setup and where you want to trigger the rule, but you would do this with PHP code added as a rule action:

$node = node_load(YOUR_NODE_ID);
$node->field_you_want_to_save[]['target_id'] = NEW_ENTITY_REFERENCE_ID;
$node->save();


Creating Omega sub theme manually I'm trying to create a functioning sub theme of Omega 4.4. I've worked  with Drush before with it, but the site is on a host that I'm not administrator of. I've tried the Drush Webservice module but not succeeded in executing the Omega Wizard. In short, the Omega Wizard may be extremely helpful, but I can't get it to work.

Next, I've tried to manually create a sub theme using the instructions here. However, the results of this is a theme catalogue in the Themes-folder, but the theme not showing up in Drupal. Perhaps I'm using the wrong instructions for the wrong version of Omega?

Anyhow, does anyone have instructions for how to install an Omega 4.4 sub theme manually for Drupal 7?

This documents manually copying the default starterkit subtheme in Omega 4.4. The instructions are similar for both "dusty" and "default" starter kits. Note that the "default" theme has libsass, and has less files then "dusty."

  Dusty: the original omega front-end set up, which is becoming increasingly outdated.
  Default: a more contemporary subtheme, front-end development wise. This is the better option.

Note: since I use a simple, one-word theme name in this example I can replace THEME-placeholders with one value. If you wish to have a more complex subtheme name, consider this array from the drush omega subtheme function:

'/{{ THEME }}/' => $machine_name,
'/{{ THEME NAME }}/' => $name,
'/{{ THEME SANITIZED }}/' => str_replace('_', '-', $machine_name),
'/{{ THEME CAMELCASE }}/' => $camel,
'/{{ THEME CAMELCASE LOWER }}/' => lcfirst($camel),

Prerequisite: Your theme's name. I'm using "mytheme" Substitute mytheme with your theme name.

Copy themes/omega/omega/starterkits/default (or dusty) to themes/mytheme
Copy default.starterkit.inc to mytheme/mytheme.info
Changes to mytheme.info

Change the name value to 'mytheme'
Insert base theme = omega to line 3
Change the theme file names from {{  THEME SANITIZED }} to mytheme
For example - from:
stylesheets[all][] = css/{{ THEME SANITIZED }}.reset.css
To:
stylesheets[all][] = css/mytheme.reset.css
Change the scripts name to css/mytheme.behaviors.js
Add regions info:
; ========================================
; Regions
; ========================================
regions[branding] = Branding
regions[header] = Header
regions[navigation] = Navigation
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = First Sidebar
regions[sidebar_second] = Second Sidebar
regions[footer] = Footer

Update theme name in files:

package.json: {{ THEME }} to mytheme
template.php: {{ theme name }} to mytheme
theme-settings.php: {{ THEME }} and {{ theme name }} to mytheme
preprocess/page.preprocess.inc: {{ THEME }} to mytheme
process/page.process.inc: {{ THEME }} to mytheme
sass/README.md {{ THEME SANITIZED }} to mytheme
The following renames are in dusty only:

.ruby-gemset
bower.json
libraries.make

Rename files as necessary:

Rename css files to css/mytheme.reset.css (default subtheme only) and css/mytheme.styles.css
Rename scss files to sass/mytheme.reset.scss (default subtheme only) and sass/mytheme.styles.scss
The following file-renames are in dusty only:

Rename css files to css/mytheme.hacks.css, css/mytheme.no-query.css and css/mytheme.normalize.css
Rename scss files to sass/mytheme.hacks.css, sass/mytheme.no-query.scss and sass/mytheme.normalize.scss

And there it is:

I've created a github of that shows the comparitive starterkit to wizard-created subthemes. Using this link, you can see all the necessary modifications you'll need to make, for dusty here or for default, here

I've updated this document out of pure curiosity. If I were in your situation, however, I would simply run the omega-wizard on my local dev environment, and push the theme to my server.


Creating view content link that links to data based on taxonomy terms how can I create view content link that links to data based on taxonomy terms?

I have stores in stores page...stores are in views..each store should have a link that links to its products.

Here's how to achieve this:

Add relationship that references the taxonomy field you use in the content type.
Add a Taxonomy term: Term ID field in Views. Exclude it from output.
Add a Custom Text field in Views.
Under Rewrite Results check the Output this field as a link checkbox. In the link path use the token for taxonomy term id - [tid]. If you want to use the core page, just enter taxonomy/term/[tid].

Hope it helps.


How to write page.tpl.php where the HTML files is more than one? I'm using Drupal 7 and trying to set my custom theme up.

I usually replace the index.html to page.tpl.php, then I change what I want it to be dynamic on my site. But now I have more than one HTML file which is about.html, blog.html and contact.html

Can anybody explain to me how to write that?

Actually you may have to create a page--front.tpl.php for index page of your website and a page.tpl.php to have all other pages.

you could also use theme debug mode too. it can be enabled by including the following in settings.php,

$conf['theme_debug'] = TRUE;

The ablove will include theme suggestions as html comments, that helps you theming your pages.


dupal form: how to assign specific id to radio button using form api I wanted to change id of radio button. But i dont know which attribute shall i use to do that.

$form['entry.497535900'] = array(
'#type' => 'radios',
'#title' => t('Category'),
'#options' => array('P' =>'Product','S' => 'Services','O' =>'Others'),

);

If you need to assign IDs to each radio option, then you can use custom theme function, to theme your radios. See example:

$form['entry.497535900'] = array(
  '#type' => 'radios',
  '#title' => t('Category'),
  '#options' => array('P' =>'Product','S' => 'Services','O' =>'Others'),
  '#theme' => 'mymodule_custom_radios',
);

The #theme parameter specifies function, which overrides the default radios styling function. You will need to define this function in hook_theme() and create the content of the function, where you can specify, how radios should be rendered.

/**
 * Implements hook_theme.
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_custom_radios' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

Then create the content of this function.

function theme_mymodule_custom_radios($element) {
  // You can access all radios options like this - $element['#options'];

  $output = '';
  // ... create html output according to your needs
  return $output;
}


Can't get the module quick edit to work (have some error screenshots) I've successfully installed the module Quick Edit that let's you edit nodes in-place (in a similar way to Panels in-place editor) and might save time.

After installing the module I've yet to see any quick edit button (img1) So I tried to check permissions and they were seem fine, and I'm the admin (img2). Than I tried to clear cache and again there was no such button, so I went to ran cron and some errors appeared (img3+4).

On the quick edit drupal page it says,

  Works with any Drupal 7 site (requires the Entity API, CTools and
  Libraries API (>=2) modules, plus the Underscore.js (>=1.5) and
  Backbone.js (>=1.0) JavaScript libraries). If in-place WYSIWYG editing
  is desired, you must also use the CKEditor module.

You need to download and install the libraries module

Then you need to create a libraries folder in sites/all folder. So it looks like this sites/all/libraries

Then you need to download the Backbone.js and Underscore.js and put them inside the sites/all/libraries folder.

I also see you have some other errors, which is not Quick Edit related. Must be from some other module you installed.

What the errors are saying is that you need to create a custom CK editor http://ckeditor.com/builder and make sure you include the Shared Space and Source Dialog plugins. So under avalable plugins (right column), scroll and find these plugins and click on the left arrow to include them on your CK editor build. Then scroll all the way down, checkmark the I agree to terms box and click on Download. Then you need unzip and put the ckeditor folder in your sites/all/modules/ckeditor/ folder. So it will look like this sites/all/modules/ckeditor/ckeditor


Files permissions with organic groups Is there a way to use organic groups to manage file permissions for files uploaded to site? I would like have of at the node level and file level.

The submodule 'Organic groups field access' of the OG project should be able to help you manage file access based on Organic Group permissions.

You can create private Organic Groups by enabling the OG submodule 'Organic groups access control'.

Depending on the useless: Make sure to add a 'Group visibility' field to the Group bundle or a Group Content visibility to the group content bundle at admin/config/group/fields.