Multi-site just separated content There is a lot of blog posts and tutorial about multi-site with content sharing.

But what about inverse of it? Multi-site with separated contents?

Exactly which tables should be shared?

here is my settings.php for sub-site:

$databases = array(
    'default' =>
    array(
        'default' =>
        array(
            'database' => 'xxx',
            'username' => 'xxx',
            'password' => 'xxx',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => 'default_portal_',
            'prefix' => array(
                'default' => 'default_portal_',
                // Users
                'users' => '',
                'sessions' => '',
                'role' => '',
                'role_permission' => '',
                'authmap' => '',
                'blocked_ips' => '',

                // Blocks
                'block' => '',
                'block_custom' => '',
                'block_node_type' => '',
                'block_role' => '',

                // CKEditor
                'ckeditor_input_format' => '',
                'ckeditor_settings' => '',

                'comment_notify_user_settings' => '',

                // Configuration
                'date_formats' => '',
                'date_format_locale' => '',
                'date_format_type' => '',
                'field_config' => '',
                'field_config_instance' => '',
                'filter' => '',
                'filter_format' => '',
                'i18n_block_language' => '',
                'i18n_string' => '',
                'i18n_translation_set' => '',
                'image_effects' => '',
                'image_styles' => '',
                'languages' => '',
                'locales_source' => '',
                'locales_target' => '',
                'node_type' => '',
                'quicktabs' => '',
                'rdf_mapping' => '',

                // Support
                'support_assigned' => '',
                'support_client' => '',
                'support_priority' => '',
                'support_reference' => '',
                'support_states' => '',
                'support_ticket' => '',
                'support_ticket_comment' => '',

                // System
                'system' => '',
                'taxonomy_term_data' => '',
                'taxonomy_term_hierarchy' => '',
                'taxonomy_vocabulary' => '',
                'variable' => '',
                'variable_store' => '',

                // Views
                'views_display' => '',
                'views_view' => '',

                // WYSIWYG
                'wysiwyg' => '',
                'wysiwyg_user' => '',
            ),
        ),
    ),
);

EDIT

Above configuration works after cache clearing, but some tables should not shared: variable and variable_store because of site_title and site_slogan ...

EDIT

If I share block table, I should enable all themes in main site.

yet I have question to ensure which tables should share?

Yes , this is good idea, in one of my past work we do something like this, dedicated  drupal core but with separate content .


Access denied for admin? Why when I am logged as admin I get an access denied page, the page is custom like mysite.com/test - added by the custom module:

function onthisdate_menu() {
  $items = array();

  $items['test2'] = array(
    'title' => 'Test route',
    'description' => 'description of test',
    'access callback' => TRUE
  );

  return $items;
}

Why is that happening?

You're missing page callback from your menu item. From the docs:

  "page callback": The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

Since your menu item is the root item (has no parents) that's probably what's causing the access denied.

Just add a page callback to your menu item, implement the function to return a string or render array to display the page, clear Drupal's caches, and it should work.


Need module for notifications like privatemsg I am using Drupal7 and notification module. Now i want the notification like Private Message module. When any comment occurs or any post occurs at that time i want notification like "Private Message" module i.e. just like "3 new messages" i want same like this "3 new comments" etc..

Can you please inform me if there is any module exists or not

There is messaging_simple  table which stores message values.

See the column timeread this provides time when the message is read. The entries which have 0 value shows unread message.

You can apply sql query to find out rows with timeread 0 for logged in user and can get the count of unread messages.


How do I override a view template in my theme folder properly? I do not know if I am something missing, but I have a View in Drupal 8 and wanted to make a Template override in my theme, where I would print-out the image URL of one field and set it as "background-image" via inline CSS.

So I turned on theme debugging to see the template suggestions and picked views-view-field.html.twig, copied the file to my theme, renamed it to match the suggestion, cleared the cache and it looks like the template override is working.

But all the variables I am trying to print-out are blank, even after clearing the cache the field just disappeared. When I try to dump() or kint() any variable written in the file (view, field, row, output) it prints "null" or completelly nothing.

What am I doing wrong?

I am sure template override works, because when I type regular text in a file it gets printed out, but all the variables are somehow missing and I can not print anything out of them.

Copy the content of the previous template used and start from there.
It is most likely that the variable you are trying to display are not available in that template.
Consider adding variables using hook_preprocess.


What would be the best way to setup a mobile theme for an existing domain with domain access module? We have implemented a multidomain portal using domain access module. Now we would like to setup a mobile site for each domain added.

Initially we thought about going for responsive layout, but as the mobile portal has very simple layout with minimum elements, using responsive model might be an overkill as it load every html elements to mobile even if most of the elements are not used in mobile theme. Also there are few features/blocks like slider etc implemented differently in mobile theme.

The m.domain and separate theme for mobile site looks like a feasible solution. But I am not sure what would be the best way to integrate it with domain access.

We want all content in the desktop domain available in the mobile domain, only theme need to be changed. It would be good if we were able to setup a domain alias where we can provide the m.domain.com in the configuration for the main domain and use the same access control as main domain, only change will be the theme and the links rel="alternate" and rel="canonical"

Also we need to setup a http redirection when a user visit the site from a mobile device. (Any suggestion for switching back to the desktop theme from mobile device and vice versa)

Is there any way to implement something like this using domain access?

You need these two modules to do this:

https://www.drupal.org/project/simple_mobile_redirect
(detects mobiles and redirects them to pre configured paths)
&

https://www.drupal.org/project/themekey
(serves any theme (e.g. a customized mobile theme) under any pre configured path)


pass argument as a wildcard to node/add/Article/560012 Case :

I do have a Article-share content type , it does contain a node reference to type "Article" , now this is my scenario :

user selects a node of type Article
he redirects to node/add/Article share
now in this form I want the selected coupon shows up in the form automatically so the user wont need to fill this field again

Some more deails:

I have a content type called "Article-Share".
This type has a reference field to Node type "Article".
I want my content creation form for type "Article Share" to use wildcards to automatically fill "Article Link".

Any suggestions how I can do so?

You will need a module for that but it's easy :

the scenario is this :
on screen 1 , you've got a form which contains a select list , when user submits this form , will redirects to a content creation form , the important thing is that the coupon id must be passed to it .

so the solution :

you will have a submission function for your first screen form

function first_screen_form_submit($form, &$form_state) {
  //enter some codes here to get nid of selected coupon
  //.
  //.
  $form_state['redirect'] = 'node/add/coupon-share/'. $nid;
  drupal_redirect_form($form_state);//this will redirects you to form and passes the nid
}

now you must alter the node creation form :

//Implement hook_form_BASE_FORM_ID_alter()
function YourModuleName_form_node_form_alter(){
  if(isset($form['type']) && isset($form['#node'])) {
    $type = $form['#node']->type;
    switch($type) :
        case 'coupon-share':
          $passedNid = arg(3);
          $passedNode = node_load($passedNid);
          //now you have the coupon node available here and can fill your field with it
          //.
          //.
          breake;
  }
}


How to create a new block programmatically? I need to programmatically create a new block. The block must show 3 last news (site content): title as a link + date of publication (format dd-mm-yyyy).

Any suggestions?

The info hook defines your block in the system:

function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

and the view hook creates the output (html) for your block:

function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('My last 3 news');

    $query = new EntityFieldQuery();
    //change news by the name of your content type
    $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyOrderBy("created", "DESC")
    ->range(0, 3)
    ->execute();

    $block['content'] = '';

    foreach($entities['node'] as $obj) {
      $node = node_load($obj->nid);
          $block['content'] .= l($node->title, "node/" . $node->nid) . ' - ' . date('d-m-Y', $node->created) . '<br>';
    }

     break;
   }

  return $block;
}

Remember assign a region to your block in YOUR_SITE/admin/content/blocks

Output:

References:

How do I create a static block programmatically?


Why does Drush require sudo? I’m running Ubuntu 14.04.5 with Drush v 8.1.8 and I can’t seem to execute Drush without using sudo. For example if I try to execute ‘drush cc all’ without sudo, I get:

‘Directory /home/myuser/.drush/cache/default exists, but is not writable. Please check directory permissions. ‘
‘Directory /home/myuser/.drush/cache/complete exists, but is not writable. Please check directory permissions.   ’

If I then manually modify the permissions on .drush and everything under it to 777, the next Drush command will work but the one after that will fail with the same error. I also tried ‘chown -R myuser:myuser ~/.drush’.  Same result.

I thought perhaps I installed Drush incorrectly, so I tried removing and then re-installing it three different ways:

Using this approach: https://www.drupal.org/node/1248790 (sudu apt-get install drush).
This way: http://docs.drush.org/en/master/install/ (executing php to load Drush from a remote file)
Finally by installing Drush using method (2) and then moving Drush into my home/bin folder and chown -R to me.

All of them have the same result — drush doesn’t work without sudo. There’s no reason I can think of why this should be. What’s even weirder is if I chown of .drush (and everything under it) to me, then execute drush without sudo, it will change ownership of directories under .drush/cache to root. I don’t even know how that’s possible since I’m not root!

Please let me know how I can get Drush to work without root privileges.
Thanks.

I'd suggest you follow the official install instructions here after removing your current install - http://docs.drush.org/en/master/install/

When you have it installed then navigate to your home folder:

cd ~/
ls -lash

At this point your .drush folder should have your user as owner (not root)

If it doesn't then run

sudo chown myusergoeshere:myusergoeshere .drush -R

You can run ls -lash again and confirm the right user and group.

You should now be able to run drush without using sudo.

The reason you get that error is because when you installed it the system created the folder using the root user in your home directory so as your user you don't have permission to modify the folder.


Logo size should not reduce after uploading - Drupal 7 I have had uploaded a logo in my site.

After uploading the image's size is reduced. Because of that, image quality is decreased and it doesn't look good.

What should I need to do TO NOT REDUCE THE SIZE OF THE LOGO after uploading.

I'm uploading via admin/appearance/settings/theme_name and using "Upload logo image" option

In admin/config/media/image-toolkit the JPEG quality is 75%. I made it 100%, still it doesn't work.

Any suggestions or advices will be helpful...

Don't use "Upload icon image", that's for favicon. Use "Logo image settings" -> "Upload logo image".

I tested this theme and both logo and favicon work perfectly. Logo is not altered in any way and favicon works, no matter what size.


Views query alter or condition not works Want add some or conditions in view queries. I tried two solutions but it not working. What I do wrong?

function up_coaching_custom_views_query_alter(&$view, &$query) {
  $search_string = empty($_GET['filter']) ? '' : '%' . db_like($_GET['filter']) . '%';
  if ($view->name != 'users' || empty($search_string)) {
    return;
  }

  // First way
  $condition = db_or()
      ->condition('users.mail', $search_string, 'LIKE')
      ->condition('field_data_field_company.field_company_value', $search_string, 'LIKE')
      ->condition('field_data_field_user_name.field_user_name_value', $search_string, 'LIKE')
      ->condition('field_data_field_title.field_title_value', $search_string, 'LIKE');
  $query->add_where(2, $condition);

  // Second way
  $query->where[2] = array(
    'args' => array(),
    'type' => 'OR',
    'conditions' => array(
      array(
        'field' => 'users.mail',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_company.field_company_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_user_name.field_user_name_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
      array(
        'field' => 'field_data_field_title.field_title_value',
        'value' => $search_string,
        'operator' => 'LIKE',
      ),
    ),
  );
  $query->set_where_group('AND', 2);
  dpm($query);
}

Ok, both solutions are work. The problem is in query fields that not exist because need add field tables. I didn't unserstand this because of this:

    catch (Exception $e) {
        $view->result = array();
        if (!empty($view->live_preview)) {
          drupal_set_message($e->getMessage(), 'error');
        }
        else {
          vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
        }
      }

Views didn't show me error.


Display Block only on users profile2 I am using vies3, profile2 and context to display the users created content on their profile2 page. Using context i can allow the block to be display on the users drupal profile, how can i extend this to only show the block on the users profile2 profile?

You want to display a unique block for each user that can be publicly seen right?

Use Display Suite to put a block into a field instead of using Context.

Or, use Contextual filters in views to use the users UID, but that's more complicated and I'm not sure how to do that since I used Display suite. I found something that might help here Views and contextual filter as user id from url


Alter a view to show the first N results I created a view via the view user interface. From a custom module, I want alter the view for display the n firsts results depending of some user parameters.

I don't find how I can do that with views alter hook functions. For example, via the pre execute view alter hook, I can get the query substructure. How can I configure this structure for not display all results by display only the first N  results?

The "limit" value define the value in the current page with the current "level" of pager (10 results of the 27 results are displayed in pager 1, 10 results of the 27 results are displayed in pager 2 and 7 results of the 27 results are displayed in pager 3). The "limit" doesn't define the total number o, f the result query.

Thanks to Kevin answer, I tried this code.

function mycustommodule_views_query_alter(ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){

    if($views->id() == "mycustomview"){
        $view->query->setLimit(7);
        $view->query->setOffset(5);
        $view->save();

        // I try also ..
        // $query->setLimit(7);
        // $query->setOffset(5);
    }
}

My view in the view page doesn't change and displays 10 results (number total of nodes). How can I set Limit and/or Offset and 'save' the change from the hook view query alter?

After Rémy's answer, I tried this code.

function mymodule_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){

    if($views->id() == "mycustomview"){
        $query->setLimit(3);
        ksm("Hey ! I pass here !"); // log function
    }
}

in drupal/modules/custom/mymodule/mymodule.module file

OR

in in drupal/modules/custom/mymodule/mymodule.views_execute.inc file

and I clear caches with "drush cr"

=> My view page display my log ("Hey ! I pass here !"), BUT, my view always display ALL result :/ Its crazy ! x)

You need to alter the pager, see ViewExecutable:initPager(), so right now only this code works (seems confusing ..):

function mycustommodule_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){
    if($view->id() == 'mycustomview'){
        $view->setOffset(5);
        $view->getPager()->setItemsPerPage(7);
    }
}

  Is that code touched only the first time ? (After running drush cr)

If so - move the method in a file called mycustommodule.views_execution.inc. It won't work on every request inside mycustommodule.module file. see here!

  Also make sure Disable SQL rewriting is not set in the view used !

For more information see the issue I addressed regarding this on d.o.


How to run entity field query in cron without getting undefined stdClass::$roles notice? I've got a cron job which executes an entity field query to count the number of some nodes associated with a user (for each user in the system). Whenever this runs I get the following in the watchdog logs:

  Notice: Undefined property: stdClass::$roles in user_access() (line 820 of […]/Drupal/modules/user/user.module).

Is there anything specific I need to do to avoid this happening (not involving changing log levels or otherwise ignoring the issue)? Any particular best practices when using Drupal queries outside the context of a "real" session? The reason I'm doing this is to get rid of any spurious noise in the logs, and reduce the chance of breaking things in case of change to both my own and Drupal code.

Query code:

$q = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $content_types, 'IN')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $uid)
    ->propertyCondition('type', $content_types, 'IN')
    ->fieldCondition('field_something', 'value', $code, '=');

$award_count = $q->count()->execute();

Stack trace:

[…]/Drupal/modules/node/node.module(3334): user_access('bypass node acc...', Object(stdClass))
[…]/Drupal/modules/node/node.module(3296): _node_query_node_access_alter(Object(SelectQuery), 'entity')
[…]/Drupal/includes/module.inc(1163): node_query_entity_field_access_alter(Object(SelectQuery), NULL, NULL, NULL)
[…]/Drupal/includes/database/select.inc(1253): drupal_alter(Array, Object(SelectQuery))
[…]/Drupal/includes/database/select.inc(1261): SelectQuery->preExecute()
[…]/Drupal/includes/database/select.inc(1275): SelectQuery->preExecute()
[…]/Drupal/includes/entity.inc(1389): SelectQuery->execute()
[…]/Drupal/modules/field/modules/field_sql_storage/field_sql_storage.module(652): EntityFieldQuery->finishQuery(Object(SelectQuery), 'entity_id')
[internal function]: field_sql_storage_field_storage_query(Object(EntityFieldQuery))
[…]/Drupal/includes/entity.inc(1216): call_user_func('field_sql_stora...', Object(EntityFieldQuery))
[…]/[my code path]: EntityFieldQuery->execute()

Running Drupal 7.56.

As you can see in the cron doc, cron runs as anonymous user so you have to run the query as admin user.

In the EntityFieldQuery DO doc you can see examples, but essentially you just need to add the addMetaData code to the end  of your query:

 $q = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $content_types, 'IN')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $uid)
    ->propertyCondition('type', $content_types, 'IN')
    ->fieldCondition('field_something', 'value', $code, '=')
    // Run the query as user 1.
    ->addMetaData('account', user_load(1));


Disable off-site payment redirect I am using Drupal Commerce Kickstart and since we are having only one payment method I would like to disable the extra step "Payment" in the checkout process which is reserved for "Off-site payment redirect".

I did not find a way to disable this directly in the UI at Checkout settings (admin/commerce/config/checkout) because this checkout pane seems to be locked.

So I digged in code and found line 309 to 315 in commerce_payment.module (profiles\commerce_kickstart\modules\contrib\commerce\modules\payment\commerce_payment.module).

  $checkout_panes['commerce_payment_redirect'] = array(
'title' => t('Off-site payment redirect'),
'page' => 'payment',
'locked' => TRUE,
'file' => 'includes/commerce_payment.checkout_pane.inc',
'base' => 'commerce_payment_redirect_pane',
 );

If I completely remove these lines the payment step is gone. If I set the locked value to "FALSE" I can disable the pane at Checkout settings.

What is the cause that this step is locked and is it safe to disable this step this way?

You don't need to disable it, because it will automatically skip itself if the payment method does not require an off-site redirect.


How to use the Features API to enable a feature? So I looked at the features API, and in order to enable a feature, they use this code:

function hook_pre_features_enable_feature($component){
};

So I go in and add this:

function mysite_pre_features_enable_feature($component){
    $component = 'roles';
};

My Feature is already there, but it never gets enabled. Why is this?

in order to enable a feature, they use this code

That's not accurate. The hook function is actually:

  Invoked on a Feature module before that module is enabled.

It's not involved with the action of enabling the feature, it's just a listener to enable it to run some code just before something else enables it.

Features are just modules, and to enable one you use the same method as if you were just enabling a module:

module_enable(['foo']);


"Drupal already installed" Message on Restored site We had an issue on a Drupal 8.8.2 site, had to restore DB, Core and Vendor, now anyone visiting the site gets the site as normal, but if admin logs in I receive:

Drupal 8.8.2
Drupal already installed
- To start over, you must empty your existing database and copy default.settings.php over settings.php.
- To upgrade an existing installation, proceed to the update script.
- View your existing site.

Of note:
Rather then restore over existing db I created a db2, restored the DB to it and pointed the settings to it (not sure if that is the issue)

I can't figure out how to stop that page from loading. I don't want to start over, running the update script does nothing but bring me back to the same page. View your existing site does take me to site but can't edit anything (looks like it just logs me out).

Seeing the install page on an already installed Drupal site usually is a sign of problems with your database connection before the request has been processed by PHP.

This may have a wide range of causes, most likely related to your database server configuration.

The first thing to check is your database logs, which may give a hint on how to solve your issue.

We often experienced a similar behavior on sites that heavily use the database. E.g. sending big queries when rebuilding page caches on complex pages. The solution there was to ensure a high enough max_allowed_packet setting. See here for more details on how to do that.


How to create a dynamic main menu tabs I want to create a dynamic main menu according to user roles. For example if an anonymous user visits he can only see the 'Home' and 'About Us' links, while registered users can see additional links like 'Contact Us'. Is there a way to do that, through a module perhaps? I don't want to edit in source code.

You can use Menu per Role module.

Project page says:

  This module allows you to restrict access to menu items based on user
  roles. It depends on the Drupal core menu.module just activate both
  modules and edit a menu item as usual. There will be a new fieldset
  that allows you to restrict access by role. The fieldset also appears
  in the node edit form.


Templatization for different countries Which is the best module to do a multilingual site for different countries. This is the exact word from client requirement.

"Site created for ABC country can be quickly adapted for country XYZ"

They are mainly looking for reuse of code.  Like they create a website for one country and they reuse the same code and same DB fro different county but language will be different.

You can maybe try something like this:

function phptemplate_preprocess_node(&$vars, $hook) {
    $language = $vars['language']->language;
    $vars['template_file'] = 'page-'. $language;
}


Commerce - delete products that do not reference a node I want to delete commerce products that are not referencing nodes. Either a delete process or report that shows which commerce products are not referencing nodes.

Try the Views Bulk Operations module.

You can create a View that lists Commerce Products

Use the Table format, showing fields.

Add a filter for the reference field and for the operator choose "Is empty (NULL)".

Add a field to the View, look for "Bulk operations: Commerce Product"

When the field settings come up, in the "Selected bulk operations" field set, check the "Delete Item" checkbox.
Arrange this field to be the first one in the list.

Save the view.

Now you will see all products that do not have a value for your reference field. The Bulk Operations: Commerce Product field will make a checkbox display for each row, and you can select one or more products to delete.

You can also check the text box in the table header, and that will "select all" products listed on the page. If you have more than one page worth of products, a button will appear that will let you select all products in the view.

Choose the "Delete Item" option from the drop down above the view and hit the button, and it will start the delete process, after a confirmation.


Sending yourself a copy of the email I m using Drupal 7 with the Webform module to send email. On a form I have checkbox to send yourself an email copy. When it is checked, there will be a field to enter the email of who sends the email. The email should be send to this address also.

I created a custom module for this functionality. This module file used for creating a send a copy of message to me functionality

function sendmail_webform_form_alter(&$form, &$form_state, $form_id) {
     error_reporting(E_ALL);
     ini_set('display_errors', 1);
     // webform_client_form_52  webform id
     if($form_id == 'webform_client_form_52') {
         $form['submitted']['send_a_mail_yourself'] = array(
         '#type' => checkbox,
         '#form_key' => 'send_a_mail_yourself',
         '#title'=> 'Send a copy of yourself',
         '#weight' => 4, // As your needed
         '#field_prefix' => '
',
         '#field_suffix' => '
',
         '#default_value' => array('yes' => t('send a copy of yourself')),
       );
       $form['#submit'][] = '_sendmail_webform_submit';

       }
     }

   function _sendmail_webform_submit($form, &$form_state) {
     $param = array();
     foreach($form_state['input']['submitted'] as $key => $values) {
        if(valid_email_address($values)) {
             $to = $values; //to email address
        }
        else if($key == 'send_a_mail_yourself' && $values == 1) {
              $send_a_mail = $values;  // Check send a mail to yourself checkbox

        } else {
          if($values) {
               $param[]  = $values;  // All remaining values to store to param array for use of email body
          }
        }
       }

          if($send_a_mail == 1) {
         $from = 'noreply@example.com';
                 foreach($param as $param_values) {
            $body[] = $param_values;
           }

        $to = $to; // Set this email address - emails will be sent to this email address!
        $params = array(
            'body' => $body,
            'subject' => 'Website Information Request',
     );
        if (drupal_mail('sendmail_webform', 'some_mail_key', $to, language_default(), $params, $from, TRUE)) {
            drupal_set_message('Thanks, we will be in contact with more information soon.');
     } else {
            drupal_set_message('There was an error subscribing you. Please try again later');
        }

    }
  }

 function sendmail_webform_mail($key, &$message, $params) {
     $headers = array(
         'MIME-Version' => '1.0',
         'Content-Type' => 'text/html; charset=UTF-8;',
         'Content-Transfer-Encoding' => '8Bit',
         'X-Mailer' => 'Drupal'
    );
    foreach ($headers as $key => $value) {
         $message['headers'][$key] = $value;
    }
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
 }


What's the side-effect of changing the file directory setting of a file field which already has contents? Before, the "file directory" setting of a file field in a bundle is set as "field/file". Now, I want that every user uploads his files into own directory, so I need to add a token in the "file directory" setting. But I'm afraid that the files uploaded in the old nodes can still show normally? If not, how to fix it?

Those files will still be shown normally unless you remove their directory manually, because the file path is stored in the database with each file information. So even when you change the folder for new files, the old ones will still know the path where they were uploaded.


How to loop over a list of Organic Group users using Rules When a user requests to join an Organic Group, I want to send an email to the group's admins. I've found this answer (https://stackoverflow.com/questions/16742925/how-to-send-an-email-to-drupal-7-organic-groups-role-members/23301910) which helps with selecting users with the appropriate role, but I can't for the life of me get a list of just the users from the current group.

You don't need any of that php stuff tenken is saying.
Just install Rules, create a new rule reacting on a user joining a group and use the action "Get group members from group audience". For this to work, you'll have to add to the conditions in the rule that the node is in fact a group.


How do I set up a new Drupal instance with all the modules from a previous one? I had a temporary instance of drupal set up with lots of modules. I now have a new instance of Drupal and I want to install all the same modules, but I can only see how to do it with the GUI admin interface, which is frankly, horrifically clunky and unwieldy.

Is there another way to do this without spending half a day manually installing them again?

I've only heard of Drush, but I'm not sure how to set this up on windows, so this might not be the best answer. Everything I search for online (e.g. 'Export drupal modules') points me back to a 'modules that exports nodes etc.', not a 'mechanism for exporting modules'.

I've also found something called Deploy but I can't tell if this is for modules or just nodes.

This is where the concept of drupal distributions comes in.

Yes you will need drush, a make file with the modules you need and a profile that installs these modules upon site-install.


select list sending old value in ajax request I have a select list on custom module form, on it's select giving ajax call and populating the second select list. But when I select the value from the first list, it is passing old value (previously selected) to the callback function (It should send currently select value).
Following is my code.

  function get_subject($form, &$form_state) {
    $form['students'] = array(
      '#type' => 'select',
      '#options' => $student_array,
      '#title' => t('Students'),
      '#id' => 'students',
      '#value' => ($students != '') ? $students : '',
      '#required' => TRUE,
      '#ajax' => array(
        'callback' => '_subject_loader',
        'wrapper' => 'subject_div',
      ),
    );
    $form['subject'] = array(
      '#type' => 'select',
      '#options' => $subject_list,
      '#title' => t('subject'),
      '#id' => 'subject',
      '#prefix' => '
',
      '#suffix' => '
',
      '#value' => ($subject != '') ? $subject: '',
      '#required' => TRUE
    );
    $form['submit'] = array(
      '#type'=>'submit',
      '#value'=>'Submit',
    );
    return $form;
  }

  function _subject_loader($form, $form_state) {
    return $form['subject'];
  }

Use Form state input rather than using values in ajax call back like below:

if (isset($form_state['input']['students'])) {
    $student = $form_state['input']['students'];
  }


Drupal to Drupal migration of url alias How can I do a Drupal to Drupal migrate that includes the migration of the "url alias"?

The field name (on both source and destination sides) for path aliases is 'path'. As Jaypan says, migrate_d2d should be mapping that for you by default.


Can one domain be hosted on two drupal instances? I have a huge Drupal 6 site, and a small, newer partial version of the site on Drupal 8. Instead of migrating, we decided to build a brand new site from scratch.

Is it possible to host the site such that:

http://www.sitename.com takes user to --> new D8 site

http://www.sitename.com/topic1 /topic2 takes user to new site.

http://www.sitename.com/topic3 /topic4 (everything else) takes user to old D6 site?

Thanks!

You can use a reverse proxy for this, both Apache and Nginx support this. What you do is that you make the Drupal 6 site available on a different URL. This might be even a local url, like sitename2.local. Add this to the hosts file on your server (/etc/hosts on Linux) and point it to 127.0.0.1. Make sure you set up a virtual host in your webserver to point sitename2.local to the root directory of your Drupal 6 site.

By using a reverse proxy you tell your webservice to forward calls to /topic/4 to sitename2.local/topic/4 and return it to the user, just like a proxy. In Nginx it should look something like:

location /topic/4 {
    proxy_pass http://sitename2.local/topic/4;
}

For Apache you need to enable the proxy modules:

> a2enmod
> proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

Your virtual host file should look something like this:

<VirtualHost *:*>
    ProxyPreserveHost On

    ProxyPass /topic/4 http://sitename2.local/topic/4
    ProxyPassReverse /topic/4 http://sitename2.local/topic/4
    (...)
</VirtualHost>

If you Google around for reverse proxy you will find tons of information on how to exactly configure them.


What are the reasons for images going missing without changes made? I have a client who is complaining that images which were there are no longer there. I wasn't sure what to think about it, so I asked him to add them again and let me know if it happens again, meanwhile I took note of the file path (/sites/default/files/styles/large/public/map.jpg).

I have now received another email saying they have disappeared, and upon checking the default Drupal broken image can be found within the WYSIWYG, but there is nothing on the actual page display of the node. I checked the file path and the image still exists on the system. There is also no new node revisions, so they have obviously not messed around with it.

Could anyone provide me with a list of explanations on what could possibly have happened here? I'm confused and I have no idea where to start with this problem!

FYI Drupal version is 7.12!

There are known issues with the images after the security update of Drupal 7.20. I would suggest you to update the latest release if it is the case.
I would also check if there is a .htaccess file preventing access to the files or folders. I remember that there was a similar issue and it was related with a .htaccess file restricting access to the files under the path where the images are saved.


How can I add multiple conditions for the same field taxonomy term in views query? I make some query for views filter for nodes. Use in hook_views_query_alter.

$definition = [
   'table' => 'node__field_characs',
   'field' => 'field_characs_target_id',
   'left_table' => 'taxonomy_index',
   'left_field' => 'tid',
   'operator' => '='
];
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
$rel = $query->addRelationship('node__field_characs', $join, 'taxonomy_index');
$query->addTable('node__field_characs', $rel, $join, 'node__field_characs');

I add array of conditions.

$q_and = db_and();
foreach($ch_id as $key => $val_array){
   $q_and->condition('node__field_characs.field_characs_target_id', $val_array, 'IN');
}
$query->addWhere(0, $q_and);

But if array $ch_id have more then 1 elements, it works wrong. It does not show any nodes.

A similar problem is described here Perform a query with an entity field condition with multiple values. But how can this be applied in this case?

you try this code:

$and = $query->andConditionGroup();
foreach($ch_id as $key => $val_array){
   $and->condition('node__field_characs.field_characs_target_id', $val_array, 'IN');
}

$query->condition($and);


Fix a constant width for first sidebar and second sidebar I'm working on Zero point Theme in drupal 7. In my home page I've three blocks - first sidebar, content and second sidebar formatted as three columns. Here the width of first sidebar and second sidebar are equal and the content has its own width (I'm ok with that). There are some pages where I have only first sidebar and content.

Previously, I was facing a problem like if I go to other pages(other than home-page) the first sidebar's width will be increased. I don't like the view so I changed the CSS.

I gave a fixed width to the blocks by editing the CSS -

.block.themed-block{
                    width: 60%;
                   }

Now, the first sidebar and second sidebar has constant width in all pages.

My Issue is : when I go to other pages where I have only first sidebar and content page, the width of the first sidebar is reduced and the content part doesn't appear from where the first sidebar ends, it leaves some space between the first sidebar and the content part. It shows some odd effect. I want the content part to start from where the first sidebar ends. Is there any way to get rid of that.

Below, I share the screenshot of my Issue.

Highlighted rectangle part is the space, that I want to get rid of.

My guess, before your css editing, the index block filled that white space, right?

you changed the width of the sidebar's content, rather than the sidebar itself (which is a region, not a block)

i don't know of the zero point theme, but look for an outer class, like .sidebar, or .sidebar-first, and set the with of that.

i looked into that particular theme.

revert all the css editing and go to the theme settings, under "layout setting -> sidebars layout" try using the 'fixed' options instead than the 'variable'.


Validation error every time on save comment form Every time I try to leave comment on a content of a certain type I get this error:

  Validation error, please try again. If this error persists, please contact the site administrator.

Refreshing and resubmitting the comment manually does not fix the problem, I always get this issue. The content type in question is displayed via a Panels Node Template, if that matters.

I traced the problem down to the the panels pane that displayed the comments list. If the comments list was disabled, comment submission worked fine; turned back on the validation error returned.

Looks like this is caused by a (likely) bug in CTOOLS. The patch in comment #1 fixed the issue.


the Private files folder outside of "sites/default/files" The Private Files directory is outside of the sites/default/files directory.

Is that fine? I haven't got any problem with that, yet.

I'm using Drupal 7, if that makes any difference.

TL;DR - It is okay even if you place the private files directory outside the sites/default/files directory. In fact, it is recommended that you keep it outside the Drupal root (source). This is hard to implement on shared hosting.

More explaination:
When you specify the path of the private files in Drupal's configuration, Drupal places a .htaccess file with Deny to All in it. Which means that Apache will not be able to serve any of the files inside that directory. The files inside the directory can only be served by Drupal and their paths are resolved as Drupal path.

Example: Let us compare how placing the same file in public and private directory changes the way Drupal handles it. Say the filename is brochure.pdf:

Public file path - If we place brochure.pdf in public directory with path sites/default/files. And in the browser you hit http://yoursite.com/sites/default/files/brochure.pdf.
This request goes to Apache (considering it as a server), Apache tries to resolve the type of request. It tries to go to the directory structure and see if it can fetch the file. In case of public files it has the permission to do so. It directly fetches the file and returns to the browser where it is presented or downloaded. In fact the request doesn't even need to go to Drupal or the PHP interpreter for that matter.
Private file path - If we place brochure.pdf in private directory with path sites/default/files/private. And in the browser you hit http://yoursite.com/sites/default/files/private/brochure.pdf.
Again, the request goes to Apache and it checks the directory to locate the file. It does not have permission to fetch the file from private directory due to Deny to All. It passes on the request to Drupal. Drupal then does the access checks as it does on all other menus (routes in D8), with access callback.

So, to summarize, it should be okay to place your private directory outside the public files.

Note: If you are hosting your site on other servers and not Apache, you might need to check if you need some extra settings as .htaccess restrictions might not work with them.


Views: Filtering nodes on the basis of logged in user role Is it possible to filter out nodes with respect to current user role? For example, I want to create a view where users can see the all the published nodes as well as the unpublished nodes they have created. And if current user is a site admin, he should be able to see all the nodes. Is it possible using views?

Yes, you can use node "Author uid" as the "Contextual filter" in the views and can set default value as "User id from logged in user" or "User id from URL" for the "Author uid".

If you will select "User id from logged in user", then it will display the node created by the logged in user  or if you select "User id from URL", then it will display the node created by the user id from the URL.

Regarding, displaying node published and unpublished, you need to set permission for user role to view "unpublished own nodes", so user can view his unpublished node.

For the site admin user, he can only view the node created by him. If you want to display all  nodes to site admin, then you need to create another view.


Count how many times a node is referenced I have a content type: classroom
I have another content type: lesson
Lesson nodes have an entity reference field (field_classroom) that reference classrooms.
I want to create a view that outputs a table like this:

Classroom
Number of lessons

Leicester Square
5

Piccadilly Circus
8

London Bridge
0

So, there are five lesson nodes that reference the "Leicester Square" classroom (all the classrooms are named after places in London), 8 that reference the classroom named Piccadilly Circus, and 0 lesson nodes referencing London Bridge.
Is there a way to achieve this in views?
I'm playing around with relationships and aggregation but I can't get it to work.

Silly mistake. I had the relationship the wrong way round. Now it's working perfectly. These are the steps:
1.) Create a relationship: Content using field_classroom (not content referenced from field_classroom)
2.) Enable aggregation
3.) Add a field: field_classroom
4.) Use the relationship
5.) Set aggregation on the field to COUNT
And it works!


show anonymous users in a view I was wondering if there was a method to show anonymous users in a view. I have looked at various alternative such as the link below for showing anonymous users.
http://scito.ch/content/count-access-statistics-anonymous-users-only-drupal-7.
I did construct a view for the number of registered users but am having a problems showing just anonymous users in a view

There is (and should only ever be) one anonymous "user" for your site.  That will be in your db users table as uid 0.

If you'd like to count the number of anonymous users that are visiting your site at a certain time you can adapt (to a custom module) something like this that is used in the admin_menu module (this is from admin_menu.module 7.x.3.0-rc starting around line 395:

function admin_menu_get_user_count() {
  $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
  $count_anon = admin_menu_session_count($interval, TRUE);
  $count_auth = admin_menu_session_count($interval, FALSE);

  return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}

function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

And then output the return values. If you want to count the all time number of anon visits to your site than that is a different story. If so, please update. Thanks.


multifield and reference to other nodes I would like to ask about my logic problem with site. I want to make a searchlist of distributors. Client selects manufacturer, and all distributors who are providing goods from certain manufacturer will be displayed. I have two content types: 1. Distributor, 2. Manufacturer. Im assigning x manufacturers to one distributor (multiple entity references). And the problem is here. I want to have for every distributor link to their shop where they offer the goods from selected manufacturer. How it can be done if one distributor can have x manufacters? I tried to search some module which dynamically adds text field for every nodereference which is set to multiple values, but didnt find anything. If I use multifield I cannot acces is aterwards with entity reference filter.

Just to be clear this is how it should look like.

Distributor1

Manufacturer-1
Manufacturer-x
Manufacturer-y

Distributor2

Manufacturer-1
Manufacturer-x
Manufacturer-y

Distributor3

Manufacturer-x
Manufacturer-y
Manufacturer-z

Distributor4

Manufacturer-1
Manufacturer-x
Manufacturer-y

Distributor5

Manufacturer-x
Manufacturer-y
Manufacturer-z

Distributor6

Manufacturer-1
Manufacturer-x
Manufacturer-y

If I understand you corretly, you need to store other field(s) together with the reference of Manufacturers, right? I think the best way is to add the (a single-value) reference field to Distributor in the Manufacturer content type along with other necessary fields. After that you can create your list with a View.


How do I use it in a system with 2 PHP-versions? On my server there are two versions of PHP: 5.4 and 5.6. Using the shell PHP 5.4 is the standard and it can't be changed because of PLESK/ODIN. The websites I'm administering are using PHP 5.6 via PLESK, so Drupal 8 works fine. Drush doesn't,  because it uses the shell.

I have installed Drush with the following commands:

php drush.phar core-status
mv drush.phar /usr/local/bin/drush
drush init

How can I change this to use PHP 5.6 in /opt/plesk/5.6?

Drush has an environment variable DRUSH_PHP to set the php executable. You can set it in your .bashrc or directly on the command line:

env DRUSH_PHP=/opt/plesk/5.6/php drush status


Drupal & AJAXified links: hook into requests before they are sent? I've got a link 'test/nojs' on a page. I've added the class 'use-ajax' to that link, so that Drupal automatically AJAXifies the link and replaces the 'nojs' part with 'ajax'. So far so good.

However, I'd like to hook into the AJAX request as there might be cases where I'd like to stop the request from being sent off to the server. However, I can't get it up and running properly.

One post say that I can do this by setting a 'hook' function in Drupal.ajax[element].beforeSend(a,b) and some places say that I can do it by settings a 'hook' function in Drupal.ajax[element].options.beforeSend(a,b). However, I can't get any of this to work.

Is there a "right" way of hooking into the AJAX process? Even better, is there a "right" way of hooking into the AJAX process for certain elements?

You can use the following code,

Drupal.ajax[element].default_beforeSend = Drupal.ajax[element].beforeSend;
Drupal.ajax[element].beforeSend = function(xmlhttprequest, options) {
  if (1) {
    xmlhttprequest.abort();
  }
  else {
    Drupal.ajax[element].default_beforeSend(xmlhttprequest, options);
  }
}


How Do I Properly Add Custom CSS Classes And IDs To Drupal 7 Sub Menus I'm having a theming problem with my Drupal secondary navigation.  I have a two level menu set up - i.e. five parent links, two of whom have children.  The problem I'm seeing is that the children have the same CSS classes and IDs.  Consequently, when I click on a parent that has children, they are appearing the same as the parents.

I have tried to modify the menu via my template.php and page.tpl.php to no avail.  I have the following in my template.php file and it is throwing errors saying $sub_menu does not exist:

function framework_menu_link(array $variables) {

  unset($variables['element']['#attributes']['class']);
  $element = $variables['element'];
if($variables['element']['#attributes'])
$sub_menu = '';
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
}

Any help or guidance anyone could provide would be appreciated.

Thank you!

+Chris

Have you tried the Menu Attributes module? It's easy to use and has great features:

  The module currently allows you to set the following attributes for
  each menu item:

  Id
  Name
  Target
  Rel
  Class
  Style
  Accesskey


When to create schema while working with config entity? We have a custom form mymoduleForm.php that is used to perform some logic by calling mymodule_preprocess_node(). We were able to add addCacheableDependency() and now the mymodule_preprocess_node hook is able to pull the latest changes even after making several changes and clearing cache.

We did not create a mymodule.schema.yml as this configuration is not used for translation or any other way then to store some value in the some_field field.

Although it appears to be working just fine without the mymodule.schema.yml file, we were wondering if it is needed. We need some guidance on whether or not this is a situation where the mymodule.schema.yml is needed (or if it always needed).

mymoduleForm.php

class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this->entity->isNew()) {
        \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
      }

    $config = $this->config('mymodule.settings');

    $form['some_field'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Some field title'),
      '#description' => $this->t('some description'),
      '#default_value' => $config->get('some_field'),
    ];

    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('mymodule.settings'),
      ->set('some_field', $form_state->getValue('some_fields'))
      ->save();
  }
}

mymodule_preprocess_node

function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);
  $config_value = $config->get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

This is a follow up question from How to clear cache for config entity after making changes?

Short answer: you should always have one, but you can avoid it if you really want (see point 3 below).

  What are schema files used for?

  The primary use case schema files were introduced for is multilingual support. We need to have a tool to identify all translatable strings in your shipped configuration so when you ship with your own settings as well as default Views, additional user roles, menu items, etc. we can offer those up for translation as part of your module/theme release on http://localize.drupal.org. The nesting levels and types would be enough for this use case.
  We also use schemas to provide actual translation forms for configuration based on your data. This use case is where types gain more importance and labels become crucial. The core Configuration translation module uses schemas to generate translation forms and save translations. The two most important built-in translatable types are 'label' for one-line text input and 'text' for multiline text input.
  Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities requires a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.
  Last but not least configuration schema is also used to automatically typecast values to their expected types. This ensures that although PHP and web forms in general favor strings over all other types, the right types are used when saving configuration. That is important so when deploying configuration, only actual changes will show up in the difference, no random type changes.

From Configuration schema/metadata


How to allow reload value in cck field? I have a problem.
I wish I achieve for my preloading fields Content Type (Type list). (pre loader like a webform).
Loading this list thereby synchronize on a table by the user.

I get to create my field and load the first time. But when you synchronize the table, it is necessary that the field starts to date.

How to allow reload value in cck field?

Thank

I find.

In my instance, I use :

 'allowed_values' => array(),
 'allowed_values_function' => '_get_list_catalogue',


Non-Gregorian dates and calendars How can I use my native calendar in Drupal?
I set Drupal to use Farsi and set Asia/Theran as default location, but the month names and years are still from the Gregorian calendar, even if they are translated in Persian.

Is there any coding method to use a calendar that is not the Gregorian one?

It is possible, but not currently in the queue for Drupal 8 core.  There is nothing stopping it from being a contrib module, though, or being added to the Datetime Extras.

Essentially, the internals of Drupal are based around the PHP \Datetime class1, which uses the Gregorian calendar.  Custom code would have to convert back and forth between this system.

I think two places would need to be updated:

Widgets would need to be created for timestamps and datetime fields to convert to the Gregorian calendar when a user enters a date.   These widgets could then be configured every place fields are used (eg, via Manage Form Display).
A new date formatter service would need to be created to convert Gregorian dates to the other calendar system for when dates are rendered.  The glitch here is that the date placeholders are baked into the field formatters in several places.  New field formatters may also be needed to handle these cases.  It would also be possible to just use new field formatters, but there are places in code that call out to the date formatter service directly (for non-field uses).  Also keep in mind that there are places in core that don't use the date formatter service and call format_date() or date() directly (this is a known issue that will be addressed).

Also keep in mind that some things need to stay in the Gregorian calendar, and render out that way.  The main place that pops into my head are where the ISO 8601 format is used, which happens in the RDFa module and when things like the HTML5 <time> element gets rendered out with the datetime attribute.

1 This is a huge simplification from how datetime and timestamps are handled by core, but the heart is still the native \Datetime class.


In Drush what is the difference between ard and arb? In Drush what is the difference between ard and arb commands? When should I use one over the other?

They're actually aliases of one another, so you can use either.

If you type drush help arb you'll see at the bottom:

Aliases: ard, archive-backup, arb

And for posterity, drush help ard:

Aliases: ard, archive-backup, arb


Exposed filter on field collection with unlimited values without creating duplicates in view? I have a 'Video' content type with a 'video_translations' field collection which is allowed unlimited values.  This field collection has a 'language' and 'url' field attached and I want to be able to filter by the 'language' field.

I've created a relationship in the View for the 'video_translations' field and set the 'Delta' value to 'All'.  Then I created a filter for the filed collection item 'language'.

Filtering works okay like this, but using the Delta value of 'All' creates duplicates in my view when viewing all items.  If I set that Delta value to, for example, '1', then filtering only looks at the first field collection item, and ignores other values.

e.g. if I have 2 'video_translations' on a single Video, the first has the 'language' field set to French, and the second to Russian, then with the Delta value set to 'All', that single Video is displayed twice. Once for each 'video_translations' value. But with the relationship's Delta value set to '1', the Video only appears once, but I'm never able to filter by the second 'language' field.

I want to display the Video once, regardless of how many values the 'video_translations' field has, and also be able to filter by any of the field collection's 'language' field.

How can I do this in Drupal 7?

The "distinct" button exists in Drupal 7 as it did in Drupal 6 but is buried. Go into "Query Settings" under "Advanced -> Other" and check the box for "distinct." That'll display duplicate values only once regardless of how many deltas exist.


Use Timeago date format for less than 24h ago only I would like to use the Timeago module as a date format. However, when the time ago has exceeded 24h, I would like it to show another format (e.g. 4 Feb, 2013) much like Twitter or Dribbble use.

I tried to tweak the code, but my skills let me down :/

Is there possibly a better module for this cause? Or do I have to make my own?

I found this code that shows how I want it to work, however I have no idea how to implement this to drupal.

Any help is appreciated, thanks.

Do users really sit on a page for a long enough time, that these dates need to be updated via javascript? Most of them will click on something and end up reloading the whole page at some point. So perhaps, a php solution is an option too?

You could achieve the php solution by using the Custom Formatters module.

If you create a new php type custom formatter, with the following code (make sure it's a datestamp type):

$element = array();
foreach ($variables['#items'] as $delta => $item) {
  $unixstamp = $item['value'];
  $time_since = mktime() - $unixstamp;
  if ($time_since < 86400) {
    $date_str = format_interval($time_since);
  }
  else {
    $date_str = format_date($unixstamp, 'custom', 'jS F Y');
  }

  $element[$delta] = array(
    '#type' => 'markup',
    '#markup' => $date_str,
  );
}
return $element;

When creating the formatter, make sure you select field type 'datestamp'. Once the formatter is created, then in the manage display tab of your content type, set the field to use this formatter.

If you don't have your date stored as a separate field, you might be able to apply the custom formatter to the node modified time, by installing the Display Suite module.

If you don't want to use any of these modules but want to hack some php into your theme or something, you can still use the same logic above with format_interval and format_date functions.

Hope that can help.


What is a Content Management Platform? Currently Drupal defines itself as a "Content Management Platform". My assumption is that they are trying to differentiate themselves from CMS which provide a much more specific goal, such as a wiki or pure blog.

I have found some research and other systems which also use the term but not a single definition.

Can anyone provide a noteworthy definition or provide one themselves which would match the current consensus? Do other broadly scoped CMS such as Joomla and WordPress fall into this category?

Thanks!

Jeff Eaton provides a pretty comprehensive post in Understanding 8: Where Drupal Is and Where it's Going, where he discusses these differences (at least in Drupal terms).

Drupal as a Framework

  The foundation of that stack is the essential "web framework" code for
  Drupal. It's the portion of Drupal that provides essential services
  any web application would require. Rendering data into HTML and other
  formats, identifying and loading plugins, handling HTTP requests and
  responses, caching, database and storage access, and so on all live at
  this layer...

Drupal as a Platform (i.e CMS)

  Moving up in the stack, we find the "building blocks" layer that Catch
  referred to as the "Platform" in his blog post. This is where we begin
  to encounter Drupal-specific approaches to CMS and web building
  problems. The Entity system, users, nodes, taxonomy terms and
  vocabularies, actions, roles and permissions, FieldAPI, text formats,
  and our concept of "Blocks and regions" live here, and can be used to
  assemble features and functionality. Reusable user interface tools and
  UX components are also here: things like drag-and-drop tools, Drupal
  7's Overlay mechanism, and so on are all reusable tools used to craft
  usable interfaces.

These differences and more, are also covered in his DrupalCon London Presentation. Product, Framework, or Platform? What They Mean, And Why You Should Care

Essentially Drupal is both, a CMF and a CMS (and more) and why these discussions have come up recently in an effort for the community to define Drupal a bit more.


How to use a terminate kernel event to log page access statistics? In Drupal 7 hook_exit is implemented in the Statistics module to gather statistics for page accesses. This change record suggest the equivalent in Drupal 8 is to listen for kernel.terminate events. Here's my code:

/mymodule/mymodule.services.yml

services:
  mymodule.page_exit:
    class: Drupal\mymodule\EventSubscriber\PageExit
    tags:
      - {name: event_subscriber}

/mymodule/src/Event/Subscriber/PageExit.php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;

class PageExit implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::TERMINATE][] = array('logAccess');
    return $events;
  }

  /**
   * Call this method whenever the KernelEvents::TERMINATE event is dispatched.
   */
  public function logAccess(PostResponseEvent $event) {

    // $access_info = $event->getRequest()

    \Drupal::database()->insert('mymodule_table')
      ->fields(array(
        'hostname' => '?',
        'referrer_url' => '?',
        'timestamp' => REQUEST_TIME,
      ))
      ->execute();
  }
}

Currently, for a single page request, the method logAccess gets called five times. I'm interested in logging the hostname and referrer url of my page visitor, just once.

In essence, I'm trying to port some of this this Drupal 7 code from statistics_exit in statistics.module:

drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

// For anonymous users unicode.inc will not have been loaded.
include_once DRUPAL_ROOT . '/includes/unicode.inc';
// Log this page access.
db_insert('accesslog')
  ->fields(array(
    // 'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
    // 'path' => truncate_utf8($_GET['q'], 255),
    'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
    'hostname' => ip_address(),
    // 'uid' => $user->uid,
    // 'sid' => session_id(),
    // 'timer' => (int) timer_read('page'),
    'timestamp' => REQUEST_TIME,
  ))
  ->execute();

Any ideas?

The comments you got are golden, my answer is along the lines of what @IvanJaros suggested, but follows a simpler approach. And take care to check the case of external caching (if any is in play).

The following should make your current approach work.

public function logAccess(PostResponseEvent $event) {

  $request_format = $event->getRequest()->getRequestFormat();

  if ($request_format === 'html') {
    // \Drupal::database()->
  }
  else {
    // Do other stuff.
  }
  ...

This snippet tries to detect requests with the html format (i.e. page requests) and will ignore other ones, like e.g. application/json.

Good luck!


Slideshow with images of a gallery ,at the end of the gallery next gallery images should start I have several modules to show the images in slideshow, but i need to show the images of a gallery with slide counter.

At the end of the last image in that slide there must a next gallery navigation,to start the next gallery images with slide counter.

It will continue as for next galleries.

Anyone say how to do this using views or by modules ? am in urgent need of this, to update

Thanks in advance.

There are a couple of things that you need to think about.

First, what do you mean by the "next" gallery? You will need that value to populate the link to the next gallery.

The slideshow can take an argument of the gallery ID, which will limit the images displayed to one gallery. You can then create another view which takes that argument and displays a field (which is a link to the "next" gallery).

You can filter by node type, order by whatever you want to order by, limit to display only one node (of type gallery), and, finally, filter by the same thing you are ordering by, but use the filter to limit the list to what is appropriate, ie, do not display nodes with node id greater than (or less than) or equal to that of the argument, so you don't get a duplicate.

Then you attach that view to the gallery view, and you have a link to the next gallery. You may be able to do something with an Ajax module if you don't want the page refresh.

I'm actually having a similar problem. The issue I'm having is that I want to display the latest gallery (my galleries have a CCK date field). I can do that, but I want to limit by gallery id. However, I won't have the gallery ID because I'm displaying the "latest" gallery, so I can't just do a simple filter by gallery id. I can sort by the date, but I can't seem to limit the results to the same parent gallery without the gallery id argument. Any ideas would be greatly appreciated.


Organize files attached to a node into folders We need to organize files attached to a page into folders (with Drupal 7). They don't necessarily have to be physical folders, virtual folders are fine.

Do you know a module like this, or do we have to implement it our own?

Update:
To be more specific: we need the ability to display attached files on the page organized into folders, the underlying filesystem structure is indifferent.

Just make a taxonomy vocabulary to simulate the folder structure. Install File Entity module. It makes fieldable files, so you can attach taxonomy for the file own - with the module Media you can do that during editing the node.

To display files grouped by folders, you can make a view to do that, and use EVA to embed it into the node. In the view you have to make a 'File' based view, just add a relationship to the node, and add a Content Id contextual filter, which use that relationship.


How can you render fields from an entity reference in node templates? [Drupal 8] For context, I'm dealing with two content types: article and team_profile. In article nodes, we have an entity reference field pulling a team_profile node in to serve as the author information.

I would just render the entity with a new display mode, but our design has the photo set directly above the published date and name, next to one another:

In D7 I would dpm($content) and drill down to the node information, double click, and pull out the rest of the reference path. I'm using kint and am able to spit out the entity reference contents to a certain level, {{ kint(content.field_blog_author[0]['#node']) }}. The next level I want to access is values, but trying the following gives me NULL:

content.field_blog_author[0]['#node’][‘values’]
content.field_blog_author[0]['#node’]=>values
content.field_blog_author[0]['#node’]->values

I'd ultimately like to render the title and field_team_image fields from the referenced node (seen here in the kint output). I haven't found information about this is the documentation or by searching. Would someone help me get unstuck?

#node there is actually the current node.

If you want to access fields and their values, start off with node, not content, which is a render array with the configured fields.

You can access the reference entity like this {{ node.field_blog_author.entity }}.

From there, you can continue again to the field of the referenced entity that you want to display. You could try calling the view method, with will view it with the default settings, you can also pass a view mode as a string to it or an array display settings (not sure about the exact syntax for that in twig).

Also, my standard reference, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a great overview of content entities, how they're structured and how to access values. Most of that also applies to twig.

And last, when trying to figure out what's in a content entity, use node.toArray(), that gives you an array representation that's very close to how you can access it as an object. While the internal structure is quite different.


How to prevent access to Views-only content? When I'm developing sites in Drupal, I create various content types and taxonomy vocabularies that I use with Views to build displays. I might not ever want the nodes to be viewable in their own right or listed by taxonomy. Visitors may never figure out the URLs to do this, but I'd still like to lock this down.

I'm aware of various content access modules, and have considered theming taxonomy displays to simply say 'page not found'. But I've yet to find a simple solution, so wondered what other people use to prevent content from being viewed outside of a View?

In D6, I set the path alias for these content types to be

no-view/[nid]

and then use

function MYMODULE_init ()
{
    $path = drupal_get_path_alias(request_uri());

    if (strpos($path, "no-view/") !== FALSE) {
        drupal_not_found();
        exit;
    }
}

I think this will work as-is in D7, but I haven't tried it.


How to add a prefix - suffix to a node title from a module I loaded a renderable array within a hook_block_view.  I need to add a prefix and suffix to the title before rendering it. How can I manage to do that ?

You have an error in the very title. Adding prefixes and suffixes is not a job for a module. You do it in template. If you need to wrap it in html tags, do it in node.tpl.php. If you need some more elaborated logic, see template_preprocess_node().


Linking an action to the button in the view I'm looking for some tips how to achieve following functionality in Drupal 8.

I have a simple view where I list filds, nothing special. One of the fields is a custom text which is rendered as a button html element. Now, I want to assign a special action to this button, it is a automatic creation of new node.

Any help will be appresated.

You can do this with the help of the Rules module. You'll probably want to create a Component (they don't have Events that trigger them, as opposed to full Rules) and connect them to your Views custom field.

Views Bulk Operations (VBO) is a better option though. It's also well integrated with Rules so you can use that instead of a Custom text Field. With VBO you get checkboxes for each Views row and a button for each action you want to perform on a Views row, so you can select more than one row at the same time.


How to save autocomplete and date type fields while adding node programmatically? I am creating a node programmatically and I have a field which is autocomplete and has number of values set to unlimited.

In the code for adding the node programmatically ,the code is as given below

    $node->field_user[]['value'] = $user->name;
       $node->field_time[]['value'] = date('m-d-Y H:i', REQUEST_TIME);
  $trans_node->field_download_flag[0]['value'] = 'YES';

So after programmatically creating a view when I check into the 'find content' place I see a node being generated but when I click on the link(where the content title is )( not on the edit link) , I cannot see the field_user in the view list

field_time
type: date
widget : popup calendar
no of values : unlimited.

field_date
type: Entity Reference
widget : Autocomplete
no of values : unlimited.

field_flag
type: boolean
widget : checkbox/radiobutton
no of values : unlimited.

I think the code for field_user should be as

$node->field_user[]['target_id'] =  $user->name;

but still i am getting error that is WSOD

I think

$node->field_user['und'][]['target_id']

and

$node->field_time['und'][]['value']

is the good way


Error on installing module I've got Drupal 7.20 on my server (skyislands.pl). I wanted to install (from my local computer) Wysiwyg module (http://drupal.org/project/wysiwyg), but I see this error. My server is running on EHCP. How can I solve this problem ?

Thanks for any help,

It is a permissions problem. You will be able to install the module by downloading it and putting it into your sites/all/modules folder


What is the proper way to show a visitor an error? I'm using a custom submit handler for a Webform, which POSTs important form data to another API. That part works, but on occasion there may be random network errors that prevent a successful submission, such as if the REST endpoint happened to be down at that particular moment (or whatever).

In those cases, I don't want the user to think their form successfully submitted when it didn't. How can I override the confirmation page with a custom error page? I tried drupal_set_message(), but it doesn't show up anywhere on the confirmation page that I could see.

Ideally, I would also be able to get back the event ID generated by watchdog logging so that the user, if they contact us by phone or email upon seeing the error, would be able to provide more information that can help us debug it.

So in summary, in a perfect world, a failed submission would result in:

The form submission ($form_state) being logged into watchdog or another log
Watchdog returns the associated event ID
The user sees a custom error page describing the error, with the event ID as an error code to help in debugging.

I can hack something together with die() and a hash of the form data as an error code, but is there a better, proper Drupal way?

Relevant code so far:

 try {
    $apiResponse = drupal_http_request($apiEndPoint, [
      'headers' => ['Content-Type' => 'application/json'],
      'method' => 'POST',
      'data' => drupal_json_encode($formData),
      'timeout' => 5 // Timeout in seconds.
    ]);

    // I'm not okay :(
    if ($apiResponse->code != "200") {
      throw new Exception ($apiResponse->data, $apiResponse->code);
    }
  } catch (Throwable $e) {
    watchdog('tfm_custom_form_handlers', "A custom form handler failed: (@code) @message.", [
      '@code' => $e->getCode(),
      '@message' => $e->getMessage(),
    ], WATCHDOG_ERROR);
  }

Thanks for the help!

Have your POST code inside a validate function, that runs last, after all other validation has passed.

Ex: $form['submit']['#validate'][] = 'mymodule_post_to_api';

and use form_set_error('form', 'Failed to connect to API, try again later'); inside your catch.

For POST's errors, don't wait for someone to report. Programmatically make Drupal send yourself or whomever maintains the code, an e-mail with the form fields & error details.

See How to programmatically send an email?


Preventing users from registering with xxx@yyy format email address Drupal seems to let users register with emails like xxx@yyy

I heard that this kind of email address can exist.
But I want users to register with only emails like xxx@yyy.zzz

Is there any way to validate this type of email format and prevent users from registering with it?

There is a core function named: function valid_email_address that will check that the syntax is valid.

Example of use:

$mail = $form_state['values']['submitted_tree']['email_address'];
if (!valid_email_address($mail)) {
  form_set_error('[submitted][email_address]', t('The email address appears to be invalid.'));
}


How to force regions to render in Overlay I've created a Seven-subtheme for use with the Admin Overlay and have added Header and Footer regions, however these do not render, despite showing on the "Demonstrate Regions" page.

I have tried to set overlay_set_regions_to_render(array(...)) in custommodule_init() however this fails to influence anything.

I eventually found the code that does this in overlay.module and applied this to a custom module, using the hook:

function mymodule_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme') {
    $info['overlay_regions'][] = 'header';
    $info['overlay_regions'][] = 'footer';
  }
}

However getting this to take effect required visiting the modules page, I don't believe simply clearing the cache worked.


Generate node edit link I'm attempting to dynamically generate a node edit link. I understand that I can manually create it by using

$editpath = '/node/'.$nid.'/edit';

but I have multiple sites that use subfolders like

  /site1_subfolder/node/123/edit

and

  /site2_subfolder/node/123/edit

I looked at the node class and I couldn't see any method that would generate this link for me. I did see that there's a NodeForm class but I didn't see any static methods I could take advantage of either.

Given a node or node id is there a way to generate an admin edit link to its edit form?

NOTE: If that's not possible I would be fine with using a function to get the subfolder names so I could do $editpath = '/'.$subfolder_name.'/node/'.$nid.'/edit';

But I'm not sure how to do that either.

UPDATE: I suppose I could do a $node->toUrl()->toString() to get the direct path and add edit at the end but this would only give me the alias, is there a way to not get the alias from this and get the direct link to the node instead?

Given a node or node id is there a way to generate an admin edit link to its edit form?

Absolutely, the Url class has a fromRoute method:

$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl('edit', $url);
$build = [
  ...
  'link' => $link->toRenderable(),
];


Display Local tasks from one page to another I have a menu structure like this:

$items["foo"] -> MENU_NORMAL_ITEM
$items["foo/bar"] -> MENU_DEFAULT_LOCAL_TASK
$items["foo/something"] -> MENU_LOCAL_TASK
$items["foo/bar/bazz/%"] -> MENU_CALLBACK

I want to have the tabs (local tasks) from page foo/bar displayed on foo/bar/bazz/% as well but I don't want to have another local task for this new page.

Any ideas on how can I achieve that? Thanks.

I kinda managed to to this by using the following piece of code:

$path = drupal_get_normal_path('path-where-local-tasks-are-displayed');
if($path) {
  menu_tree_set_path("navigation", $path);
  menu_set_active_item($path);
}


How to pass a parameter into a form upon creating? I have a form, which contains an additional field. And I want to initiate the field via the form constructor.

class ServicesForm extends FormBase {

    private $service_type;

    public function __constructor($_service_type){
        $this->service_type = $_service_type;
    }

The form is created in a controller.

class ServicesController extends ControllerBase {

    public function getServices($service_type){
        $data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm');

        return $data;
    }

Could you clarify me, how to pass the parameter $service_type to the form inside the controller method ?

Maybe, should I do it without FormBuilder and getForm ?

Just add it to your form's buildForm method signature:

public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) {
  // Use $arg
}

Then literally pass it to the form builder's getForm method:

$data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm', $service_type);


Help with a D7 database query and update I am not familiar with the Drupal 7 database API. I want to alphabetized a menu.
Can anyone help me write a database query to retrieve all the menu item links of a certain parent (plid = 228) and order ascending by title? Within that result set, can anyone help me write a database update method to update each menu item's weight sequentially (counter starts at 0 and increments)?

Something like this should work, but I have not tested this code. Please comment on this if you have questions.

$result = db_select('menu_links', 'ml')
  ->fields('ml', 'mlid')
  ->condition('ml.plid', $plid, '=')
  ->orderBy('ml.link_title')
  ->execute();

$i=0;
foreach ($result as $row) {
  db_update('menu_links')
    ->fields(array('weight' => $i))
    ->condition('mlid', $row->mlid)
    ->execute();
  $i++;
}

At this point they would all be ordered by title, and you could print the menu wherever needed.


Execute Sql Query in drupal I have SQL Query and I want to execute it in Drupal. My SQL Query is like this.

select cat.tid as cat_tid, cat.name as cat_name, cat_parent.parent as cat_parent_tid,
count(deals.nid) as no_of_deals
from
taxonomy_term_data as cat

left outer join taxonomy_term_hierarchy as cat_parent on cat_parent.tid=cat.tid

left outer join field_revision_field_categories as store_categories on
store_categories.field_categories_tid=cat.tid

left outer join field_revision_field_store as deal_stores on field_store_nid=store_categories.entity_id

left outer join (select * from node where type='deal' and status=1) as deals on nid=deal_stores.entity_id

where cat.vid=5

group by cat.tid, cat.name, cat_parent.parent

I converted this query with the help of this module https://drupal.org/project/query_coder

and got the resulted query as

$query = db_select('taxonomy_term_data', 'cat');

$query->addExpression('count(deals.nid)', 'no_of_deals');

$query->fields('cat', array('tid', 'name'));

$query->fields('cat_parent', array('parent'));

$query->leftJoin('taxonomy_term_hierarchy', 'cat_parent', 'cat_parent.tid = cat.tid');

$query->leftJoin('field_revision_field_categories', 'store_categories', 'store_categories.field_categories_tid = cat.tid');

$query->leftJoin('field_revision_field_store', 'deal_stores', 'field_store_nid = store_categories.entity_id');

$query->leftJoin('', 'deals', 'nid = deal_stores.entity_id');

$query->condition('cat.vid', 5);

$query->groupBy('cat.tid');

$query->groupBy('cat.name');

$query->groupBy('cat_parent.parent');

$result = $query->execute();

Now how can I execute this query in drupal, I tried to import this query in views 3 but got some unexpected error, Also I tried to add this query into the block but again getting the same error. I also created a custom block in a custom module that too did not worked. Please help me how can I execute this query. Answer will be greatly appreciated.

You should better start debugging the query.Things that might be help you debugging the query.

Install devel module. Having logged in as admin visit "yoursitename.com/devel/php" here you can execute any php code.
Put your query there and add this dpm($result); single line of code in the last of query. Execute the query, see what you get as result.
If the query execution is throwing error visit "yoursitename/admin/reports/dblog" and try to figure out the reason for the error.

You can also cross check if the query returned with drupal wrapper functions is same as your original query by stringyfying the query object, to do that add

`dpm((string) $query);`

just before $result = $query->execute(); and also remember to comment $result = $query->execute(); as execution of query may cause error in your case.


Theming Drupal fatal error messages Whenever Drupal encounters an unrecoverable error, it displays an error message.

Is there a way I can provide a template for this page?

The closest thing you come by is the maintenance-page.tpl.php, It doesn't cover all cases, but if things go wrong but not that wrong that Drupal can't post a page, it uses maintenance-page.tpl.php to display the error(s).

The error itself is displayed using drupal_set_message


Image URLs aren't MIME encoded in email I'm using Drupal core 8.9.3 and Mime Mail 8.x-1.0-alpha3.
I have installed MimeMail and implemented mymodule_mail hook.
The UI is set to use "Mime Mailer mailer". The UI for Mime Mail is configured to Not 'Link images only', and to use 'Full HTML'.
Emails are sent and display correct html with embedded image tags.
However there is a problem with the image being MIME-encoded and included as a message attachment.
The below simplified email only has a paragraph tag enclosing an image tag with a test src as  src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png".
Below is the raw email.
Please, any suggestions.
Date: Thu, 20 Aug 2020 01:46:23 +0000 (UTC)
Content-Transfer-Encoding: 7bit

This is a multi-part message in MIME format.

--e3e18d39bfaeb05c93e9fe993b85d9033ac7dadb1
Content-Type: multipart/alternative;
 boundary="caf5a2b1e29cb0704a73a98e3c656acf261f57860"
Content-Transfer-Encoding: 7bit

--caf5a2b1e29cb0704a73a98e3c656acf261f57860
Content-Type: text/plain; charset=utf-8
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

--caf5a2b1e29cb0704a73a98e3c656acf261f57860
Content-Type: text/html; charset=utf-8
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://ww=
w.w3.org/TR/html4/loose.dtd">

    <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf=
-8">
    <title>Mime Mail message template</title>

&#13;

--caf5a2b1e29cb0704a73a98e3c656acf261f57860--

--e3e18d39bfaeb05c93e9fe993b85d9033ac7dadb1--

MimeMail is not MIME encoding url images in email

That's correct. Mime Mail is still in alpha and that feature isn't working correctly yet. If this feature is important to you please participate in the issue queue at https://www.drupal.org/project/mimemail
Images are usually only delivered as attachments if they are not publicly accessible on the server. A complete link to an external image should work just fine in any email client.
But let me also note that there is something going on that you didn't mention - the Mime Mail module will NEVER use 7-bit encoding, and will NEVER use quoted-printable encoding. So it's quite possible that you're doing something that breaks the behaviour of Mime Mail.


How to generate a list of which Features are enabled in which Spaces? I'm running a Drupal 6.x site with Organic Groups, Features, and Spaces, and I'm interested in generating a list of which Spaces have which Features enabled. Preferably a table, with Spaces along the Y axis, and Features along the X axis.

Any ideas regarding how to generate this? I can generate a list of Group Spaces using Views, but can't find a field for the enabled Features.

Features are modules, and Views 3.x can make listings of enabled modules. But as explained in How to make a Feature available only to certain Spaces?, this is not possible, since modules are enabled site-wide.


Taxonomy URL incorrectly translated On a multilingual site (source language: English) I have a view that displays a few product categories. The categories are represented by Taxonomy terms. If I display the (translated) category names linking to the respective category overview page, everything works perfectly: The links are being translated, too.

But when I introduce a category image (an extra field in our category Taxonomy type) the generated image link will never be translated. This means: My view renders the category name as link in the Interface text language selected for page (e.g. http://example.com/de/tastatur/xy-123) and the category image as link in English (e.g. http://example.com/en/keyboard/xy-123). I even have tried to set the Rendering language parameter to German, but the image link is always being rendered in English.

Is this a bug, or am I doing it wrong?

I found a workaround, but I hope someone will come up with a better solution.

If I include the Term ID as a hidden field …

… it is possible to rewrite the category image with a link generated by the router:

This works, but we are missing the hreflang attribute in the link, and the alt attribute of the category image is still English only.


How to setup Page Cache to work with the Flag Module and Views? I have a Site where Views are used to display flagged Nodes.
When i turn on Cache Pages for anonymous Users, the anonymous Users only see the change in the Views until the cache is cleared. (If logged in no problem). What is the best Way to deal with this caching issue. I would prefer that all pages with views where item flags are updated would be recached. Is this possible ?

Similar to the first answer but not assuming your cache is in the database. (memcache, redis, apc, etc)

function hook_flag_flag($flag, $entity_id, $account, $flagging) {
  $view_name = '<view_name>';
  $display_id = '<display_id>';
  $cid = $view_name . ':' . $display_id . ':*';
  cache_clear_all($cid, $bin = 'cache_views_data', $wildcard = TRUE);
}


Print out list of Imagecache presets I just need an array of the preset names, is there a simple way to do this?

imagecache_presets

Get an array of all presets and their settings.

Parameters

reset: if set to TRUE it will clear the preset cache

Return value

array of presets array( $preset_id => array('presetid' => integer, 'presetname' => string))


How to pull taxonomy fields I am trying to pull out a image field that is attached to a taxonomy term. I have tried using field_view_field with no luck. Does anyone have a good working example?

Thanks!

Some thing like this:

    $tid = $items[0]['tid'];
    $term = taxonomy_term_load($tid);
    //it turn out that taxonomy_term_load gets empty array for my custom field
    //that's why  after some poking around Drupal API i come up with the following
    $term_page =  taxonomy_term_view($term, $view_mode = 'full');
    $term_url = taxonomy_term_uri($term);
    $image_url=$term_page['#term']->field_client_logo; //this is my custom field name
    $image = theme('image', array(
      'path' => $image_url['und'][0]['uri'],
      'alt' =>  $term->name,
      'title' => $object->title,
    ));
    return l($image, $term_url['path'] , array('html' => TRUE));


Installing Drupal 7.22 fails at database configuration step on Win7 I succeeded to install drupal 7.22 on my production server but still fail to have it running on my local EasyPHP running on win7 64b.

At database configuration step of the install process I have the following message:

Warning: in DatabaseConnection->__construct() (line 304 of C:\Program Files (x86)\EasyPHP-5.3.2i\www\drupal-7.22\includes\database\database.inc).
In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.
Failed to connect to your database server. The server reports the following message: .

You might note that no error message is actually reported.

The mentionned line 304 is opening the connection:

// Call PDO::__construct and PDO::setAttribute.
parent::__construct($dsn, $username, $password, $driver_options);

I verified db name, credentials, and other settings by connecting on the database with MySQL Workbench which succeed to connect to db.

I tried editing myself the default.settings.php:

$databases = array(
  'driver' => 'mysql',
  'database' => 'drupal-7.22',
  'username' => 'datagrmdb',
  'password' => 'mypassword',
  'host' => 'localhost',
  'port' => 3306,
  'prefix' => 'drupal_',
  'collation' => 'utf8_general_ci', // also checked that DB is configured this way
);

but that still failed.

I tried editing settings.php directly and reloaded the install process to continue but it stop saying that "Database is already installed". It suggest to empty the db but it is already empty.

Back to drupal wizards I also tried using 127.0.0.1 instead of localhost and setting 3306 manually but that did not changed.

There is another drupal database (another version) in mysql but I assume that should not cause any problem.

EDIT: I verified php_pdo.dll and php_pdo_mysql.dll exist in the php/ext directory

Any hint?

Thanks Clive for the suggestion.

Writing www/test_pdo.php:

<?php
try{
    $dbh = new pdo( 'mysql:host=127.0.0.1;port=3306;dbname=drupal-7.22',
                    'mydb',
                    'mypassword',
                    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>

proved the connection worked for "127.0.0.1" but not for "localhost", my initial setting.

So I changed sites/default/settings.php and reloaded and that worked.


Why doesn't a cloned theme work as the original theme? I've cloned a theme, by duplicating and renaming it, in /sites/all/themes/. When I switch to the new theme, portions of the theme, a slideshow, don't work.

It looks like views_get_view_result() in template.php is not returning anything. Is there some configuration I need to set up per theme?

I'm new to Drupal and I am helping out a friend. The site is using Drupal 7.

In template.php the functions that begin with the template name e.g. themename_preprocess_page need to be renamed to have the new theme name in them e.g. newthemename_preprocess_page.


Preprocess custom CCK fields and print image URL in TPL file I want to preprocess a image field and later print it in my rss.tpl file and I'm currently using drupal 6.

This are the following codes I've tried in the template.php file but no luck :(

$vars['image'] = $field_uppdrag_logo;

&

/*$vars['image']=$node->field['field_uppdrag_logo'][0]['value'];

&

$vars['image'] = $node['field_uppdrag_logo'];*/

My tpl file:

<?php
// $Id: views-view-row-rss.tpl.php 3296 2009-05-27 23:08:21Z tim $
/**
* @file views-view-row-rss.tpl.php
* Default view template to display a item in an RSS feed.
*
* @ingroup views_templates
*/

?>
<item>
<title><?php print $title; ?></title>
<link><?php print $link; ?></link>

<description><?php
$description = html_entity_decode($description, ENT_QUOTES, "ISO-8859-1");
print strip_tags($description);
?>
</description>
<image>
<?php print $field_uppdrag_logo[0]['view']; print $image; print $field_uppdrag_logo;
?>
</image>
<?php print $item_elements; ?>
</item>

How exactly do I accomplish this?

Try the below:

$vars['image'] = $node->field_uppdrag_logo[0]['value'];