Why do images rendered with image_style_url disappear on iPhone? I use "image_style_url" to render images in node template. Everything works fine on web browsers. However, these images disappear on iPhone.

Here is my code:

        <?php
            foreach($node->field_project_pics[LANGUAGE_NONE] as $project_pics){
        ?>
                <img class="carousel-item" src="<?php print image_style_url('eve_project_page_detail__700x476_', $project_pics['uri']);?>" alt="">
        <?php
            }
        ?>

Link: http://tvphong.x10host.com/node/62

Any suggestions?

The problem is with jcarousel. The images are rendered fine, but width and height is set to 0 on mobile.
You should be able to set widht and height in CSS.
See possible solution here: https://www.drupal.org/node/576016#comment-6041834
Attached is iphone rendering:


remove 'publishing options' and other settings from node/add I have a role which allows users to add nodes, viewing the admin form, but I don't want the user to be able to see  Is there a way to remove it?

hook_form_alter() or use CSS if you don't care if the values are overridden.


Entity Metadata Wrapper: Setting User Reference Problem

How do I set a user reference value from the reference module using an entity metadata wrapper?

So Far

I have a form submit. It's creating an node with a user reference field. I can't work out what structure will submit the value.

First I tried submitting a user account (object), however this throws an awful error.

global $user;
$ewrapper->field_user_permission->set($user);

I then tried submitting uid, however it said it was expecting an array not a string.

$ewrapper->field_user_permission->set($user->uid);

I then tried creating a custom array based on printing out the array of a field that was already set.

$user_perm = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

 $ewrapper->field_user_permission->set($user_perm);

But that printed out another horrible error. What should I be using to submit the user reference?

 PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'uid' for column 'delta' at row 1: INSERT INTO {field_data_field_user_permission} (entity_type, entity_id, revision_id, bundle, delta, language, field_user_permission_uid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6), (:db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 246 [:db_insert_placeholder_2] => 246      [:db_insert_placeholder_3] => contact_details [:db_insert_placeholder_4] => uid [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 182 [:db_insert_placeholder_7] => node [:db_insert_placeholder_8] => 246 [:db_insert_placeholder_9] => 246 [:db_insert_placeholder_10] => contact_details [:db_insert_placeholder_11] => access [:db_insert_placeholder_12] => und [:db_insert_placeholder_13] => 1 ) in field_sql_storage_field_storage_write() (line 451 of C:\XAMPP\htdocs\drupal\modules\field\modules\field_sql_storage\field_sql_storage.module).

EDIT

New error for creating a new level:

$user_perm[] = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

$ewrapper->field_user_permission->set($user_perm);

PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {field_data_field_user_permission} (entity_type, entity_id, revision_id, bundle, delta, language, field_user_permission_uid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6_uid, :db_insert_placeholder_6_access); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 253 [:db_insert_placeholder_2] => 253 [:db_insert_placeholder_3] => contact_details [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6_uid] => 190 [:db_insert_placeholder_6_access] => 1 ) in field_sql_storage_field_storage_write() (line 451 of C:\XAMPP\htdocs\drupal\modules\field\modules\field_sql_storage\field_sql_storage.module).

Looks like Drupal is trying to set the delta column to the string "uid", which suggests you need another level in your array:

$user_perm[] = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

$ewrapper->field_user_permission->set($user_perm);


Timefield [entityform:field-name:value_formatted] token not working in Rules I am having troubles using token replacement for the Time field field type provided by the module Timefield  in Rules.

The token pattern [entityform:field-name:value] works just fine (it gets replaced by the raw "offset value" of the field - I'm using this field in an Entityform), but I just can't figure out how to display the formatted value.

I've followed directions in the pattern replacement help text, and tried different combinations of hyphens and low hyphens to no avail: [entityform:field-name:value_formatted], [entityform:field_name:value_formatted] and [entityform:field-name:value-formatted] - none work.

I've already posted a request for support in the Timefield issue queue, but was wondering if anyone here has had a similar issue, and can point me in the right direction? Thank you in advance.

EDIT: After some additional testing, I've discovered that the [entityform:field_name:value_formatted] token DOES work in some situations, such as inside a Rules Component. It does NOT work if the Rule is triggered by the event After saving new content(for nodes) or After saving a new entityform submission (for Entityforms). Obviously this seems to be a bug, but I don't have the time to figure out where this problem happens. Apparently the value token of the field is built right away, but the value_formatted is not readily available when the Rule is triggered right after creating a new entity. Any thoughts?

Since this problem seems to be a bug, and just in case someone else runs into this issue, there is a workaround you can do within Rules to get the formatted value of the time field. It involves:

Enable the module PHP filter
Use the action Execute custom PHP code to run a PHP snippet that calculates
the formatted value using the raw value provided by the token


Rule iteration check I am currently making a site that will implement a system of volume licenses and I am using a system of checking user registration info to check for certain rules.
My rule works like this

i. On the event of a new user being generated

ii. Check for two conditions present in the user registration info

Check one AND Check two

iii. Grant the user a certain permissions role.

Problem: I need this rule to only work for X amount of users they have added with X being the amount of users that is allowed for with their volume license. I do not know a way nor can I find a way to check against how many times a rule is ran and then disables the rule if a certain number of users have received a role this way. Any ideas?

When the rule is ran a certain role is granted to the user. So in your rule's condition add a PHP (or any other way) and check for the number of users who have this role.


How can I avoid the output of my module is cached? I have a module I wrote that prints dynamic data for JavaScript variables.

function javascript_api_page_attachments(array &$page) {
$page['#attached']['html_head'][] = [
        // The data.
    [
        '#type' => 'html_tag',
        // The HTML tag to add, in this case a  tag.
        '#tag' => 'script',
        // The value of the HTML tag, here we want to end up with alert("Hello world!");.
        '#value' => javascript_api_print_parameters(),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
];}

My problem is when Drupal caches the page.Need to stop caching my pages in drupal.

How can I avoid the output of my module is cached?

As Eyal mentioned, you can pass the variables from your module to jQuery like this:

mymodule.module

function mymodule_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'mymodule/auto';
    $attachments['#attached']['drupalSettings']['cool'] = 'hello world';
  }
}

mymodule.libraries.yml

auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

auto.js

(function($, Drupal, drupalSettings) {

    $( document ).ready(function() {
      alert(drupalSettings.cool);
    });

})(jQuery, Drupal, drupalSettings);

This will show a js alert message saying "hello world".


how to put a submit button with a pre-defined submit function by calling drupal_render? I've been search results for hours but cannot find an answer to my problem.

I want to show a list using theme("table",...); inside my table, there's a column of buttons, which each functions as deleting the record for this row. Therefore, I did something like this:

foreach($person_list as $pyid => $record){
  $render_ele = array('remove'.$pyid => array(
      '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
      "#attributes" => array("pyid" => $pyid,'action' => "remove"),
    ));
  $rows[] = array(
    $record['full_name'], // full name
    $record['matric_no'],  // matric no
    $record['room_number'], // room number
    $record['position_name'],
    is_numeric($record['cca_points'])?$record['cca_points']:"Not Assigned Yet",
    drupal_render_children($render_ele),
  );
};

However, when I clicked on the button, the submit function I've defined is not called (it called the default submit function instead).

When I try to add another default button into my form like this:

$form += array(
  'nani' => array(
    '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
  ),

Both this button and my old-not-functioning submit button works.

I therefore conclude that it's a JavaScript problem... possibly some JavaScript is not included when I call the drupal_render by myself.

Could anyone help on how to solve this problem?
Thanks a lot.

Update:
I called drupal_render, because I want to pass the rendered result to rows[] so that I can put these elements inside a table, like this:

$render_ele = array('remove'.$pyid => array(
      '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
      "#attributes" => array("pyid" => $pyid,'action' => "remove"),
    ));

$rows[] = array(
  $record['full_name'], // full name
  $record['matric_no'],  // matric no
  $record['room_number'], // room number
  drupal_render($option),
);
return array(
"person_list" => array(
  '#type' => 'fieldset',
  "#title"=> t("Group Members"),
  '#collapsible'  => TRUE,
  "#collapsed"  => FALSE,
  "#children"   => theme("table",array('header'=>$header,"rows"=>$rows)).$add_member_str,
  '#weight'     => 10,
),

);

Are you returning those $render_elem from your form function, when drupal_get_form calls that form id callback? Because i see you call drupal_render_children, but drupal need to know about it in form of form api array. drupal_get_form expecting you return from your form_id function form api array of form elements, so it can do some operation like checking, if current request is POST and contains form_id of your form and some name of submit button.

EDIT: Try add all submit buttons to your form array, but set their property #printed => true, so they won't be rendered, but drupal will be notified about those buttons and can run your submit functions.


Calling a block by AJAX I want to call a block on a page by AJAX. This is appearing in content and not in a block region.

[Use case: I have a View listing countries and their details; I want to add, at the top of the View, the user's country. I want the page to be cached, hence using AJAX to call back a View Block]

In the header of my view I have:

In hook_menu I have

$items['example/test'] = array(
    'title' => 'AJAX Delivery Test',
    'page callback' => 'show_example_block',
    'delivery callback' => '_basic_print',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

I then have two functions:

function _basic_print($page_callback_result){
  print $page_callback_result;
}

function show_example_block(){
  if (isset($_COOKIE['country'])){
    return views_embed_view('example', 'example_block', $_COOKIE['country']);
  }
}

This works fine, but I'm wondering whether I'm missing anything. Is there a simpler, slightly more native way of doing this?

<?php
$block = module_invoke('module_name', 'block', 'view', 0);
print $block['content'];
?>

Try including the view block.


Retrive $message variables in javascript file I am using Drupal 7.

In the template file page.tpl.php there is a variable called $message which prints the messages like error, warning etc.

I want to access this variable in a JavaScript file. How can I do so?

In your page.tpl.php file:

$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

Then in your JavaScript file you can access $message variable like this:

var message = Drupal.settings.my_settings.message;

Reference: The Drupal JavaScript API


Problems moving to production site I have developed a D7 website locally (WAMP), now I want to move it to a production server.

The production server has a SVN repository, so when I want to move my local files to the server I do a commit of all the changed files.
To sync the databases I get a dump of the local DB and I import it in the DB on the server.
First of all, is this a proper way to move my site to production or is there a better workflow?

The problems I encounter are these:

When I enable caching and aggregation on my local site and then sync the two databases, when I go to the production site it's like all my stylesheets are gone. There's no css styles applied whatsoever.
When I disable caching and aggregation and sync the databases, the styles are back but it's like it's the design of a month ago. The design of the local site doesn't resemble the design of the production site. When I look at the page source, I see the CSS files getting called as: pages.css?mmtwln. What does this ?mmtwln mean?
I can't login to the admin pages on the production site. When I enter my username and password nothing happens but the page getting refreshed. No error message, no red border around the textboxes. The rewrite module is enabled on the production site. I also set the $base_url and $cookie_domain in the settings.php (I have a multisite configuration, should $base_url and $cookie_domain go in sites/default/settings.php or sites/mysite/settings.php?).

If anyone can help me with any of these questions, or point me in the right direction I'll be forever grateful.

Exclude /sites/*/files/css and /sites/*/files/js from repository. It's just a cache so it should never be committed or migrated.
Before each migration purge /sites/*/files/css and /sites/*/files/js. That way you will get rid of months old cache. After each migration, make sure these directories are writeable. mmtwln seems to be a string added by Drupal or some module to prevent proxy caching, or it may be a string added by a proxy itself. it shouldn't affect static files at all (except cache prevention, but even that isn't sure)
Your site fails at saving cookies. Check your cookie domain settings in sites/mysite/settings.php and make sure you have right data in example.org/admin/config/system/site-information

If above is insufficient:

manually (via ssh/sftp/ftp) compare offending CSS files. Does the version downloaded from server look the same as version you was sure you uploaded? If not, consult your sysadmin as your server is malfunctioning somehow.
if the version you download from server via ssh is the same you uploaded, but differs from the one you downloaded via http, check carefully your .htaccess - probably there are some redirection rules that make your server to serve file from different location. Common offender is boost module, if you used to have it installed and now only it's rewrites are left, you can easily get the exact behaviour you described.


How to change a field value with a Rules Action? I'm trying to set up a Rules  Action that can change the value of a field. I created an Action Set with a data type of Node. When I go to create a Rules Action, I have access to every default Drupal node field, but no fields.

Is this simply not possible? Do I need some other module to make this work?

You first need to add a condition to check if the field exist on that node, only then it is available to the actions. There is a specific condition to do this.


Site redirects to old URLs after moving to a new server I am in the process of moving a Drupal site to a new server.
I copied the database and moved all the files.
The old URL for the site is http://www.sniffingmusicians.echidna-band.com/ and the new is http://www.sniffingmusicians.com/, which point to a different server.
Even though the frontpage of new is there, when I log in, I am redirected to the old domain.
Additionally, all the content is using the old URL. I changed the value of $base_url in settings.php, but there is no real impact.
Where else can I reconfigure my site's URL?

Maybe you can use this module:

Path Redirect (Drupal 6)

Redirect (Drupal 7)


Send HTML email from my module I have a problem while sending a HTML email through my module, Here is my code below:

.install file

function invite_an_user_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('invite_an_user' => 'invite_an_userMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function invite_an_user_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['invite_an_user']);
  variable_set('mail_system', $mail_system);
}

and here is the .module file:

class invite_an_userMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

Here is the email that I got:

Hi myemail@email.com,&nbsp;

Your friend another_email@email.com, invited you in My Site Name. Please cleck on the link to accept the invitation below:

http://something.com/referral/3139323e

&nbsp;

Thanks,

My Site

Now the problem is that, when I received the email I can see all the tags in my email. And the header of the email is

MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes
Content-Transfer-Encoding: 8Bit
X-Mailer: Drupal

I believe this should be text/html rather than text/plain.
Am I doing something wrong? Is there any different method to send HTML mail? Feel free to ask any questions.

Solved that.
I added a line on my code i.e $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;'

class invite_an_userMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

This is now working for me.. Yeppi :)


How does Drupal not rely on Foreign Indexes for matching table row information? I am so confused right now in creating a custom table within Drupal 7. My db schema builds a table with three fields one of which is a uid field. I don't have much experience with databases and I was confused as to how to match, relationally, the uid field of my table with the users->uid field. I am told that the foreign key operation within the D7 appear to do this but that they are only there as documentation, the foreign key operation doesn't actually do anything.  Is there a way, within the D7 schema, to link two table row items such as uid -- if so how?

Due to mostly historical but also database portability reasons does Drupal currently not use foreign keys.

That however doesn't stop you in any way to relate to other tables. All you need to do is insert the user id into your table and then to a JOIN to the users table if you want to query it. Or do a user_load_multiple() on the uid's separately. If you have a large amount of data, that might actually be better for performance (The default node list in Drupal does that because a LEFT JOIN can get very slow if you have millions of nodes).

You would have to do this in any way, foreign keys don't do this automatically. They do validate your data (e.g. you can't insert a non-existing uid) and you can define how to act when users are deleted (either prevent delete or delete the referenced records too, basically). In the case of users, this wouldn't help you anyway, due to the advanced and configurable User cancellation that Drupal does (e.g. you can configure it to re-assign all public data like comments to the anonymous user).


How to declare one custom module's dependency on another custom module I'm developing a set of site-specific custom modules, and one of them depends on the other one being enabled.

I'd like to declare this dependency in the .info.yml file, but the docs only show how to declare dependencies on contrib projects:

  Dependencies should be namespaced in the format {project}:{module}, where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name.

How do I declare a dependency on a module that is only found in the local codebase?

Try this just like contrib projects.

dependencies:
  - your_module_name


Alter page content using custom module I'm writing a custom module which will process information using an external service and need to display any errors thrown by this service.

I already have a variable containing error messages.

How can I target a page body markup to show the error message? I have tried hook_page_alter but failed not knowing if a page body can be processed at this stage.

Thanks

You can use the Drupal message system.

Ex: drupal_set_message(t('Error message goes in here'), 'error');

In you case: drupal_set_message(t($yourvariable), 'error');


how to edit multiple menu itmes on menu management page Is there a way to edit multiple menu items on menu management page. I have a site with lots of menu items under one menu, if I want to change the parent of multiple menu items I will need to drag each menu item individually to the parent. Is there a way we can select multiple menu items and change there parent.

And is there a module which allows us to collapse and expand the menus as per our requirement.

Some thing like Taxonomy Manager Module.

i dont think there is a module that lets you do bulk menu item edits. another option you might want to try is just show the weights of each item and manaually adjust it in that manner so you dont have to drag each one.


$_POST returns empty value in custom service created a custom service resource to catch some data from the user through post method. but while I am accessing the service ie
    http://dev.localhost:8082/rest/send_mail/retrive.json

Query: curl -X POST -H "Accept-Encoding: gzip" -H "Content-Type: application/json; charset=utf-8"

sending the  data in POST is :
     {
     "nid" :"1834",
     "recipient" :"charubachi.rath@abc.com",
     "sender":"charubachi.rath@abc.com",
     "subject": "xyz",
     "body":"a"
    }

How to accept the data

in my .module file

<?php

/**
 * Implementation of hook_services_resources().
*/
function send_mail_service_services_resources() {
 $api = array(
'send_mail' => array(
  'operations' => array(
    'create' => array(
      'help' => 'Drupal 7 Services 3 test',
      'file' => array('file' => 'inc', 'module' => 'send_mail_service'),
      'callback' => '_send_mail_service_create',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
      'access arguments append' => FALSE,
      'args' => array(
        array(
          'name' => 'nid',
          'optional' => FALSE,
          'source' => array('data' => 'nid'),
          'type' => 'int',
          'description' => 'The nid of the node to get',
        ),
        array(
          'name' => 'recipient',
          'type' => 'string',
          'description' => t('recipient'),
          'source' => array('data' => 'recipient'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'sender',
          'type' => 'string',
          'description' => 'sender',
          'source' => array('data' => 'sender'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'subject',
          'type' => 'string',
          'description' => 'subject',
          'source' => array('data' => 'subject'),
          'optional' => TRUE,
          'default' => '0',
        ),
        array(
          'name' => 'body',
          'type' => 'string',
          'description' => 'body',
          'source' => array('data' => 'body'),
          'optional' => TRUE,
          'default' => '0',
        ),
      ),
    ),
  ),
),
);
 return $api;
}

in my call back function when I am trying to print $_POST I am getting empty values.

You are passing every element as individual element, so you can't get these values in $_POST array. I have executed your code at my end and retrieve each element value by following call back function.

function _send_mail_service_create($nid, $recipient, $sender, $subject, $body) {
  echo "nid => ".$nid;
  echo "\nrecipient => ".$recipient;
  echo "\nsender => ".$sender;
  echo "\nsubject => ".$subject;
  echo "\nbody => ".$body;
}

Output:

nid => 1834
recipient => charubachi.rath@abc.com
sender => charubachi.rath@abc.com
subject => xyz
body => a

If you want to have these values in an array then you can use this in following way:

 /**
   * Implementation of hook_services_resources().
   */
  function send_mail_service_services_resources() {
    $api = array(
      'send_mail' => array(
        'operations' => array(
          'create' => array(
            'help' => 'Drupal 7 Services 3 test',
            'callback' => '_send_mail_service_create',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'access arguments append' => FALSE,
            'args' => array(
              array(
                'name' => 'title',
                'optional' => FALSE,
                'source' => 'data',
                'type' => 'string',
                'description' => 'The data collected through JSON',
              ),
            ),
          ),
        ),
      ),
    );
 return $api;
}

function _send_mail_service_create($arg) {
  print_r($arg);
}

Output:

Array
(
    [nid] => 1834
    [recipient] => charubachi.rath@abc.com
    [sender] => charubachi.rath@abc.com
    [subject] => xyz
    [body] => a
)


ABT term reference field hidden in Node View I am using "Access by Term" configuration to control VIEW and UPDATE access for a content type with a Term Reference field in the content type. See screenshot.

But setting this configuration hides the term ref field in Node View.

How do I fix this?

screenshot of the term ref ABT config fieldset:

Make sure to assign "Allow users to view ABT terms on node page." permission to desired roles.


How to create a table with a filter? I am using drupal 7

The following code turns an array into a pagered table.

$rows = $data[data];
$per_page = 30;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));
echo $output;

Is it possible to add filters to the table?

Thanks

Updated 21/04/2016 as Per Neograph734s answer

I have built a module based around the code Neograph734 gave as an example.

My array is built like

Array
(
    [0] => Array
        (
            [EventTime] => 23/04/2016 15:00
            [EventType] => Foo
            [EventName] => Bar
            [EventRating] => 99.12
        )

    [1] => Array
        (
            [EventTime] => 23/04/2016 18:00
            [EventType] => FooFoo
            [EventName] => BarBar
            [EventRating] => 94.84
        )

The only ammendment I have made is in field to seach as below

foreach ($rows as $key => $row) {
  if (preg_match("/" . $form_state['storage']['title'] . "/", $row['EventName'])) {
    $temp_rows[$key] = $row;
  }
}

The table initially loads, I have a text area and a submit button. When I enter a search term the page reloads but the table does not filter, it still shows all results.

The html out put is

23/04/2016 15:00
Foo
Bar
99.12

What more do I have to change to get the text field to search the results?

Thanks

It can be done by wrapping your table in a form, and then use the form API to render your table and re-render it on submit. You can have a look at this comment: https://www.drupal.org/node/1770512#comment-6428358

In short the render funtion:

function MY_MODULE_build_form($form, &$form_state) {
  // Filter field.
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title to look for'),
    '#size' => 15,
    '#default_value' => isset($form_state['storage']['title']) ? $form_state['storage']['title'] : '',
  );

  // Submit button.
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Find"),
  );

  // Modify table array here.
  // If your API supports filters, you can use that too.
  // My regex is bad, so you might need to tweak this.
  if (isset($form_state['storage']['title'])) {
    $temp_rows = array();

    foreach ($rows as $key => $row) {
      if (preg_match("/" . $form_state['storage']['title'] . "/", $row['field_to_search'])) {
        $temp_rows[$key] = $row;
      }
    }

    $rows = $temp_rows;
  }

  // Render the table array.
  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Empty Rows')
  );

  return $form;
}

And the Submit function

function MY_MODULE_build_form_submit($form, &$form_state) {
  // Set the provided filter value in the storage.
  $form_state['storage']['title'] = $form_state['values']['title'];
  // Show the form again.
  $form_state['rebuild'] = TRUE;
}

You might want to fancy it up with some fieldsets, but those are left out to keep the answer understandable.


Is there a module that can record when and for how long each user logs in for? (Drupal 7) I'm working on developing a website as part of an academic project that requires tracking individual user activity throughout a long period of time. We need to do the very minimum track when users log in and for how long (or until they timeout). I haven't been able to find a module that does this, except for Open Web Analytics which is breaking some of our pages.

I'm not completely closed to the idea of rolling my own solution but I'd like to do it through a tested module if possible.

You are looking for User Visits Advanced module, It have the option to track the hours visited by the users.

  The User Visits Advanced module is a contribute module for the User
  Visits module. It is extremely useful for social networking sites who
  wish to provide their users with statistics about the number of times
  a the users profile page is being viewed and by which other users.

  This module comes with its own database table to store statistics per
  user profile (uid). At cron time, the data from the user_visits table
  is collected, aggregated and stored in the user_visits_adv table. It
  stores

  the total number of visits per uid
  the number of visits of the X past days per uid
  the most recent visitors uids of the past Y hours


Restricting node access for nodes that are associated with other nodes which have user reference I have one content type Jobs. These include a user reference field which is the contact.

I have another content type called Job Applications. The include a node reference field that links to Jobs.

How can I make so that public if someone attempts to read a URL for a job application, they won't be able to access that node unless they are contained in the user reference in the job node associated with that job application node.

I know that nodeaccess modules offers restrictions for content types containing user reference. I could add a contact user reference field in the job application content type BUT how do I keep it hidden (I think there is a module for hidding fields) AND more importantly how do I automate things so that when a job is selected (or used through node reference auto url) the hidden contact user reference field will automatically adjust based on that job node's user reference field.

Note: I don't want to restrict access by roles.

Update:

Job
Contact (user reference)

Job Applications
Job (node reference)
Contact (user reference) <-------- I need this to be copied automatically from the job (that is referenced in the node reference) contact user reference

I don't have enough rep to comment, however, if you are referring to an authenticated user (logged in). You can set the Access Control rules for the logged in user per node. If the user is not logged in, then it is not possible as anybody with a valid URL can view the node.

If you want to hide fields in a content type node. Go to Structure->Pages->View Node (you will have to enable this first in case it isn't). Then create a new variant for that content type and then manually add fields you want the authenticated/anonymous user to see. Make sure you have Context and Selection rules enabled and that admin roles are excepted from viewing that variant. In other words, admin will see everything.


MSSQL Incompatibility with Organic Group Views Filter Handlers I have a view which filters all the organic groups for a user. I wanted to add a Views Filter to filter by OG Role, however it is not possible.

I would very much appreciate any help. Basically any OG Role filter using a Views Filter Handler cannot be used if the database is an MSSQL database. When selecting one of the filters, it errors out and then the view has to be re-created since the view can no longer be shown within the UI. I opened a drupal issue a few months ago, but no response as of yet.

The error message is as follows:

  PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Column 'og_role.rid' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.: SELECT r.*, r.name AS _field_0 FROM {og_role} r GROUP BY r.name; Array ( ) in og_handler_filter_user_roles->get_value_options() (line 14 of C:\inetpub\wwwroot\sites\all\modules\og\includes\views\handlers\og_handler_filter_user_roles.inc).

I'm almost postive that I have to rewrite Line 13 to support SQLSRV database types.

Line 13: ->groupBy('r.name')

Here is the relevant code:

/**
 * Field handler to provide a list of OG roles of a user.
 */
class og_handler_filter_user_roles extends views_handler_filter_many_to_one {

  function get_value_options() {
    $this->value_options = array();
    // Get all role names.
    $results = db_select('og_role', 'r')
      ->fields('r')
      ->groupBy('r.name')
      ->execute();
    foreach ($results as $result) {
      $this->value_options[$result->name] = $result->name;
    }
  }

  function query() {
    // Get the og_membership table from relations.
    foreach ($this->query->relationships as $alias => $info) {
      if ($info['table'] == 'og_membership') {
        // If there is a og_membership table present. Add some conditions.
        $rel = $this->relationship;
        $this->query->add_where_expression(NULL, $alias . '.gid = ' . $rel . '.gid');
        $this->query->add_where_expression(NULL, $alias . '.group_type = ' . $rel . '.group_type');
        break;
      }
    }

    parent::query();
  }
}

I fixed it by changing Line 13 to:

->groupBy('r.name')
->groupBy('r.rid')
->groupBy('r.gid')
->groupBy('r.group_type')
->groupBy('r.group_bundle')


Why are my webform conditionals not always working? We have 2 partially same webforms with conditional fields, opening a number of components depending on the selection with radio buttons. When logged on as administrator, both forms work fine. when logged on as simple user, only one webform all works fine, the other shows all components as it were designed.

We did recreate the conditionals already and the permissions are same on both forms.  Also no error message is generated in any way.
Anyone has similar problem or has ideas?

As our native language is Belgian Dutch and we use a comma for decimal separator, I added a simple replacement for comma to dot in webform_calculations.js. This resulted initially in a javascript error for empty fields, and meanwhile the code was reproduced in Drupal's default files. Since only one webform has calculated fields only that form was affected when logged on as user. After correction a new file was generated and strange enough only administrator login used it, so all worked fine, while the user logon kept using the faulty file, even after all cache cleaning (Drupal and browser) and rebuilding.Replaced all files with correct code..
Problem solved.


Multi-language with domain name specific doesn't work I am working on a multi-language website. I am setting content in both English and French.

When I use path prefix as my detection method, it works fine, like poc-local.com and poc-local.com/fr. When I use domain as my detection method, it doesn't work, like fr.poc-local.com.

I am getting a 302 error, and "the page isn't redirecting properly" error. How can I fix this?

I found the answer for this.

I have installed global redirect module and now it's working.

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

But Now I am having another one problem.My language Switcher block is not working.When I switching from one language to another language the recently switched language url displaying for all languages...


How to create a custom template for entities? I'm having a dickens of a time overriding entity.tpl.php to create custom themes for my entities.

I am using ECK and Inline Entity Form. I've created entity section with bundle masthead. I've linked this to a node.

In a subtheme of the bootstrap theme, I then try to create a custom theme for this entity in a file called entity--section--masthead.tpl.php (note: I've also tried section.tpl.php and section--masthead.tpl.php and all sorts of permutations). Clear Cache. Nothing.

The only documentation is a few years old, and one of the most recent comments says this SHOULD work without the need for various hooks.

You don't need to add entity string to the template file name. These are theme hook suggestions for entity built with ECK (assuming your entity and bundle names):

section.tpl.php
section--masthead.tpl.php
section--masthead--full.tpl.php
section--[ID].tpl.php

As you can see there is a naming conflict because section is a drupal builtin template. It would be safer to use different name for your entity.


Content Statistics: Total View not showing up in Services I'm pretty sure this worked the other day, but today I checked and it didn't appear in my Services

If I add a new field such as body, it appears in my json file.. When I add Content Statistics: Total Views it won't add it.

I tried doing it a dirty way by adding a Global Text and use a replacement pattern, but then it outputs it like: [totalcount]

Also worth noting I can see it in the preview.

As I understood, this is a permission problem and it is possible that only admin is allowed to see that view.

You can set the permissions in the view itself so that it is available to all users otherwise just log-in as Admin to see the 'view'.


What does the rule event mean "Drupal is initializing" What does "Drupal is initializing" mean as a rule event?

In Drupal 7, the rule will run when hook_init() is called. As explained on the Drupal documentation page for hook_init():

  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.
  When this hook is called, the theme and all modules are already loaded
  in memory.

  This hook is not run on cached pages.

  To add CSS or JS that should be present on all pages, modules should
  not implement this hook, but declare these files in their .info file.


How to create an alternate title for a node when in a nodequeue? We want to be able to override the title of certain content items, but only temporarily, while they're included in a nodequeue. For example, we have a nodequeue view block in a small "featured" sidebar, without much room for long titles.

I want to avoid adding an alternate title to each content type because there are lots of content types and the alternate title only needs to be used while the node is in the nodequeue (ie, featured). Once the node gets replaced in the nodequeue, the alternate title would be cluttering up the database.

I found a module called Nodequeue Annotate, that happens to have the data structure I needed but it's intended for an unrelated use case. I've written a companion module to make it do what I need, but it seems like a bit of a hack to piggyback on a module to make it solve an unrelated use case.

So, I'm curious how would others handle that use case?

I've used this css quite often in these cases:

width: // short width;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

Which turns something like

A great new article about something so important that we have highlighted it for you

into

A great new article about som...

Obviously, this works best when the jist of the title is in the beginning of it :)


How to hide Input Format Options and help text under a textarea? How to hide Input Format Options and help text under a textarea when adding|editing a node?

You can use hook_form_alter in a custom module to do this.

For instance, in drupal 7:

// hook_form_alter function
function CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
    // We want this on a specific node type
    if ($form_id == 'NODE_TYPE_node_form') {
        $form['#after_build'][] = 'CUSTOM_MODULE_NODE_TYPE_node_form_after_build';
    }
}

// afterbuild function
function CUSTOM_MODULE_NODE_TYPE_node_form_after_build($form) {
    // We want this on a specific field
    $form['YOUR_FIELD']['und']['0']['format']['#access'] = FALSE;
    return $form;
}


Serialize selected fields I have a requirement in a project having 350 fields, but when I use views, I am facing a lot performance issues. So in place of reading all the data from individual tables, can I use serialization as alternative and serialize only few fields?

Is it possible in Drupal 8?

Depends on why you think you need fields. Fields in Drupal come with their own structure, they are exposed to Views, etc. Lets assume you manage to store a number of fields in a single serialized blob. How would sorting, filtering work?

Perhaps what you are looking for is more along the lines of a custom field widget, that exposes a large number of textfield forms, and stores the data captured in a serialized entry as opposed to 350 individual fields?


How do I get the menu block choice "Expand all menu items" to stay checked I have 2x menu blocks. One in the header and one in the footer. I'd like the header one to stay unexpanded, but expand all the items in the footer.

When I check "Expand all menu items" in the footer, save the result and come back to the block settings it is unchecked when I review.

8.7.6

That is not the default behavior. I suppose you have installed Menu Block module.

In that case the "expand all" option from Drupal Core does not seem to work, you will need to use the "expand all" option from the Menu Block module. You can find this at "Advanced options" in the block configuration.


Query method not triggered in custom filter handler? I'm using Views 3.

I needed to create a custom Views filter that handle dates range. So I looked at example and tried to mimic the behavior and I got some trouble.

It seems that when I extend my own class from views_handler_filter, the query method is never invoked, BUT if I extend my class from let's say views_handler_filter_string it works.

I must forget something but I'm stuck here.

Here is my code, if someone can take a look and advise me about what happened, I would be very grateful.

Here is my .views.inc file :

<?php
  class v3d_date_custom_filter extends views_handler_filter {
    var $always_multiple = TRUE;

    function value_form(&$form, &$form_state) {
      //parent::value_form($form, $form_state);
      $form['value']['v3d_date']['period'] = array(
        '#type' => 'select',
        '#title' => 'Period',
        '#options' => array(
          '7_days' => 'Last 7 days',
          'yesterday' => 'Yesterday',
          'today' => 'Today',
          'custom' => 'Custom dates'),
        '#default_value' => 'custom',
        '#attributes' => array("onclick" => "period_click(this);"),
      );

      $form['value']['v3d_date']['start_date'] = array(
        '#type' => 'date_popup',
        '#date_format' => 'Y-m-d',
        '#title' => 'Start date',
        '#size' => 30);

      $form['value']['v3d_date']['end_date'] = array(
        '#type' => 'date_popup',
        '#title' => 'End date',
        '#date_format' => 'Y-m-d',
        '#size' => 30);
      }

   function exposed_validate(&$form, &$form_state) {

     if(is_null($form_state['values']['start_date']) &&
        is_null($form_state['values']['start_date'])) {
        return TRUE;
     }

    /*
     * If we get array for start_date or end_date
     * errors occured, but the date module will handle it.
     */
     if(!is_string($form_state['values']['start_date']) ||
        !is_string($form_state['values']['end_date'])) {
       return TRUE;
     }

     /* Get day, month and year from start_date string */
     if(!preg_match('/(\d+)-(\d+)-(\d+)/',
        $form_state['values']['start_date'],
        $start_date
        )) {
       return TRUE; }

     /* Get day, month and year from end_date string */
     if(!preg_match('/(\d+)-(\d+)-(\d+)/',
        $form_state['values']['end_date'],
        $end_date
     )) {
       return TRUE; }

     /* Create timestamps and compare */
     $start_date = mktime(0,0,0,$start_date[1],$start_date[2],$start_date[3]);
     $end_date = mktime(0,0,0,$end_date[1],$end_date[2],$end_date[3]);

     if($start_date >= $end_date) {
       form_set_error('start_date','Start date must be anterior to end date.');
     }
   }

   function query() {
     die('fdsfds');
     $this->ensure_my_table();
     $field = "$this->table_alias.$this->real_field";
     dsm($this);
   }

 }
?>

And my .module file

<?php
  function custom_filters_views_api() {
    return array(
      'api'=>3,
      'path' => drupal_get_path('module','custom_filters') . '/views',
    );
  }
?>

And  part of my views_data that use my custom filter :

<?php

function voice_views_data() {

  $data['v_tp_voice']['date_utc_agent'] = array(
    'title' => t('date_utc_agent'),
    'help' => 'date_utc_agent',
    'field' => array('handler' => 'views_handler_field'),
    'filter' => array('handler' => 'v3d_date_custom_filter'),
    'sort' => array('handler' => 'views_handler_sort')
  );

  return $data;
}

As suggested by todinov, you can use Drupal contrib modules Date along with its sub module Date Views which will most probably handle any kind of filter in Views. If it doesn't help, you can achieve it through code by implementing hook_views_query_alter.


JSON:API resources error: "This resource attempted to serve data that contains unsupported resource types." I'm trying to make a custom JSON:API resource for flaggings using the JSON:API Resources module.
Right now, I simply want to return all the flaggings of a given bundle with an EntityQuery.  (Later, I will customize the EntityQuery, which is why I am need to go beyond what JSON:API provides by default.)
My code is based on the module's example code.
MYMODULE/src/Resource/MyQueue.php
/**
 * Processes a request for a collection containing a user's article nodes.
 *
 * @internal
 */
class MyQueue extends EntityQueryResourceBase {

  /**
   * Process the resource request.
   *
   * Code example:
   * https://git.drupalcode.org/project/jsonapi_resources/tree/8.x-1.x/tests/modules/jsonapi_resources_test/src/Resource.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return \Drupal\jsonapi\ResourceResponse
   *   The response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function process(Request $request): ResourceResponse {

    $cacheability = new CacheableMetadata();

    $entity_type_id = 'flagging';
    $entity_type_bundle = 'MY_FLAGGING_TYPE';
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
    $entity_query = $this->getEntityQuery($entity_type_id)
      ->condition($entity_type->getKey('bundle'), $entity_type_bundle);

    $paginator = $this->getPaginatorForRequest($request);
    $paginator->applyToQuery($entity_query, $cacheability);

    $data = $this->loadResourceObjectDataFromEntityQuery($entity_query, $cacheability);

    $pagination_links = $paginator->getPaginationLinks($entity_query, $cacheability, TRUE);

    $response = $this->createJsonapiResponse($data, $request, 200, [], $pagination_links);
    $response->addCacheableDependency($cacheability);

    return $response;
  }

}

With this code, I'm getting the following error:

LogicException: This resource attempted to serve data that contains
unsupported resource types.

I don't understand why I'm getting this error, or what it means.

If I set $entity_type_id to node and $entity_type_bundle to page, everything works as expected.
If I set the $entity_type_id to 'custom_content_type`, one of the content types I configured in the admin UI, it doesn't work; I get the same error.
I tried to set $entity_type_bundle to all three flagging bundles on my site; none of them work.
The $entity_query is correct for the flaggings.  I can do $entity_query->count->execute() and I get the correct count.
I am logged in as an administrator with all permissions.
I can access the jsonapi in my browser as an admin at /jsonapi/flagging/MY_FLAGGING_TYPE and I see the flaggings as I expect.

This error is the result of not setting the _jsonapi_resource correctly in the routing file:
MYMODULE.routing.yml
# Defines a route where a user's flaggings can be found.
MYMODULE.user_flaggings:
  # %jsonapi% is a placeholder for the JSON:API base path, which can be
  # configured in a site's services.yml file.
  path: '/%jsonapi%/MYMODULE/queue'
  defaults:
    # Every JSON:API resource route must declare a _jsonapi_resource. The
    # value can either be a class or a service ID. Unlike the _controller
    # route default, it is not possible to declare a method name to be called.
    _jsonapi_resource: Drupal\MYMODULE\Resource\MyQueue
    _jsonapi_resource_types: ['node--page', 'flagging--MY_FLAGGING_TYPE']


Drush Make: error "unable to unzip" I'm trying to setup a new project using the Drush make command. I'm working on localhost (xampp) on a Windows 8.1 machine.

The problem is that if a module present in my make file requires an external library (e.g. colorbox or plupload), make will detect that and will download said dependency, but then will fail to decompress it, resulting in the following error:

plupload-7.x-1.7 downloaded.                                                [ok]
Found makefile: plupload.make                                               [ok]
plupload downloaded from                                                    [ok]
https://github.com/moxiecode/plupload/archive/v1.5.8.zip.
Unable to unzip                                                          [error]

As a result, the whole make operation is aborted.

I searched for a solution and found this stackoverflow answer that seems to address my problem but is not very detailed. I tried using Cygwin (x64), found an "unizp" package in it, tried to download it and copy the unzip.exe file in the Program Files (x86)\Drush\GnuWin32\bin folder, but now when I run my make project I have a new error message, this time as a dialog box (not in the console, then):

The program can't start because cygbz2-1.dll is missing from your computer.
Try reinstalling the program to fix the problem.

Followed by a unzip.exe has stopped working Windows dialog box.

I can find the missing DLL (cygbz2-1.dll) in the C:\cygwin64\bin directory. So I tried adding this path to my PATH environment variable (and restarted my computer to be sure), but I still have the same "missing DLL" error.

Is there something I'm doing wrong
(I'm not familiar with cygwin at all, so I don't know if I'm using it right...)?

Get unzip for windows:
http://gnuwin32.sourceforge.net/packages/unzip.htm
It solved the "unable to unzip" problem for me.


How to bind javascript to ctools modal load I have a ctools modal popup that has no Drupal generated form but an external iframe that loads a form into ctools modal. I have some jQuery codes to be invoked when the iframe gets reloaded (ie. to assume external form gets submitted).

This jquery code initiated and works fine with a normal page(without ctools) while javascript has been added by drupal_add_js().

How can I do the same with cTools?

// MENU
function dw_common_menu() {
  $items['download/%ctools_js/register'] = array(
    'title' => 'Register',
    'page callback' => 'dw_common_ajax_download_register_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
// Page callback
function dw_common_ajax_download_register_page($js = NULL) {
  /*
   * $sess_key : create a unique session key if not exists;
   * @TODO : instead of md5(REQUEST_TIME) use some other random function as multiple users
   * might access at a same time.
   */
  $output = "";
  $iframe_source = 'http://example.com/cn/iframe.form.php';
  $output .= '<iframe id="site-contact-us" src="' . $iframe_source . '" frameborder="0" scrolling="no" width="232" height="378"></iframe>';
  // Attaching jquery iframe event load in the ctools output itself.
  // The script from files are not invoking as window.load() doesn't takes effect in ctools window.
  $jsscript = "";
  $jsscript = 'jQuery(document).ready(function() {
    (function is_key_authorized(){
      alert(\'sd\');
    }
      });
    })();
    is_key_authorized();
    });';
  $output .= '<script language="javascript" type="text/javascript">' . $jsscript . '</script>';
  // Fall back if $js is not set.
  if (!$js) {
    return $output;
  }
  ctools_include('modal');
  ctools_include('ajax');
  return ctools_modal_render('Register', $output);
  exit;
}

Here I am trying to concatenate <script> to ctools modal output as drupal_add_js not helping to load.

I know this is an old question, but maybe this answer can help someone - I know I searched for an answer for a while.

I had a similar issue, I wanted to execute some javascript when a specific page of mine was rendered by ctools modal.

I found the answer in the help folder of the ctools module ctools/help/modal.html :

  If you need to do more than just render your modal, you can use a CTools $commands array. See the function ctools_modal_render() for more information on what you need to do here.

How to apply that to this situation: you need to grab the contents of the very small ctools_modal_render() function and use it to add commands to the array of commands that is executed in the function. This is the function:

function ctools_modal_render($title, $output) {
    $commands = array();
    $commands[] = ctools_modal_command_display($title, $output);
    print ajax_render($commands);
}

This is what my snippet looks like in my page - I wanted to add a body class among other things, so I could style the #modalBackdrop for the modal overlay based on context, so here's my modified page function:

function gc_alterations_modal_page($js=null){

    $page = array();

    $page['search-results'] = array(
        '#markup' => '
My Markup
'
    );

    if( $js ) {
        // Required includes for ctools to work:
        ctools_include('modal');
        ctools_include('ajax');

        // alternate to using: ctools_modal_render('Search', $page);
        $commands = array();
        $commands[] = ajax_command_invoke('body', 'addClass', array('myclass-modal'));
        $commands[] = ctools_modal_command_display('Search', $page);
        print ajax_render($commands);
        return;
    }

    return $page;
}


Proper javascript notation The following code creates navigation links for a Twitter Bootstrap carousel. The script runs perfectly when saved on my local machine as well as hosted as its own document. When placed into a Drupal page, however, the javascript is modified. I understand that Drupal requires a special Javascript structure. Is that the case with my code below? Any suggestions would be helpful. Thanks!

--- You can see how Drupal closes tags on Line 10

Original Code - working:

$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            html += '
'  + $(item).attr('data-title') + '
';
        }
        html += '

';
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

Generated code after placing in Drupal - broken:

$(document).ready(function() {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '
'  + $(item).attr('data-title') + '

';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });
});

Behavior handling has changed again in Drupal 7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler. add code like this way.

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
    $('#headerCarousel.carousel[id]').each(function() {
        var html = '

';
        for(var i = 0; i != $(this).find('.item').size(); i ++) {
            var item = $(this).find('.item').get(i);
            html += '
'  + $(item).attr('data-title') + '

';
        }
        $('.btn-navbar').after(html);
        $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();

    }).bind('slid', function(e) {
        var nav = $('.nav-collapse[data-target="' + $(this).attr('id') + '"] ul');
        var index = $(this).find('.item.active').index();
        var item = nav.find('li').get(index);
        nav.find('li.active').removeClass('active');
        $(item).addClass('active');

        if(index == 0) {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
        if(index == nav.find('li').size() - 1) {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
        } else {
           $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
        }
    });

   $('.bootstrap .nav a').bind('click', function(e) {
       var index = $(this).parent().index();
       var carousel = $('#' + $(this).closest('.nav-collapse').attr('data-target'));
       carousel.carousel(index);
       e.preventDefault();
   });

    }
  };

})(jQuery);


Is there a way to add a persistent querystring across multiple pages? I want to add a persistent query string to pages once it is introduced (for the context module to maintain a page layout inside an iframe). At the moment, I'm checking the http referer for the string and redirecting to the current url + query string.
This works fine, except:

It's an extra page load. Not a big issue as it's an admin page inside an iframe that's not used much.
It breaks batch pages. I think I can get around this by checking if arg(0) is "batch" and then add the referer to $_session and then check for it.

This seems really convoluted, hacky and prone to breaking the site for a user if I don't get the session variable deleted straight away.

hook_url_outbound_alter() doesn't work for forms unfortunately so is there a better way?

The way I would go about this would be to dedicate an alias subdomain and perform the redirect before hitting the application.

For example, Apache can be configured via mod_rewrite to add any query parameter to the requested URL:

  # Add iframe=1 to query parameter if requested from iframe domain.
  RewriteCond %{HTTP_HOST} ^if.example.com [NC]
  RewriteCond %{QUERY_STRING} !iframe=1 [NC]
  RewriteRule ^(.*)$  http://if.example.com/$1?iframe=1 [L,R=301]

The only problem this causes is that D7.5 now forcing iframes to only originate from the same domain so you'll have to explicitly allow iframing from this different domain in your settings.php:

# Allow iframing on host requests to the iframe domain
if ($_SERVER['HTTP_HOST'] == 'if.example.com') {
  $conf['x_frame_options'] = '';
}


Views: How to change entity view mode settings when a contextual filter is available? I have a view it displays a few nodes in teaser mode. The view takes contextual filter and when filter is available I would like the content (node) to be displayed in full view mode. Is this possible?

Just create a view with two page displays.

The first display will be on the path with no arguments and will display teasers.

The second display will be on the same path with an argument such as thepath/% and will display full view mode.

When you alter the format and add the contextual filter in the second page, make sure to select it only for that display, otherwise it will overwrite the first display as well.

This is what views displays are for. Use it.


Return to views navigation list of nodes after editing a node in the list I am using Views Navigation module. I have created a list of articles using views and selected "Add navigation links on node pages accessed from this view" under "Views Navigation" in Advanced. The views navigation is working fine and I can go back and forth in the views list of articles.

Now if I edit the node (while viewing a views navigation list) and submit the edited node, I was returned back to the node page without the "views navigation" links appended to the URL. Hence I cannot move back forth in the list (the list is gone; it behaves like a simple node view).

The scenario is that this views navigation list will be used by editors and moderators who may edit an article while viewing the list so they should be redirected back to this list once they edit an article.

One of the solution I am thinking is to alter node edit link using hook_menu_alter(). Is there any non-programmatic way of doing this? I have tried Rules and captured the appended URL parameters but I don't know how to alter a node edit link. Can someone please point me in the right direction?

Many Thanks

I found a solution, through code unfortunately, using hook_url_outbound_alter().

For anyone trying this, I have implemented the following code and it is running perfectly:

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
// get current position and list token
$position = isset($_GET['position']) ? $_GET['position'] : NULL;
$list = isset($_GET['list']) ? $_GET['list'] : NULL;

// only when viewing nodes through views navigation
if ( $position && $list && preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    $path = 'node/'.$matches[1].'/edit';
    $options['query']['destination'] = 'node/' . $matches[1] . '?position=' . $position. '&list=' .$list;
    }
}

Thanks


How can I pass the filter parameters of one view to a different view on the same page? Summary

I have two seperate views on the same page - one Page and one Block that show two seperate content types respectively, but have a filter exposed for a field that they share.

On the page of the first view, I have attached a block display of the second into a new region. I want the filter values of the exposed filter of the first view to also feed into the filter values of the second block view, if possible.

How it's currently set up

I have two views.

The first view, "Local branches", is a Page display that surfaces content of type Local branch. This content type has a Location field, powered by the Location module. On the view page, there is an exposed filter criteria:

Location: Distance / Proximity

which is exposed to the user as a text field and the origin in the filter settings set to Postal Code.

The code is then sorted by Distance / Proximity.

On the view page therefore, there is a text field where users can enter in a post code and it will return results closest to that Postal code.

The second view, "Shops", is a Block display that surfaces content of type "Shops". This content type is almost identical to the "Local branch" content type, in that it also has a Location field.

In this view, I have again an exposed filter:

Location: Distance / Proximity

that is set up the exact same way - but note that this is a Block display. It's again sorted by Distance / Proximity.

Finally, on the Page of the first view, "Local branches", I have placed the second view's Block, "Shops" in a seperate region.

My hope is that the Shops block will somehow pick up the exposed filter settings from the URL built by the "Local branches" view, which looks like this:

http://www.example.com/local-support?distance[postal_code]=EN11+8RX&distance[search_distance]=100&distance[search_units]=mile

As you can see there are three parameters that power the exposed Postal code search form. Here's a crude diagram:

Problem

The Block view, "Shops", doesn't respond to the filter values in the URL, but just outputs all results sorted arbitrarily (there is no other sort atm). I would like it to respond with results as if it were using the exposed filter values from the "Local branches" view as its own exposed filter.

Potential solutions and queries

One thing I did try was to programatically create the "Shops" block, and render it on the view page /local-support and see if I could use the $_GET parameters and feed it directly in to the view. Code to generate the output looks something like this:

function _mymodule_shop_block_view() {
  $view = views_get_view('shops');
  $view->set_display("block_1");
  $view->set_arguments($args);
  $view->pre_execute();
  $view->execute();
  $content = $view->render();

  return $content;
}

The problem is I'm not sure what the value of $args would actually be in this case. I want to exectue and render the view, but pass the $_GET params in somehow, but they're exposed filter params so I don't know if $view->set_arguments is actually appropriate in this case?

My other thought that was because the "Shops" view is a Block display, the exposed filter won't work as it should. Could I try building it as a page display, expose it the Location filter as a block, and then rendering it in a block? I could hide the exposed filter in CSS (bad I know but if you haven't guessed by now I kinda wanna get this working).

Could attaching the block to the Page view integrate it - is it possible to do view attachements across separate views?

Thanks for taking the time to read this - I hope there's enough info about what I am trying to achieve!

Yes, it's possible to have 2 different views on the same page sharing the same exposed filter query parameters.

The trouble you're having is, by default, a block display doesn't show any exposed filters. The only way to enable this is by enabling the Use AJAX setting on the block view under the Advanced section in the admin UI. Once set, both the block & page Views will pick up on the same location[postal_code]/location[distance]/location[search_units] query parameters.

Of course this means, you'll have 2 different form filters on the same page but you can kludge your way around it with a style rule to hide it (e.g. #block-views-my_block_machine_name-block div.view-filters { display: none; }) or some other means of hiding the form.


mysql binary log makes disk full Suddenly, I got my website down (drupal 6.19) and could not start mysql (too many tables got crashed).
by checking df -h, I found that the MySQL partition is full due to very large binary log files (I keep binary logs for one day only, expire_logs_days = 1); by checking mysqlbinlog for one of the bin logs I found out that most of the entries are for cache tables (cache_form, boost_cache, boost_cache_relationships, cache_content, etc) and for sessions table; some of the data is repeated many times.
by the way, i have watch ls -lh and the bin-log files got larger exponentially (every one or two minutes i got new binlog file with 100M file size!!)

Do you have any idea of what causes this? How can I fix this problem?

I guess one obvious improvement would be to use a different cache backend.

If you have a single server and enough memory, you could use an APC backend (D6: http://drupal.org/project/cacherouter, D7: http://drupal.org/project/apc) to have various of the often used caches directly in shared memory. That is probably the fastest cache solution you can get.

Another alternative is Memcached, which is especially interesting if you have multiples servers that should share a cache.

Note that you can't move the cache_form because that contains information about currently displayed forms and is not really a cache since it contains unique information, not just aggregated things like the others, which can always be cleared. Also, some other caches, especially cache_update, you might want to keep in the database, because that shouldn't be cleared like the rest as it contains information about update information of your used modules, something that doesn't change that often and can be very slow to re-fetch if you have many of them.

You can also move the sessions information out of the database, for example can you place it in MongoDB, and there are probably others too.


How to make the Rules module block flagged users from sending entityform submissions? I am trying to create a simple block user functionality on my site. I have a "Block/Unblock User" Flag that other users can block and unblock so they stop getting contact emails from (via entityform)

The entityform is set up like (logged in users):

NodeReference: Points to content they are interested in. I use tokens to fill in the authors name, email, etc...
Message: Text message to email field_nodereference:author:mail

So I am trying to create a rule (using the Rules module):

Event: Before saving a entityform submission

Condition:
NOT User has roles: entityform-unchanged:user is administrator (admins can bypass rule)

Entity is of bundle: Parameter: Entity: [entityform-unchanged], Entity type: Entityform Submission, Entity bundle: Contact Article Creator

Entity has field: Parameter: Entity: [entityform-unchanged], Field: field_nodereferencearticle

User is flagged
Parameter: Flag: Block/Unblock User, user: [entityform-unchanged:user], User on whose behalf to check: [entityform-unchanged:field_nodereferencearticle:author

Actions:

Page Redirect to site:url
Show Message: Warning: Was unable to send messsage. The Recipient has blocked you from contacting them.

So the basic premise of this is if a user blocks another user, this rule will preprocess all Contact Article Creator eforms and see if the potential recipient has blocked the user. If so, redirect to the front page with a warning stating the user blocked them.

EDIT 1: However, every eform I submit goes through. I can't get the rule to not submit.

EDIT 2: Here is the actual exported rule.

{ "rules_block_user_from_sending_message_if_user_blocked_them" : {
"LABEL" : "Block user from sending message if user blocked them",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "entityform", "flag" ],
"REQUIRES" : [ "rules", "flag", "entityform" ],
"ON" : { "entityform_presave" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "entityform-unchanged" ],
      "type" : "entityform",
      "bundle" : { "value" : {
          "contact_seller" : "contact_seller",
          "contact_seller_anonymous" : "contact_seller_anonymous"
        }
      }
    }
  },
  { "entity_has_field" : { "entity" : [ "entityform-unchanged" ], "field" : "field_listing" } },
  { "flag_flagged_user" : {
      "flag" : "block_unblock_user",
      "user" : [ "entityform-unchanged:user" ],
      "flagging_user" : [ "entityform-unchanged:field-listing:author" ]
    }
  }
],
"DO" : [
  { "redirect" : { "url" : [ "site:url" ] } },
  { "drupal_message" : { "message" : "Was unable to send message. ", "type" : "warning" } }
]

}
}

It seems pretty obvious to me that something in any of your Rules Conditions is not working as you'd expect/want them to work. Which would also explain your "I can't get the rule to not submit".

Basic debugging

You clearly have a combination of Rules Conditions that need some debugging.  Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, since you have 3 Rules Conditions in a single rule, you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 2 out of the 3 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

Advanced debugging

Something else that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Login shared between subdomains If I should allow users to log in using the same username/password, what should I consider when choosing between the following solutions?

Install, and use Bakery Single Sign-On System on the main site, and all the subdomains.
Share the database table containing the user data.

Bakery decouples the multisites — if you're sharing a table, you must use exactly the same Drupal version on all sites in the multisite configuration, and update them in lockstep.  With Bakery, the Master and Slaves can be running different Drupal versions.  Additionally, any modules that modify the users table on the Master site would need to be applied to the Slave sites with corresponding settings.

Bakery improves scalability — user accounts are not created on slave sites until they are needed, conserving server computational and data storage resources.

Bakery synchronizes sessions — for example, if the user logs out of one Bakery site, the user will be logged out of all Bakery sites in that group.  (To achieve equivalent behavior with shared tables, you'd also need to share the sessions table, which would further complicate maintenance.)


Attaching assets if the page contains a table I want to attach a CSS file to a page only if it contains a table. I tried

function my_assets_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'my_assets/fancy';
  }
}

from the guide "Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module" but it does not work. The hook itself and the condition works. The question is where I have to save the #attached array in the $types variable?

I appreciate your help and feedback.

PS: The following hook attaches the CSS as expected:

function my_assets_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_assets/fancy';
}

Edit: While using the site I noticed that my CSS loads on sites like "/admin/structure/types". The Twig Debug hint says "THEME HOOK: 'table'". I guess this is important because it does not say this on the other tables I was waiting for to load the CSS.

'#type' => 'table'

OK, so I tried it out in a Vanilla D8.6 with a custom module like yours and the Bartik theme enabled. I placed hook_element_info_alter in the custom module and checked what Kint ksm($info) would return me (matching the code from your question that would be ksm($types)). I visited the front page and I saw 'table' in the array so I thought there must be a table on that page somewhere and the library should get attached. But it didn't. Because there actually was no table.

Only after I added a custom block to the custom module, placed the block somewhere prominent and let it output some sample code from class Table:

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['contacts'] = [
    '#type'    => 'table',
    '#caption' => $this
      ->t('Sample Table'),
    '#header'  => [
      $this
        ->t('Name'),
      $this
        ->t('Phone'),
    ],
  ];
  return $build;
}

And then the library suddenly got attached as documented. So, yeah, everything's fine. You just need to be sure you really have a '#type' => 'table' element on that page. That's all.

'#theme' => 'table'

As @4k4 asked in the comments to your question it seems likely you used '#theme' => 'table' to build your tables. Then attach the library directly like that (snipped copied from the Node core module):

$build['node_revisions_table'] = [
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $header,
  '#attached' => [
    'library' => ['node/drupal.node.admin'],
  ],
  '#attributes' => ['class' => 'node-revision-table'],
];

Although in this case you could also make use of hook_preprocess_table to have that pattern applied to all tables you've built using '#theme' => 'table'.

/**
 * Implements hook_preprocess_HOOK().
 */
function my_assets_preprocess_table(&$variables) {
  $variables['#attached']['library'][] =  'my_assets/fancy';
}

<table>

OK, so after we finally found out you put a table as markup into the body field of your node, using CKEditor, here's what's needed to attach your library accordingly.

You can't check for '#type' => 'table' or '#theme' => 'table' at this point, as your table is just markup. So simply check for the existence of a <table> tag. Or even better, check for just <table, because who knows what else attributes can come after that. Pay attention for the two underscores in the function name, and replace body with the machine name of whatever field you need to preprocess.

/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function my_assets_preprocess_field__body(&$variables) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  $items = $variables['element']['#items'];

  $value = $items->first()->getValue()['value'];

  if (\strpos($value, '<table') !== FALSE) {
    $variables['#attached']['library'][] = 'my_assets/fancy';
  }
}


Create node content from external HTML After a few attempts browsing the web, I don't figure out how to download HTML from a given url, and create node content from it.

What I would achieve is quite simple :

Have a link-like field in my content type
The source code of this page is downloaded either in the Body of the content, either in a MHT-like file
Viewing the node displays it either in the bodyeither` in an IFrame.

The content creation would happen mostly from a dedicated script creating a new content through Drush, filling only the Title and the link field.

The main goal of this is to save short-lived webpages in a drupal website, and ideally being able to index them.

I'm open to any ideas : module, coding, whatever.
Don't hesitate to give me advice !

Thanks

This would have to be done using a custom module. I do not know of a contributed module that would perform this. Probably because a module like this could be seen as a huge copyright infringement lawsuit waiting to happen.

But if I were to do this I would use GuzzleHttp as the engine to pull down the content. Then take that content and create a new entity using entity_create(). Where you have to focus your efforts will be sanitizing the information you "guzzle" off the web so that you do not create security issues in your site from XSS, SQLi, or other vulnerabilities. The process would be triggered on node-save.

This is just the basic idea, I cannot explain how to write the entire module as that would be pages of content.


Filter criteria date and granularity In my view I filtered for date "greater than now" and in the settings I put granularity "day".

I can see the 3 events correctly, but they are grouped by "month" and not in chronological order though.

Is there any option I can't find by myself to view the events in chronological order?

I sorted by date ASC

This is the export display:
https://kopy.io/DRwkf

This is the export of all the view:
https://kopy.io/KJsM0

In your views sort settings, make sure your Date sort is the first one, because it seems that there is another sort by entity title applied first

UPDATE
After checking the view export:
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['granularity'] = 'month';

You are sorting the results using "Post Date" of the node, not the date field, you should remove this and add the date field instead


How can I create Change Password block? We can create reset password block by \Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordForm') in d8, but change password block \Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm') didn't work for me.
This is my code:

public function build(Request $request) {
  $session = $request -> getSession();
  $session->set('pass_reset_hash', $hash);
  $session->set('pass_reset_timeout', $timestamp);
  $user = \Drupal::currentUser();
  $expiration_date = $user->getLastLoginTime();

  $myblock = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm::class', $user, $expiration_date, $timestamp, $hash);
  return array(
    '#type' => 'markup',
    '#markup' => drupal_render($myblock),
  );
}

First of all try to take a look at the buildForm method in the UserPasswordResetForm class, it takes some parameters.
So you must call getForm like this:
\Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm::class', $user, $expiration_date, $timestamp, $hash);

This is the function docs,

$user = User requesting reset.
$expiration_date = Formatted expiration date for the login link, or NULL if the link does not expire.
$timestamp = The current timestamp.
$hash = Login link hash.

So when those parameters are added the form should render perfectly.


Bootstrap tooltip form inline errors I tried "Inline Form Errors" module but it add errors message content after form element.
How to add inline form errors with bootstrap tooltip or popovers directly to inputs and selects? Does somebody do something like this?

Solve this by element pre render callback and ife module.

function _custom_bootstrap_pre_render_input($element) {
    $types = array(
        // Core.
        'password',
        'password_confirm',
        'select',
        'textarea',
        'textfield',
        // Elements module.
        'emailfield',
        'numberfield',
        'rangefield',
        'searchfield',
        'telfield',
        'urlfield',
    );
    if (empty($element['#type']) || !(in_array($element['#type'], $types) || ($element['#type'] === 'file' && empty($element['#managed_file']))) || !isset($element['#id'])) {
        return $element;
    }
    $error = ife_errors('get', $element['#id']);
    if (!empty($error)) {
        $element['#attributes']['class'][] = 'error-tooltip';
        $element['#attributes']['data-content'][] = $error;
    }
    return $element;
}


Page view printed in a block I have created a page view, and I want to put in a block. I am not looking for a block view.

Try using the panels module.  Although it will require some learning, you can use the Panels module to "override" the way nodes are displayed (you can choose from all nodes or overriding specific content types, specific user roles, etc.)

Using this approach, you can make a "page" view display as a block.  In fact, with Panels, you can basically use any content in Drupal as a  "block."  This power does come with some complexity but it should allow you to do what you want with some experimenting.


Why do I get a page without CSS styles? Why would the page at admin/people/permissions have very little information and appear like it doesn't have any CSS style applied?

I have disabled the dev themer and all is better.


Programmatically Setting Content Ranking Factors For Drupal Search I've added a dropdown to Drupal search page interface. I would like for users to be able to select this control to sort results according to Date or Keyword Relevance.

I'm able to get the dropdown value in a submit handler, however, I don't know how to programmatically alter the weight of 'keyword relevance' and 'date'.

Here is my submit handler. Any help would be greatly appreciated.

function test_sort_form_submit_handler($form, &$form_state) {
  drupal_set_message("Drop Down Value Is: " . $form_state['values']['search_sort']);
}

I would do this with a view instead of trying to tweak Drupal's search page:

Create a view
Add the filter "Search: Search Keywords" and expose it
Add two sort criteria: your date field and the "Search: Score" field and expose both of them
In Advanced > Exposed form > settings, check "Allow people to choose the sort order" if you want to give people that option
Add the fields or setup the display as you prefer

You can set the default sort option by ordering the sort criteria and the asc/desc setting by choosing that option for the top criteria. You can also use the Better Exposed Filters module (full disclosure: I'm the maintainer) to combine the sort field and direction into a single dropdown and/or rewrite the text of the options.


How can I avoid the feed link is printed in my theme? My current theme displays a Subscribe to link that is output from
the core/themes/stable/templates/misc/feed-icon.html.twig template. I don't want to display it in my theme. Whatever I try, I can't find which template or which string prints this link.

How can I avoid the link is printed?

If this is a view, you can hide the feed icon using this method.

  Go to Structure > Views > Frontpage > Edit. Then click on "Feed" at the top. In the second drop-down box, select "Disable Feed." Then "Save" the change.


Print array in field value I have created a custom form in form field following code is there.

 $form['display_result'] = array(
   '#title' => 'Result' ,
   '#type' => 'textarea',
   '#value' => !empty($dval) ? $dval : null,
   '#default values' => '',
 )

Problem is $dval is array which includes following code:

    stdClass Object
(
    [to] => Tove
    [from] => Jani
    [heading] => Reminder
    [body] => Don't forget me this weekend!
)

I am getting following warning:

  Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /var/www/html/D7/includes/bootstrap.inc)

It's recommended to use #default_value instead of #value.

You have to use property of object instead of whole object. For example $dval->body.

$form['display_result'] = array(
    '#title' => t('Result'),
    '#type' => 'textarea',
    '#default_value' => !empty($dval->body) ? $dval->body : '',
  );


How can I change the Add to Cart button text on specific product forms? What is the easiest way to change the Add to cart form button text to something custom? I want to change the text only on certain product types. How should I approach this?

Take help of hook_form_alter. Get the ID of the form for the product display where you are trying to change the text & do something like this --

function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Check Out');//Put the text which you want to make appear instead of "Add to cart".
  }
}

I also have several product display with custom text for "Add to cart". It took some time for me figure out the easy way. Have Fun :)


How can you gitignore items in a Drupal project without modifying core? I have a Drupal project, and we want to use Git for version control, but we need to have some folders that are ignored by Git. The problem is that .gitignore seems to be a core file. After the last "drush up" command, the gitignore file was replaced.

So, other than asking each developer to manually add entries to his or her global .gitignore file, is there a good way to effectively .gitignore a path in Drupal?

While .gitignore, .htaccess and robots.txt will come as part of the package when you clone Drupal, they should not be considered part of core and you should not feel that they cannot be changed or replaced with your own files.

This is what I do: Prior to updating (drush up), I make a backup of those three files.  After updating, I use the CLI program diff to compare the newly updated version with my backup (typically, my .gitignore have more entries at the end than those that come with Drupal).  If nothing else has changed, I just overwrite the one that came with Drupal with the backup.  If diff shows that the "drupal part" of .gitignore has changed, I copy those changes into my backup version before overwriting.  (Same procedure with .htaccess and robots.txt.)


Changing to date field based on from date using javascript I have a form written using Drupal's FAPI (Drupal v7.15). The form includes two date fields - a from date and a to date. I've installed the Date module and both fields are both set-up to use the 'date_popup' widget.

Now I want to make the to date automatically change when the from date is updated by the user. Eg if the user sets the from date to 1st Nov 2012, I want the to date to automatically change to match the from date. Ideally I would also like the date picker to disable all options earlier than this date. This is the same behaviour you see on many travel sites, such as expedia.com.

I can't find a good example of how to add the Javascript to do this. I can only see AJAX examples, and it seems unnecessary to make a round trip to the server to do this - the browser has all the info it needs to do so client side.

If I understand you right it should be as simple as dropping something like this into a JS file included in the page:

(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $('#edit-from-date', context).change(function() {
        $('#edit-to-date', context).val($(this).val());
      });
    }
  }
})(jQuery);

Disabling certain dates is a bit more complicated but there's an example here that should point you in the right direction.


How to show status messages in modal window? Here, I tried many different ways to show status messages in pop window but was not able to get success in any way. So, basically i want to  show all the status message of site in modal box whether it is configuration message or submit on site of form. Please give suggestion for this if any.
Thank you

The easiest would be by installing any from a few modules that do this out of the box

Two of the most used modules are nicemessages and better_messages


Access Drupal globals in Twig As documented here, there are some global variables defined by Drupal. How can I access them in twig?

These variables are not available to template files, but you can easily add it to every template file by implementing hooks.

You need to prepare variable for twig files. To use the global variables in twig files you need to set it.

Prepares variables for the page template:

You will get details  template_preprocess_page.

function template_preprocess_page(&$variables) {
  $variables['base_path'] = base_path();
}


Translate site name in multi language site How can I translate site name for multi language site in drupal 8 ?
For Example:

in site/en -> site name : Hello
in site/fr -> site name : Bonjour

I found it .

1 ) Install "Configuration Translation" module.

2 ) Go to "Basic site setting" ( admin/config/system/site-information )

3 ) Click "Translate system information" tab.

4 ) In front of your language click on "Add" button.

5 ) Then set your site name and click on "save translate" .


How to show views block output in drupal menu? I have views block and I want to display its output in sub menu when user mouseover on main menu. I on't know how to implement it. Is there any module for it?
Please help tell me how can I display views block in drupal menu?.

If you are trying to build a dropdown menu, you can have a look at Nice Menus. This module provides blocks that automatically generates dropdown menus from a selected menu.

If you want to build something more particular than a basic dropdown menu based on Drupal menu system, you should add your block to a hidden region in your html and then move it in the DOM with jquery.

You can do something like that:

// Get menu item
menu = jQuery('#selector .to li');

// Get block
block = jQuery('#block-block-myblock');

// Force hide
block.hide();

// Append the block to the menu item
block.appendTo(menu);

// Show / hide menu on hover
menu.hover(function(){ // Function to be run on mouse hover
  block.fadeIn();
}, function(){ // Function to be run on mouse out
  block.fadeOut();
});

Hope this will help you !
Cheers