How do I assign variables from BlockBase object? I want to create a Block-Module for drupal 8 (beta 12). To display the Content I want to use a twig-template (mytest-block.html.twig).

But the Twig-Template needs some Data to Display, So I need a Method to assign Some Variables from MytestBlock.php to the Template.

I know how to assign Variables from mytest.module, but I have no idea how to assign Variables from the Block-Plugin MytestBlock.php.

Or is it possible to access the instance of MytestBlock.php and therefore call a method which would return the variables as an array?

My MWE-Module consists of following files:

mytest/
├── mytest.info.yml
├── mytest.module
├── src
│   └── Plugin
│       └── Block
│           └── MytestBlock.php
└── templates
    └── mytest-block.html.twig

File Content mytest.info.yml:

name: mytest
description: A Testmodule
core: 8.x
package: Custom
version: 0.1
dependencies:
    - block
type: module

File Content mytest.module:

<?php

function mytest_theme() {
    return array('mytest_block' =>
        array('variables' => array('test' => 'hello')));
}

function template_preprocess_mytest_block(&$variables) {
    $variables["test2"] = "hello2";

    //a call to get_variables() would also be an option, e.g.:
    //$variables = array_merge($variables, $A_INSTANCE->get_variables());
}

File Content mytest-block.html.twig:

Template
{{ test }}
{{ test2 }}
{{ test3 }}
{{ test4 }}

File Content MytestBlock.php:

<?php

namespace Drupal\mytest\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;

/**
 * Provides a Test-Block
 *
 * @Block(
 *   id = "MytestBlock",
 *   admin_label = @Translation("My Testblock"),
 * )
 */
class MytestBlock extends BlockBasMytestBlock.phpe implements BlockPluginInterface {
  public function build() {
    return array(
        '#theme' => 'mytest_block',
        /*here I want to assign some variables: e.g.:
         * test3 = hello3 */
    );
  }

  public function get_variables() {
    retrun array("test4" => "hello4");
  }
}

In this example, only test and test2 are assigned, but I want, that test3 and test4 are assigned too.

Via try and error, I found out, that declaring the variables-array in the function mytest_theme() makes it possible, to set the variable in the MytestBlock-Class:

Changes in mytest.module:

function mytest_theme() {
    return array('mytest_block' =>
        array('variables' => array('test' => 'hello', 'test3' => null)));
}

Changes in MytestBlock.php:

class MytestBlock extends BlockBase implements BlockPluginInterface {
  public function build() {
    return array(
        '#theme' => 'mytest_block',
        '#test3' => 'hello3',
    );
  }
}

But I still have no idea how to access the Block-Plugin Instance in mytest.module.


How to remove "Submitted By" data from google search engines in drupal7? How can I prevent showing of Submitted by username information on google search result pages.

I looked into some of the answers but I am not sure those solutions will remove from google search. I am thinking those are related to drupal search engines.

Here are the links:

Remove "Submitted by" on search results

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

Please help me regarding this. It will be more appreciated if solution will workout for already created data/nodes as well.

If you don't want the content to show up in Google search, you have a couple options.

Hide the "Submitted by" in Drupal itself.  You can do this by going to the content type edit page and unchecking the box for "Display author information."
Use a theme template for the content types and move the "Submitted by" information to the bottom of the content. If it is shown at the bottom instead of the top, Google is unlikely to use that information in its search results, since it gives information toward the top higher priority.

What you shouldn't try to do is show information to users but somehow hide it from Google.  This is likely to make Google mad and if they detect it, your site will be penalized.


Regions. how can I disable a region? (not disabling blocks) I want to disable a region, to not show blocks in this region to an specific page. I want this because, I have several blocks (more than 20) so in this case is necessary enter to each block, and configure in what page or pages must not be showed. Well I can do that, I just want to know if exist some way to make this task in a more practical way, or in a programmatically way.

I am using Drupal 6.

The context module is a very handy way to control blocks on a site which uses them extensively. It allows you to define contexts which show and hide blocks. It will stop the blocks from even being loaded so will help performance.

It makes it much easier to define where and when the blocks appear. Rather than defining things per block you define what blocks appear per context.

This video seems to explain things well.


How to change theme template for the same block that is loaded twice on the page? We have created two menu blocks: main_menu (region=main nav) and main_menu_footer (region=footer) that are added to all pages. They both are displaying the same main navigation menu except main_menu_footer only displays the first level and main_menu displays all levels.

I have a custom module, mymodule that I am using to assign a custom twig template, menu--main.html.twig. This twig template is being assigned to both blocks.

How can I setup the twig templates so that the main_menu uses main--menu.html.twig template, but main_menu_footer uses main--menu--footer.html.twig?

Goal:

main_menu block uses main--menu.html.twig template
main_menu_footer block uses main--menu--footer.html.twig template

Current setup

function mymodule_theme($existing, $type, $theme, $path) {
  $items = [];
  $items['main__menu'] = [
    'base hook' => 'menu',
    'render element' => 'menu',
  ];

  return $items;
}

This is usually done at the theme level, not the in a module. Unless you want to create your own implementation of a menu.
First of all, enable Twig Debugging then in locate in DOM the templates you want to override.
In your active theme, create a file with the same name as the twig template you want to override. Copy the code from the original template and customize it as you like


D8 Views - Contextual Filter by Month & Year? (Content date field) We have a dev site finally patched all the way up to 8.5.3. Our old site (8.4.0) was using a Views patch (just for reference) that allowed for a content date field to be contextually filtered by month and year:

https://domain.com/events/042018

returned all events with month 04 and year 2018.

Now on views 8.5.3 this patch is no longer applicable and seems to be integrated for Created Date and Updated Date. But I don't need these date fields. I am trying to access a content date field that I made.

Does anyone know how to do this?
or
Can you help me get started on creating a custom views contextual filter handler that can access this custom date field?

Thanks so much!

Example of View: Show all events. Contextually Filter by Date. But instead of an exact date, only grab month and year parts, i.e. show all events for July 2018 /events/201807

Remove your date contextual filter, by clicking remove.
click Add a contextual filter, and search for the date field and select the "Year+month" granularity. Then click add.

once you are done you should have your contextual filter look like this:

Now you can go events/201807 and it would give you the same results.

update: this granularity is available for all date fields under the contextual filter option (node.field_somedatefield (year_month) provided the field has been added normally using content types manage fields section:


Opposite to theme_get_setting To Set In the template.php file, we grab the theme settings:

if(theme_get_setting('fix_sidebar')){
...
        variable_set('fixed_navbar',1);
    }

Based on the theme setting(i.e fix_sidbar'), we want to reset another theme setting(i.e fixed_navbar) as you see above. However, it does not appear to be working. It is not showing up theme settings that has:

 $form['style']['fixed_navbar'] = array(
        '#title' => t('Fixed Navbar'),
        '#default_value' => theme_get_setting('fixed_navbar'),
        '#type' => 'checkbox',
    );

How to do the opposite of theme_get_setting API to reset the setting with new value? Thank You

If I understand you correctly, you should be doing this

$form['style']['fixed_navbar'] = array(
    '#title' => t('Fixed Navbar'),
    '#default_value' => variable_get('fixed_navbar', 1),
    '#type' => 'checkbox',
);


How to create a line graph of the total user points on a profile page? I'd like to have a line graph of my users' total user points in time on their profile page. Users shouldn't be able to modify the graph: it should simply graph the user points from the day the user registered until today. I'd like to use the Charts module, but I don't know how I can provide the necessary data (date and daily total points).

Perhaps it's also handy to mention that the profile pages on my website have been overridden with "user_view" (see: How to create a profile page?) into a panels page.

How can I achieve this?

Edit: I tried to find a solution, using Field Collections as @Felix Eve suggested in his answer. I've successfully added a Field Collection to my users, but I'm still stuck at these points:

Save the userpoints at the end of the day as a field collection item for all users.
Graph the userpoints in a Chart.

Solving these problems, solves this problem aswell.

I realize this is an old post, but I wanted to add a workable solution for those that find this question when searching the topic.

I've been able to use a combination of the Charts module to create a view that display the history of the user's total userpoints.

It is fairly straight-forward to create a view that displays all of the userpoints transactions of a given user, however, I found the trickiest part to be display a 'running total' of a user's points.

The following recipe should help you create a view that charts the progression of a user's points over time.

Step 1: Download, enable the Charts module

Step 2: Create a view that Shows "Userpoints", and create a block view with the Chart display format. Screenshot below:

Step 3: Add the relationship Userpoints:User

Step 4: Add the following fields:

Userpoints Transactions: Timestamp
Userpoints Transactions: Points
Global: Math Expression

Step 5: Set the expression for the math expression field to: [expression] + [points_1]. You should also adjust the label for this field.

Step 6: In the chart settings, set the label to be the timestamp field and the data to be the math expression. Also, set the chart type to line.

Step 7: Add a sort criteria to sort by the timestamp field. Set the timestamp format to be Y-m-d.

Step 8: Add a contextual filter: User:uid to filter by logged-in user's uid.

You may want to create a page view to see the chart in action:


add content page doesnot work for other users I created a few users that are responsible for adding content to the website. they are just allowed to add/remove content (defined by role). the problem is the add content link (mywebsite/node/add) does not display the add page, it just displays MY page.tpl.php . I guess add page is overridden by my page.tpl.php , how can I have admin add page for other users ?

you should include print render($page['content']); in your page.tpl.php file otherwise, it will not display content for the page.

content is default block which Drupal use to render content of a page.

If you do not want to use content region in your theme, then you can set View the administration theme permission for your user role.

Setting permission:

Go to  Administration -> People -> Permissions
Checked check-box of View the administration theme for your user role and save form.


how can I make view_slideshow module thumbnail pager scrollable? I am using the view_slideshow module.
When user goes to the property page(Content type property) I am showing the images using view slide_show module.
Main image is moving as a main slider image and thumbnail are being shown under the main image as thumbnail pager.

Now here is a problem:
Thumbnail pager is coming in a div its working fine if the number of images are 3-4.
But if the number of images are 8-10 then they are not being shown in the thumbnail pager div.I want to make the thumbnail pager div scrollable with arrow buttons on both end.

So if user clicks on the next arrow of thumbnail pager then that thumbnail will comes into the thumbnail pager div.

Thanks

Views Slideshow JCarousel will suits your problem description best . Before Installing it you need to have views and views slideshow  enabled.One extra work you need to do is to create two folders in sites/all/libraries folder

1) sites/all/libraries/jcarousel - download the .tar file from https://codeload.github.com/jsor/jcarousel/legacy.tar.gz/0.2.9 and extract here.

2) sites/all/libraries/jquery.cycle - save here the .js file you get form http://malsup.github.io/jquery.cycle.all.js link.

Now .

create a view of content of TEST (let here be the content type is TEST).
Select Format slide show and click settings . Now in Bottom Widget(you can select top widget also) check the pager checkbox.
It will ask all the requirements like Number of visible pager item and scroll items . Save it and you are done.


.htaccess: Options not allowed here I just moved a new drupal site onto a directory '/drupal_test' under my current site. So that I can test it while my current site is still running.

When I go to the directory www.mysite.com/drupal_test. I got this error:

**Internal Server Error**
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Apache/2.2.16 (Debian) Server at www.bromptontech.com Port 80

I used putty command line to access the error log on the server and I got errors like this:

/var/www/drupal_test/.htaccess:Options not allowed here

I searched around and it seems something to do with the Allow Override settings, some say it is in httpd.conf, but I can't find this file anywhere, I can only find relevant code here in /etc/apache2/sites-enabled/000-default, I can see the  tags.

Our IT guy gave me the root account to access the server, but he can't help me more than that, while I really have very limited knowledge about the server and these command lines, please can anyone help me with this? Thanks a lot!

As your running the drupal from sub directory so modify the line containing "RewriteBase" (may be line no. 102) of .htaccess, change "# RewriteBase /drupal" to "RewriteBase /drupal_test".

And if the above thing doesn't works for you than please try the following:
Search for "<directory /var/www/>" in the "/etc/apache2/sites-available/default" file and change it as below:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>


Update a view page content without refreshing the page Is there a module that updates a view automatically when it is changed, without refreshing the view page?

For example, when a new node is added to the view or deleted from the view, or a node is edited, the view is automatically updated without refreshing the page.

What is the best way to do this?

I've been trying to find the answer to this for some time and I don't think I can improve on the previous answer.... but I think it is not really correct.

The way I would approach it is to put more of the Views formatting functionality in some JQuery Javascript so that the Javascript fetched the data for the View from the Drupal server via JSON and not HTML.

Then periodically - rather than using Views Hacks autofresh - it would say "give me all the records for this view which are newer than this datetime"

Unfortunately this would require hand coding for now as I have not seen this in any contributed module.


Drupal Module - Mailing List, cannot export list, get browser error I've just started using the mailing list module, but when I put it on my live site I get an error when I try to export the list of entries. I did get an actual Drupal error which is

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

this put an entry in my Log which I followed up on the net and found this page http://drupal.org/node/1206916 entry #11 led me to a link which should fix this, I tried this, but now I just get a Browser failure saying it cannot locate the file.

any ideas? or is there a better mail module?

If you are having trouble with the module you are using, there are other mail-type modules available.

MailChimp - Module to utilize subscriptions/emails with mailchimp.com
Simplenews - Publishes and sends newsletters to lists of subscribers (still in Alpha)
Notifications - Complete Subscriptions/Notifications Framework aiming at extendability and scalability (still in Alpha)


how to add exposed drop-down filter with options in a view of custom table In a drupal 7 website, I have a view that is based on a custom table. I have a status column in that custom table, which is type of integer and has 0 or 1 value, and in a view I want to add exposed filter with dropdown, with values somehow like below
$options[0] = 'No';
$options[1] = 'Yes';

So that a user can choose a value from dropdown and filter out data.
So in my views.inc file I have implemented hook_views_data(), then I have added the following code to make that field accessible in a view
$data['custom_users']['status'] = array(
      'title' => t('User Status'),
      'help' => t('User Status'),
      'field' => array(
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
  );

Now when I am trying to add exposed filter using this field I am not able to make it available as dropdown. I am only getting a textfield as exposed filter for this field.
Any help will be appreciated.

You can use hook_form_alter() for this.
simply change the field type to select and add your options.
here is my working code
// implements hook_form_alter
function project_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'views_exposed_form') {
    $view = $form_state['view'];
    // add your view name in 'view_name'.
    if ($view->name === 'view_name') {
      // Checking status field is exists or not.
      if (isset($form['status'])) {
        $form['status']['#type'] = 'select';
        $form['status']['#empty_value'] = '';
        $form['status']['#empty_option'] = 'All';
        $form['status']['#options'] = array('0' => 'No', '1' => 'Yes');
        $form['status']['#size'] = 1;
        $form['status']['#attributes'] = array('id' => 'status-list');
      }
    }
  }
}

hope this will work :).


File upload with title I want functionality where editor will be able to upload files and name that files whatever he wants, I just want additional field next to file upload field, is there any module which can do that?

Thanks.

This functionality is already provided by Drupal core. Just edit the settings for your image field in content type and enable 'Enable Title field' to have Title field for your image field.

For example,
Go to 'Structure » Content types » Article' and 'Edit' the settings for 'Image' field. (admin/structure/types/manage/article/fields/field_image)

There you will see two checkbox fields 'Enable Alt field' and 'Enable Title field' which can be enabled to provide image related info for each image upload.


How do I iterate through images using file_create_url()? I am trying to add Lightbox feature to images. This is the code I used in the node template.

<a class="lightbox" href="<?php echo file_create_url($node->field_images['und'][0]['uri']); ?>" data-plugin-options='{"type":"image"}'>
 <?php print render($content['field_images']); ?>

This works fine if I have the "field_image" limited to 1 value, but in my case the field_image can have several values (the user can upload several images).

For the first image $node->field_images['und'][0]['uri']) is correct; for the second image the path would be $node->field_images['und'][1]['uri']).

So how should I iterate through multiple images?

UPDATE(per @Clive feedback):
Here is my updated code:

<?php if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
   $uri = $item['uri']; ?>

<a class="lightbox" href="<?php print $uri ?>" data-plugin-options='{"type":"image"}'>
<?php print render($content['field_images']); ?>

<?php
}
}
?>

I have 2 issues with it: The URL is not correct per my comment below. Second on every iteration it prints all images. For example if I have 2 images: it prints {img1/url1, img2/url1} and then on the next iteration it prints {img1/url2, img2/url2} instead of img1/url1 on the first iteration and then on the second iteration img2/url2.

How would I modify the 'print render($content[]);' to print partial content?

How  would I modify the $uri to print the full URL path?

UPDATE2(per @Rupesh feedback):
Here is my updated code:

<?php if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
   $uri = $item['uri']; ?>

<a class="lightbox" href="<?php print file_create_url($uri); ?>" data-plugin-options='{"type":"image"}'>
<?php print render($content['field_images']); ?>

<?php
}
}
?>

Now the only issue I have is that on every iteration it prints all images. For example if I have 2 images: it prints {img1/url1, img2/url1} and then on the next iteration it prints {img1/url2, img2/url2} instead of img1/url1 on the first iteration and then on the second iteration img2/url2.

Now I need I modify the 'print render($content[]);' to print a partial content on every iteration. For example on first iteration it will be print render($content[][0]); and on second iteration it will be print render($content[][1]); etc.

Something like that (it does not work, with a blank page )

<?php for ($i = 0; $i < count($content['field_images']); $i++):
 print render($content['field_images'][$i]); ?>
 endfor;
?>

The count is wrong, it outputs 17 instead of just 2 images.
What would I change in in the code above to get it to work?

Thanks.

You're probably looking for a for loop, but Drupal has a specific function for this, field_get_items():

if ( ($items = field_get_items('node', $node, 'field_images')) ) {
  foreach ($items as $item) {
    $uri = $item['uri'];
  }
}


Custom Entity: define a view in entity reference field I defined a custom entity and for a entity reference field I want to set the view reference widget and a view/ display to be used instead of an autocomplete.

I tried many different settings - nothing worked. The latest version not working is:

$fields['user'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('User account'))
  ->setDescription(t('The user account this profile is connected to'))
  ->setSetting('target_type','user')
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'string',
    'weight' => -6,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'views',
    'settings' => array(
      'handler_settings' => array(
        'view_name' => 'users_without_profile',
        'display_name' => 'entity_reference_1',
        'arguments' => []
      ),
      'weight' => 20
    )

  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

For the form view setting I also tried

  ->setDisplayOptions('form', array(
    'type' => 'views',
    'settings' => array(
      'view_name' => 'users_without_profile',
      'display_name' => 'entity_reference_1',
      'arguments' => [],
      'weight' => 20
    )
  ))

and

  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
        'handler' => 'views',
        'handler_settings' => array(
            'view_name' => 'users_without_profile',
            'display_name' => 'entity_reference_1',
            'arguments' => [],
        ),
        'weight' => 20
    )
  ))

No success. Can somebody give me a hint?

The handler settings are part of the base field itself, rather than being a setting for the form display.

This should work:

$fields['user'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('User account'))
  ->setDescription(t('The user account this profile is connected to'))
  ->setSetting('target_type','user')
  ->setSetting('handler', 'views')
  ->setSetting('handler_settings', [
    'view_name' => 'users_without_profile',
    'display_name' => 'entity_reference_1',
    'arguments' => [],
  ])
  ...


Unsubscribe users from Simplenews from a specific Newsletter category I send newsletters from my Drupal-7 website using Simplenews module. I have a general category, that has all my site users and it is the category I use the most.
Although, some of the newsletters are sent to a smaller target group (women-only, men-only etc).
My problem is that when users click on the unsubscribe link from a newsletter that is not from my general category, then they unsubscribe from this category only and not the general.
What I want to achieve, is that when a user is unsubscribed from any newsletter category, to automatically unsubscribe him from the general category also.

I think it should work. Use hook_simplenews_unsubcribe_user which will

/**
 * Invoked if a user is unsubscribed from a newsletter.
 *
 * @param $subscriber
 *   The subscriber object including all subscriptions of this user.
 *
 * @param $subscription
 *   The subscription object for this specific unsubscribe action.
 *
 * @ingroup subscriber
 */
function hook_simplenews_unsubscribe_user($subscriber, $subscription) {

}

Add this in your custom module. I think $mail and $tid will be available in $subscrption variable.

function module_simplenews_unsubscribe_user($subscriber, $subscription) {
  simplenews_unsubscribe_user($mail, $tid, FALSE, 'website');//$tid -s your genral category tid.
}


Is Contact module the right choice for multiple ask a question pages? I have a set of pages already developed. For each page I need to add a new page with an "Ask a Question" form to let end users contact via email the corresponding page owner.

I tried the Contact module but it doesn't seem the right choice.

One of the requirements is to hide the recipient email address from the user.

How can I create such a customized form and be able to set a different recipient on each page? Do I have to create a new Feature?

Depends , you can use the webforms module to create custom forms it's better suited for creating forms than the contact module


How to Replace Value of CKEditor Field via Custom Module Drupal 8.x

I have a custom module and I am trying to wrap any string beginning with a hash tag in an 'a' tag via RegEx.

MYMODULE.module:

function MYMODULE_preprocess_node(&$variables) {

    if ($variables['elements']['#node']->get('field_name')->value != '') {

        kpr($variables['elements']['#node']->get('field_name')->value);
        $variables['elements']['#node']->get('field_name')->value = $newValue;
        kpr($variables['elements']['#node']->get('field_name')->value);

    }

}

I've left the two kpr() statements which do show initial value, and the RegEx replaced value, correctly. However, the value of the CKEditor field is not being replaced. It appears my 'equals' operator has no effect.

How do I replace the value of the CKEditor with my updated value?

Referencing this Stackoverflow question: https://stackoverflow.com/questions/22040272/using-php-replace-regex-with-regex

I have had some success.

MYMODULE.module:

use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = $newValue;
  }
}


how can i see recurring payment details on my website? Currently i am using ubercart for recurring payment everything is working fine i can see status of mine recurring payment on paypal account

But how can i see recurring payment details on my website i have searched so many times on google but not got any relative article.

When i go to /admin/store/orders/39/recurring that page always shows blank details  .

I'm able to see my memberships at /admin/store/orders/recurring (this is Drupal 6). From there I can edit the recurring fees and search based on a number of different properties.


How do I filter the current year? Initially, I have installed the Token module and created a Views block containing years.

I want to filter out the current year from the block (it should not show the current year).

In filter criteria, I have changed content:year ([current-date:custom:Y]), but it is not filtering the current year, and it is showing as follows:

2013(3)
2014(5)
2015(6)
2016(2)

I am expecting the output to be as follows:

2013(3)
2014(5)
2015(6)

How can I achieve this? Any help is greatly appreciated.

You may want to check if using the Views Date Format SQL module could be a solution. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.


Programmatically change block content on page render only I have a situation where I want to change the content of a block on certain conditions, but not permanently.

I'm using a theme_preprocess_block() hook to change the content of the block, but it's not carrying through to the page render:

function MYTHEME_preprocess_block(&$variables) {

  if ( $variables['base_plugin_id'] == 'block_content'
    && $variables['attributes']['id'] == 'block-mycustomfooterblock' ) {

    $variables['content']['#block_content']->set('body', [[
      'value' => 'New Content',
      'format' => 'full_html',
    ]]);

Even after clearing caches, the block content doesn't get replaced with "New Content".

I added this line

$variables['content']['#block_content']->save();

However, that permanently saved the change to the block, which I don't want.

How can I alter the block content just for the page render?

You should probably try

$variables['content']['body'][0]['#text']= "html content";

complete example

function THEMENAME_preprocess_block(&$variables) {
  if ( $variables['attributes']['id'] == "block-newblock" ) {
    $variables['content']['body'][0]['#text']= "html content";
    $variables['content']['body'][0]['#format']= "full_html";
  }
}


add Bundle field to a custom entity I am trying to add a new bundle field into my custom entity, I added the following code into the MyCustomEntity.php file, I uninstalled my module, so, I installed it again, the field is showing up on the view, but in my data base the field is not added.
Could you please support me?
$fields['new_name'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('New Name'))
  ->setDisplayOptions('form', [
    'type' => 'text_textarea',
  ])
  ->setRevisionable(TRUE)
  ->setTargetBundle($bundle);

Thank you, I will really appreciate your support.

For the Entity base field update, You'll need to also add an update hook to apply it
For example:
Installing a new field storage definition
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_update_N
 */
function example_update_8701() {
  $bundle = 'article';
  $field_storage_definition = BaseFieldDefinition::create('text_long')
  ->setLabel(t('New Name'))
  ->setDisplayOptions('form', [
    'type' => 'text_textarea',
  ])->setRevisionable(TRUE)
  ->setTargetBundle($bundle);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('new_name', 'node', 'EXAMPLE_MODULE', $field_storage_definition);
}

Documentation: https://www.drupal.org/node/3034742


Matching a route with a "file path" I'm trying to debug a route that should work like the one(s) used by the private: file scheme (i.e., a path like system/files/path/to/file, where path/to/file is an arbitrary string that may contain '/' characters).  I more or less copied the the router definition.  For private files:

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

For my "knock-off", which uses a custom scheme called 'session:':

file_example.files.session:
  path: '/example/file_example/files/{filepath}'
  defaults:
    _controller: '\Drupal\system\FileDownloadController::download'
    scheme: session
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

As near as I can tell, my route is never matched; yet the private: case works. What's different here?  How can I debug how the router makes its decisions?

Part of what I need to know is just what route got picked when the private: scheme actually works.  So it would be handy to get a link to the current route. This is a fairly obvious thing to do, but I can't find a reference in the docs.  How can I determine what the "current route" is for current request?

This is a case where reading the routing file is a bit deceptive.

There are actually two similar routes defined in system.routing.yml:

system.files:
  path: '/system/files/{scheme}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
    scheme: private
  requirements:
    _access: 'TRUE'

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

After watching in the debugger, it turns out that the matched route is actually system.files, and not system.private_file_download.  But it will not match a tailed-URL at all without help.

The help needed is a "path processor", which is a routine that the router calls to let code do unusual things with route matching.  Here's the one that's used for private: and temporary: files, among other users in Core:

In core/modules/system/src/PathProcessor/PathProcessorFiles.php:

class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

A path processor is a service, and needs a "tagged" service definition.  Here's the one for Core's path processor for the /system/files subpath:

In system.services.yml:

  path_processor.files:
    class: Drupal\system\PathProcessor\PathProcessorFiles
    tags:
      - { name: path_processor_inbound, priority: 200 }

Once I'd added the correct route and service definitions, my custom URL scheme works the same way the Core file scheme URLs work.


Get length of the teaser I need to get the setting on what length the teaser of a custom made content type is set.

I tried Google'ing for it, but so far I have ziltch results.
I also tried looking in the database, in the field_config_instance, field_config and the variable tables, but they couldn't give me a value either...

Now, I'm hoping you experts could help me to point me to the right direction?
Would be appreciated. :-)

Thanks in advance.

Please check ReadMoreControl module, this might help you..By this module you can add Read more links to other supported view modes


How to translate the language switcher links In Drupal 8.1 the language switcher (block can be placed in a region) shows the languages labels in English:
English | German | French

I want to translate it. Visiting mysite/de the label should be in German:
Englisch | Deutsch | Französisch

mysite/fr --> labels should be translated in French

The words "German" and "French" and "English" are translated into all languages in my drupal installation. Yet the language switcher shows the labels in English all the way.

How translate it?

I'm still looking for this same answer, but there is a way to translate them, so you can have them as English | Deutsch | Français in the language switcher for all languages: just translate the language name on /admin/config/regional/language


Is there a means to pass some php.ini settings to the drush command? Running drush -d status results in this error: Drush command terminated abnormally due to an unrecoverable error. The full output is add below.

  Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.12 sec, 7.41
  MB]
  [bootstrap] Initialized Drupal site default at sites/default [0.12
  sec, 7.41 MB]
  [notice] Cache HIT cid:
  5.7-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.13 sec, 7.41 MB]
  [debug] Drush bootstrap phase :
  _drush_bootstrap_drupal_configuration() [0.13 sec, 7.41 MB]                                                                       [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_database()
  [0.16 sec, 9.16 MB]
  [bootstrap] Successfully connected to the Drupal database. [0.16 sec,
  9.16 MB]                                                                                [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_full()
  [0.17 sec, 9.16 MB]
  [bootstrap] Undefined index: sitename domain.module:2922 [1.24 sec,
  31.05 MB]                                                                                [notice] Undefined index: path domain.module:2923 [1.24 sec, 31.05 MB]
  [notice] Drush command terminated abnormally due to an unrecoverable
  error. [1.24 sec, 31.06 MB]
  [error]

Is there a way to configure a separate php.ini for drush in the .drushrc file or in settings.php, or pass some settings on the drush invocation?

First, remember that php.ini for Command Line Interface is separate and has nothing to do with php.ini your webserver is using. To find where that file is, follow this question on SO as this is not really on-topic on Drupal Answers.

If you want to set some php.ini values in drushrc.php, you need to use ini_set() PHP function. Just remember that not all values are changeable like that, only the ones with PHP_INI_USER (or PHP_INI_ALL, of course) on this list.


How to modify the layout or look-and-feel of a specific node? How to modify the layout or look-and-feel of a specific node

Example path is example.com/node/230

Which file tpl file should I copy and rename to the id above?

I had done it before in Drupal 6, but when I try to do in Drupal 7 it failed.

One of the things you can do to help with this is to enable Theme Debug mode, see here:

https://www.drupal.org/node/223440#theme-debug

This will tell you what templates are currently being used, and will provide suggestions for what templates to use, when you inspect the source of your node page (the suggestions are in HTML comments, so make sure they're enabled in your inspector).

It also details how to create your own custom template suggestions, the patterns of which is detailed here:

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

Make sure you place the templates inside your theme directory in order for the theme to pick them up.


How to connect to drupal 7 using web service? can I connect to my Drupal website using web services and pass a variable (with post method) to it? I know that forms in Drupal actually have hidden elements so that it is not possible to submit the form from external sources.

There is also a service module but I don't think I can achieve what I am trying to do with it.

The following is what I am trying to do with Drupal:

When I connect to www.drupal-site.com/web-service (web-service is just an example), I would like to be able to post variables to it and perform complex database queries. I would also like to return the result of the queries in json (using echo maybe). I would also like to be able to remove the headers and footers of my drupal site.

I really need some direction on how this can be achieved.

Your use case can be achieved using Services module easily.

All you need to do is write a hook_service()

refer http://drupal.org/node/118126 Or just look into the services module's any child module, may be user_services.

Do this,

Write a service that exposes all your query parameters as fields.
Accept these parameters into your web service callback and perform your business logic.
Return your results, this is just a return statement, no JSON conversion here.
ex: return $output.
//$output contains your array or data structure that you have as a result of your queries.

Now, how to convert the data to JSON. ?

Services module will provide you intermediate servers,  XML-RPC, JSON. (these are by default, there are more avaialable on drupal.org). These servers function as end points to whom you can connect using external applications or entities. ex: http://www.domain.com/services/json.

Thats it, the flow will be,

You connect to the endpoint, URL http://www.domain.com/services/json. Pass the data in JSON.
the JSONserver will convert that into PHP and will pass it to your web service callback.
You do the processing and return the data to the web service in PHP.
The server converts the data into JSON again.
This is handed over to the HTTP request that requested the processing in the first place.


Editing display of submission results I'm working on a Drupal 8 site, and I'd like to adjust how the results (/admin/structure/webform/manage/form-name/submission/ID/edit) display – the client doesn't want to see all of the fields and submission-related information (UUID, URI, etc.), and wants to see all of the form submission fields filled out here as well.

I see that there's an option for submission views, but I don't see a similar option that applies to the Edit tab. I also see there's a Webform Views Integration module, but that looks more like what I'd want if I wanted to put a view within a form.

Is there configuration I'm not seeing to adjust the submission edit screen, or a better method of reviewing submission details on a page whose display I can customize?

Thanks!

Is there configuration I'm not seeing to adjust the submission edit screen

No, there is no config screen to customize this "edit" screen.

  the client doesn't want to see all of the fields and
  submission-related information (UUID, URI, etc.)

You can use hook_form_alter() in a custom module and remove the submission information section.

  and wants to see all of the form submission fields filled out here as
  well.

They should be already be filled out, unless the user left them empty. Make these fields required if they should be filled out.

  I also see there's a Webform Views Integration module, but that
  looks more like what I'd want if I wanted to put a view within a form.

In correct, this allows you to display the webform results in a View. This is exactly what you need, well if you want to make an alternate page that has that "edit" info.

Also, you could alter the Webform's edit route so it uses your Webform View instead, but you would lose the edit ability tho. Since the View just displays what was entered and is not a form.


How to install eComma with Panelizer? I want to install the eComma 7.x-1.x Drupal module, providing word-wise annotation features. However, its installation instructions do not work in my environment, probably because I have also Panelizer installed and something has to be done different then.

These instructions integrate the eComma 7.x-1.x installation instructions, but with your requested modifications to make them work with Panelizer.

Create a basic installation of Drupal for your local development. You need to use MySQL / MariaDB as your database, eComma won't work with PostgreSQL at the moment [reason].
Install eComma (assuming you use drush, which is a great tool for Drupal developers …):

drush dl ecomma
drush en ecomma

If you want to install the module in a way that allows you to contribute back with Github pull request, replace the content of the eComma module with the Github repository's 7.x-1.x branch:

cd <your_docroot>/sites/all/modules/;
rm -R ecomma/*;
git clone "https://github.com/coerll/eComma.git" -b 7.x-1.x --single-branch ./ecomma

Install the patch mentioned in the eComma README. It fixes Community Tags' Drupal issue #2193175, which otherwise leads to Server Error 500 on node view pages (/node/<some-node-id>).

cd sites/all/modules/community_tags
wget "https://www.drupal.org/files/issues/community_tag_tagadelic_d7_fix-2193175-4.patch"
patch -p1 <"community_tag_tagadelic_d7_fix-2193175-4.patch"
rm "community_tag_tagadelic_d7_fix-2193175-4.patch"

Go to "Administration → Configuration → Search and metadata → Clean URLs" (/admin/config/search/clean-urls) and select "Enable clean URLs".
Go to "Structure → Taxonomy → Add Vocabulary" (/admin/structure/taxonomy/add) and add a vocabulary.
Add or edit the custom content type that you want to use eComma on.
In the edit form of that content type, go to the horizontal tab "Comment settings" and set "Preview comment: Optional".
Go to "Manage fields" for your content type (/admin/structure/types/manage/content-type-name/fields) and add a new field.

Use field type "Long text" (it will only work with that, not with "Long text and summary").
Go to the field settings. If you problems doing so (like "Notice: Undefined index: instance in ecomma_form_alter() (line 351 of …/ecomma.module).", you can manually enable eComma for the field in the database instead of doing the next two steps. You would use a query like:

INSERT INTO ecom_ecomma_field_enabled (field_name, content_type_name, ecomma_enabled)
VALUES (''your_field_name", "your_content_type", TRUE);

In the field settings, use "Number of value: unlimited" (though that's probably not obligatory).
In the field settings, select "Enable ecomma commentary features", right above the "Save settings" button.

Again, go to "Manage fields" for your content type (/admin/structure/types/manage/content-type-name/fields) and add a new field of field type "Term reference", using the "Autocomplete term widget" and selecting your Vocabulary from the field settings.
Go to "Configuration → Content Authoring → Community tags" and select "Enable community tagging" for the new vocabulary that you created.
Go to "Configuration → jQuery update → jQuery and jQuery UI CDN" and select "None".
Edit your eComma content type again, there go to the horizontal tab "Community tags settings" and select "Community tagging form: Block".
Go to "People → Permissions" and

Check "Community Tags: tag content" for authenticated and anonymous users. This will also enable unauthenticated users to see the tags, but not to tag.
Check "Community Tags: edit own tags" for authenticated users.
Check "Comment: view comments" for anonymous and authenticated users. This will enable unauthenticated users to see the comments, but not to comment.

Configure Drupal to show the "Long text" text field of your new content type, plus various eComma blocks, when somebody views a node of that content type. Depending on what layout mechanism you use (vanilla Drupal, Panels / Panelizer, Display Suite, context etc.) this will be different. Here's how to do it for Panelizer:

Go to "Administration → Structure → Pages", enable "Node template" and edit it.
In the node template, create a new variant of type "Panel", with the optional feature "Selection rules".
Add a new selection rule for your new variant, and doing so choosing "Node: type" from the dropdown list and later the content type(s) which you want to use with eComma.
Go to the "Content" section of your new variant, click a gear icon where you want to add content, choose "Add content" from the dropdown.
In the content selection dialog, go to the "Node" tab and select the Long Text type field you want to use eComma on (it starts with "Field: …" in this list). The eComma annotation dialog will not appear if you add this field as part of an aggregate, like by putting in the full rendered node with this dialog!
Click the gear icon again, click "Add content", and now from the Miscellaneous tab of the dialog, one by one, add the "Community tagging form" block and all blocks starting with "eComma". Normally these blocks are nicely integrated into overlapping tabs in eComma, but I could not yet find out how to achieve this with Panelizer. The "Community tagging form" block is needed because if not adding it, it will not appear as part of the JavaScript tagging form either!
Save this all.

Test your setup.

Create a node of your new content type.
Enter some text in the "Long text" text field – not in the "Body" text field. And save.
View the node and select text with mouse cursor to start annotating it.


Manually removing database records of a module I inherited a Drupal 7 site that appears to have a history.

I'm receiving the following error when updating modules or clearing the cache:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'website_staging.search_api_server' doesn't exist: SELECT base.id AS id, base.name AS name, base.machine_name AS machine_name, base.description AS description, base.class AS class, base.options AS options, base.enabled AS enabled, base.status AS status, base.module AS module FROM {search_api_server} base WHERE (base.status IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2)) ; Array ( [:db_condition_placeholder_0] => 3 [:db_condition_placeholder_1] => 2 [:db_condition_placeholder_2] => 6 ) in EntityAPIController->query() (line 187 of /home/website/apps/api/docroot/sites/all/modules/entity/includes/entity.controller.inc).

The question is: where in the database do I need to remove any and all traces that point to this table?

Background:

I figured this was just a module that somehow did not install its tables right somehow. Uninstall, reinstall and done, right?

Two problems:

Uninstalling a module also yields this error, and does not work
The Search API module (http://drupal.org/project/search_api) never was installed at all

It appears the previous developers created a custom module, and named it 'search_api'. My guess is that later they went and did a blanket update of the site modules using drush, and starting updating the custom module far enough to install something to the database. Then they realized their mistake, and replaced the custom module in its original location (but did not rename it).

Nowhere in my modules is there a pointer to the search_api_server table, so it must be somewhere in the database.

So my plan as it stands is:

Somehow fix the error
Uninstall the custom search_api module
Rename the custom search_api module and reinstall

And I need some help with step 1

I second the voices above.

My recent experience to get out of the pdoexception is crude and more akin to a 'big hammer' rather than anything elegant.

make a backup of your database and the code
either use a UI like phpmyadmin OR sql if you feel more comfortable with code
create the table it says is missing (website_staging.search_api_server)
add at least 1 variable (id)... take the defaults of integer
you don't have to add a value to the table, just create it and add the definition for the id variable
try your uninstall again

In my case for my custom module practice development, I also had to add a second variable because there were two 'keys' on the table.  But I'd try this with just the one variable (id)... hopefully it will be enough to get you out of the PDOexception and onward to module/code review.

The concept here is to give Drupal the minimum info it needs via manual PHP/SQL creation so it can 'connect the dots' and move forward to execute your commands (uninstall).
JW


Programmatically get the date field value All I want to do is get the value out of a date field in Drupal 8, but they have done an expert job of making this impossible. The error I get is that 'dateTimeObject' is protected so I have no access to it.

Try this out -

$schedule_start = $form_state->getValue('field_start')->format("Y-m-d H:i:s");
$schedule_end = $form_state->getValue('field_end')->format("Y-m-d H:i:s");

Provide your own desirable format.


How to add picture to every panel? I am using the panels module and the mini panels modules.

I have mini panel with two section (left and right).
For my design, I want to add a picture on the left side of each section. These pictures are not supposed to come from any node or content, they are just pictures for design purpose only.

How can I do that?
If you suggest CSS, I will be happy to understand how?

I am a newbie, and building my first Drupal site, so I will appreciate any help.

Thanks.

All your panels have a common class. Probably .panels. You need to see if your left panels also have a common class, probably .panel-left or something. You can use your browsers element-inspector to see this. It will show you something like this (simplified example) if you select your node that has panels:

    content

This gives you a clue where to set your background in CSS.

.panels .panel-left {
  background:url('path/image');
}

You need to find classes that the elements you want to style have in common, but are unique enough so that you style only those.


Custom plugin modified results in WSOD PluginNotFoundException I've created a module with a custom Plugin ("group_user"). It all worked great until I modified the code and accidentally introduced an error. This resulted in a WSOD Drupal\Component\Plugin\Exception\PluginNotFoundException</em>: The "group_user" plugin does not exist. I cannot even uninstall the custom module since either drush or the WSOD show the same error. Even undoing the code changes in the code do not work. I've found this bug description which is discussed in the following issue. There does not seem to be a working solution yet. Is there any way I could manually "remove" the plugin or find the "location" it is still loaded?

Plugin definition its a tandem between the plugin manager wich defines how your plugin type should be discovered and instantiated; and the plugin definition method itself that could be either using YAML files or annotations. Depending of which you used to define you new plugin type is how you must proceed in order Drupal find your plugin implementation. Said that if your plugin is used in a configuration entity you can find it querying your configuration table as follows:

SELECT * FROM config WHERE name LIKE '%group_user%' OR data LIKE '%group_user%';

In the other hand if your plugin is invoked directly in code by calling the plugin manager method createInstance you can then find where it is being used with a simple search in your custom code using your favorite editor or IDE. I emphasize on custom code as is a custom plugin type cannot be (yet) in contrib code.


How can I generate a link from a text field and a URL in a View? I have an entity type consisting of 2 fields, a description field and a URL field, and I want to create a view with a single column which consisting of the description outputted as a link to the URL, ie Description.

I don't know whether I am doing it the right way. I tried to use the tokens and rewrite results to create URL in the form Description but it winds up pointing to the Drupal node. Is there some way of creating some kind of calculated field pointing to the URLs?

In Views you have a couple of ways to do this:

Method 1:

Add the url field to the view, but "exclude" it from the display
Add the description field to the view, but re-write its out put to a link and add the URL token replacement as the URL or path.

Method 2:

Add the url field to the view, but "exclude" it from the display
Add the description field to the view, but "exclude" it from the display
Add a global field for custom text and inside of it add field-description where field-url and field-description are the replacement token from the fields added to the view.

Note: In views it is important the order of the fields, so if using method 1 the url field has to be placed before the description field.


How to add an error notice with jquery? Been trying to add a custom error notice with jquery, but so far the div looks funky

jQuery('h1').prepend('
Start
');

Any tips how to get this to work? As I understand Drupal uses the error div.

Drupal uses messages as the 'base' class for messages so this should work:

jQuery('h1').prepend('
Start
');

Note that you shouldn't escape double quotes inside a string unless the string is actually wrapped in double quotes.


How to show preview of entered values in previous steps in webform with multiple steps I am configuring a "Webform". In my webform field components, I am using "page break" in order to create Multiple step forms.

But I like to show the entered value in previous steps in current step.

for example, if user is in step 2, I want to print entered value of step 1 bellow the form.
or if user is in step 3, I like to print the entered value of step 2 and step 1 bellow the form.

is there any module to run this scenario? or I have to program a custom module?

Please guide me.

Thanks a lot

You can try Webform Bonus Pack module, it have the option to preview webform fields before submission.

  which allows you to add a summary component directly to your form in
  the same way you would add a textfield or any other component type.
  Install that module and add a summary field to your form, selecting
  which fields you would like to include in the summary. If you would
  like it on its own page, make sure to add a pagebreak component first.

also take a look at this https://drupal.org/node/435232


How do I migrate CCK filefield? I'm migrating a Drupal 6 site with CCK filefields to Drupal 7. I installed the Drupal 7 CCK module, and I'm ready to do the migration except for a filefield field.

Migrate fields states:

  Missing field module: 'filefield'. This field cannot be migrated.

The filefield module isn't available for Drupal 7. Is there an other module, or any other way of migrating a Drupal 6 CCK filefield to Drupal 7 fields?

Update

I just realized it's an audiofield. Basically it's a filefield with an audio widget.

Not sure whether I should call this a solution or a workaround. Anyway:

In D6 I removed audio representation of the filefield. This makes it an ordinary filefield. Then migrated to D7 using the CCK migration kit and then added the audio representation again. Done.


Generated CSV cannot be read by Feeds Using Views Data Export module, I am generating a CSV file of the latest 10 content. Then on another Drupal site, I am trying to import those nodes with Feeds.

The problem is when I give the url of the generated CSV, Title and Body fields cannot be imported. The nodes are generated, but those two fields are empty. Other fields like tags, date, etc are imported fine.

When I manually download the CSV, put to server via FTP, then make Feeds get the CSV from there, everything works OK.

I also tried the option "Provide as file" from the Views Data Export settings. Not working either.

What is the problem with generated CSV's address?

It drove me crazy but in the end, I found the issue.

The website has a default language other than English. When I look at the CSV url (as a logged in user) I see the correct headers in the CSV (because my language is English). But when an anonymous user looks at the url, he sees the translated headers :) So the headers dont match with the ones I set up in the Feeds settings.


Need help with import problem on Aquia DEV desktop for Windows I am trying to import a DEV version of a site using the import function on Aquia Dev Desktop

I can successfully import the codebase and the sql dump file, but every time I go to the site, I get this error

**Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required '/var/www/xhprof/header.php' (include_path='.;C:\php5\pear') in Unknown on line 0**

We have tried this on three different laptops, all using the same Windows 7 configuration. We get the same result every time. This leads me to believe that there is something wrong with the files that I was given to import

Does anybody have any insight into what might be happening?

Thanks!

We fixed this with a hammer.I hope we can find a more precise fix in the future.

These are the instructions I gave to our team

Go to root directory of your original localhost Drupal installation  (aka codebase)
Copy all the stand alone files –leaving the folders uncopied
Go to the root directory of your Drupal installation that you are trying to import (aka codebase)
Delete all the stand alone files in the codebase (leaving folders)
Paste in all the stand alone files from the localhost codebase

This should get things working again.


Most popular content content modules in Drupal 7? What's the best way to do most popular content in Drupal 7?

I've been using the Most Popular module because I haven't been able to find anything else, but that only has ~750 odd users spread between the D6 and D7 versions. Surely popular content is a fairly-common requirement? That leads me to believe there's a better maintained (and hopefully less buggy) module that does the exact same thing, just it has an obscure name and I can't find it via Google. If so, what is it?

(If you're going to crucify me for asking for an alternative module, note that I've contributed several issues and a documentation patch for Most Popular, and have volunteered to contribute code patches. However, there hasn't been a single commit on that module in ~6 months.)

Thank you!

Almost all functionality of this module you can implement using Views + Radioactivity module as it is described here drupal.stackexchange.com/a/21075/7313


List Private Organic Groups Publicly without giving access to the node page? I have a view setup to list my OG Nodes, those nodes and their greater content need to be private to only the group, but on the front end of the site I want to list some of the featured Nodes.  As it stands the node access system is removing those nodes from my public listing.  Any solutions to keep the full node private, but list these OG Nodes publicly?

You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

  Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_db_rewrite_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.


How to translate a button? I have a website in English language and i want to translate some button in own language .
i know that i can add my language and simply translate all my stuff, but the point is i have to translate these buttons like subscribe in Simplenews module in en language.

Here is my step :
i went to config/regional/translate/translate and add my word to translate but i could not do that .

am i missing something ?

You can use the module String Overrides which allow you to do what you asked for.

(As my low reputation I need to put here some more useless details :-) )

Copied From the module page:

Provides a quick and easy way to replace any text on the site.

Features:
Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


AJAX Throbber - Keep throbber image but delete Please wait... message? This question has been asked a few times in various forms but is there a simple way to keep the animated blue throbbing image but delete the Please wait... text?

I'm trying this in my form_alter hook:

unset($form['my-model']['#ajax']['progress']['message']);
// or
$form['my-model']['#ajax']['progress']['message'] = '';

But this appears to remove the message AND the animated throbber! I want the throbber to remain. Is it a requirement for message to not be empty for the throbber to even render?

@Jimajamma answered the question correctly in the first comment.

 $form['my-model']['#ajax']['progress']['type'] = 'throbber';
 $form['my-model']['#ajax']['progress']['message'] = NULL;

Must explicitly be set and configured within the ['#ajax'] form element.


running "drush @remote status" gives "bash: drush: command not found" I tried to follow solution here: Why does drush say "command not found" when I try to execute remote commands?

But it did not work for me, the url /usr/local/zend/bin does not exists in my hosting provider.

I can't run any remote command from my local, I dould test the connection doing

drush @remote ssh

and it correctly connects through ssh, so the problem is not in the connection. Please help me with this =( Thanks

The other question that you reference answers your question perfectly, except for the fact that Drush is located in a different location on that user's remote system.  Since drush @remote ssh works for you, type which drush on the remote system, to find out where your Drush is located.  You are likely to get an answer similar to /home/USER/.composer/vendor/bin/drush.  You need to insure that the directory /home/USER/.composer/vendor/bin is in your PATH.  This directory might vary if you did not install Drush using Composer, as recommended in the Drush README.
If which drush produces no output at all, this means that you forgot to install Drush on the remote machine.  Use composer, following the same instructions you would for your local machine, in the above-referenced README file.
Pay particular attention to the following part of the installation instructions:

Add Composer's global bin directory to the system PATH (recommended):
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

The 'sed' line shown above adds an export PATH statement to the TOP of your .bashrc file.  It is important to set your PATH early, because .bashrc exits just a few lines in when running in non-interactive mode on most Linux distributions.  Most of the other places you might be tempted to set the PATH (.profile, etc.) are not sourced at all in non-interactive mode.  So, if you do not set the PATH in the right place, then Drush will work from an interactive shell (e.g. after drush @remote ssh), but most remote Drush commands (e.g. drush @remote status) will not.


search only on taxonomy and user autocomplete drupal 7 I would search only on user and taxonomy in autocomplete but not search in content. I try many modules :

Views Autocomplete
Filters  Search Autocomplete
Custom Search
Term Search

But none complete that ! any clues would be good.

Filters Search Autocomplete works great for that but there a bug with entity Reference

We can achieve this by following these steps:
Add the required node reference field as relationship.
Add a title field in fields and give them the above relationship.
Add the title in combine filters.
It Worked for me :)

read more on drupal.org


"You are not authorized to access this page." in Chrome after returning from offsite payment After concluding checkout flow on site I'm redirected to offsite payment service (Datatrans).
There if I finish payment and I get redirected back to:
/checkout/order_number/payment/return
or I cancel payment and get redirected back to:
/checkout/order_number/payment/cancel
on site I get the message:
You are not authorized to access this page.
At that point I'm not logged out - if I just reload the page (click on browser address bar and hit enter to open page again. I get redirected to:
/checkout/order_number/order_information
Important - this happens only in Google Chrome. In Firefox this works well.

Possible solution would be adding following rows to .htaccess file inside <IfModule mod_headers.c> block.
  Header always edit Set-Cookie (.*) "$1; SameSite=None; Secure"
  Header onsuccess edit Set-Cookie (.*) "$1; SameSite=None; Secure"

Some more info on this issue:
https://docs.datatrans.ch/v1.0.1/docs/security-samesite-cookies


user relationship status as a visibility rule per panel pane how make a visibility rule based on UR status I've made a function to get the status between the visitor and the visited profiles

I ask if the module provide it or could i make it appear in visibility rules for panels module if it provide any hooks for that

From: http://drupal.org/node/1185210

User Relationships provides individual panel pane visibility checks based on relationship status.
In order to use this functionality:
Make sure that the User context has been enabled for the current variant (most likely current user)
Add a new visibility rule for the pane you would like to control
Select 'User Relationship' and configure for your use case.

That being said, I wrote those instructions for Drupal 6 while porting this feature to 7 and there may be bugs with the 7.x implementation. If you find anything make sure to post what you find on the issue queue.
If you want to customize your implementation further that code would be a good starting point, and please post any additional visibility rules back to the queue.


How do I programmatically enable a view mode? Let's say I have created a new view mode with DS. How can I activate it programmatically?

I want to achieve this because I'm doing an export with features but, despite the Features module exports DS settings and layouts, it does not automagically activate them. I'm planning to active this new display inside an install hook or something like that.

I looked in the tables schema, but I could not tell what activates a view mode.

Use following code to enable view mode programmatically in Drupal 7:

module_load_include('inc', 'field_ui', 'field_ui.admin');
$bundle_settings = field_bundle_settings('ENTITY TYPE', 'BUNDLE');
$bundle_settings['view_modes']['VIEW MODE']['custom_settings'] = TRUE;
field_bundle_settings('ENTITY TYPE', 'BUNDLE', $bundle_settings);

Replace ENTITY TYPE, BUNDLE, VIEW MODE with your values.


Is it possible to alter $form_state before it is passed to user_profile_form_submit? I have a form posting updates to the user account.
The problem is I need to add some more data to the post object before user_profile_form_submit gets a hold of it.

Is this possible in Drupal 7?

There many ways to alter the $form_state values. It would be nice if we know what you wanna change so that we can say the best way to do it. Any way the following hooks can help.

hook_form_alter
hook_validate
hook_form_submit

You can have your own submit function either by overriding the $form['#submit'] values in hook_form_alter or add one to modify the values.


No emails being sent when using User Registration Password set up When a new user registers with my website it displays "Thank you for applying for an account. Your account is currently pending approval by the site administrator.
In the meantime, a welcome message with further instructions has been sent to your e-mail address."

However, no email is sent from the site at all.

I have my settings so that approval is required from the administrator before the user can be activated. Also, they set their password up on the registration screen.

Im using v1.4 of the User Registration Password module, and Drupal 7.41

Could someone let me know why no emails go to the administrator or the users ? Emails were being sent without the module installed, but I really want users to set their password up front.

This all works perfectly now, i needed to use an email address that belongs to my domain i.e. anything@mydomain.co.uk otherwise it gets blocked, therefore use this email in Configuration/Site Information and also in the Trigger rule I created to alert me when a new user is created. Thank you for guiding me towards using the Dev version.


Subclassing content type forms I was wondering how would you guys approach a situation where your Drupal7 site required a couple of custom content type, yet most of the fields would be shared across them. What I mean resembles a typical object-oriented case of a super class and its subclasses.

I want it so that I can make the admin-side content filling easier for the owner of the site. I also assume that for me, as the author of the form it would be a great time-saver if I could base one on another.

Is it possible? Does it make sense? Or would you rather make one type with all possible fields merged onto one form, then tweak the suggestion template so that irrelevant parts are /shown/hidden upon changing a dropdown menu that specifies the subclass?

Anyone been through a similar problem?

Or would you rather make one type with all possible fields merged onto
  one form, then tweak the suggestion template so that irrelevant parts
  are /shown/hidden upon changing a dropdown menu that specifies the
  subclass?

If you're going the single-type route, here are two tips: Drupal Forms API supports conditions, check the docs; it might be useful to take a look at the Prepopulate module.


Single Bulk Operation on several blocks I would like to display on a single page several blocks generated by views and associate the same bulk operation to all of them so that the user only needs to click execute once.

Where would you start to achieve this ?

All ideas welcome.

If you have a specific list of blocks you want to alter, get their deltas and invoke hook_block_view_alter in a custom module, as follows:

function YOURMODULE_block_view_alter(&$data, $block) {
  switch($block->delta) {
     case 'delta1':
     ...
     case 'deltaN':
       // alter the block in the required way by modifying the $data array
       break;
  }
 }

If you want to alter ALL blocks created by a particular module, say, views, do a switch on $block->module, instead, i.e.:

function YOURMODULE_block_view_alter(&$data, $block) {
      switch($block->module) {
         case 'views':
         case 'SomeOtherModule':
           // alter the block in the required way by modifying the $data array
           break;
      }
}

Bear in mind that hook_block_view_alter is called for ALL blocks, so if your site has lots of blocks, this may be a performance hit.


Drupal 7 #ajax callback on form submit Hello I have created a custom form added a # ajax callback on form submit

    $form['hotel_book_form']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Check Availability'),
    '#ajax' => array(
      'callback' => "list_rooms",
      'wrapper' => "replace_hotelbook_div",
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

and I have added this wrapper as suffix to the form

    $form['hotel_book_form'] = array(
    '#type' => 'fieldset',
    '#title' => t('Book Hotel'),
    '#weight' => 5,
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '

',
  );

but when I click on form's submit button the page gets simply reloaded and the ajax callback function does not fire.

You haven't actually wrapped the element, you've inserted an empty
 immediately before it.

You need to use #prefix and #suffix to wrap an element in HTML:

...
'#prefix' => '
',
'#suffix' => '
'


Drupal 8, use variable defined from custom form in custom template twig I created a custom form, a custom twig template, and I 'linked' both with a theme hook.

From my buildForm method of Form Class, I defined a variable like this :

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#foo'] = array("key_a"=>"value_a", "key_b"=>"value_b", "key_c"=>"value_c");
  // do some work ...
  return $form;
}

From my twig template, when I dump or sho all availables variables with :

{{ dump() }}
{# or with kint #}
{{ kint() }}

I see my array '#foo' is present in variables availables from my custom twig template. The "#foo" array is in a 'element' array.
My question is, how can I get and print the content ?

If I do a sample :

{{ #foo }}

I get a syntax error because there is a 'sharp' (#) character.
I tried :

{{ element.#foo }}
{{ element.'#foo' }}
{{ 'element.#foo' }}
{{ foo }}
...

Sometimes I get an error, sometimes a NULL printed result..How can I print my array, get keys and values ?

Thanks you !

Like javascript you need to use bracket notation to get hash key variables:

{{ element['#foo'].key_a }}


How do I get comment form? In Drupal 7, comment form can be rendered using the following code.

drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));

How can I achieve the same in Drupal 8?

See https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21CommentLazyBuilders.php/function/CommentLazyBuilders%3A%3ArenderForm/8.2.x.

You create a comment entity and then get its form.

<?php
$values = array(
    'entity_type' => $commented_entity_type_id,
    'entity_id' => $commented_entity_id,
    'field_name' => $field_name,
    'comment_type' => $comment_type_id,
    'pid' => NULL,
  );
$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$form = \Drupal::service('entity.form_builder')->getForm($comment);


Adding Theme Suggestions Programmatically For Views (Rows & Fields) For a site I'm currently building I've got a variety of views, all with multiple display modes for different pages.

For example, I have a venues view, one block is named listing which lists all of my venues content type. I have another block which has some more specific contextual filters.

My issue is, this different block is styled the same, and has the same markup as my listing block so I don't want to have to duplicate my Twig templates for the rows and fields, for each display mode I have.

What my idea was is to add a function to my .theme file that would allow me to list display modes for a certain view, and add a single theme suggestion off that back of that. This way I can rename my Twig templates, and re-use the same ones for row and field level, on as many display modes as I'd like.

As I'm not using a theme suggestions alter hook, I'm not sure how I actually add theme suggestions.

Here's what I've got so far:

/**
 * Theme suggestions for views.
*/
function spve_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $id = $view->storage->id();

  // Venues
  if($id === 'venues') {
    // Venues grid
    switch($view->current_display) {
      case 'single_occasion_type_listing':
        $suggestion = 'views-view--venues-grid';
        break;

      default:
        $suggestion = null;
        break;
    }
  }
}

Obviously I'd need to replace either $suggestion with the correct function to add a theme suggestion, or add a bit at the end of my function to add a theme suggestion based of my $suggestion variable.

Your Solution is good, but there is a cleaner one. You can use the hook_theme_suggestions_HOOK_alter, so you do not have to check if it's a view or whatever you want to check.

In your case it would look like this:

    function spve_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
        // If you want you can add a template suggestion for all views
        // based on their ID:
        $suggestions[] = sprintf('views_view__%s', $variables['view']->id());

        // Or you can check the ID, add suggestions, do whatever you want
        // ...
    }

    function spve_theme_suggestions_views_view_field_alter(array &$suggestions, array $variables) {
        // Check here the id, add suggestions, do whatever you want
        // ...
    }

More informations in the Drupal Theme API


Print a text if a view result is equal to a certain value In a template file, how can I use PHP to print some text if a view has a certain value?

The view uses the node ID, so I guess this argument needs to be passed to the view (as it would be if the view was embedded onto the page).

Here is my attempt:

<?php
  $view = views_get_view('hide_weight_2');
  if ($view->execute_display('default', $args) == 'Yes' ):
?>

Result of view was yes

<?php endif; ?>

If I understand well your question, I guess that you can make this in a rough way from a template View. Inside this template file you can add the respective conditional to show your text.

Here is the part of views-view-unformatted.tpl.php when each result is printed:

<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

Then, you can parse $row to catch the respective value and print a message. You can use preg_match() to match the value For example, instead of <?php print $row; ?> you could use:

<?php
  if (preg_match("/(here text to match)/i", $row)) {
    print "Aha!:" . $row;
  }
  else {
    print $row;
  }
?>

I guess you can improve this seeking per target fields.


"Radios" not creating multi options? I am creating a radio button like this:

$form['paymentMethodSelect'] = array(
    '#type' => 'radio',
    '#title' => $this->t('How would you like to make payment?'),
);

This works and creates a single radio button. Now according to documentation, to create multiple radio buttons, you change "radio" to "radios". But if I do that:

$form['paymentMethodSelect'] = array(
    '#type' => 'radios',
    '#title' => $this->t('How would you like to make payment?'),
    '#default_value' => 'eft',
    '#options' => [
        'eft' => 'EFT (Electronic Funds Transfer)',
        'cc' => 'Credit Card',
    ],
);

But if I do that then I end up with this:

Any idea why I am not seeing two radio buttons as expected?

Your code still shows radio instead of radios for '#type' attribute.

$form['paymentMethodSelect'] = array(
    '#type' => 'radios',
    '#title' => $this->t('How would you like to make payment?'),
    '#default_value' => 'eft',
    '#options' => [
        'eft' => 'EFT (Electronic Funds Transfer)',
        'cc' => 'Credit Card',
    ],
);

Otherwise there is no other problem I see in your code.
Sample code from D.O

$form['settings']['active'] = array(
  '#type' => 'radios',
  '#title' => $this->t('Poll status'),
  '#default_value' => 1,
  '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
);


Load CKeditor with Simplified Toolbar on dynamically created page element Drupal 6
ckeditor 3.6.4

I have page that loads the text area dynamically, so I am using

  CKEDITOR.replace('textarea-id');

Which works, but it is bringing in the full toolbar. I would prefer that the simplified toolbar is used, but it would also be acceptable to use the toolbar I have defined if loading the simplified is not possible. Least desirable would be to hard-code the toolbar, but I consider that a last resort. How do I accomplish this?

I have tried

 CKEDITOR.replace('textarea-id',
    {
        toolbar : 'myprofile'
    });

Which throws  js error:
Type x is undefined
, I think related to the fact that it cant load the profile. Suggestions?

For better or worse, this is how I did it:

http://joe-riggs.com/blog/2012/11/drupal-ckeditor-load-configuration-settings-on-dynamic-page/


How do I pass a response from a Webform custom handler back to Drupal to display on the confirmation page I have created a custom module for a custom Webform handler. The custom handler submits to an external SOAP api. There are various response options that are received back from the SOAP api that currently I am printing to screen (for testing purposes). But when using this module in production, I obviously want these responses to be displayed at the top of the confirmation page.

Is there some way to populate a token (possibly the Webform Handler Response token?), which I can then use to print the information on my confirmation page?

F

Your two options are…

OPTION 1: Add the SOAP API's response value  as a hidden element's value using something like

$webform_submission->setElementData('response_value', $response->value);
$webform_submission->resave();

OPTION 1: Store the response in $_SESSION and use

\Drupal\webform\Plugin\WebformHandlerInterface::confirmForm
\Drupal\webform\Plugin\WebformHandlerInterface::preprocessConfirmation

to alter the confirmation message or page.


Bluehost cloud hosting, varnish caching issue authenticated user I have narrowed down my problem to varnish on my cloud server provided from bluehost.

When logged in you make an edit, but it is not reflected back until 5-10 minutes later.

Clearing all caches, browser history, etc. nothing helps expect logging into bluehost and clearing the varnish cache.

Any ideas?

Just to add that varnish only work for anonymous user not for authenticated.

There are various module available to purge varnish cached data on a particular event such as node insert, update, delete and many more.

Configure events properly in module configuration and that should do the needful.

Following are module :

expire

purge


Change Page Title on Add Node Page Which hook/filter do I need to use to modify the 'add node' page title (This Title)?  For example, when viewing "/node/add/" I want to change the title from 'Create ' to 'Add New '

There are a few different ways you could do this, but the way you asked for would utilize hook_form_alter():

<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mynodetype_node_form') {
    drupal_set_title('My new title');
  }
}
?>

This would be in a custom module named custom.module... drupal_set_title(), when called anywhere in the page load, will set the title appropriately. You're basically hooking into the node form rendering process, and saying 'set the title to what I want' at that point.

If you'd like to further differentiate what the title would be depending on whether the user's creating a new node or editing an existing node, use Devel module's dpm() function to print out the $form_state array, and check to see if there's a node ID already or not—if there is, you are editing a node; if not, you're creating a new node. Set the title appropriately.

While hook_form_alter() would probably be the most robust page (in case someone was viewing the node add form from somewhere other than node/add/[type]), you could also check the path in hook_init() and set the title there, or from a variety of other places (in Drupal 7, hook_page_alter() perhaps).


problem migrating my drupal site PDOException: SQLSTATE[42000] [1044] Access denied for user I have just loaded my drupal 7.32 site to JustHost from my pc (running xampp) copied the files across, and exported and imported the database to JustHost cpanel, i browse onto the website and I get the error message below. I have triple checked my database name and username of the database and password and they are correctly specified in my settings.php file. My database was called 'school2' on the pc, but I'm not sure that will affect anything.

I get this error message:-

PDOException: SQLSTATE[42000] [1044] Access denied for user 'caerleon_prim'@'localhost' to database 'caerleon_prim' in lock_may_be_available() (line 167 of /home4/caerleon/public_html/includes/lock.inc).

Can anyone help?

With JustHost you need to assign the user to the database from the Database Maintenance drop down page. Instructions are on their site too. I did this, and it fixed my problem.


How do I turn off mobile menu collapse for bootstrap 3 theme in drupal 8? I am looking to use a different mobile menu solution and replace the default bootstrap 3 mobile menu.

How can I turn off the bootstrap collapsed mobile menu function?

Just override the menu--main.html.twig template that comes along with the bootstrap theme, and replace the HTML classes with your own classes, then the bootstrap mobile styling won't affect your menu.


Add close button in ctools model dialog I am using ctools modal dialog/popup window to display some records. The default close button is working fine. How can I add a custom close button?

Thanks

As for this issue commited on November '11, you should be able to close any CTools modal window with a link that has the class "ctools-close-modal"

For example, in my modal I've got this for element to cancel and close:

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), '#',
       array(
         'attributes' => array(
           'class' => 'ctools-close-modal'
          ),
         'external' => TRUE
       )
     )
  );


After adding a column to a module's schema, should the new column also be placed inside hook_schema? I have my own module which implements its own schema. I now want to add a column to the table provided by the schema, which I plan on accomplishing via hook_update_N() and db_add_field().

My question is essentially what the title of this question is: after I add the new column to the schema, should the new column also be placed inside the module's hook_schema() implementation? Example (adds a column named mynewcolumn to the schema of the module mymodule):

function mymodule_update_6000() {
  $ret = array();

  db_add_field($ret, 'mymodule', 'mynewcolumn', array(
    'description' => t('This is my new column'),
    'type' => 'text',
    'size' => 'big',
    'not null' => FALSE
  ));

  return $ret;
}

At this point, do I place mynewcolumn inside mymodule_schema()? Or does mymodule_update_6000() fully take care of proper installation and uninstallation?

hook_update_N() is only used when updating a module, while hook_schema() and hook_install() are used only when installing a module. Since there are users who install the module, the database field must be also added in hook_schema().


How to add custom css file to subtheme of omega kickstart theme? I have created a subtheme of "omega kickstart theme" and I want to add some custom css files to it. I searched and got some solution(which didn't worked for me), the solution is as follows:

create your custom css file and place it in css folder of your subtheme.
edit your subtheme.info file(edit under optional css code of info file) as follows:

css[yourthemename.css][name] = 'Your custom products styles'
css[yourthemename.css][description] = 'This file holds all the product page CSS of your theme.'
css[yourthemename.css][options][weight] = '12'

The other Solutions were as follows:

Specify your custom css path file in info file as

stylesheets[all][] = mycustomcss.css

Make use of "drupal_add_css" function in template.php as follows

function MYTHEMENAME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $path = drupal_get_path('theme', 'MYTHEMENAME');
    drupal_add_css($path . 'MY-THEME-PATH');//PUT UR CSS FILE PATH
  }
}

I tried this function twice with two different paths. First I gave path as '/css/mycustomcss.css' and second time I gave path as '/MYTHEMENAME/css/mycustom.css'.

UNFORTUNATELY NONE of these solutions worked for me. Am I missing something or is it something else?...please help.

I was missing one line in code. here is what you have to do. in your .info file under optional css code write the following code.

css[yourcustomcss.css][name] = Your custom products styles
css[yourcustomcss.css][description] = This file holds all the product page CSS of your theme.
css[yourcustomcss.css][options][weight] = 12
settings[alpha_css][yourcustomcss.css] = 'yourcustomcss.css'

Now go and enable your 'yourcustomcss.css' in Appearance/yourthemename/settings/toggle-styles


User Profile Picture Cached After Change When changing your profile picture (using core pictures support) the image is uploaded correctly but is saved with the same file path as the old image.

The result is even though the image is uploaded correctly, the browser has cached the old one and still displays it, making it seem as though the new picture wasn't uploaded.

Forcing a refresh (ctrl + f5) resolves the problem, but this is not normal user behavior and has already caused confusion.

Is there a way to force a reload for this? Change the image path? Set an expires header? Open to suggestions.

use a random tail after the filename like
http://www.domain.com/filename?122492834932
it will detect your file as a new file and browser cache will not read it as the same as the old one


My sitemap.xml have a different domain and this is an error I have created a site with a development domain name. Now this site is online (camperlife.it), but sitemap.xml created by XML sitemap module still contains the development domain name.

I have rebuilt sitemap many times, but without success.

Where is my problem ?

I think you have a setting wrong.

Browse to the XML Sitemap settings page (admin/config/search/xmlsitemap/settings).

Expand the Advanced Settings section.

Check/set the Default Base URL.  Typically, I set this to make sure the default base URL gets used, as rebuilding from drush won't set it properly if you don't $uri set in your site alias.


Complete export of Drupal nodes I am programatically generating nodes in my local Drupal 6 installation.  I have to do it locally because I don't have access to some of the more nifty PHP commands / modules that I need in order to create the modules on the production server.

These nodes come out properly formatted with aliases already created, and I would like to export those to the production server with aliases intact.

I have been attempting to use the Node Export module, however that doesn't preserve aliases (as far as I can see anyway).  The Deployment module has never left alpha for Drupal 6, and I have been running into errors while using it.  When it did work, aliases were not preserved.

Is there a method to preserve aliases available?

I've successfully used a combination of the following modules to do similar migrations:

feeds (for import)
feeds_tamper (data normalization and mapping)
views_rss or views_bonus (RSS feed of nodes or CSV export)

I can see (although I've never used) a patch for the Feeds module to maintain aliases as found here http://drupal.org/node/1284522

One big bonus with using the Feeds module for import is it understands (through a hashing system) data that has already been imported. So, if you used the ViewsRSS module you can setup a timed event for Feeds to grab only the new or update existing content without having to initiate a transfer on the production server -- they just stay in sync. I've also implemented a workflow where nodes are only published in the RSS feed after they have been reviewed by an editor ...

Cheers,

Rob McCrea


Views filter: Filter by number of field values Is there a way in Views to create a filter that shows nodes by number of values for a field? For example, to create a view of nodes, showing only those with two or more terms from a given vocabulary?

did you look if you have access for your designated field to the "delta" version of this field ?

This will do the trick.

If you don't, I'd advise to use aggregate and COUNT values of the field. Will work the same. Create a filter with that field, activate aggregation, count.


Printing block on all pages of a contenttype In my page--front.tpl.php i have a menu block rendered using:

<?php
$block = block_load('menu', 'menu-basic-menu');
print render(_block_get_renderable_array(_block_render_blocks(array($block))));
?>

Which works as expected.

What should i do to print this block on all pages of a specific content type?

Help appreciated

You can created the page.tpl.php and put a condition to check the content type then print this block.

page.tpl.php API Drupal 7

From node object you can find the content type to check condition.

<?php print_r($node);?>

More specific to your question.

<?php global $node;
    if ( isset($node) && !empty($node) && $node->type == 'type_name') {

            $block = block_load('menu', 'menu-basic-menu');
            print render(_block_get_renderable_array(_block_render_blocks(array($block))));

    }
 ?>


How to override exposed filters view I have one form of exposed filters of view. I need to override few elements of that, like change options for select box dropdown and like that.

For that I have created view, and used hook_form_alter, but the changes are not reflecting.

My work:

function custom_module_form_alter($form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form' && $form['#id'] ==
         'views-exposed-form-advanced-search-page') {

         print_r($form['submit']);  //debug
         $form['submit']['#value'] = t('Search');
         print_r($form['submit']); //debug
    }
}

As shown above, to test, I am just trying to alter the label of submit button, and for debugging, I have added two print_f, statement, output of which are as follows:

First print_f():

Array ( [#name] =>
        [#type] => submit
        [#value] => Apply
        [#id] => edit-submit-advanced-search
      )

Second print_f():

Array ( [#name] =>
        [#type] => submit
        [#value] => Search
        [#id] => edit-submit-advanced-search
     )

As shown, the label is changing, but it is not reflecting to the form.

Considering module weight, I have also tried giving more weight to my module tham views weight. But nothing changed.

Please suggest, if I am missing something.

-- Thanks for your time.

You have to pass the variable as reference.

So the function would should be

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