Hook user login never gets called? We have an existing application with users and we would like to get our user base to accept the terms and conditions. In this regard I did some research and see that legal module comes the closest to desired functionality however there is one concern:

By default the legal module only shows up on login when a user has accepted terms and conditions on registration and only if the terms have changed. What we want to do is to get every user to see that upon login until they accept them.

I looked at the module code and see there is a hook_login function. No matter what I do, this function does not get called. I have tried to backtrace the login system and find out that certain modules do get their hook user login called but some do not. Legal module would be one of them. Any thoughts on how to trouble shoot this further?

The hook is as follows:

function legal_user_login(&$edit, $account) {
  echo "Legal module hook login called"; <--- never see this
  exit; <-- does not get called

  global $user;
  global $language;

  if ($user->uid == 1) {
    return;
  }

  // Get last accepted version for this account
  $legal_account = legal_get_accept($user->uid);

  // If no version has been accepted yet, get version with current language revision.
  if (empty($legal_account['version'])) {
    $conditions = legal_get_conditions($language->language);
    // No conditions set yet.
    if (empty($conditions['conditions'])) {
      return;
    }
  }
  // Get version / revision of last accepted language.
  else {
    $conditions = legal_get_conditions($legal_account['language']);
    // No conditions set yet.
    if (empty($conditions['conditions'])) {
      return;
    }

    // Check latest version of T&C has been accepted.
    $accepted = legal_version_check($user->uid, $conditions['version'], $conditions['revision'], $legal_account);

    if ($accepted) {
      return;
    }
  }

  $uid = $user->uid;

  // Log the user out and regenerate the Drupal session.
  module_invoke_all('user_logout', $user);
  drupal_session_regenerate();

  // We have to use $GLOBALS to unset a global variable.
  $user = drupal_anonymous_user();

  $query = NULL;

  // Deal with destination from password reset one time login link,
  // by creating a new one time login link and setting it as the destination
  // after the T&Cs have been accepted.
  if (arg(0) == 'user' && arg(1) == 'reset') {
    $token = drupal_hash_base64(drupal_random_bytes(55));
    // This is a new, anonymous-user session.
    $_SESSION['pass_reset_' . $uid] = $token;
    $query = array('destination' => "user/$uid/edit?pass-reset-token=$token");
  }

  if (!empty($_REQUEST['destination'])) {
    $query = array('destination' => $_REQUEST['destination']);
  }

  unset($_GET['destination']);

  $result    = db_select('users', 'u')
    ->fields('u')
    ->condition('uid', $uid)
    ->range(0, 1)
    ->execute()
    ->fetchAllAssoc('uid');
  $signatory = array_pop($result);

  drupal_goto('legal_accept/' . $signatory->uid . '/' . md5($signatory->name . $signatory->pass . $signatory->login), array('query' => $query));
}

Just add a (boolean) field to the user.

  For new Drupal 7 site you can use:

  Admin > Configuration > People > Account settings > Manage fields
  Another method is using Profile2 module, a successor of Content
  Profile Drupal 6 module If you have started with a minimal install
  profile you will need to enable the Field UI module to access Manage
  fields via the Account settings.

Then, in a custom module, invoke hook_user_load and there, check if it's set. If not redirect to a page where the user needs to accept the terms and this field get updated.

Or, have a look at EU cookie compliance, it does more or less what you want.


Drupal Commerce Paypal WPS - Connection refused I am trying to get the WPS module to work for Drupal Commerce but I am getting an error. After the payment is made in my logs I see.

  Attempt to validate IPN failed with error -111: Connection refused

The code that this relates to in the pay pal module is:

// Process the HTTP request to validate the IPN.
$response = drupal_http_request($host, array('method' => 'POST', 'data' => implode('&', $variables)));

// If an error occurred during processing, log the message and exit.
if (property_exists($response, 'error')) {
  watchdog('commerce_paypal', 'Attempt to validate IPN failed with error @code: @error', array('@code' => $response->code, '@error' => $response->error), WATCHDOG_ERROR);
  return FALSE;
}

The $response has an error in it (Connection refused).

As I am using the sandbox the $host is https://www.sandbox.paypal.com/cgi-bin/webscr.

I can confirm that I do receive the IPN from PayPal (some dd() statements proved this), but when we check to see if PayPal sent it, the code falls over.

Any ideas what could be going wrong? I am preusming it is more likley to be enviromental rather than code.

This was an environmental problem. The Drupal server did not have a direct connection to the internet. Setting the proxy settings in settings.php got this to work.

http://devincarlson.ca/blog/configuring-drupal-use-proxy-server-when-making-external-http-requests

In my case the settings I had to set were:

$conf['proxy_server'] = 'my server';
$conf['proxy_port'] = 1234; // port number


Why can't I connect to my Solr server? I am attempting to configure Solr search with a drupal web page on a dev server.
I have installed the server and the Search_API_Solr modules along with it's dependencies.  When I try to connect the Search_API_Solr module to my server, I get the error:

  The Solr server could not be reached.  Further data is therefore unavailable.

  SOLR SERVER URI: http:// host_machine:8983/solr/#

  CONNECTION: The Solr server could not be reached.  Further data is therefore unavailable.

To attempt to remedy this, I've tried linking directly to the core that I have setup (e.g. http://host_machine:8983/solr/mycorename) to no success.

Does anyone have any experience fixing this?  I've searched through every bug/support post I came across and attempted all of the solutions with no fix.

P.S. I've read somewhere that you can't access a Solr server if the Drupal site is running on the same host. I don't know the validity of that.

Any suggestions would be much appreciated, thanks.

It turns out that if you use the IP of your host machine, if you're hosting Solr and the Site on the same box, you can't use the IP of the box to connect.  In my case, I was trying xx.xx.xx.xx:8983/solr/my_core which was failing.

After changing the address to http://127.0.0.1:8983/solr/my_core I am finally connected.


Hide Fields Based on Role Possible Duplicate:
  Is it possible to assign permission to fields?

I have a contact type called contact form, and I want to alter the fields that are visible when adding that contact type, based on the user role. I want admin to be able to change the value of fields such as 'status', 'date completed' etc but I don't want these to be visible to the anonymous role.

Sounds like the function of Field Permissions module.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


How do I get the logo path? I have a custom logo and I have tried to get his path in this way theme_get_setting('logo_path'), but no expected result.

I am using the code in a custom block, in input PHP.

logo_path seems to only be set if you override the theme's default logo via its theme settings. To get the default logo, use theme_get_setting('logo').


Entity:media doesn't exist error when searching for url in "add link" in wysiwyg When adding a link into a rich text field (wysiwyg) (see images bellow) and searching for a keyword the throbber icon keeps spinning and that's it.

I looked at the error logs and found the following, this was working recently, no idea what happened.

Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "entity:media" plugin does not exist. Valid plugin IDs for Drupal\linkit\MatcherManager are: entity:contact_form, email, entity:contact_message, entity:feeds_feed, entity:node, entity:scheduled_update, entity:taxonomy_term, entity:user, entity:file, front_page"

If anyone has an idea what happened?
Drupal 8.7.3

I had a similar problem, but not with entity:media, but with entity:shortcut

I ended up by deleting the matcher from the database.

It is in the datatable config under the name "linkit.linkit_profile.ckeditor"

SELECT * FROM config WHERE name= "linkit.linkit_profile.ckeditor";

The data is stored in a serialized string. To remove it, you must be confident in editing serialized strings, which is a bit dangerous.

I used (UN)Serialize.me to convert the unserialized string to a JSON string, then edited the JSON in JSON Editor Online and back again.

I first tried to use drush to export the config, editing the config YAML file and then importing, but it yielded the same error.


Show current page on Drupal 7 breadcrumb Is there anyway to add the current page title on drupal 7 breadcrumb?

Some themes - like Zen - provide this option, so check under Appearance -> Settings.  If your theme doesn't offer the option, you can edit your theme's page.tpl.php - simply add $title after the $breadcrumb variable.  Alternatively you could override theme_breadcrumb().


How does Drupal know which Entity View Mode to use? When Entity View Modes are defined, how does Drupal know which to use? Are they only useful with Views, or can they be used in the node display as well? If so, is that specified in the template, or somewhere else?

With a tiny bit of glue code you can use specific node template files for different view modes, so they can become pretty useful:

function MYMODULE_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'some_type') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__some_type';
  }
}

That will allow you to use template files with names like node--article--some-type.tpl.php specifically targeted to that view mode.

Other than that MPD's answer has all of the other common cases covered.


how to gzip compress js/css in drupal 7 My site will run on D7. but it will too slow. i want to compress (gzip) js and css. I have check my site on https://developers.google.com/speed/pagespeed/insights and it will told me for compression of js can css files.

The easiest way is to go to Configuration > Development > Performance (admin/config/development/performance), and enable:

Cache pages for anonymous users
Cache blocks

And also:

Compress cached pages
Aggregate and compress CSS files
Aggregate JavaScript files

For websites with mostly anonymous (not logged-in) visitors, this is often sufficient. Note that if you enable compression in Drupal, you should not enable page compression on the web server level (Apache) as well.


Why can only administrators see blocks? I'm using the Paragraphs and Block field modules to display a list of nodes within the content of a page. This works great while authoring, but as soon as I log out from the administrator account, the node list vanishes from the page. The component is still there, but the content is not rendered.

Here's is the twig template for my block paragraph type:

{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
'paragraph--id--' ~ paragraph.id.value,
]
%}

<div{{ attributes.addClass(classes) }}>
  {{ content }}
</div>

Not a lot going on, as you can see.

Does anyone have any experience with the block field module and can walk me through this?

EDIT:

I did some digging into the block field module source, and determined that this is the line of code causing the failure:

if (!$block_instance || !$block_instance->access(\Drupal::currentUser())) {

More specifically, it's the second condition. So for whatever reason, the current user doesn't have access to the block instance unless the current user is an administrator. Does anyone know how to solve this?

EDIT 2: I should probably mention that the blocks I'm trying to show are created by a view. I double checked that the access property on the generated blocks should allow all user roles.

EDIT 3: I did a little more digging, and verified that if I return AccessResult::allowed() from Drupal\views\Plugin\Block\ViewsBlockBase::blockAccess, the problem disappears. So what's happening is the view is saying the block ID is inaccessible for some reason.

EDIT 4: I discovered that setting the "Bypass content access control" permission on all users fixes the issue. However, I'm not sure this is desirable. Is there a way to fix the issue without setting this?

FACEPALM

ok, I found the ideal solution. When I looked at my authored nodes in /admin/content, it listed them all as Status: Published. HOWEVER, when I selected all of them, selected "Publish Content" from the action dropdown, and hit "Apply to selected items", suddenly everything appeared in the view block field.

My guess is that something in the database needed to be updated. Seems like a bit of a bug, though - this should have been automatically handled by either Drupal or the block_field module.

Anyway, fixed now.


How to create a drush command without drupal? I'm attempting to create a drush command for use outside of a Drupal install.  It's basically a script to make a copy of a distribution starter kit and do some string replacing.  I'm following the sandwich example.

I'm running into two issues...

1) I created mycommandfile.drush.inc in a new folder.  If I try to run the command it says the drush command cannot be found. So I copied the file to my /.drush folder and it finds the command.  Any idea why that would be the case?

2) The second issue is that with the file in the /.drush folder it is telling me that I need a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.  In my command declaration I have 'bootstrap' => DRUSH_BOOTSTRAP_DRUSH.

1) Drush only searches certain folders for Drush commandfiles.  Run with --include=/path/to/your/drushcommands, or set $options['include'][] = '/path/to/your/drushcommands'; in your drushrc.php if you'd like to use a directory other than $HOME/.drush.

2) If you have in fact set your bootstrap to DRUSH_BOOTSTRAP_DRUSH, then you should not be getting that message.  Maybe there is something wrong with your commandfile definition; can't guess what it might be from the information provided, though.

For a quick start on writing a new Drush command, see the drushify project.  It will create a template for you very quickly.  Perhaps you could compare the template drushify creates with the commandfile you put together.


Validate username field in user registration form, drupal 7 I need to compare the text in the username field with the text in email field of the registration form. If they are not equal i want to stop the registration. I think i should use a hook but i really don't know where to start from.

Any idea?

You can do this by using hook_form_FORM_ID_alter() and adding an extra validation function to the user register form:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_validate_register_form';
}

function MYMODULE_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['mail'] != $form_state['values']['name']) {
    form_set_error('name', t('Name and email must be the same.'));
  }
}

I'm not 100% positive those $form_state['values'] keys are the right ones so you'll need to inspect the form to make sure; but the logic is the same either way.


How to bring the REMOTE ID of a commerce payment into the checkout completion page? We're running on Drupal 7.72 and using Commerce and Commerce Webform to take payments on the website.
We would like to display the REMOTE ID (seen below) on the checkout completion page. We are not able to find any tokens for this purpose readily available in the replacement patterns.
How would we go about trying to achieve this?
Apologies - I'm pretty new to using this module.

Unfortunately, because each order may have any number of payment transactions (meaning there is no strict 1:1 relationship), we cannot provide a simple token to make this available. You could create a custom Order token for the logic you know works on your site (e.g. [commerce-order:payment-id] that prints the remote ID of the first successful payment associated with the order). Otherwise you could customize the checkout completion page through a custom checkout pane, message text, etc.


Setting default image style to 'original image' in formatter In a custom formatter that I'm writing, I have a problem with default_value for an image style.

function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_formatter' => array(
      'label' => t('My Custom Formatter'),
      'field types' => array('image'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'settings' => array(
        'trigger_image_style' => '',
      )
    ),
  );
}

function MYMODULE_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array();

  $image_styles = image_style_options(FALSE);
  $element['trigger_image_style'] =  array(
    '#type' => 'select',
    '#title' => t('Trigger image style:'),
    '#description' => t('Image style to be used for trigger'),
    '#default_value' => $settings['trigger_image_style'],
    '#options' => $image_styles,
  );

  return $element;
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  $html = "";
  $settings = $display['settings'];

  // ensure deaults?
  if (!isset($settings['trigger_image_style'])) $settings['trigger_image_style'] = '';
  //.....
}

Seems that Drupal will return incorrect path:

image_style_url($settings['trigger_image_style'], $item['uri']);

until I explicitly set a style of my choice. The incorrect path will have double slash, as in:

http://example.com/sites/default/files/styles//public/trigger-images/test1.jpg

I thought that empty string simply means 'use original image'... How should I tell Drupal to use original image if the style is not set or is an empty string?

It is have simple solution when you want specified image_style use something like

  image_style_url('850x450',$file->uri);

and when you don't want use any image style and want use origin image use

 file_create_url($file->uri);


How can I format the date like this in search-result.tpl? In node.tpl I have

<div class="imported-text">

Created on <?php print date('l', $node->created); ?>, the <?php print date('jS', $node->created); ?> of <?php print date('F Y', $node->created); ?>.

</div>

But when I place this in search-result.tpl I get an error. <?php print $info_split['date'] ?> can only use the short format AFAIK.

I find it is generally best to do things in a consistent way and since the drupal template_preprocess_search_result() function uses Drupal's format_date() function I recommend also using that when overriding things.

So to leave the date in the default info variable but change the format I would do this, in my template.php file of my theme (or a custom module, depending on my requirements):

/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Override the date format.
  if (!empty($result['date'])) {
    $variables['info_split']['date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
  // Reset the info variable based on the new date.
  $variables['info'] = implode(' - ', $variables['info_split']);
}

If I wanted a date variable available in my template that was separate from the info variable I would do this:

/**
 * Variable preprocessor for the search result template.
 *
 * @see search-result.tpl.php
 */
function MODULE_OR_THEME_NAME_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Add a custom date variable for use in the template.
  $variables['custom_date'] = '';
  if (!empty($result['date'])) {
    $variables['custom_date'] = format_date($result['date'], 'custom', 'l, \t\h\e jS \o\f F Y');
  }
}

Then to use that variable in the template file you would do something like this:

<?php if ($custom_date): ?>
  <div class="date">
    <php print $custom_date; ?>
  </div>
<?php endif; ?>

Something I recommend to make things even a bit better again is instead of using the 'custom' date formatter, make a preset for "l, \t\h\e jS \o\f F Y" in the Drupal UI at admin/config/regional/date-time, then use that preset like this:

format_date($result['date'], 'preset_name');

Then you can easily change the format in future via the UI.

In this case I would recommend calling the preset "Search result date" or something along those lines so that you know what it is used for when looking the the UI and you know what will be affected if you change it.


How to have an extension in hook_menu() I am trying to create a menu with a file extension in hook_menu() with the following code:

$items['pdf/products/%.pdf'] = array(
    'title' => 'Download PDF',
    'page callback' => '_pdf_get',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
);

It works fine without the .pdf.

Any ideas how I can do this?

Why do you need the .pdf part in the hook menu?  Can't you just perform a check on the arg() function in your _pdf_get function to ensure that the argument contains ".pdf" and if not, redirects the user to the url with ".pdf" appended?


How to add 4 side by side containers I would like to add 4 columns/containers just above the footer of the homepage. Similar to the triptych blocks that the Bartik theme offers, except I would like to have 4 of them. I am using a Zen sub theme.

How would I go about adding 4 block and having them display one next to another?

You just need to define them in your .info file...

regions[four_first]   = Footer panel (first)
regions[four_second]  = Footer panel (second)
regions[four_third]   = Footer panel (third)
regions[four_fourth]  = Footer panel (fourth)

Then add them to your page.tpl...

<?php if ($page['four_first'] || $page['four_second'] || $page['four_third'] || $page['four_fourth']): ?>
    <div id="footer-panels-wrapper">
       <?php print render($page['four_first']); ?>
       <?php print render($page['four_second']); ?>
       <?php print render($page['four_third']); ?>
       <?php print render($page['four_fourth']); ?>
    </div>
<?php endif; ?>

When you have done this they will appear in /structure/blocks

The rest is down to CSS...


How to add menu items to system.admin_content parent? parent: system.admin_content route handles /admin/content path. I'm trying to add more items to the menu tabs visible on that page.

So I'm doing this:

# test.routing.yml
entity.admin.test:
  path: '/admin/content/test_entity'
  defaults:
    _entity_list: 'test_entity'
    _title: 'Test entities'
  requirements:
    _permission: 'administer content types'

# test.links.menu.yml
test.admin:
  title: Test entities
  route_name: entity.admin.test
  # I have also tried using route defined in my entity type annotation
  # route_name: entity.test_entity.collection
  parent: system.admin_content
  description: 'List and edit site test entities.'

The route works (I can access page at /admin/content/test_entity), but menu item is not displayed. If I change parent to for example system.admin_structutre then the menu item is shown on /admin/structure list without problems.

Dont use test.links.menu.yml instead use test.links.task.yml

in test.links.task.yml try the below code...

entity.admin.test:
  title: 'Test entities'
  route_name: entity.admin.test
  description: 'List and edit site test entities.'
  base_route: system.admin_content


how to get XML content over HTTP request? I'm building a module and I need to  get XML content over HTTP request.

The idea is to create nodes programmatically with the retrieved data from the xml file.

Can I do this?

Its a little bit of a learning curve , but I would recommend using the feeds module for this

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

you can then load xml (or csv) to nodes, and map its contents to nodes.
This is preferable to writing your own custom functionality.

but if you do, drupal_http_request(), and then node_save() for constructing the nodes would be the way to do things.
If you do code it yourself, Id recommend getting comfortable with running scripts with drush, as that'll be easier than battling timeouts in the browser


Login button not showing after upgrade to PHP 5.3 I upgraded our web server to PHP 5.3 as a bit of software requires it, and suddenly the login button on one of our Drupal websites has disappeared! Submit buttons from other Drupal forms have disappeared too.

I've looked in the source code of the page, and the form is indeed missing a submit button.

Is this a known problem? If not, how might I diagnose the error?

To diagnose the problem, make sure you display all errors (notices included) and that they reported somewhere (log, watchdog, ...), it should be a function incompatibility. Usually it is about parameters that are passed by reference for certain native functions or something like that (introduced in PHP5.3).

Then when you have identified the problem, open an issue on the module project (I bet it will be a contrib module or one of your custom module) so that the module maintainer can update it.

Drupal 6 is relatively old and versions prior to 6.14 are not working with PHP 5.3. Make sure you have the latest version, see also http://drupal.org/requirements/#php.


Change currency code to symbol I'm translating the Drupal Commerce site into Japanese.
I want to change the currency code　JPY to symbol "円".

But keeping rest of the symbols (￥) as it is:

I referred this question and also made changes accordingly. But it didn't help me.
Please guide me.

One more question regarding it, is it possible to use 2 symbols for the same currency? Is there any way to display "円" replacing this "JPY" only? I don't want to use String Overrides.

Edit: It is ok if I completely change the symbol　from "￥" to "円". I tried doing this by altering commerce.api.php file, but it didn't reflect anything.

If it is a form, you can use hook_form_alter along with the PHP function str_replace to replace JPY with 円. Let me know if you need further help.

EDIT:

<?php
  function YOURMODULE_form_alter(&$form, &$form_state,$form_id) {
    if ($form_id == 'your_form_id') {
      print str_replace("JPY", "円", render($content));
    }
  ?>


Backup and Migrate writing empty files locally When I do either a scheduled or a manual backup, that's all I get. When I also write to NodeSquirrel, the NodeSquirrel backups are fine.

The problem started when I moved the private file folder to a level below the Drupal user "home" directory (it's a CentOS/cPanel server), to avoid these backups getting added to the overall server backup files - or so I originally thought (see below).

I've since figured out that I can exclude the files from the backup via a script. I pointed the private files directory back the original directory (one level below the web root), but I'm still getting empty files, even though Backup and Migrate sends me messages that the backup completed successfully.

I've checked permissions; I can manually write to that directory as the Drupal user (via nano). Anyone else experienced this?

Update:

Now when I back up the database ONLY, it works as expected. I actually get a compressed .sql file that looks like what I'd expect. But when I try to back up the public files directory, it reports "Public Files Directory backed up successfully to XYZ-2016-12-20T22-20-22 (444.61 MB) in destination Manual Backups Directory in 7 min 42 sec." However, this is what's in the directory:

-rw-r--r-- 1 dUser dUser      0 Dec 20 22:28 XYZ-2016-12-20T22-20-22.tar.gz
-rw-rw-r-- 1 dUser dUser      0 Dec 20 22:28 XYZ-2016-12-20T22-20-22.tar.gz.info

Have altered max_execution time in php.ini, and tried changing dir permissions to 775 and ownership to dUser:webserverUser to no avail.

Next tried drush bam-backup files. First time I got "Unable to create or write to the save directory 'private://backup_migrate/manual'." (!!!)
And drush was operating under root! So I changed permissions to 777 on the whole directory structure and the drush back up was successful, but why? It did kick out an error, though: "Error while sending QUERY packet. PID=7537 database.inc:2227".

So now I'm quite confused. Was it one of the updates I did to Drupal core? I don't believe the backup_migrate module had an update in that time frame.

TIA for any insights or advice!

Found out the problem: a file system quota on that particular user on the server. Drush finally gave me this clue when I ran it as the web user:

drush bam-backup files
dm-0: write failed, user block limit reached.
file_put_contents(): Only 0 of 400 bytes written, possibly out of free disk space files.inc:411                         [warning]
Public Files Directory backed up successfully to XYZ-2016-12-27T23-28-18 ( bytes) in destination      [success]
Manual Backups Directory in 12 min 59 sec.
Error while sending QUERY packet. PID=19337 database.inc:2227

Of course there was plenty of disk space, just not available to that user, and I never saw that message when running the command as root. There was enough space available to write the database backups, just not the files directory backup (600MB). Of course, BAM sent me emails saying the backup was successful. I still don't know what the error sending the QUERY packet is about, but the earlier problem of mysql crashing noted did not reappear. Also, I discovered that the web user was not the owner of the module - I forgot to change the ownership after having drush 'update all' earlier (as root); that could have caused the other problems, but the main issue was the disk quota.

In any case, drush bam-backup archive finally worked. Hope this helps someone else in the future.


use menu item title instead of page title in breadcrumbs I have been trying to display the menu item title as the trailing item in my breadcrumbs, other than the page title.

At this point, I override the template_breadcrumb() function with a custom function. At the end of the string variable, I have put drupal_get_title() to append the page title to the breadcrumb trail.

Please find a snippet out of the breadcrumb function below:

foreach($breadcrumb as $value) {
  $crumbs .= $value;
}
$crumbs .= drupal_get_title();

Now, when available, I would prefer the linked navigation item title to be displayed as trailing breadcrumb item. If not available, I will display the page title.

How can I check if this page is attached to a menu item, and retrieve the title, in order to display it as a breadcrumb item ?

Perhaps you could look at this module: http://drupal.org/project/menu_breadcrumb
It sounds perfect for your needs.

Some details from the module's project page:

  By default, Drupal 6+ use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.


How to make a block visible on a particular page and as well as on taxonomy term page? here is my situation,

I have a Taxonomy menu block built using taxonomy_menu and taxonomy_menu_trails module. And I have used block_term module to display the menu on nodes with given term(s).

Now, how can I display the same taxonomy menu block on taxonomy term pages as well?

I tried adding the taxonomy term page link to display block only the listed pages. but it did not work. while doing this I had both the conditions (Display on nodes that are taged to terms and Show only on listed pages) checked.

Well from what I understood from your question, you can use following lines of code in your template file where you want to display the block:

if(arg(0) == 'taxonomy' && arg(1) == 'term') {
  $tid = (int)arg(2);
  $term = taxonomy_term_load($tid);
  $taxo_term = $term->vocabulary_machine_name;

  if ($taxo_term == "your_vocabulary_name") {
    print render($page['your_block_region']);
  }
}

PS: I dont know if this is very standard(drupal) way to achieve this but it has        worked for me.


User cancellation error When I delete/cancel a user account from admin, I got the attached error.
It is saying that the table cache_entity_profile2 is not found. Yes, the table does not exist actually. I am using the modules entity cache and profile 2.
The error is not generated every time, but very often.

The underlying problem is which module's responsibility it is to maintain that table.
All relevant info and links are in this issue: https://drupal.org/node/1387268


Does Drupal's theme('table') works in email body? I want to send the list of some of the node information in email to users.

I have created table of information using theme('table') function. Now I want to send this table to email to user.

Is it possible to send theme('table') using Email ?

Will it work when user will see the information in Email ?

I am sending table structure in Email, is this possible to achieve it?

I have attached the relevant code to generate table and send mail.

$header = array(
            array('data' => t('Title'), 'field' => 'n.title'),
            array('data' => t('Author'), 'field' => 'u.name'),
    );
    $query = db_select('node', 'n');
    $query->leftjoin('users', 'u', 'u.uid = n.uid');
    $query->fields('n',array('title', 'created', 'nid', 'type'))
    ->fields('u',array('name', 'uid'))
    ->fields('b',array('body_value'))
    ->fields('c',array('subject'));
    $query->condition(db_or()->condition('n.type', 'post', '=')->condition('n.type', 'forum', '='));
    $query->condition('n.uid', $user->uid, '=');
    $result = $query->execute();
    $rows = array();
    foreach ($result as $row) {
        if($row->subject) {
            $titlerow = l($row->subject, 'node/'. $row->nid).'</br>'. $row-
        }
        $rows[] = array( $titlerow,
                t('Reply Posted by: ').l($row->name, 'user/'. $row->uid)
        );
    }
    $params = theme('table', array('header' => $header, 'rows' => $rows, array('class' => array('ajax-sample-table'))));
    $language = language_default();
    $send = TRUE;
    $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
    if ($result['result'] == TRUE) {
        drupal_set_message(t('Your message has been sent.'));
    }

You can read drupal_mail() in HTML for how to output HTML in an email sent with drupal_mail().

As you are outputting links, I will add a note about that. By default l() outputs relative links that outside the website are not much useful. You need to force Drupal to output absolute links, for example using the following code.

if ($row->subject) {
  $titlerow = l($row->subject, "node/{$row->nid}", array('absolute' => TRUE)) . '
' // Your code here is not complete.
}
$rows[] = array(
  $titlerow,
  t('Reply posted by !user-link', array('!user-link' => l($row->name, "user/{$row->uid}", array('absolute' => TRUE))))
);

If you have the Devel module installed, you can see (using the following code) the difference between the output of your code, and mine.

print l('Test page', 'node/1') . "\n";
print l('Test page', 'node/1', array('absolute' => TRUE));

In my test site, what I get is the following.

Test page
Test page

As side note, remember that the $options parameter for l() can receive the same values the $options parameter for url() accepts.


Has anyone worked on a built-in CLI terminal [w/ drush]? What would make my experience with clients/end-users easier is if there was a self-contained GUI-like terminal that would be exclusive to their drupal 7 subsite in a multi-site configuration. This would allow them to be full-stack developers without the headache of managing *nix users?

The only reference I could find was for Drupal 6 - https://drupal.org/project/terminal.

In the meantime, the way I can think of manually achieving some of this is to write custom forms on a user dash (page--front.tpl.php) that would trigger drush calls on the server side for particular (custom) tasks. Maybe add some ajaxy for wiz-bang.

Now granted, a lot of the customs tasks I can think of atm can be achieved via drupal modules - such as editing css, limiting access to module uploads, and even exposing features. It's just turning each one of those on/off for over 100+ sites is cumbersome, and so it'd be nice to leave it up to the end-user to manage their own site.

Without paying Pantheon to do the same thing.

The upcoming Drush 7 now has drush core-cli which used the Boris shell


A way to generate line charts where each dataset comes from a view with specific arguments I've got a view which shows download count and playback count (for musical works). This view may be filtered on time intervals, and is capable of returning downloads and playbacks for this time interval only.

Now, I'd like to generate an "overview" which simply will be the product of this view but with different time intervals. I'd like the resulting table to be something like:

when         downloads  playbacks
last week    10         100
last month   50         287
last quarter 200        437
last year    1000       1836

Is there a way to achieve this without doing it as a specific module? Is there a module out there which is capable of collecting data from a view, putting it together and generate a table and possibly charts for that?

'I' can answer that very last part of your question about charts. The views integration of the charts module is a solution for that. Here is an intro about it from the charts community pages:

  Anybody familiar with the views UI can use the charts module to create
  charts without coding PHP snippets, as one typically does when using
  the Charts API.

  So site building knowledge is sufficient to create charts using Views,
  you don't have to be like an experienced Drupal developer (who
  probably would rather want to use the Charts API instead).

To be complete: I'm the new co-maintainer of the charts module ... Working on transforming the latest (pretty old and stable) RC1 release of it in an official release of it.


how to show a link only on my own profile node? tried this code:

<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
$url = privatemsg_get_link(array(user_load($node->uid)));
print '
'. l(t('Send a private message to the author'), $url, array('attributes' => array('class' => 'lichnoe'))) .'
';
}
?>

but this doesn't works. It displays on my own profile, but doesn't displays on other user's profile. What i'm doing wrong?

The code you have posted above will check if you are on the user/[uid] page for the user that is logged in. So it will take effect for the user's own user page. If you wanted to post the link on all pages except the user's own page you should instead do

if (arg(0) == 'user' && is_numeric(arg(1)) && $user->uid != arg(1)) {


How to alter image captcha title in drupal 7 I am working on drupal 7 image captcha module.I want to alter or hide image captcha title like 'What is in your code'.How can I do it by without hacking the module?

use hook_form_FORM_ID_alter() and Form API pre_render function. E.g:

// Explains pre_render. This is when you create a form;
function feedbackForm($form, &$form_state) {

  $form['#pre_render'][] = 'feedbackForm_pre_render';

  $form['name'] = array(
    '#title' => t('Ваше имя'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  $form['actions'] = array(
    '#type' => 'actions',
  );

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Отправить'),
  );

  return $form;
}

function feedbackForm_pre_render($element) {
  $element['captcha']['captcha_widgets']['captcha_response']['#title'] = t('Защитный код');
  return $element;
}

You can also use hook_form_alter() function:

function MY_MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);

  if($form_id == 'FORM_ID') {
    $form['#pre_render'][] = 'feedbackForm_pre_render';
  }
}


How do I submit a form via AJAX? I'm using the Webform module for Drupal 8. The module confirmation settings for a form are the following:

Page (redirects to new page and displays the confirmation message)
Inline (reloads the current page and replaces the webform with the confirmation message.)
Message (reloads the current page/form and displays the confirmation message at the top of the page.)
URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page.)

But how am I able to submit a form via AJAX so that the page doesn't reload on submit, but a confirmation message still replaces the form? What did I do wrong?

EDIT:

Here is the solution which works:

First you have to hook the form alter function and set an AJAX callback (as in echo's answer):

use \Drupal\Core\Form\FormStateInterface;

function MYTHEME_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) && $form['#webform_id'] == 'MYWEBFORM' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' => '\Drupal\MYMODULE\Controller\DefaultController::processFormSubmission',
      'event' => 'click',
    );
  }
}

Then in the processFormSubmission function you can process the form (put use \Drupal\Core\Form\FormStateInterface; at the top of your file) like:

// Instantiate an AjaxResponse Object to return.
$ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

/* do sth */

// in the DOM: replace the form with the text 'form submitted'
$ajax_response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('#MYFORM', 'form submitted'));

return $ajax_response;

I can't post all the code you would need, but essentially you will want to do a form alter, and add an #ajax item on the submit button and point it at a callback. This callback will perform validation and submission - at the end of it you can issue a ReplaceCommand. Here's an example:

function mymodule_form_submit($form, FormStateInterface $form_state) {
  // code here to handle the submission aspect
  // you'll need to manually submit form value data to Webform using webform api

  // if successful, this is the response
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('selector', 'data'));
  return $response;
}

Where selector is an HTML element, and data is what you want to replace it with.

Sounds like you would want the selector to be the id of the container wrapping the form, and the replacement should be the confirmation message from Webform (you'd have to get it from fetching the config of that form). This will cause a non page refresh and instead, the form will be replaced with the confirmation message.


append settings.php during profile installation I would like to add lines to my settings.php during my custom installation. I'm using some $conf['...'] to match external content to my drupal and i would like not to do this by modifying directly the file.
During my custom install i want to use the external content to have a fully operational website after running my script.

Do you have an idea how i can do this ?

Thanks.

Checkout this post about Collecting and writing configuration settings to setting.php from an install profile.

It describes how a custom task (via hook_install_tasks_alter()) was injected into the installation profile to display a custom form and, upon submission, how drupal_rewrite_settings() can be used to inject the custom settings into settings.php.


Creating module can display map in page or block in drupal I have two days I'm trying to develop my custom module.
I want to display map in block but nothing happened.
how i can called css an js file and show them in page or block?

function exemple_init() {
  drupal_add_js('http://maps.googleapis.com/maps/api/js?sensor=false', 'external');
}

function exemple_block_info() {
  $blocks['exemple'] = array(
    'info' => t('Google Map Exemple'),
    'cache' => DRUPAL_NO_CACHE
  );
  return $blocks;
}

function exemple_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'exemple':
        $block['content'] = '';
  }
  return $block;
}

Firstly adding a JS file globally in hook_init function is wrong unless you want the file to be loaded on each page of your site. To add a JS file to a block use the #attached property in hook_block_view

eg:

'#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),

Secondly, I assume you want to show an address from Google Maps in your block.
In that case pull the embed code from Google Maps https://support.google.com/maps/answer/3544418?hl=en
and use that embed code in the block.

Sample Code for it: http://pastebin.com/5h1c2SBU

Though still curious about the JS file.


How can I get rid of Contribute 8.x-5.0-beta3 module? What's wrong with Contribute 8.x-5.0-beta3 module?

After 8.6.10 update I have a problem with Contribute module.
First it's marked as outdated/not supported but on some sites I can not remove it fully as it lefts something in the db.

So finally I get the errors like

"The following module is missing from the file system: block_user bootstrap.inc:276"

even after the

drush pm:uninstall

It's a composer managed install.

Always you have to first uninstall the module, then remove the codebase from filesystem.

Composer have nothing to do with installing or uninstalling of modules in drupal. Composer is responsible for downloading the needed files, or removing if not longer in use.

If you first remove the files from the filesystem, you cannot uninstall it properly, because drupal not knows what to do.
Therefore you see such errors about missing things.

What can you do now to get rid of this error if such happen:

Go one step back & put missing files back to filesystem.

If you use git, checkout your last composer.lock before this error, than type composer install to get the old module files back.
Or use your backup or your ftp-program to bring the module files back.

Now you can uninstall the module as you like, perhaps using the gui or with drush (typing drush pmu modulename). This step is important, because it removes all things installed by this module. If you skip this, you will get such errors.
Now delete unwanted module files again:

checkout your newest state of composer.lock (without that module)
and type composer install and composer will remove the unwanted files

Don't forget to clear the cache. (drush cr)


Dynamically change Commerce Customer profile type on checkout I need the following in Drupal Commerce:

On checkout, two radios should be presented (e.g. Email & Postal)
Upon selection of one of these, a different customer profile type should be attached to the order
Only fields related to the selected profile type should dynamically show up.

I'm perfectly able to accomplish this through FormAPI, but that wouldn't be tied to the Commerce system unfortunately.

Someone knows how the right way?

Thanks

If you can accomplish this through the Forms API, then go for it. There's no specific Commerce way to make this happen.


How to make the autocomplete term widget (tagging) case-sensitive? I notice that although the Autocomplete term widget (tagging) happily autocompletes terms with their right letter case, after saving the terms are changed to lower case. E.g. I have two tags "Drupal" and "drupal" and although I autocomplete "Drupal" and save the node, what gets saved is "drupal".

Is there a way to force case-sensitivity for this widget -- or vocabulary?

You are looking for Termcase module, It will do that.

  It prevents users to use different cases on terms. With termcase you
  can make sure all terms in a vocabulary begin with an uppercase or
  that they are all formatted to lowercase.

There are five options available:

No formatting
Ucfirst: convert the first character of the term to uppercase
Lowercase: convert all characters of the term to lowercase
Uppercase: convert all characters of the term to uppercase
Propercase: convert the first character of earch word to uppercase

You can define these settings per vocabulary. The module even enables you to update all existing terms in a vocabulary and select whether or not you want to convert synonyms as well.


Webform - Show/Hide fields based on day of the week selected from Datepicker I have a little issue with a webform.
I am setting a booking system and some items are only available on some days of the week.
I have modified the date field to be a textbox with popup calendar
I need to show/ hide some field based on the Day of The Week selected ( if Day is Tuesday or Day is Friday then Show the fields, otherwise, hid them)
Any help is welcome, because with the conditionals, i can only do it based on date not on the day itself.

thank you

I think the easiest solution is to do this with jQuery.

To get the value from the datepicker field and convert it to a weekday you might do something like this.

Add this function to your JS file:

// Accepts a Date object or date string that is recognized by the Date.parse() method
function getDayOfWeek(date) {
  var dayOfWeek = new Date(date).getDay();
  return isNaN(dayOfWeek) ? null : [0, 1, 2, 3, 4, 5, 6][dayOfWeek];
}

Use this code to get the value from the datepicker:

var datepicker = $('#your_datepicker_id').datepicker("getDate");

Then do like this:

var today = new Date();
if (!today.getDay() == getDayOfWeek(datepicker)) {
  $('.field-names-to-hide').hide();
}

I think that something like this will do it.


Drupal Search Result Sorting in Desc order I am trying to change my Drupal site's search results. Currently it's showing the default search results by node "Updated or Changed" but i want to change it to node "Created or Published" into Descending ORDER. So all the search results will be  ORDER BY CREATED or PUBLISHED. I have looked at many files but couldn't have any success.

Which files do i have to modify and what code?

Any help will be really appreciated.

Thanks!

Similar questions here

Use hook_preprocess_search_results and set your criteria there.

Here's the .module file you can use, this sort nodes by their creation time with a descending order. You need to create a .info file to make the module work, also remember to replace [MODULE_NAME] with your own module's name. This is not perfect but at least gives you the data in the order you want.

<?php
/**
 * Implement hook_preprocess_search_results()
 */
function [MODULE_NAME]_preprocess_search_results(&$vars) {
        $results = $vars['results'];// via dsm (Devel module), we can see node creation time is available under the 'results' array
        usort($results, function($v1, $v2) {
          return $v2['node']->created - $v1['node']->created; // sort by created time, DESC order
        });
        $value = '';
        $output = '';
        $output_results = array();
        foreach($results as $item) {
          $value .= theme('search_result', array('result' => $item, 'module' => $vars['module']));
          $output_results[] = $value;
          $value = '';
        } // store all results into an array
        #dsm($output_results);
        $output = implode(" ", $output_results)."
"; // convert array to string
        $vars['search_results'] = $output;
        #dsm($vars);
}

.info file:

name = Search Desc
description = sort default search by creation date in DESC order
core = 7.x

search.tpl.php file, you need to copy this file from modules/search/search-result.tpl.php and put it under your theme dir, do not modify the original.

<?php
$info_split['date'] = date('m/d/Y - H:i', $result['node']->created);// replace update time with created time
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info_split): ?>

<?php print $info_split['user'].' '.$info_split['date']; ?>

    <?php endif; ?>

Update:
Given Drupal's default search ranking criteria (by content relevance), an additional hook is needed inside the .module file for OP's question. After adding this, you need to go to /admin/config/search/settings and set the Influence for the 'Node Creation Date' field at the bottom of the page, re-index, and run cron.

/**
 * Implement hook_ranking()
 */
function [MODULE_NAME]_ranking() {
  return array(
    'node_created_date' => array(
      'title' => t('Node Creation Date'),
      'score' => 'n.created',
    ),
  );
}


Generate image URL from FID I have a custom form in Drupal 8, which has a image upload field. I am storing the file ID of that uploaded image. Now I need to generate the URL of that image.

How can I achieve this?

Get the image file src (url)

$fid = 1;//The file ID
$file = \Drupal\file\Entity\File::load($fid);
$path = $file->getFileUri();

OR

$path = 'public://images/image.jpg';
$url = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($file->getFileUri());


Drupal PHP Coding Standards I have declared two items in my hook menu.

//Calls a function that enables inputting/updating data of a particular template.
$items['user/%user/myid_inputting'] = array(
    'title' => 'MyID Inputting',
    'description' => 'Inputting data for a particular data',
    'page callback' => 'myid_inputting',
    'page arguments' => array(1),
    'access arguments' => array('perform_regular_task'),
    'file' => 'includes/myid_inputting.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -20,
);

//Calls a function that enables ID printing
$items['user/%user/myid_printing'] = array(
    'title' => 'MyID Printing',
    'page callback' => 'myid_printing',
    'page arguments' => array(1),
    'access arguments' => array('perform_regular_task'),
    'file' => 'includes/myid_printing.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -19,
);

I had used two separate files for the two items. Is that best practice in Drupal?
I just notice some functions that I used are redundant when separating the code between the two. What are advantages and disadvantages of doing so?

If the code in myid_inputting() and myid_printing() is different and large, you might want to keep these callbacks separate. I generally avoid having too many lines in one file, so whenever it's possible to logically organize the code of your module into files, it's better to do so.

Regarding the code that is redundant: I always have a separate file with helper functions where I store functions that need to be shared. Include this file at the top of the .module file, and you're all set. You can see an example in my D7 module boilerplate on Github.

Here's how you would include the helpers file (this would go at the top of the .module file):

// Load the helper functions.
require_once dirname(__FILE__) . '/YOUR_MODULE.helpers.inc';

Back to your case - leave different code in separate files, make helper functions for the rest and move it to YOUR_MODULE.helpers.inc. This works great for very large modules as well, and is self explanatory when more people are working with you on a project.

Hope this helps.


How to show selected options only if item is selected in select? I have created a select option for Province which has values of #1, #2, #3

and I have created a second select for Municipality with values #4,#5,#6,#7,#8,#9,#10,#11,#12

If I select #1 in Province I want to show #4,#5,#6 in Municipality select only.

Can this be achieved? If so how?

You may use Reference field option limit module to accomplish this
task

  This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.


Change database column type in hook_update_N I have a column in my database, its type is int. Now I need to store decimal numbers. How can I change its type to decimal with hook_update_N?

In basic terms you just need to call db_change_field() in your update function, with the spec for the new field:

function MYMOUDLE_update_7001(&$sandbox) {
  // Create the definition for the field
  $new_field = array(
    'type' => 'decimal',
    'precision' => 16,
    'scale' => 2,
    'not null' => TRUE,
    // etc...
  );

  db_change_field('table_name', 'field_name', 'field_name', $new_field);
}

If your field is a primary key/part of an index, you'll need to manually drop those indicies and recreate them (see the documentation page for a more detailed explanation).


How to properly add inline Javascript code to a webform with javascript injector module I have recently started leaning Drupal 7. I have built my first Webform and I'd like to add a field that calculates automatically number of days between two dates as shown in below  I tried to follow this tutorial but I didn't understand it so I tried to use the module js injector to solve the problem!

This is the JS injection rule that I used

jQuery(document).ready(function($) {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});
});
});

But it doesn't work. Can you help me finding the error? It seems I didn't write it well on Drupal as js rule.

This is the javascript code that I want to write:

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet"             href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
});
});
</script>

You need to use proper Drupal jQuery Syntax.

Screw the js injector module, you can do the same like this:

Create a block, for Text format select Full HTML and put this code

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>

(function ($) {
$( document ).ready(function() {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});

});
})(jQuery);

</script>

Place the block in some region.

For Visibility Settings

Pages, select only listed pages and type the url for your webform.


how to import cck data from drupal6 to drupal7? Now I have to upgrade to drupal7 website from drupal6, but there has been a new during the upgrade of the old site data, mainly CCK and taxonomy, what would I do for the way to the input of CCK in 6 to 7?
How can I do this?

You could use the Migrate module along with the Drupal-to-Drupal data migration module

Migrate

  The migrate module provides a flexible framework for migrating content
  into Drupal from other sources (e.g., when converting a web site from
  another CMS to Drupal). Out-of-the-box, support for creating core
  Drupal objects such as nodes, users, files, terms, and comments are
  included - it can easily be extended for migrating other kinds of
  content. Content is imported and rolled back using a bundled web
  interface (Migrate UI module) or included Drush commands (strongly
  recommended).

Drupal-to-Drupal data migration

  migrate_d2d provides a framework based on the Migrate API for
  migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the
  Drupal 7

Another option would to use the feeds API to import data. You could create feeds of the contents in drupal 6 and use feeds API to create the required contents in Drupal 7

Data export import is another module that does import and export of content.

Node export this another module that can be used along with Feeds


How to add user upload files to git when the node is pulished? my requirements is:

some users are adding application file drupal system adding node.
initially that node is in unpublished state. Once the admin is publishing the node that uploaded file need to be pushed to into github repo.
If there any module available for git interaction Please suggest.

You can take advantage of the Version control api

  Version Control API is an engine for Drupal integration with a variety
  of version control systems. The focus is primarily on working with
  canonical, server-side repositories. It provides basic tools that
  allow for things like history listings, commit access controls,
  triggered actions when new code comes in, and direct on-disk
  repository management.

  This module is a core engine and does nothing on its own without a
  "backend" module that provides integration with a specific VCS (e.g.
  git, bzr, svn). This module provides a consistent base interface (UI
  and API) for interacting with all the different backends.

You will also need the version control git backend as the module does not work on it's own

  This module provides an implementation of the Version Control API that
  makes it possible to use the Git version control system. It can
  retrieve commit information by parsing commit logs.

  The Git backend depends on the Version Control API module. It also
  requires Git >=1.7.2 to be installed on the server.


Views Slideshow fixed 1st slide even though its random order I'm using D7.15, Views Slideshow 7.x-3.0, jQuery Cycle 2.9999.8.

The problem is that when Slideshow initially starts, even though it is set to show random order of slides (~100 nodes linking via Views), the first slide is always the same and it is shown in a bit glitched way - it does not works as a link, it is shown for shorter amount of seconds and in general does look like it is shown while all the rest of slideshow is loading. Starting from the second slide the order is random and it works perfectly. It can also be recreated in case of page refresh - if you refresh the page in any browser you may get the same result no matter of what browser you use. You can check it here http://www.scanorama.lt (the main slider part).

I have searched for this issue registered at Drupal issue queue, but it looks like that there is none.

Any ideas, what could be the reason for such glitch?

It appears as if your slides are always appearing in the same order in the source code.

Are you sure that the order in your view is set to random?

i.e
SORT CRITERIA,
Global: Random (asc)

nothing else.

Also I would really recommend not having that many nodes in your slideshow as It creates an insane amount of html markup which is not great for a number of reasons and performance will really take a hit. 5 or less slides would be ideal I would say about 10 should be an absolute maximum.


Modify how Drupal builds fields on a per form basis I want to change the way Drupal builds specific fields on a specific node edit/add form on my site. For example, when I use print drupal_render($form['textarea']); in my node--CONTENTTYPE--form.tpl.php file, I get the default Drupal render of the field widget. I want to modify the HTML markup of the field widget.

There are three ways I can think of that might solve this problem:

Using a forms equivalent of the theme_field() hook. This seems ideal, but after searching for the last few hours, I haven't found anything on this.
Building custom field widgets for every field type I'm using on that node. This is definitely not ideal and I have to believe there's an easy way to do this in Drupal from a theme point of view.
Manually build the HTML markup for the form and field in node--CONTENTTYPE--form.tpl.php with print $form['textarea']['und'][0]['title']; and the like.

Is there a hook in Drupal to do this, or must the code for every field I want to modify be manually generated?

I think your third option is the most direct solution since you are only looking to change one form and that file will only be called when you use that form.

The only alternative I can think of is to use hook_form_FORM_ID_alter and iterate through the form items, putting html into the #prefix and #suffix values; or creating #attribute['class'] or #attribute['style'] values depending on what you are trying to achieve.


Get programmatically value of sub field collection item of a field collection I have a field collection

field library

and a sub field collection

field book

which has a  field collection item field title.

to get the first field collection I use a wrapper:

$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_library->value() as $key =>
$field_collection_wrapper) {
$ffp = $field_collection_wrapper->field_title[LANGUAGE_NONE][0]['value'];
}

but I need another for each inside the first foreach to get the item of the sub collection.
How should I do it?

I think this should be structured properly. It should give you access to each book on each library item.

$node_wrapper = entity_metadata_wrapper('node', $node);
$libraries = $node_wrapper->field_library->value();
foreach($libraries as $library){
  $library_wrapper = entity_metadata_wrapper('field_collection_item', $library);
  $books = $library_wrapper->field_book->value();
  foreach($books as $book){
    $book_wrapper = entity_metadata_wrapper('field_collection_item', $book);
    $title = $book_wrapper->field_title->value();
  }
}


node_type_get_type() and hook_uninstall() I have a job_post module, which defines the "job_post" content type.

In this module I have hook_unistall() which calls node_type_delete() to remove that content type.

After uninstalling, I have the following error from the Comment module:

  Notice: Trying to get property of non-object in comment_node_type_delete() (line 343 of ....\comment.module).

I have this error because the $info variable in node_type_delete() is set to FALSE.

Why when my module is installed and when I am printing var_dump(node_type_get_type('job_post')) on any page, I have an object, but when I'm trying to print the same code in my unistall function I get FALSE and this error?

job_post.install

/**
 * Implements hook_install().
 */
function job_post_install() {
  node_types_rebuild();

  $types = node_type_get_types();
  node_add_body_field($types['job_post']);

  $body_instance = field_info_instance('node', 'body', 'job_post');
  $body_instance['type'] = 'text_summary_or_trimmed';

  field_update_instance($body_instance);
}

/**
 * Implements hook_uninstall().
 */
function job_post_uninstall() {
  $instances = field_info_instances('node', 'job_post');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }

  // Force rebuild of the node type cache
  // as Clive suggested didn't help
  // _node_types_build(TRUE);

  node_type_delete('job_post');

  field_purge_batch(1000);
}

job_post.module

/**
 * Implements hook_node_info() to provide our job_post type.
 */
function job_post_node_info() {
  return array(
    'job_post' => array(
      'name' => t('Job Post'),
      'base' => 'job_post',
      'description' => t('Use this content type to post a job.'),
      'has_title' => TRUE,
      'title_label' => t('Job Title'),
      'help' => t('Enter the job title and job description')
    )
  );
}

/**
 * Implement hook_form() with the standard default form.
 */
function job_post_form($node, $form_state) {
  return node_content_form($node, $form_state);
}

If you look at the code that the Forum module executes in forum_uninstall(), you will notice that it just deletes the field it defines, but it doesn't delete the content type it defines.

function forum_uninstall() {
  // Load the dependent Taxonomy module, in case it has been disabled.
  drupal_load('module', 'taxonomy');

  variable_del('forum_containers');
  variable_del('forum_hot_topic');
  variable_del('forum_per_page');
  variable_del('forum_order');
  variable_del('forum_block_num_active');
  variable_del('forum_block_num_new');
  variable_del('node_options_forum');

  field_delete_field('taxonomy_forums');
  // Purge field data now to allow taxonomy module to be uninstalled
  // if this is the only field remaining.
  field_purge_batch(10);
}

Your module should do the same, and avoid deleting the fields defined for the content type (if they are not defined from the module), or the content type itself.


Correct way to create Departments/Categories cck selectors in Drupal 7? 1. My Scenario:

I'm building a shopping cart and using Ubercart+Drupal 7 for it.

Manufacturers will be able to log in and create their own products with

Product attributes {Name, SKU, price etc}
Department + Category - can be multiple
a brand

A product can exist in multiple Department/Categories too.

Sample screenshot:
http://picpaste.com/pics/menu.1375842751.png
(wanted to post here but low reputation, can an admin post it here pls?)

2. Elaboration of the situation

I'm having trouble figuring out the most correct, stable and fastest way to set up Department/Categories with the following goals and criteria:

2i. Product - CCK fields for adding Department, Categories to product:

Select a department, and it's associated category (Dep+Cat)
There are going to be about 12 Deps, 15 Cats each = 180 categories. I do not want to list this as an entire taxonomy dropdown - confusing and ugly. My thought right now is to have two multi-select boxes side by side - "Department" with 12 items & "Category". To illustrate, here's a simple wireframe: http://picpaste.com/Add_dept_cat.png
As per the wireframe, manufacturers can list the product in multiple related departments and categories.

2ii. Add / Create + Add brand to product
 - Add an existing brand to the product
 - If brand doesn't exist, add a new brand and add it to the product
 - Brands are attached to the manufacturers who created them

2iii. I'm searching and finding modules such as taxonomy_menu, taxonomy_hierarchy and content_taxonomy. However a lot of them look like they are not stable or supported for Drupal 7. Even if they are ok, I'm not sure if I'm heading in the right direction by using these modules.

2iv. Shoppers (Authenticated users) should be able to see the main menu on top which actually lists the departments available. On hovering, a particular department's categories & brands within are shown. They can click a department from the menu or drill down to category or brand. On selecting one of these three, the product listing comes up -- if department, shows department items, allowing filtering by brand/category -- if category selected, e.g "moisturisers", shows all items and allows filtering by brand --- if brand selected, shows all items for that brand in this department / category, allows you to move up and see all items for the brand in this department, and in other departments..

3. Question

Having said all that, my question is more to do with the CCK input fields of department, categories & brands and the underlying taxonomy / menu structures and modules. For 2iii, any tips are welcome, but I'm not at that stage yet anyways so I'm not looking at that yet.

I'm having trouble with

how I should structure my data in taxonomies or other structures (menus?)
how to create the cck fields for the manufacturer to add multiple department / categories to his product
how he can add a brand to his product or create and add a new brand to his product

Ideally I want to achieve the above with modules in the most Drupal-correct, stable and fastest way possible, without having to write any code.

Thanks

Edit: one more question. If user adds multiple "Department-category" to a product, how to allow one of it to be the "main"?

Your concern is true. Anyone that tried to build an eshop with multiple categories had the same question in the beggining.

  1) how I should structure my data in taxonomies or other structures (menus?)

You can create a large taxonomy tree the way I see it on the screenshot. Use taxonomy_manager for better UI. Also to display the taxonomy trees as mega menus you can search for "mega menu" in the drupalmodules.com you will find many such modules.

  2) how to create the cck fields for the manufacturer to add multiple department / categories to his product

You can use the Hierarchical_select module. It is a must for such functionality.

  3) how he can add a brand to his product or create and add a new brand to his product

Create a new Vocabulary for Brands and add a field with autocomplete. You can use Hierarchical Select also. It has an option (with proper permissions) to add a term if it does not exist.


Any success using Vagrant + Samba for Drupal Projects? I was desperately hoping that I'd be able to mitigate the ridiculously awful performance of Drupal in our Windows + Vagrant dev environments by using Samba rather than Virtualbox shared folders, but so far I've had exactly zero success. Has anyone else succeeded? If so, anything you can share to help?

I haven't been able to get past this error when attempting to mount the network share:

  Failed to mount folders in Linux guest. This is usually because
  the "vboxsf" file system is not available. Please verify that
  the guest additions are properly installed in the guest and
  can work properly.

We're running:

Win7/Win8 host
Ubuntu 12.04 guest
Vagrant 1.6.3 + vb-guest plugin
Virtualbox 4.3.12

I've seen indications around the Google-sphere that I can SSH into the guest and do some magical symlinking, but my vagrant box is powered off when the mount fails. I can't access the box.

Help?

The git project Druphpet is doing exactly what you want to achieve.
https://github.com/alehkot/druphpet

It's using a Samba server under your guest(Ubuntu) accessible via Windows explorer: "\192.168.9.10\data"

For sure you Drupal website becomes really fast, because your webserver is accessing files locally(inside Linux)

The only problem with this approach is that every modifications of your Drupal code inside your Windows text editor (themes, custom module...) become slower because not local.

The other problem is that when the vm is off or crashed, you can't access your Drupal files anymore.


Drupal website was hacked? What is the hack that can cause my Drual website to be blank, without showing any message error.. Not be able even I enter .../users, -> blank. It was absolutely brilliantly showing fine.

If you want to see this Drupal website URL, go ahead:

http://fightforhongkongdemocracy.net

Thanks.

There is a guide on drupal.org with multiple troubleshooting methods to resolve white screens with no ouputs: https://www.drupal.org/node/482956


Is there a Node Reference URL Widget module for entity references? I just learned that there is the nice Node Reference URL Widget module.  Basically, it allows you to add a add a A link in the node view pages of content type B, if there is a node reference A->B.  When you are viewing a B node, clicking on the add a A link would lead you to the node creation page of content type A, with the A->B field populated with the B node you were just viewing.  That way the user do not need to figure out "which node B am I adding this node A to?"

Our sites mainly use Entity Reference.  Is there a module that provides similar functionality for entity references?

OK.  I see there is Entityreference prepopulate.

  Allow prepopulating any Entity reference field via URL

Going to try it now.


arbitrary order of nodequeues in a view What is the best way to arbitrary order nodequeues in a view?

Drupal 6.26
Nodequeue 2.11
Views 2.16

ended up using subqueues, was not quite what I wanted.


How do I load an external class into the Controller? I'm playing with module building in Drupal 8, but can't really figure out how to include a custom class which does not extend any other. The class' only purpose is to reduce the amount of code I have in a controller.

However, I get the error:

  Fatal error: Class 'Drupal\first\FirstClass' not found in /var/www/drupal/modules/first/src/Controller/DefaultController.php on line 30

How do I let DefaultController.php know where to find FirstClass.php? Should I just do an include_once()?

Routing file:

first.default_controller_hello:
  path: 'first/hello/{name}'
  defaults:
    _content: '\Drupal\first\Controller\DefaultController::hello'
    _title: 'first Title'
  requirements:
    _permission: 'access content'

Controller function:

namespace Drupal\first\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\first\FirstClass;

class DefaultController extends ControllerBase {

  /**
   * hello
   * @return string
   */
  public function hello($name)
  {
    $a = new \Drupal\first\FirstClass();
    dsm($a);
    return "Hello ".$name." !" . $a->getV();
  }
}

Outside Class:

<?php
namespace Drupal\first;

class FirstClass {

    public static function getV() {
        return 'well it works?';
    }
}

Drupal 8 uses a autoloader standard called PSR-4: http://www.php-fig.org/psr/psr-4/

Practically means your namespaces should result in the following directory structure

first
  - src
  --- FirstClass.php
  --- Controller
  ----- DefaultController.php
  - first.info.yml


How to handle / cleanup obsolete aggregated css / js? I'm only using Drupal 7 built in CSS / JS aggregation, however the files folder where the css.gz and js.gz files live are filling up at a fairly rapid pace, and while I'm sure it'll be a while before it starts to totally fill up the drive, nows as good a time as any to get a handle on the situation.

Current file count in /js is 335
Current file count in /css is 451

Is there any standard method I should be employing to deal with this situation? I'd prefer a solution that keeps the drupal in the loop.

Additionally, I see that many of the gz files have non-gz counterparts. Is there some reason both .css and .css.gz files are kept? Degredation maybe?

Thanks

This is actually by design so that cached pages with older versions of files don't get broken. See this closed issue.

TL;DR: They will be deleted automatically 30 days (or whatever your drupal_stale_file_threshold variable is set to) after they were created via drupal_clear_css_cache() and drupal_clear_js_cache(). So the solution is to modify the drupal_stale_file_threshold value to something lower than the default 30 days.

When are old files deleted

  Old cache files are not deleted immediately when the lookup variable is emptied, but are deleted after a set period by drupal_delete_file_if_stale(). This ensures that files referenced by a cached page will still be available.

  drupal_delete_file_if_stale() defaults to 30 days - so if a) Cron is running properly and b) you see aggregated files older than 30 days, you have a different problem.

variable_get('drupal_stale_file_threshold', 2592000) is the 30 day check.
variable_set('drupal_stale_file_threshold', 172800) would change the timeout to two days. On a site where cache handling is strictly controlled, the time could be even shorter.

Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7
See drupal_delete_file_if_stale() for more information.

Is there some reason both .css and .css.gz files are kept?

  If CSS gzip compression is enabled, clean URLs are enabled (which means that rewrite rules are working) and the zlib extension is available then create a gzipped version of this file. This file is served conditionally to browsers that accept gzip using .htaccess rules.

  Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7 (In the function comments)

Also see drupal_build_js_cache() which is nearly identical to drupal_build_css_cache().


Contextual Filters within Block Display? using d7.4

I am trying to setup a block on my node pages that will show:
View Count
Comment Count
Flag Count

My node paths are setup as:
category/categoryname/nodetitle

I know I need a Contextual Filter to link this view to the Node Title (right???) - but how do I designate a path for that within a block? I know I can name a path with a View-Page Display- but I need this to be shown inside a block, not a page.  What am I missing here?

Thanks for the reply!  This newbie appreciates it!

In the Block Display, create a contextual filter with these settings:

Content: Nid (not title)

Under "When the filter value is NOT available" check "Provide default value" then choose "content id from url"

Under "When the filter value IS available or a default is provided" check "Specify validation criteria" then choose "Basic Validator" or any other you like.


Enabling aggregate and compress CSS files caused error on site access I set this tick box in the performance area, and on clicking Save I now cannot access the site, even the performance area to disable this! any one know if I can directly change this in the DatabasE?

EDIT:
I have refreshed the Database, thankfully no updates since it went live. This does raise the question though as I'm not the only one who has had problems with these performance tick boxes, how do you back out of an error?

I would still like the answer cause i'm trying to get to the bottom of these performance settings.

thanks for any replies.

I found this from http://drupal.org/node/782510

In your settings.php file, add

$conf['preprocess_css'] = CACHE_DISABLED;

Seemed to work for me on a quick test


How can I change the delete message "This action cannot be undone." in a specific content type? I have a version drupal 6 and I need to change the next message that is shown  when I am going to delete a content:

"This action cannot be undone."

I need to change this message only for some content types, not in all.

Thanks for your help.

Try this code (it works for me - Drupal 6):

function module_change_default_messages_form_alter(&$form, $form_state, $form_id) {
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'delete') {
      $node = node_load(arg(1));
          if ($form_id == 'node_delete_confirm') {
              if($node->type == 'story'){
                $form['description'] = array('#value' => "here replace to \"this action cannot be undone\"");
              } else if($node->type == 'page'){
                $form['description'] = array('#value' => "this action cannot be undone");
              }
          }
      }
}

or you can use the PHP switch statement for more content types.


How to dpm() the Drupal.settings.basePath var For debugging purposes I need to use dpm to output the value of Drupal.settings.basePath. I tried this (but not working):

dpm(Drupal.settings.basePath); // not working

Drupal.settings.basePath is a javascript variable, not PHP...you can't access it on the server side like that.

I imagine the output you're getting in the message area is 'DrupalsettingsbasePath', which is how PHP would interpret Drupal.settings.basePath, along with a few PHP Notices complaining about the use of an undefined constant.

Assuming you're using a browser that supports console.log, to debug the base path just add the following in a javascript file that's included in your page:

console.log(Drupal.settings.basePath);

The variable will then be printed to your browser's console area.


Getting rid of personal blogs I am using the built in blog module with Drupal 7, and I don't like the fact that "Every user gets a personal blog."

For instance, if a user with administrative privileges (Joe Schmoe from our company) makes a blog entry, within the blog entry, you will see a link for "view Joe Schmoe's blog." I would much rather it say "view (company name here)'s blog" or show nothing at all.

Unfortunately, I cannot find any settings for this. Is it possible to disable this feature or get this feature to work the way I would like?

You can alter the title of the link using hook_node_view_alter in a custom module.

For example

function MY_MODULE_node_view_alter(&$build) {
  // dpm($build['links']['node']['#links']);
  $build['links']['node']['#links']['personal_blog']['title'] = t('view company blog');
}

You will have to use some logic to only apply the link to a certain user etc.

I'm not sure about the actual link concerned so if you have devel installed, uncomment the dpm() part and inspect the array to find the correct link.


Send daily automated mails to specific roles programmatically I'm working on a D8 project and I want to send every day an automated mail to all users with a specific role, lets say 'custom admin'. The mail should contain the results of a database query.

Rules module is not complete yet so I was thinking to use hook_cron.

Is this the right approach or is there a better way to achieve this?

Thank you in advance for any help/idea.

Yes! hook_cron is a good approach. Of course, you also will have to set up the server cron, which will trigger the Drupal one. Or at least that's the cleanest solution.

Here you can read how to configure cron.

If you don't use an OS cron to trigger, the following use case may appear.
You set the Drupal cron to run each day at 00:00.

But nobody is browsing the site at 00:00. The next user will come at 6:54 in the morning. By the request the cron will know: oh.. it's 6:54, I should have run the cron at 00:00, so I will run it now.

If the subscribed modules have heavy processes on going, the request for the user could be slow. There is your module, which sending emails (not a big deal) but also the Drupal garbage collector (temporary files, abounded fields etc..) may run by this time.
If this is the first extra cron hook of your site: don't mind it. It won't change much.


Bootstrap: Responsive tables with WYSIWYG text format I use WYSIWYG  as text format and inserted tables under the filed using MYSIWYG are not responsive and make the site unresponsive.

It looks really bad in mobile phones.

Website without table:

Website with table:

Things I tried so far and didn't work:

Zurb responsive tables
Responsive Tables Filter
Responsive Tables
After adding table with WYSIWYG I changed the text format to Full HTML and didn't work

Option 1: Use Responsive Tables
To have more control over table columns, use the Responsive Tables module. Some details about it (rom its project page):

Adds a library to allow tables to function better in responsive layouts.
You can manually add the library to any table on the site. You also have the option of using the Better Views Tables module to configure the responsive table controls through the Views UI.

Option 2: Use a responsive theme
You should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "is designed from the ground up as a mobile-first responsive theme". However that has like 5 module dependencies ...
For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.


Am I able to populate an entity form text field with a value from a URL link on an external site I am trying to pass a url variable from an external 3rd party site and have that variable populate an entity form text field that I have on an entity form on my company's website.

Basically we have a "Request for Information" form on our drupal site that people can come to and fill out. We have some 3rd party companies that have links to our form on their websites. We are trying to be able to track which website the person filling out the form came from so we want to add a url variable to the links on their websites so that when a user clicks on the link on their site that it takes the url variable from that link and places it in a hidden field on our drupal entity form.

Is this at all possible?

Yes. Checkout the Field default token module. It lets you substitute tokens in place of a field's default value. In your case you want to use [current-page:query:var] for your field's default value. This will let you send someone to the URL http://example.com/my_entity_form?var=DEFAULT which will pre populate the field with DEFAULT.


How do I modify the query parameters? I want to modify query parameters used when accessing a Drupal page. I tried implementing hook_url_inbound_alter(), but it only allows to parse/modify the path, and it doesn't allow any interaction with the query string.

I see there is also drupal_get_query_parameters(), which allows to read the query parameters.

I could detect the presence of a query value in index.php and do a string replacement on the value if needed, but I don't want to pollute the front controller.

Do you have any better advice?

1) you need to implement EventSubscriber, use KernelEvents::REQUEST in getSubscribedEvents() method

2) then you use \Drupal::request()->query->set('key', 'value');


Build something like open atrium I just installed open atrium and was amazed how it works and how its made. It is made to work with just some clicks while installation. I want to build something like this. I just want to pre configure just blogs, gallery and forums and with some groups. Installation profile knowledge i need. what else should i know properly so as to build such a thing.

You're going to want to understand the relationship between Organic Groups, Spaces, Context, Features and possibility the Persistent URL and Strongarm modules. Aside from Organic Groups, they were all created by the same developer who started Open Atrium.

Here is one very basic run-through about how Open Atrium works.

Here is a description of how each of those modules factor into the OA structure.

Be warned: I don't think I've seen a more complex site built with Drupal. Most of those modules are not only complex, but also genius.


Improving template/rendering performance I'm running a Drupal commerce site and using Views to display up to 30  product node teasers per page.  The product display content type has a several fields (image, desc, manufacturer) and I am also using the flag module so that users can mark favorite products. As a result, the query ends up being fairly large with several joins.

Views statistics reveal that despite the complex query, the slow page loads are due to the rendering time it takes...

Query build time    21.13 ms
Query execute time  1.67 ms
View render time    4237.2 ms

How do I improve my Drupal template/rendering performance to get my pages to load faster?

I would check for File IO; what does profiling your site tell you. I had similar issues and created the http://drupal.org/project/imageinfo_cache module and my views performance improved a lot by reducing file IO.

Seeing that your on shared hosing, checkout this http://kpayne.me/2012/02/04/use-register_tick_function-to-profile-your-code/


create ftp connection using drupal I have made my own module, that has a form where the user can upload a file.
Once the file has been collected, Drupal should open an FTP connection to a server and upload the file into it.
I have found "Storage API" and "Media Move" modules that seems to have this kind of functionality, but I have no clue on how use those modules with my custom code.
How do I make an FTP connection from Drupal to an external server and upload the file?

cURL ist the perfect library for this. It's available on most PHP servers. Check this for an example.


Smart Paging Clean url redirects to Queried strings automatically I just use Smart Paging module and it works great. Except one thing, when I click on next link, next page clean url is automatically redirected to queried string url.

Like xyz.com/some-url.html/p/0/1 to xyz.com/some-url.html?page=0%2C1

I'm not able to figure out the reason for this.

Can you please help?

Thanks.

Issue was with Global Redirect Module. Patch here https://www.drupal.org/node/1843500#comment-7535655 works, testing it on development site for now.


Making images go to external sites in Slick carousel I have a custom content type which collects one image and one URL per node. I have the Slick module along with Views set up to cycle through these images on the home page. I haven't been able to make the carousel images link to the external URLs. In Views I have this:

In the Global: Custom text field, I have this:
{{ field_library_photo }}
It's not using that markup. What's most confusing is that the images are displaying in the carousel. I have the photo field hidden and Drupal isn't using the custom text so I don't know how those images are being accessed.
What step have I missed to make this work? Thanks!

I found the solution. In the Slick settings, I set the Link to the custom text field. For most of the time I've been working on this that field did not show up in the Link dropdown. But suddenly it did.

At first it's misleading because the Views preview shows the original image with the smaller linked image overlaid. However, if you go back to where the block is placed, the images will appear correctly. Whew!


How to remove a region from omega grid I need to have a full screen image carousel and I'm using a sub theme of omega.

Ideally, I'd like to render the image through a custom module which I have put in the branding region.  Because the images needs to be full width I need to render the branding region outside the grid.

What's the best way to go about removing the branding region from the grid and rendering it outside?

Thanks,

This is actually pretty complicated.  The major problem is that both the region and the zone that it is in have the grid classes on them.

You need to implement a template_process_zone() in your theme, and then remove the grid classes from $variables["content_attributes_array"]["class"].  You then need to implement a template_process_region() and remove them from $variables["classes_array"].

Any other regions in that zone will then have grid problems, and the containing zone won't have a grid container definition.

Your other option is to use CSS to override the grid definitions for the zone and region.  Depending on your site and the theme, you may be able to get away with using a full zone wrapper around things, and then using positioning on the region to make it appear full width.


JQuery FadeIn effect and Omega Theme I am trying to use the fade in effect in Drupal when I load a page.

In my Omega sub-theme I have included the following line in its .info file.

scripts[] = '/js/custom.js'

In the script, I have included the following code.

$(document).ready(function() {

$("body").css("display", "none");
$("body").fadeIn(2000);

});

If I load the page, I see no effect at all, but I clearly see that my JavaScript is in the header.

<script type="text/javascript" src="http://localhost/innodru/sites/all/themes/CHILDTHEME/js/custom.js?m2zpiw"></script>

I have cleaned the cache and tried a lot of things, but it does not look like is working.
I am using Drupal 7.

You should not be using document.ready. Instead you should use drupal behaviors. Even though document.ready will work. Behaviors is the drupal 7 way to do things as these behaviors get called after ajax calls too.

css

body {display:none;}

javascript

(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                    $('body', $context).once().fadeIn(2000);
            }
    };
})(jQuery);

And FYI
Omega adds a 'responsivelayout' event that will get fired every time the layout is set/changed including when the page loads so you could potentially make the page display straight away on mobiles and fade in on others.

(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                $('body', context).bind('responsivelayout', function(e) {
                    if($('body', context).hasClass('responsive-layout-mobile')){
                            $('body').once().show();
                    }else{
                            $('body').once().fadeIn(2000);
                    }
                });
            }
    };
})(jQuery);

I have not tested the code BTW, but you get the idea