Drush isn't bootstrapping drush script I can't get drush to bootstrap my script. I'm using version 5.9.

Below is my test script (test.drush):

#!/usr/bin/env drush

$site = drush_sitealias_get_record('@site1');
_drush_sitealias_print_record($site);

$result=drush_invoke('core-status');
drush_print($result['output']);

while ($arg = drush_shift()) {
  drush_print($arg);
}

And I have the aliases defined in ~/.drush/aliases.drushrc.php (see end of post).

When I run test.drush @site1 it doesn't bootstrap the script with site1. It has access to the alias because it can output the site record. Also it outputs @site1 as an argument. It should remove @site1 from the argument list and bootstrap it but it doesn't.

Below is the output:

$aliases['site1.local'] = array (
  'root' => '/Users/mark/Documents/drupal6',
  'uri' => 'http://site1.local',
  '#file' => '/Users/mark/.drush/aliases.drushrc.php',
);

 PHP configuration     :  /private/etc/php.ini
 Drush version         :  5.9
 Drush configuration   :
 Drush alias files     :  /Users/mark/.drush/aliases.drushrc.php

@site1

BTW running drush @site1 status on the command line works fine

Also, is there any way to change the current site in a script. When I use:

drush_invoke('use', '@site2')
$result=drush_invoke('core-status');
drush_print($result['output']);

it doesn't apply to the subsequent drush commands but it does the next time you run the script.

aliases.drushrc.php:

$aliases['site1'] = array(
  'root' => '/Users/mark/Documents/drupal6',
  'uri' => 'http://site1.local',
  'db-url' => 'mysql://user:password@127.0.0.1/site1'
);

$aliases['site2']=array(
  'root'=>'/Users/mark/Documents/drupal7',
  'uri'=>'http://site2.local',
  'db-url'=>'mysql://user:password@127.0.0.1/site2'
);

Drush shell scripts such as the one you show above do not automatically bootstrap to any argument passed to them.  (EDIT: This is due to a bug.)  You have a few options.

1: Force the bootstrap:

$site = drush_shift();
drush_bootstrap_max_to_sitealias($site);
drush_invoke('core-status');

2: Do all of your work in a subshell:

$values = drush_invoke_process($site, 'core-status');

Those two should get you started.  Note that option number two will re-bootstrap Drupal in an isolated subshell every time you call drush_invoke_process.  drush_invoke always works on the currently-bootstrapped site, and you can only bootstrap once.  Therefore, that drush_invoke('use', ...) trick won't work.  'use' is only for use in the shell, not in scripts.

There's another error above.  This code isn't working as you expect it is:

$result=drush_invoke('core-status');
drush_print($result['output']);

What's really happening here is that drush_invoke is printing the output of drush status to stdout, and drush_print is printing nothing.  You'll get $result['output'] if you use drush_invoke_process.

In my somewhat biased opinion, the Drush chapter of the Definitive Guide To Drupal 7 covers these topics pretty well.  It is available for download as a free sample chapter at http://definitivedrupal.org/book/26-drush


hreflang links added to page source without translation When Interface Translation module is enabled in Drupal 8, I get hreflang links to ALL languages on the site for every page view sourse, no matter if the content is translated or not.

If alternate hrefland is active on all of the pages, even untranslated ones, it creates some SEO problems.

I want to remove these links. Is any Drupal way to do this?

These are added via a hook_page_attachments() implementation in content_translations.module. The code looks like it should not add any hrefs unless an entity translation has been created.

Some tests on my site seem to indicate that this is working correctly.  Do you have another module that is trying to add these and doing it incorrectly?

That said, you should be able to implement a hook_page_attachments() function (in something with a execution weight that runs after the content code).  In this look at the $page['#attached']['html_head_link'] array for the items to remove.


Unable to view Taxonomy term page: Access denied I am unable to view/see any Taxonomy term page in the front (Access denied).

I can edit Taxonomy in the admin backend.

Example:

http://localhost/{Taxonomy-group}/car

Result:

Page "Access denied - You are not authorized to access this page."

Setup

Alias URL (Taxonomy term paths)

Default path pattern (applies to all vocabularies with blank patterns below)
[term:vocabulary]/[term:name]

Tried but didn't work

Clear cache
Rebuild permissions
Update alias

Does anyone have any idea how to fix this issue?

Check out the Access Denied Backtrace module.


Feeds mapping to Entity ref by Entity ID not working I’ve created a Feeds importer for a commerce product variation type. The product type is a commerce mp3 file. In it’s content type the mp3 refers to an album product. So in the Feeds mapping there is a target that reads ‘Album reference (Entity reference by Entity ID)’.

so far nothing has worked to get the mp3 product to refer correctly to it’s album reference. The album btw, is also a commerce product.

In my latest test example, the album name is ‘So Open’. I confess i’m not clear exactly on what an Entity ID is?! In looking at the Album on it’s Devel page i see the vid and nid are both 626.

my attempts have include the following:
’So Open’ -> error,
So Open (no quotes) -> error
626.

This latter 626 does not generate an error but also does not populate the field correctly once the product is created. That ref. is simply left blank.

Perhaps the problem is I don’t understand what an Entity ID really is.

Does anyone know what i should be putting there? and how to find out that product’s Entity ID?

Might be important: Are the product displays (the albums) already in the site or are you importing those as well?

Entity IDs are generic unique identification numbers that entities use to reference each other. Nodes are a certain kind of entity and their id is "Node ID" but you are looking for the Product ID, which, Kickstart 2 does a really good job of hiding from the site builder. Try going to admin/commerce/products/variations to see all your products and when you click edit on one, the number in the url is your entity id for that product.

So, when you create an album with mp3s, the structure looks like this:

Album (node id: 123)
  |__ commerce_product (field), Value: 23,24,25

MP3-1 (product id: 23)
MP3-2 (product id: 24)
MP3-3 (product id: 25)

All of the "id"s are entity ids.

Regardless, you can use the entity field query finder function of the feeds_tamper module to locate an entity reference while importing a CSV using Feeds.


How to load absolute CSS and JS assets I would like to load CSS and JS from https://static.example.com . The typical page contains:

<link rel="stylesheet" href="/sites/default/files/css/css__wBfhyL83sORKzo__AgHv4HOGuOoSbIzIaa4clq9PXs.css?pik02l" media="all" />

and contains similar entries for JS.  I would like to add https://static.example.com to the front of the href="URL" for both CSS and JS.

I'm am aware that this can be done with a contrib module.  I would like to find a hook or some other way to add this to my custom module.

Even though you don't want to use a contrib module I will recommend the CDN module anyways. It does what you want, but if you don't want to use it you can still look at how they do it.

They define a lot of services, but the most interesting one is this one:

cdn.file_url_generator:
    class: Drupal\cdn\File\FileUrlGenerator
    arguments: ['@app.root', '@file_system', '@stream_wrapper_manager', '@request_stack', '@private_key', '@cdn.settings']

The class FileUrlGenerator then does checks for files to determine if they should be rewritten and rewrites them.


Add class in panels region I am trying this for long time. I am trying to add additional class in panels region. I am using panel page to display one of my node. I want to add region class but I am not getting success. Is there any way to achieve this? Is it possible to rewrite layout template in my theme? If so I can achieve this quickly. For example I wonder if it is possible to override layout template based on my node content type.

Thanks a lot.

You can create custom layouts in your theme for panels, there's a fairly good how to guide here: https://drupal.org/node/495654

If you wanted to use different layouts for different nodes, you can add a variant to your panel pages, and under "selection rules, select "node:type" and select the content type you want. Then you can assign different panels layouts to each respective variant under the layout tab.


Give permission to dealer_user_role to create users and profile2 fields I have situation as follows:

I have three types/roles of users.

AdminRole
Dealer Role
CustomerRole

I have given permission to "Dealer Role" to create/add "Customer Role" user.
That works fine for me.

But my daunting task is as follows:

I am using "Profile2" module for "Customer Role" user.

I have created one profile_type in Profile2 module in which 6 fields are there with separate page for editing profiles page.

Also i have enabled UNIQUE REGISTRATION Path.

Although i have access to the unique registration path when none of the user is logged in system and administrator is log-in.

I want to give "Profile2" module permission in a way that "Dealer Role" having permission to create/add data to the "Customer Role".

In simple, when "Dealer Role" is logged in system, dealer can manage "Customer Role" user.

Thanks
Same

global $user;

$uid = $user->uid;

$accessRoleArr = '';

if(in_array('Admin',$user->roles) || in_array('Dealer',$user->roles) || in_array('Customer',$user->roles))

{ return FALSE; }


How to display User profile fields to anonymous visitors? Currently I am developing an application in Drupal 7 , and my requirement is to display User profiles(profile image,DOB,Course,Year of joining etc.,) to anonymous users . I have used profile2 module to store them in the Database. The same information I wanted to display when a visitor clicks any of the User link. But i stuck in this part.

Please assist me in solving this...!

Thanks in advance
-Syam Kumar

Normally this is simply done within the permissions admin section (/admin/people/permissions if I remember right). Simply give anon users the permission to view profiles and those fields.

Maybe the module you are using causes the fields to be hidden. Check the permissions of that module as well.


Commerce 2.x Taxes missing I installed commerce 2.x and all seemed well. I have recently noticed there's no sign of any settings to configure taxes. When first setting up a store the taxes section (see image) wasn't visible as an option.  My "vendor/commerceguys" folder contains zone, intl, enum and addressing.

Do I have to run the composer command "composer require "drupal/tax"" or something? To install commerce in the first place I ran "composer create-project drupalcommerce/project-base mystore --stability dev" as instructed on the drupal commerce site so puzzled no tax setting are available? Also where does composer manager come into it, is this something I need to proceed?

Thanks for any help

Short answer: Taxes doesn't exist.

Longer answer:
Taxes have not yet been implemented for Drupal commerce 2.x. You can follow along in the issue queue, git or IRC if you want to track the progress.

One of the relevant issue would be Tax data model.


How to place size of file in the node in the title? I want create page for issues of newspaper. Title of the issue page must contain the issue number, date of publishing and size of newspaper file in MB.

I implemented number and date in title with Automatic Entity Labels and Token modules. But how I can place in title size of the uploaded file?

I tried to use custom module:

/**
* Implements hook_token_info().
*/
function mytokens_token_info() {
$node_tokens['field_file']['size'] = array(
  'name' => t('File size'),
  'description' => t('File size'),
);
$node_tokens['field_file']['size']['mbytes'] = array(
  'name' => t('In MB'),
  'description' => t('File size in MB'),
);
return array(
  'tokens' => array(
  'node' => $node_tokens,
  ),
);
}

/**
 * Implements hook_tokens().
 */
function mytokens_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();

if ($type == 'node' && !empty($data['node'])) {
$node = $data['node'];

foreach ($tokens as $name => $original) {
  if ($name == 'mbytes') {
    $replacements[$original] = $node->field_file['und'][0]['filesize']/(1024*1024);
  }
}
}

  return $replacements;
}

But my tokens don't shows in the token tree and nothing replacements occur.

Install Token and you can use [file:size] in your title to fetch file size. Here is the list of all file tokens you can choose from.


Multilingual Breadcrumb I need to show a breadcrumb on my client website but it is required to be in two languages I have tried several approaches and modules but all of it show the breadcrumb in one language only.

Please, If anyone have an idea about this I appreciate your help.

Besides, Could you please explain more about using default drupal breadcrumb what should I have been installed to use breadcrumb correctly? Do I need breadcrumb + another module ???

Regards,

Assuming you want your breadcrumbs like this:

  Home/La Casa >> Node/Nodo >> Friends/Amigos

You could override template_preprocess_breadcrumb like so:

  function MY_THEME_preprocess_breadcrumb(&$variables)
  {
     $breadcrumbs = &$variables['breadcrumb'];
     foreach($breadcrumbs as &$breadcrumb)
     {
         $breadcrumb .= '/' . locale($breadcrumb, null, 'SP');
     }
   }

Don't quote me on the langcodes, and this would require that you have the locale module installed and enabled, but it should output the above example breadcrumb.


How to add prefix (label) and postfix to commerce price field I am trying to implement Drupal Commerce in an existing site with existing nodes. In this process I need to replace the existing price field with the commerce price field. Since this field is locked, I cannot change the label.

So I thought I could use the raw price format and just add a prefix as a label in template.php or possibly in a hook in *.tpl.php file. But after spending hours googling without finding how to do this, I give up and post this question here. Anybody got an idea?

I'm not 100% that I understand your question correctly but I assume you need to add prefix & suffix to your commerce product prices. In that case, Drupal Commerce Extra Price Formatters does exactly that, have you tried using this module?


Create fields programmatically via content type settings I want to make a module to create custom fields to a content type. But I want to be able to turn the fields on and off via the content type edit page.

So I want to add a tab to the vertical tab part at the bottom of the content type edit page where I have a single on off checkbox. When selected and saved, fields are created. When not selected the fields will be removed (or not created).

I created the option in the node type form. By using this:

function HOOK_form_node_type_form_alter(&$form, &$form_state){
$form['new_option'] = array(
    '#type' => 'details',
    '#title' => t('NEW OPTION'),
    '#group' => 'additional_settings',
);

$form['new_option']['new_option_options'] = array(
    '#type' => 'checkbox',
    '#title' => t('Create fields'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => 10,
);
}

But how can I save the value of the checkbox in config and use it as default_value.

Thanks Clive, I ended up using the following code to set and get the config settings.

function module_name_form_node_type_form_alter(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //create vertical tab
    $form['new_option'] = array(
        '#type' => 'details',
        '#title' => t('New option'),
        '#group' => 'additional_settings',
    );

    //add checkbox to vertical tab
    $form['new_option']['new_option_options'] = array(
        '#type' => 'checkbox',
        '#title' => t('New option checkbox'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#default_value' => $node_type->getThirdPartySetting('new_option','new_option_options'),
    );

    //create submit handler
    $form['actions']['submit']['#submit'][] = 'module_name_form_submit';
}

function module_name_form_submit(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //set checkbox value to config and save
    $node_type->setThirdPartySetting('new_option','new_option_options',$form['new_option']['new_option_options']['#value']);
    $node_type->save();

   //enable/disable fields
}


Embedded nodes and views Let's say I have a general content type called "Zoo". A Zoo may have several animals (animals will have a title, image, and description). Now at first, it may seem like I should just have an "Animal" content type and then somehow relate them, but all animals are unique to the zoo. (If two zoos contain a tiger, they will be completely distinct tigers, with their own images/titles/descriptions).

I have a view (already working), that lists the animals. I'd like for the animal titles to link to a page where the animal information (image/title/description) is available.

Because each image (animal) needs it's own respective title and description, and a Zoo may have several images (animals), I've tried to find a way to relate the information, since simply adding fields to the Zoo content type is fruitless.

The closest module I've found is Field Collections, and I'm technically able to reference the information correctly. The problem I'm having with it is, in the view list, I can't figure out how to show the titles of the animals and have them link to somewhere useful.

This "useful" place they link to is what I referred to previously, somewhere with the animal's information (image/title/description).

I know this example seems a little convoluted, and almost like I should use the node reference module. But the real use case requires not having to make separate nodes in separate areas and relating them, but rather making all of them at one time.

I would advise node References and Entity Views Attachment

Create 2 content types: 1) Zoo - 2) Animals
Animals has a "Node reference" to a Zoo
Create 2 views: 1) Zoo - 2) Animals -  Attach entity contents by relating them and contextual filters on nid

This way you can create Zoo pages [node] with all the animals in the zoo
On the animal pages [node], you can show which zoo(s) the animal belongs

You can also create pretty overview [views] pages


How to download file by clicking on icon in file module? I have a File field in drupal 7 (with file module) which I forced with views to display as an icon and name of the file which uploaded. The Name displays as a link (to download file). Now I want to link the icon to the file too. So when users click on the icon they would be available to download file (and I prefer to exclude the name from display).
What should I do now to make the icon as a download link?
Thanks.

I guess the problem is that 'html' in $options is set to FALSE by default, thus stripping the icon html code generated by theme().

I tried modifying a bit the code above and it worked perfectly:

/**
 * Implements theme_file_link().
 */
function yourtheme_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' =>     $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Updating 'html' to TRUE so that the html code to display the icon is     printed
  $options += array(
    'html' => TRUE,
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '' . l($icon, $url, $options) . ' ' .     l($link_text, $url, $options) . '';
}

Note that I added 3 lines (plus a commented line, 4) to update the value of HTML.


Keep info in one place to be use in several locations As per title, what is the best practice, say if i want to save/keep info such as details of the website in one place so that when i want to change something i dont have to go thru every pages/blocks to amend it.

For example : company phone number.

Right now i have it in footer and contact page. Is there a way to change it so that every place that have the phone number will automatically change too?

There really isn't a best practice. I'd say it depends on the intent and what part of Drupal's CMS functions best fit your scenario. For example:

Is it a part of distributed theme template? It could be a theme settings.
Is it a part of functional application logic? It could be a variable added to a site configuration form.

For most practical purposes of boilerplate phone info in a footer, I'd think most people would go for block with a region placed in the theme's footer, but Drupal is flexible by design so you could see alternative decisions depending on the intent.


Hide the actual location of a node on Views with GMap Module What I'm trying to achieve is to hide the actual location of a node, either by replacing the marker with a circle, overlaying or inserting a radius(circle) around the actual location. Tried to do this with the help of macro builder but it doesn't accept replacement patterns in order to send the coordinates to the circle macro.

Any help is welcome, thanks in advance

Resolved the issue by adding a marker in a circle format, setting maxzoom and clearing all cache.


How to disable Commerce, but still have the module for later use? So I have a client that needs the ability to have a store without the actual eCommerce right now. Later, the client will enable the checkout/payment features of Commerce and run it like normal. So basically:

1) Client still needs the catalog, create products, show products and pricing, etc.
2) A customer can't actually purchase anything, there is no cart, you can't checkout, etc.

Is it as easy as disabling the cart submodule? Or would hiding the add to cart buttons and requiring higher levels of auth to view /cart? I've thought of both but don't know what would be foolproof.

I know I can just create custom content types that will do the same thing as creating products, but I know in about six months or so they want to turn the ecommerce on and I don't really want to have to convert everything to products and do all the work then. I'd like to just create the products normally right now and just flip a switch later.

Drupal modules in general can be disabled and uninstalled without major problems. Last version of Drupal Commerce (1.5) includes 20 modules, and some of them are totally independent. You definitely can disable Cart and Cart UI modules without disabling others such as the Product and Tax modules.

However, there is an important bug in Drupal Commerce relevant to re-enabling modules that it's still not fixed. See http://drupal.org/node/1361562


Link to anchor on current page with smooth scroll I have smooth scrolling working (https://drupal.org/project/scroll_to_destination_anchors) and I have linking to anchors working (https://drupal.org/project/menu_token) but I can't get my desired result of clicking a menu item and then scrolling to the anchor. I only need this to work on the current page - if the anchor is on another page, I am ok with the menu item loading the other page and jumping (not scrolling) to that anchor.

Do you have any idea?

Solved by using the Void Menu module and using the id of the anchor as one of the void options.

For example, my menu item says "<void2>" where void2 contains the id of the div "#aboutus".


Does db_query and db_insert escape input values? prevent sql injection? I've been reading through the documentation, but I feel like it's always a little bit vague on this, perhaps I'm missing something.

function foomodule_my_hook_menu_callback($unescapedUserInputString) {
    $sql = "select name from {foo_table} where bar=:inputString";
    $result = db_query($sql, array(':inputString' => $unescapedUserInputString));
}

Is the above code vulnerable to an SQL injection attack? Or will :inputString get appropriately escaped to make it safe for SQL? (I know I need to sanitize it for proper values in my implementation, but I'm just referring to the SQL safety)

What about with db_insert()?

$insert_id = db_insert('foo_table')
                ->fields(array(
                    'name' => $unescapedUserInputString,
                ))
                ->execute();

these functions are abstractions on top of php's PDO library. They are essentially prepared sql statements ... passed values to the query are safe from SQL-injection.

Feel free to jump into the PHP PDO Manual.

EDIT:

eg,

  Many of the more mature databases support the concept of prepared
  statements. What are they? They can be thought of as a kind of
  compiled template for the SQL that an application wants to run, that
  can be customized using variable parameters. Prepared statements offer
  two major benefits:

  The query only needs to be parsed (or prepared) once, but can be
  executed multiple times with the same or different parameters. When
  the query is prepared, the database will analyze, compile and optimize
  its plan for executing the query. For complex queries this process can
  take up enough time that it will noticeably slow down an application
  if there is a need to repeat the same query many times with different
  parameters. By using a prepared statement the application avoids
  repeating the analyze/compile/optimize cycle. This means that prepared
  statements use fewer resources and thus run faster.

  The parameters to
  prepared statements don't need to be quoted; the driver automatically
  handles this. If an application exclusively uses prepared statements,
  the developer can be sure that no SQL injection will occur (however,
  if other portions of the query are being built up with unescaped
  input, SQL injection is still possible).


Why is the chart button missing when trying to create a chart using Easychart? I have chart content type and chart content.

But when I try to add content I do not see the chart button, as shown in this image also:

Have a look at the Easychart support request "Installation on Drupal8". It contains varioous hints about what might be the cause of your issue, such as in these comments in it:

nr 3: You need to install embed & entity_embed to get the chart buttons.
nr 8: I ... didn't have Libraries API module installed.
nr 8: It appears to look for ec.min.js. The Easychart library that drush installed for me didn't have ec.min.js , but copying ec.full.min.js to ec.min.js makes it all work

Note: I added the hyperlink here for the Libraries API (it's the commonly used one, there is no Easychart specific variation of it ... at least not that I'm aware of).


Table width in view not run i have problem with table width in view.
This is my setup of view:

in my style.css i have this:

.novinky-telo{
width:50px;
background-color:red;
owerflow:hidden;
}

but result is:

I need only 50px width, have you any ideas?

owerflow:hidden;

you missed spelled overflow

overflow: hidden;


How to print a raw field value containing special characters in a node template? I have a text field which get filled with an URL, I am now trying to get the raw value of this field like "http://example.com", but every method I tried like

entity_metadata_wrapper
field_get_items and field_view_value
field_extract_value

just returns the following " http:  example.com"

How can I pull it out right?

Edit:

Debug says:

[field_externer_link] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => /download/hier.jpg
                        [format] =>
                        [safe_value] => /download/hier.jpg
                    )

My node.tpl content: (Also tried methods mentioned above resulting in same output as you can see below)

$object = entity_metadata_wrapper('node', $node);
$externer = $object->field_externer_link->value();
echo '
Download
';

The output:

Download

Something like $row->field_link['und'][0]['value'] should give you the field. For security you should use  $row->field_link['und'][0]['safe_value'] but I don't know how the link will be affected in this.
Drupal has a nice function called debug(), which can output arrays, objects etc. as drupal_message. It helps to see how the arrays are built up ;)


Force download string as text file I'm trying to return the results of a db_query as a raw text file. The php solution uses header() to instruct browsers to download content. I've attempted using header() in an AJAX callback function, but the following error code is always returned:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: this is just a test

I'm looking for a way to save a php string value to a file client-side, ideally without requiring the file to first be saved on the server. Alternatively, if I could pass a value from an AJAX callback directly to javascript for post-processing, that would work too (haven't found an AJAX callback with this capability).

Here's my test code (that produces the above error):

<?php

function test_download_form($form, &$form_state) {

  $form['form_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['form_wrapper']['download_submit'] = array(
    '#type' => 'button',
    '#value' => 'test download',
    '#id' => 'download_submit',
    '#ajax' => array(
      'callback' => 'test_download',
    ),
  );

  return $form;
}

function test_download($form, $form_state) {
  $dateFile = rand(10000000, 99999999)."_test.txt";
  $dataString = "this is just a test";

  //header() and drupal_add_http_header() behave the same
  header('Content-Type: application/text');
  header('Content-Disposition: attachment; filename="'.$dateFile.'"');
/*
  drupal_add_http_header('Content-Type', 'application/text; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="'.$dateFile.'"');
  drupal_send_headers();
*/
  echo $dataString;
  exit;
}

I ended up making some modifications to the Drupal CSV module (code). The module code demonstrates that you can stream information directly to the client with header() designations. From what I was able to find, you aren't able to use form headers within form callbacks. An alternative method involved passing information with sessioning to an empty page (that doesn't have header restrictions). This had several undesirable consequences:

1.) Session information is saved temporarily server-side, increases time to load to client due to having to write twice.

2.) Finite memory allotment for sessions.

The solution below does not have these limitations:

<?php

function test_download_form($form, &$form_state) {

  $form['form_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['form_wrapper']['download_submit'] = array(
    '#type' => 'submit',
    '#value' => 'test download',
    '#name' => 'retrieve',
  );

  return $form;
}

function test_download_form_submit($form, &$form_state) {
  $characters = 'ACGT';
  $randomString = '';
  $n = 50000000;

  for ($i = 0; $i < $n; $i++) {
    $index = rand(0, strlen($characters) - 1);
    $randomString .= $characters[$index];
  }

  //https://git.drupalcode.org/project/csv/blob/7.x-1.x/csv.module
  drupal_add_http_header('Content-Type', 'text; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="test_header_method.txt"');
  $fp = fopen('php://output', 'w');
  fwrite($fp, $randomString);
  fclose($fp);
  drupal_exit();
}


How to remove reply link? I've installed the AJAX Comments module in my Drupal site.

Am unable to find the configuration to remove the reply Link from the comment reply, kindly suggest.

Attaching a screenshot below:

You can implement template_preprocess_comment() in your module file or theme's template.php file. And check if comment has Parent Comment ID (pid), if yes then remove reply link.

/**
 * Implements template_preprocess_comment().
 */
function [MODULE/THEME_NAME]_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  if (!empty($comment->pid)) {
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}


form submit handler is not called I tried to mimic the multiple user deletion feature of user.module but for some reason the confirm form submit handler never get called. I don't know where the problem lies in. Following is a working sample of module except for the function delete_multiple_server_confirm_form_submit which never gets executed.

function mymodule_menu() {

  $items['testservers'] = array(
    'title' => 'Manage Servers',
    'page callback' => 'display_servers_callback',
    'page arguments' => array('delete'),
    'access callback' => true,
  );

  return $items;
}

function display_servers_callback($args = '') {

  $op = isset($_POST['op']) ? $_POST['op'] : $args;
  $op = strtolower($op);
  $build_form = array();

  if (!empty($_POST['table']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
    $options = $_POST['table'];
    $build_form['delete_multiple_server_confirm_form'] = drupal_get_form('delete_multiple_server_confirm_form', $options);
  }
  else {

    $build_form['display_servers_form'] = drupal_get_form('display_servers_form');
  }

  return $build_form;
}

function delete_multiple_server_confirm_form($form, &$form_state, $servers) {

  $path = current_path();

  return confirm_form($form, t('Are you sure you want to delete %title?'), $path, t('This action cannot be undone.'), t('Delete'), t('Cancel')
  );
}

function display_servers_form($form, $form_state) {

  $header = array(
    'server_name' => array('data' => t('Server Name')),
    'location' => array('data' => t('Location')),
    'protocols' => array('data' => t('Protocols')),
    'status' => array('data' => t('server status ')),
  );

  $servers = array(
    array('server_name' => 'us1', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us2', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us3', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
  );

  $options = array();

  for ($index = 0; $index < count($servers); $index++) {

    $options[$index] = array(
      'server_name' => $servers[$index]['server_name'],
      'location' => $servers[$index]['location'],
      'protocols' => $servers[$index]['protocols'],
      'status' => $servers[$index]['status'],
    );
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No servers found'),
  );

  $options = array();
  $operations = array('delete' => array(
      'label' => t('delete servers'),
      'callback' => 'delete_multiples',
    ),
    'suspend' => array(
      'label' => t('suspend servers'),
    ),
  );

  foreach ($operations as $operation => $array) {
    $options[$operation] = $array['label'];
  }

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'delete',
  );

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

  return $form;
}

function delete_multiple_server_confirm_form_submit($form, &$form_state, $servers) {

  drupal_set_message('working');
}

After careful rereading of the user module, i realize that 2 more hidden form values need to be added so  the same delete_multiple_server_confirm_form will get called again after confirming action,otherwise the display_server_form will be rendered.

$form['table'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
$form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

 foreach($servers as $id) {

    $form['table'][$id] = array(
         '#type' => 'hidden',
         '#value' => $id,
         );
   }


Migration to localhost causes 404 errors I'm trying to copy my site on my computer.

I've successfully downloaded and setup all the things. My site localhost URL is http://localhost/rich/ and when I run this URL, it opens my site homepage perfectly; after this, any clickable link gives me a 404 error page.

When I run this URL http://localhost/rich/user on my localhost, it gives me the following error:

  Not Found

  The requested URL /index.php was not found on this server.

Can anyone tell me what is wrong? What should I do it to fix it?

Recently had simmilar issue. If your Drupal site were set up with clean url-s , you might want to change

#   RewriteBase /

in .htaccess file

Try comment it out.
If commented, try to uncomment it.
Try to add subdirectory in that declaration, if drupal is installed
under any

Of course, check mod_rewrite as was suggested by optimusprime619


Where is the 'Access Rules' in Drupal 7? I want to restrict site registration by email domain.

It used to be under Administration → User Mgmt.

I can't see any similar, or has this functionality been removed from the standard module set?

For anyone that might be asking the same question - email and username rules were moved to a separate module: User Restrictions.

http://drupal.org/node/1020672


How can i pass JavaScript variables back to PHP Controller in Drupal 8 I have a custom module which uses a Javascript library called Bootstrap Table. Among other things, this library allows me to create tables with clickable rows. Currently, I can pass variables from the PHP Controller into the Javascript library. These variables are used to feed the fields in the table.

What I want to do next, is to define an event (when a row is clicked) which would then return the value of the row and pass it back to the PHP controller.

The controller would use this returned variable to perform some specific action and update the information displayed in the table.

As far as I know, I should use AJAX, but so far I have not been able to accomplish what I want.

This is some of the info I have found.

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

How do I pass JavaScript variables back to PHP?

controller function use with ajax

You're right, you'll need to create a php controller for this task.

This involves a number of steps

In your custom module you'll need to add your controller in /yourmodules/src/Plugin/rest/resource

In this example I created one called HelloRest.php

<?php

namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Driver\Exception\Exception;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
 * Provides a resource for accepting rest calls
 *
 * @RestResource(
 *   id = "hello_rest",
 *   label = @Translation("Hello Rest Handler"),
 *   uri_paths = {
 *     "canonical" = "/hello/{name}",
 *     "https://www.drupal.org/link-relations/create" = "/hello"
 *   }
 * )
 */

class HelloRest extends ResourceBase {
    /**
     * Responds to GET requests.
     *
     * Returns a watchdog log entry for the specified ID.
     *
     * @param int $id
     *   The ID of the watchdog log entry.
     *
     * @return \Drupal\rest\ResourceResponse
     *   The response.
     */

    public function get($name = '') {
        $response = ['message' => 'Hello '.$name];
        return new ResourceResponse($response);
    }
}

Then I enabled the route using the REST UI module here https://www.drupal.org/project/restui to do so. There is probably another way to enable the route but I'm not sure how. Also you want to make sure every role you need has permissions to access the rest call. In my case I wanted everyone that visited the site to have access so I had to make sure that anonymous users had access to that route.

Now that you have that created all you have to do is perform an ajax call to it to get your response back.

jQuery.ajax({url: location.protocol + "//" + location.host + "/hello/"+name+ '?_format=json", success: function(result){
        console.log(result.message);
}}


Removing the upload button in managed files I want to save a image file  into my custom content type using forms api and node_save().

The below code works fine but I also get the upload button as it default in managed_file .

I don't want the upload button. So I tried type=file but it did not work. How can I remove the upload button ?

Also if you just select the file and submit the form it works so I really need to just find a way to remove the upload button.

$form['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/'
);

The work to separate out the managed_file element is done in file_managed_file_process(), which is the default #process function for that type of element.

To hide the upload button you need to implement your own simple #process function for the element:

function MYMODULE_my_form($form, &$form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/',
    '#process' => array('MYMODULE_my_file_element_process')
  );

  return $form;
}

function MYMODULE_my_file_element_process($element, &$form_state, $form) {
  $element = file_managed_file_process($element, $form_state, $form);
  $element['upload_button']['#access'] = FALSE;
  return $element;
}


Docker website running locally not loading CSS I'm completely new to Drupal, and I'm running this multi-container Drupal-Docker app locally, and website is only loading HTML, no CSS.

These are the only error warnings I am getting.

  exception 'PDOException' with message 'SQLSTATE[08006] [7] could not translate host name "dbname=template1" to address: Name or service

Any help?

You forgot to link the db container. Look at the quickstart here https://hub.docker.com/r/feikede/drupal8-docker/ and take care for the "--link" to your database container.


How can I add a playlist to content type? I need to add a playlist of mp3 or waves to custom content type. I installed some modules, but nothing seems to work:

I installed audiofield that allows upload of files.
I installed some plugins, such as wordpress player, but it isn't accessible to screen readers (flash buttons are unlabeled).
I installed jPlayer, but there are many errors when I attempt to display content, such as undefined index.continuous, undefined index.entity etc.
I installed able player, an accessible able player, but tracks are not visible.
I try to install jw_player, but it doesn't install due an error index.description undefined.
I tried to set file field as an audio file, but track are not visible.
I tried to change theme, switched to bootstrap instead of bartik, but nothing change.

I don't know how to do. Is Drupal able to play audio files?

The aptly named AudioField module has the functionality you're describing

  Audio Field module adds new field that allows you to upload and play audio files in HTML5 audio player or one of selected Flash players. Currently it supports 6 different Flash players

It definitely works, I've used it, and it has support for both of the formats you mentioned. Follow the installation instructions and you shouldn't have any problems.

Just to nitpick, and perhaps clear up some confusion: Drupal cannot play audio files, no - your browser can, when it is given the right HTML (or when flash is used). But Drupal just generates the HTML, it doesn't have anything to do with the audio files themselves (beyond facilitating upload/storage) or how the browser interprets them.


How to know when to use $config or $settings overrides in settings.php? I want to be able to disable certain options of modules on non-production environments.

For example:

Disable XMLSitemap from running
Set "Read Only" mode for Search API indices to TRUE
Set robots.txt string to

User-agent: *
Disallow: /

How do you know whether you should override $config or $settings in settings.php?

Would it be:

$config['search_api.index.acquia_search_index']['readonly'] = TRUE;

or

$settings['search_api.index.acquia_search_index']['readonly'] = TRUE;

Also, how can you confirm if these overrides are working? Is there an admin overview page that lists these things?

From settings.php, regarding $settings:

Settings:
$settings contains environment-specific configuration, such as the files
directory and reverse proxy address, and temporary configuration, such as
security overrides.
@see \Drupal\Core\Site\Settings::get()

From settings.php regarding $config:

Configuration overrides.
To globally override specific configuration values for this site,
set them here. You usually don't need to use this feature. This is
useful in a configuration file for a vhost or directory, rather than
the default settings.php.
Note that any values you provide in these variable overrides will not be
viewable from the Drupal administration interface. The administration
interface displays the values stored in configuration so that you can stage
changes to other environments that don't have the overrides.
There are particular configuration values that are risky to override. For
example, overriding the list of installed modules in 'core.extension' is not
supported as module install or uninstall has not occurred. Other examples
include field storage configuration, because it has effects on database
structure, and 'core.menu.static_menu_link_overrides' since this is cached in
a way that is not config override aware. Also, note that changing
configuration values in settings.php will not fire any of the configuration
change events.


PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server I recently tried to setup a dev environment for my production site and replicated the same architecture.

I've a server hosting Drupal, a second server for mysql and a memcached server. All the setup was good.

Exported the Prod DB
Installed Drush
Made sure the latest code is pulled
run Drush status

Drupal version         :  7.37
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  ip address
 Database port          :  3306
 Database username      :  username
 Database name          :  dbname
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.9
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /path/to/root/folder
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

The issue is when trying to load the website I get :

PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'ip-address' (13) in lock_may_be_available() (line 167 of /var/www/cw/html/includes/lock.inc).

Any idea why this is happening ? If I run drush sqlc I'm able to connect to the remote database.

Any help will be much appreciated.

For anyone having the SAME error code, please check if you have SELinux enable by typing sestatus. If that's the case then your firewall is most likely blocking the connection to the db.

To allow it you can use the following command line :

setsebool httpd_can_network_connect_db=1


Add User Edit and Profile pages to Quicktabs I'm using the module Quicktabs on my user pages.

As you can see here I now have 2 rows of tabs and would like to move the User Edit and Profile to the Quicktabs tabs.  However the options of block, view, node, qtabs and callback don't seem to cover these pages.

Has anyone else got around this problem.

thanks in advance

I create my quicktabs programmatically most of the tines exactly to avoid this kind of problems and expedients.

You need to choose 'callback' for both tabs, and use 'user/x' for profile and 'user/x/edit' for the form.

What x is?

the user uid, but since you need it to change based on the current user, you need to take it from the path the tabs will be displayed on.

assuming the path is

"mysite/candidate/{user uid}/dashboard"

replace x with %2 (or %3).

you don't have the uid in your path?

then create the quicktab programmatically :)


Referencing nodes reciprocally I have a content type called Project which can relate to n projects of the same content type. This is done with a field called related projects using the D8 core Entity References. A possible relationship could look like that:

            Project B
          /
Project A
          \
            Project C

Project templates should show all linked projects in both directions. Also would be great to edit the relations in both ways, when editing Project A but also when edition Project B.

This works fine for projects which have projects defined in the Related Projects field, like Project A in the example. But it doesn't work out for referenced projects like Project B and Project C. This is because of the directed nature of Entity References.

I try to use Corresponding Entity References module which "syncs the node reference between two node types which have a nodereference to each other" configuring it like that on /admin/config/content/cer:

First field: related_projects
Second field: related_projects
Package: Node: Project

But Project B and Project C don't get updated when saving Project A. What am I doing wrong? Or is there another possible solution for syncing node references?

You can display both directions in Parent-Child Entity references with Views. You don't need to edit the reference to note direction in any special way.

The Entity reference field is already showing Children information on Parent nodes (your Project A is showing Project B and Project C).

List Parent links on Child nodes using Views

To show Parent links on nodes that are referenced from that Parent (backwards relationship) create a block and display it on the Child nodes:

Create Views of type Content Project. You'll probably have the Title field already there, leave it for now just for testing.
Add a Contextual filter ID from Content Category and configure it:
When the filter value is NOT available:
Provide default value
Content Id from URL
When the filter value IS available or a default is provided
Specify validation criteria
Validator Content
Project

Now if you enter the node ID (either Project will do: A, B or C) into the Preview argument field, it will only show that node Title in the Views results. This is just to test that our contextual filter is working correctly, when we place it on Project pages.
Add a new Relationship Content using field_project_reference (Relate each Content with a field_project_reference set to the content.) This is the backwards Relationship! Be careful not to include the forwards one that is called "Content referenced from field_project_reference"!

Require this relationship because it makes sense, we want only the results if the node we're on actually has a Parent, but it won't matter much if you don't tick this.
Edit the existing Title field and set it to use the Relationship from the previous step. The field using that Relationship will show the title of the Parent node, and not the one you're currently viewing, like it did up until now.

Edit the label to say "Other Projects referencing this Project" or similar.

Under No results behavior choose
Hide if empty

This will ensure that if the node you're currently viewing doesn't have any other nodes referencing it, nothing will be displayed. Otherwise, you'd get the Label and No results text (if you have it configured which you always should), or just the Label "Other Projects referencing this Project" with nothing listed there. With "Hide if empty" the block will not display anything which is more inline with displaying Fields on node pages.
Now place this Block on Project nodes in Content region if you want it show close to the orignal Entity reference field, set the Block settings Content ID: Node from URL and restrict to show it on Project types only.

You can use these Views to display other information from references nodes, not only Titles.

In Drupal 7 the module Relation provided two-way references, but it seems in Drupal 8 you can recreate that without that module. If you need fields on your Relation/Entity reference or other features read the comments at the bottom: Relation for Drupal 8 Development.


Output og:image:url if the og:image exists I'm working on a website with Drupal 8 and the metatags module. I need to not output the metatag og:image:url if the og:image exists.

If it possible to do using the module? If not I would have to create a module for that?

I found a module that did something similar and just changed a bit:

function remove_generator_page_attachments_alter(array &$attachments) {

  $has_image = false;
  $index_to_remove = -1;

  foreach ($attachments['#attached']['html_head'] as $key => $attachment) {

    if ($attachment[1] == 'og_image_url_0' || $attachment[1] == 'og_image_url') {
      $index_to_remove = $key;
    }

    if ($attachment[1] == 'og_image_0' || $attachment[1] == 'og_image') {
      $has_image = true;
    }
  }

  if($has_image && $index_to_remove > -1) {
    unset($attachments['#attached']['html_head'][$index_to_remove]);
  }

}


Autocalculate computed twig field I'm building a form which should calculate some values during the form view. I've tried to use the computed twig field. The calculation is working after submission and also, when I move to the previous or next page but I want the field to be calculated immediately after the base values has been entered (jQuery/AJAX).

If theres no way of doing it automatically, how can I accomplish this using a "Calculate" button?

I hope somebody can help with this issue or give an example for a form which is using this kind of calculation.

Cheers

if you use the form API to build your form, then you can use the ajax form API.

In the field you want to trigger ajax method, use this :

$form['test'] = [
  '#type' => 'textfield',
  '#title' => 'A Textfield',
  '#required' => TRUE,
  '#ajax' => [
    'callback' => '::ajaxTest',
    'event' => 'keyup',
    'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ],
  ],
];

Then create a ajaxTest function in your Form :

public function ajaxTest(array &$form, FormStateInterface $form_state) : array {
  // you can use the $form_state here to get values of all your fields
  $my_value = $form_state->getValue('my_field');
  // Make your logic code here
  $new_val = 'foo';
}

And then just add a AjaxCommand to your ajaxTest function :

$response = new AjaxResponse();
$response->addCommand(new InvokeCommand('#my_id_to_change', 'val', $new_val));
return $response;

You can find all those in the Form and AJAX API here https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.5.x, regards.


Extract email addresses from composite field type using Computed Twig I am using a custom composite field type to gather multiple pieces of data from a user. This custom composite field type contains a field which gathers the email addresses entered.
What I am trying to do is use a Computed Twig field to extract the email addresses entered within the custom composite field type and use an email handler to send a confirmation email to all those email addresses, however, I am having real trouble trying to reference a field inside a composite field type. I have used multiple pieces of twig code, but all I seem to be able to reference is the values from all the fields in the custom composite and not a specific field.
I am really new to twig, so do not understand the full capabilities yet, but does anyone know how to reference a field value inside a composite field type, using twig?

I'll provide 2 links as an answer, but it has really been answered by others.

Write custom webform handler:

How to create a custom Webform handler to submit to a SOAP API

Use hook_form_alter() to add a custom submit handler.

Add a custom submission handler to a form

Drupal 8 version of hook_form_alter(): https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.8.x


Link in main menu does not point to specified path I'm trying to add a link to my site's about page to the main menu as an "About" link. I have configured it in the following manner:

Menu link title: About
Path: node/2
Description: (none)
Enabled: selected
Show as expanded: deselected
Parent link: Main menu
Weight: 1

I do get an "About" link created in the main menu, but this points to http://about/
and not to http://{sitename}/node/2. I know that I can add the full URL and adding the full URL does work, however, I'm interested to this with relative paths.

Try setting the $base_url variable in your settings file. Open settings.php, usually sites/default/settings.php, and search for '$base_url', there are instructions within the comments about how to set it correctly.


Slightly different menus for different domains I'm using Domain Access module (http://drupal.org/project/domain) for running few very similar sites out of single Drupal 6 installation/database.

What I need is to have slightly different menus between those sites.

Generally, most items will be exactly the same throughtout all domains, on some of them though I don't want specific items to be displayed (for example, maybe later there would be other requirements too).

Haven't found any module offering such functionality, so considering other options now.

Simplest and easiest solution would be to hide them using CSS, but definitely this is not a good solution.

hook_menu_alter was disqualified as well, for quite obvious reasons.

What I'm thinking about right now is doing it from theme_menu_item() / theme_menu_item_link() level. Haven't looked yet into possibility of basing it on (something like) node access permissions (which actually would mean writing own module for this), going to do it as well, but meantime perhaps someone could suggest even different approach?

Right. So I have written my own module to do what I wanted, using hook_form_menu_edit_item_alter() for configuration, and hook_translated_menu_link_alter() for displaying.

If anyone is interested in checking it out, initial dev version of the module is available in my sandbox here - http://drupal.org/sandbox/maciej.zgadzaj/1209152 - before I promote it to full project...

Edit:

Now promoted to full version available here: http://drupal.org/project/domain_menu_access


How do I save the values for a custom fieldset? Relating to my question (here). I made a custom field set to toggle organic group visibility. The UI looks and functions as it should, meaning when I have both my fieldset and $form['group_access'] fieldset showing, I can toggle settings from either and the changes show correctly in both. When I hide $form['group_access'] with $form['group_access']['#access']=FALSE; the values do not appear to get written to the database when I hit save. Shouldn't I be able to set $form['group_access']['und']['#entity']->group_access['und'][0]['value'] to the values in my custom fieldset? Any ideas? Thanks

One way to do it would be in hook_form_alter add a custom validate handler:

$form['#validate'][] = 'my_custom_validate_handler';

then you should be able to do (double check that with debug(), print_r() or devel):

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

    $form_state['values']['group_access']['und'][0]['value'] = 1;

}

Another way would be to set a '#default_value' and it should be something like that:

$form['group_access']['und'][0]['default']['#default_value'] = 1

Hope that helps!


Add title and alternate text to image automatically? In my site users can upload content and also images.

My goal is that when a user is uploading content to the site, and also an image - the title of the content will be also the image title and the alternate text of the image.
Currently I am using the core image field.

Is there a way or a module that can achieve all that?

The most direct way might be to do something along these lines in hook_node_presave() in a custom module:

function YOURMODULE_node_presave($node) {

  if(isset($node->field_image)) {
    $node->field_image[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_image[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

where field_image is the actual name of the image field you have in your node.

If you don't want your users to be see or to attempt to change this, just make sure the alt and title boxes aren't checked in the field setup, eg:

as this is just for the field add/edit widget in the form; the above code will still work even if these attributes aren't "enabled."


If Content Type Equals, then I'm trying to get run some code if the content type of the current page is equal to events. I am using Drupal 8.

However, I'm unable to write the if statement.

I've tried:

if ($node->type == 'events'){...}
if (Node::getType == 'events'){...}

I also saw this question, but I have no idea how to apply it.

Full code:

// Add og:event:start_date meta tag

function MY_THEME_preprocess_html(&$variables) {
  if ($node->getType() == 'events'){
    $time = [
      '#tag' => 'meta',
      '#attributes' => [
        'http-equiv' => 'og:event:start_date',
        'content' =>  $node->field_next_time->value,
      ],
    ];

    $variables['page']['#attached']['html_head'][] = [$time, 'og:event:start_date'];
  }

}

You need to pull the node object out of the variables array.

$node = $variables['node'];

In certain preprocess functions this may not be available, so you can try the request service:

$node = \Drupal::request()->get('node');

The object must be of type Node. Therefore:

$node->getType() == 'events'

As Berdir mentioned, you should check and ensure that $node is a valid Node object to see if it is an instance of NodeInterface before operating on it. This will prevent fatal errors in the event that $variables['node'] is actually a node and not some ad-hoc variable created in code from which you can't call methods on:

Example 1 (using $variables array):

if (isset($variables['node']) && $variables['node'] instanceof NodeInterface) {
  $node = $variables['node'];
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}

Example 2 (using the request):

$node = \Drupal::request()->get('node');

if (isset($node) && $node instanceof NodeInterface) {
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}


Load a file entity by URI Is there a way to load a file by URI in Drupal 9 and/or Drupal 8?
In Drupal 7 it is possible using the following code.
$uri = 'public://file.xyz';

// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files); // If empty, $file will be false, otherwise will contain the required file

Taken from here https://www.drupal.org/forum/support/module-development-and-code-questions/2012-06-06/load-a-file-by-uri#comment-6493610

There is the loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface that allows to define required condition in searching the file entity by the given file URI:
/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;


rules autotag module, bulk retagging existing nodes I am using the rules autotag module. It's working fine for adding new nodes. But what would I do for retagging existing nodes (approx. 40,000)?

According to this autotag issue on d.o, titled "How to re-tag all content":

  Use Views Bulk Operations (VBO).
  Create a bulk view with the 'Save post' operation
  In the view, select the nodes you want to re-autotag and execute (which will resave all the nodes)

Note the different autotag modules:

autotag uses your existing taxonomies, can be used with VBO.
rules autotag doesn't have the UI of autotag, it's possible to use this one with VBO as well.
autotagging uses 3rd party services


Entity reference form in views below node I have a machine content type (clients have machines) and i would like to display all their machines in a view (done) and have a webform/entity form display below the node so that the client can submit issues to the machine. Therefore my end result should look something like this;

Johnny's machines;

Machine 1 - Model Number 234567

Form exposed

Sumbit form button

Machine 2 - Model Number 876543

Form exposed

Sumbit form

Etc.

Any ideas how I might be able to pull this off?

Thanks

Ok. After suffering on many different options to get this integrated, I eventually decided to use a workaround. I used the standard node comment form and created a view to display teaser nodes. It works. It's not necessarily the right option but it might help someone looking for something similar.

Thanks for your help guys.


Is check_plain() enough? Is check_plain() enough for re-displaying the text entered by users in the browser, or should I still filter with filter_xss()?

I imagine the question is about using check_plain(filter_xss($string)), or filter_xss(check_plain($string)).

check_plain() and filter_xss() have two different, and in contrast, purposes:

check_plain() encodes special characters in a plain-text string that is then displayed as HTML.
filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. In particular its purpose is:

Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

If you use check_plain(), the string passed to the function is supposed to be used as plain text; in such case, filter_xss() is not necessary.
If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() is not necessary.

If the question is about using check_plain() and filter_xss() on different parts of the same string then, as greggles pointed out in his comment, you can use (for example) check_plain() on the content of tag attributes, and filter_xss() on the entire HTML tag.


Menu translation tab how-to? I have a menu in the original language English. Spanish is active in admin/config/regional/language . Custom menu link is active in admin/config/regional/content-language . I now have a Translation tab in admin/structure/menu/manage/mymenu/translate. I click Add in the Spanish row, change the label and Description (only Description is sufficient). Then what?
How do I add menu items to the now supposedly created Spanish version? I tried several things but could not figure out where this new (empty?) Spanish menu is? It would be logical and consistent when now an "Add link" button would also appear in admin/structure/menu/manage/mymenu/translate/es/edit like in admin/structure/menu/manage/mymenu.

What is missing is some simple help text right in the forms that guide our thoughts in the right direction. For instance what is the purpose of the "Menu language" select box? Is that to change the language of the whole menu? But wasn't the language fixed already at creation (the default language)? I could not find a decent explanation so I resort to the help of somebody who managed to got it working.

So far you've translated only the menu configuration consisting of Label and Description. The menu language select box is for the original language of the menu, in your case English.

The translation of menu links works independently by translating the menu links themselves, which is content translation and works the same as for nodes. You see a Translate tab when you click on Edit for a menu link in the main screen of the menu (after you've enabled content translation for custom menu links in admin/config/regional/content-language as you've already done).

The menu items are the same for all languages. If you want to have a different set of menu links for each language then you have to use separate menus.


Create related nodes to specific node I am using Drupal 7.

In one of my requirements i need to create related node to specific node.

For ex. I have created a node of content type "article". For particular node of "article" node

say nid:9 then i would like to add related node to this node.

So when i view nid:9 at that time it should also display related nodes, and also when i view the newly created node, at that time nid:9 should be displayed in related node display

So both nodes should be displayed vice versa in each others detail view.

There's quite a few modules that relate two (or more) nodes together, Entity Reference and Relation are both popular.

I'd probably recommend the Entity Reference module as that comes with a couple of field formatters that display the referenced entity. If you used the Relation module you'd probably have to build a fairly complex view with contextual filters and relationships - this screencast series should help with that.


Taxonomy path to a view instead to the taxonomy page? I have a Vocabulary taxonomy with some terms (alfa, beta,). This vocabulary is se to be sync with a menu (myMenu) using the taxonomy_menu module.

I need the path of the terms (the path of the menu items) to be products/[term:name] instead of taxonomy/[term:name].

'products' is the path of a view page and the term name will be taken as a argument.

How can I accomplish this?

The TVI module should help you with this:

  The TVI (Taxonomy Views Integrator) module allows selective overriding
  of taxonomy terms and/or vocabulary with the view of your choice.
  Using TVI you can easily create custom views to output all terms in X
  vocabuarly.


Can't add iframe to paragraph - iframe is stripped for attributes I have a problem with adding an iframe to a paragraph.

In Text formats and editors, I have checked "Limit allowed HTML-tags" and then added <iframe> to allowed tags.

But when adding an iframe tag with attributes to the CKEditor, all attributes are removed and only the tag is remaining.

When I uncheck "Limit allowed HTML-tags", the iframe is shown as expected but I do want to restrict HTML tags.

Is this a bug or am I adding the tag wrong?

If this is your output:

It's likely you need to specify the allowed attributes as well under Limit allowed HTML-tags. e.g.


Remove "Password reset instructions" hint on reset you password page? Could not find any hooks or templates for it.

You want to use hook form alter like this:

function mymodule_form_alter($form_id, &$form) {

  if ($form_id == 'user_edit') {
    $form['fieldname'] = '';
  }
}

If you install devel and kint, then you kan kint($form), to see what the fieldname is.


Conditional display of paragraphs items We use Paragraphs quite extensively in our site. We have about 10 bundles available.

What we' like to do is alter how the paragraphs are displayed on various pages; Ie, we'd like to remove bundle a and display only bundle b. Then, in an alternate view, we could have only bundle c and none others displayed.

Short of writing some page/node/paragraphs alters I'm looking for a nice clean way I can achieve this. Maybe 'view modes' for an entire paragraph.

Note paragraphs behave similarly to field collections, so any suggestions for FC are welcome also.

So, I fixed this by writing a new module that creates custom panels panes.

Using the base Panels plugin code seen here http://fourword.fourkitchens.com/article/creating-custom-panels-panes-and-use-substitution-too I created a custom panels pane.

With the custom panels pane, I added a setting for bundles;

$bundles = paragraphs_bundle_load();
$options = array();
foreach ($bundles as $key => $data) {
  $options[$key] = $data->name;
}

$form['display_bundles'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => $conf['display_bundles'],
  '#title' => t('What bundles should be displayed?'),
);

So when adding a pane in Panelizer, there is a setting for selecting which paragraph bundles are displayed.

Then, when rendering the pane, I check which bundles are allowed and then render them, returning an html block.

$nid = $args[0];
$node = $contexts['panelizer']->data;

if ($node->type == 'article') {

  $para_ids = $node->field_nova_section_main[LANGUAGE_NONE];
  $para_ids_array = array();
  foreach ($para_ids as $delta => $data) {
    $para_ids_array[] = $data['value'];
  }

  $return = '';
  $paras = paragraphs_item_load_multiple($para_ids_array);
  $idx = 0;
  $keys = array();
  foreach ($paras as $entity_id => $entity_data) {
    if ($conf['display_bundles'][$entity_data->bundle] !== 0) {
      $return .= render(field_view_value('node', $node, 'field_nova_section_main', $node->field_nova_section_main[LANGUAGE_NONE][$idx++]));
    }
    $idx++;
  }
}

$block = new stdClass();
$block->title = '';
$block->content = $return;

return $block;

So now, rather than adding the node field to a Panelized layout, I add my custom pane and select which bundles I display.


How to hide user profile(edit current password, email, picture, everything) based on role? When user logged in with common shared username and password, I wanted to hide user profile for some of the user based on the given role.

So, I want a feature where user can just logged in and logged out with the given shared user name and password and, I don't want to allow them to change their password or I don't want to allow them to edit in their profile.

I have created separate role for this users.

I came to know that we can hide edit user profile with CSS:

display: none;

Is there any other way to hide user profile based on some roles?

You can set access for fields as FALSE as per user roles.

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state) {
  global $user;
  if(in_array('your_role_name',$user->roles)) {
    $form['account']['pass']['#access'] = FALSE;
    // Similarly other fields, but fields can not be required fields on profile.
  }
}


Entity base field requires value despite setRequired(FALSE) I have set a field in my entity to not required using

->setRequired(FALSE)

However when I then leave the field blank and try to save the entity I get this error

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

Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category' cannot be null: INSERT INTO {myentity_field_data} (id, langcode, uid, question, category, runtime, anonymous_vote_allow, cancel_vote_allow, result_vote_allow, status, created, default_langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => en [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => test [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1 [:db_insert_placeholder_7] => 1 [:db_insert_placeholder_8] => 1 [:db_insert_placeholder_9] => 1 [:db_insert_placeholder_10] => 1442607827 [:db_insert_placeholder_11] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 930 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

So is this a result of setRequired or some failure of my entity reference?

Your field was likely created in the database with setRequired(TRUE) which means your field cannot contain NULL values. If you change your field to setRequired(FALSE), then NULL values will be allowed.

Inspect your *_field_data table and check if the field schema IS_NULL = TRUE, if not, then you will need to update your field schema by running an update hook. See Write update functions for entity schema updates for information on how to update your entity schema.

If you have not deployed your module anywhere other than locally then it should be safe to modify your database directly without creating an update hook.


How do you add the 'Edit View' Links? How do you add the 'Edit View' Links in the gear icon that appears when you hover the mouse over a block. I can see "Configure Block" but I want also "Edit View" option.
I know these icons are the output from the Contextual links module that comes with Drupal core so I'm not sure how to merge the two to be used on 1 block.

Can you Please Check this, Hope its help you. https://www.drupal.org/documentation/modules/contextual


How to access data from external MS SQL database tables in a Drupal site running on MySQL I am currently working a academic medical department that uses a lot of MS SQL databases because faculty set them up - making us the maintainers :(

We also recently launched Drupal 6 site on LAMP, with the goal to move from what was supposed to be a .NET shop to PHP and MySQL ... go open-source!

My problem: Fetch data from external MS SQL database tables into Drupal which runs on MySQL, more specifically integrating Views 2 with this external data and dynamically show it on the site.

What I have found out so far:

People have tackled this problem since Drupal 4, but no one is owning it and so ... no stable solution.
Drupal can only run one type of db driver per site. Either MySQL/PostgreSQL/etc ... given you have the driver.
The MS SQL drivers that are there are not stable and still only solve the problem if my site would already run on MS SQL.
The are interesting modules that rely on the schema module to build table definitions and enable access to external MySQL data. (Table Wizard, Data API)

Right now: Looking into how the Data API module can be used for my purpose by creating a plugin for it for instance.

Any thoughts that would help me in how to access external MS SQL tables would be very appreciated.

As pointed in the question, Views is currently unable to do it. It relies on Drupal's DB Layer which is currently unable to query different DB engines and doesn't support MS-SQL. Views 3 (currently in alpha) provides pluggable query backend so it must be possible to write a backend on top of PDO ODBC or an other mean to reach the MS-SQL DB. Queryin the MS-SQL DB from PHP will probably be a performance issue. Views' caching will certainly be needed to avoid unnecessary repeated queries to the server.

In order to work around this and avoid diving into Views 3, you may use Views (2) to query the Drupal's database, or another one on the same engine. And simply import the needed data into this database. This is what I recently did on a project with a small amount of daily updated data. I used PDO ODBC (with unixODBC and FreeTDS) to periodically import data from a MS SQL Server database into MySQL tables. The tables were then exposed to Views using Views' API. The Data module could also have been used for this purpose.

Another option may be to import the data from MS-SQL as Drupal's nodes. If the data are imported as nodes using a custom content-type with the needed fields (using CCK), you get Views integration as well as the tons of existing modules to leverage Drupal's nodes.

One easy solution to import external data into Drupal is the Feeds module. While initialy build as a rewrite of the Feed API to import RSS and Atom feeds, Feeds is actually a powerful framework to import data into Drupal. It can easily be extended through plugins and hooks to support different data sources, formats and processors.


Content disappeared for authenticated users Suddenly, I have encountered a weird problem. I see my site flawlessly as admin and unauthenticated users. But all the timestamp-based content (Like blocks-forum thread etc.) disappear when I log in as a (non-admin) user.

I have checked server's time and truncated session table and flushed all cache but the problem persists. Really appreciate your hints.

Go to admin/user/permissions and then tick the check-box for authenticated users under  access content and then click save.


How to use conditional not to print a field if empty in user profile? As in node.tpl.php, I would like in user-profile.tpl.php to test if a field is empty or not to show my html.

I tried it :

<?php if (!empty($user_profile['field_myfield'])): ?>
<?php print render($user_profile['field_myfield']); ?>
<?php endif; ?>

But it does not work.

Have you the solution?

Have you thought of using Entity Metadata Wrappers?

You can wrap the user profile using $user_profile_wrapper = entity_metadata_wrapper('user', $user_profile);, and then you can find out if the field has a value with:

if (isset($user_profile_wrapper->field_myfield)) {}

This should tell you if the user profile HAS the field, and then you might use:

$value = $user_profile_wrapper->field_myfleid->value();

to actually get the value and test if it's empty or not.

Sources:

https://www.drupal.org/documentation/entity-metadata-wrappers
Checking for existence for a field on an an entity_metadata_wrapper


Custom Entity's Custom Fields doesn't show in when trying to Add Field in Views I've created a custom entity and allowed administrators to add custom fields to this entity using the "Manage Fields" Form; however, the custom fields I add to the entity does not appear in the list that pops up when trying to "Add Fields" in a view.

How does one go about making custom fields appear in the Views?

I ran into this just today. Turns out you shouldn't set data_table in the entity type annotation if translatable is FALSE. Otherwise views associates all of the fields with the data_table, but data_table is never associated with base_table due to translations being disabled.


How to generate an unique serial ID based on a select value I am Drupal beginner. I have created one webform with some fields (name, college, branch, address, email, contact number etc.). And when this form gets submitted I need to generate a unique registration number based on the selected college code and a serial number).

I also installed Webform Rules module but I don't understand how to achieve that.

Can anyone please help me to generate unique serial ID based on a field value during the Webform submission?

You can use webform hooks for add your custom code before sending the data or saving it into the database. Create hidden field in webform and set the value of the same using hook_webform_submission_presave
For Ex.

function yourmodule_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  $component_id = 4; // where 4 is your hidden component id
  // Add your logic for registration code
  $submission->data[$component_id][0] = 'registration_code_you_wish_to_set';
}

Or If you want unique registration number check this module http://drupal.org/project/regcode

Hope this helps.


All taxonomy terms of a specific depth On a Drupal 7 site I have a view with a bunch of exposed filters (using Views + BEF) for taxonomies. Some of these taxonomies have terms with different depths. Is there a way I can dynamically show only the values of a specific depth? For example, one filter would have the depth 0 terms, another would have just the depth 1 terms.

I know that I can use "Limit list to selected items" and manually do it, but that feels clunky and requires more maintenance as terms are added. I also tried playing around with simple hierarchical select without success.

Is there some way of achieving this without manually adding terms to the exposed filter option list?

In the Views filters, there are 2 default filters for taxonomy. You want to use Content: Has taxonomy terms (with depth), then select the vocabulary and depth of the terms to include.


Hide html / code based on content type I'm using a block of code that shouldn't be displayed on certain content types (not blocks, but actual code). When I use this approach, I'm getting undefined variable and trying to get property of non-object errors:

<?php
    if(function_exists('views_get_page_view') && views_get_page_view() ||  arg(0) == 'user') {
      $showpage = "yes";
    }
?>

<?php if (((!empty($node)) || (!empty($showpage))) && (($node->type != 'article') && ($node->type != 'basic_page'))): ?>

(Show all this)

<?php endif; ?>

It's the check if the visitor is on a user related page that causes the errors, but I have no idea how to fix this. Can someone help me out?

$node isn't available on user pages. But when $showpage is set, you are checking a property on the $node object. This gets the two errors you are describing.

I'm not sure what you are trying to do but you can troubleshoot by breaking out your booleans. I find it helpful to break logic onto multiple lines whenever possible, so that other people (and I) can read it later.

From:

if (((!empty($node)) || (!empty($showpage))) && (($node->type != 'article') && ($node->type != 'basic_page'))):

To:

if (!empty($node) || !empty($showpage)) {
  if ($node->type != 'article' && $node->type !='basic_page') {
    // do that stuff
  }
}

So - when $showpage is not empty but $node is, as on a user page, $node is undefined.

I'm not exactly sure what you are trying to do but I think it is along the lines of "show this stuff on node pages that are not basic page and not article, or when the $showpage variable is present.

In which case:

if ((!empty($node) && !in_array($node->type, array('article', 'basic_page'))) || !empty($showpage))

Or more readably,

if(function_exists('views_get_page_view') && views_get_page_view() ||  arg(0) == 'user') {
  $showpage = 'yes';
}
elseif (!empty($node) && !in_array($node->type, array('article', 'basic_page'))) {
  $showpage = 'yes';
}

if (!empty($showpage)) {
  // do that stuff
}

It isn't a one-liner, but the longer code is easier to read, troubleshoot, and prevent errors.


How to implement search autocomplete for specific content types? How to implement search autocomplete it should show suggestions for specific content type only suppose recipe and collection .

I have used search exclude(node) module for searching nodes of specific content types.

But i am not able to figure out how to add search autocomplete programatically  or by using some module.

Create a new view of content. Click on + Add  select Autocompletion Callback and add a path/url to it.

In Filter add Type filter so only shows certain content types.

In /admin/config/search/search_autocomplete edit the search block

For WHAT - WHAT TO DISPLAY IN SEARCH AUTOCOMPLETE SUGGESTIONS? change this to your view's autocompletion callback.

For more info read the documentation.


Themekey with mobile detect not working properly I am using themekey module with mobile detect module for switching mobile and desktop version of themes. Some time it works and some time not. On Apple devices it load the mobile version. I'm currently using a Shared Hosting provider and I'm using boost module in order to generated my caching.

The mobile detect module had some issue with caching. The Drupal 7 Core caching have been supported since few weeks ago by a sub-module call "Mobile Detect Caching."

However, the developer mention that he boost probably would not work.... Here is what the developer said:

  It will only work with Apache(?). I doubt it will work with Varnish,
  Boost, or similar. I suspect it will work with {cache_page} in
  alternate caches, but I didn't test this.

In the comments you mention that you are using a Shared Hosting and you depend on the boost module and what you should do ?

Well, I would recommend you to follow the issue Drupal Cache + Mobile Detect Conflict where the still discussing this module caching issue. In addition to follow you should ask for boost support or an alternative. They might try to implement this module with the boost module.

In the mean time, I would recommend to used a free CDN called CloudFlare and let them generated the caching instead of the boost Module. However, you probably would not get the same results as the Boost module.


Set order / weight of user profile core fields against user profile custom fields Is it possible to set the order of core fields against custom fields added on user profile page?
I want to bring the status field to the bottom of the list.
I'm trying the code below but without succes:

function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['status']['#weight'] = 100;
}

I want something in the following order for example:

Username (core)
Password (core)
Custom field 1
Custom field 2
Status
(core)

Thanks in advance

You can just try and set the weight as follows

$form['status']['#weight'] = field_info_max_weight('user', 'user', 'form') + 10;

Have not tried it but I am pretty sure it will work. This will make sure the status will always be the last field.

Also it should be $form['account']['status']['#weight']


Can I use Simpletest to test site upgrades? Going through upgrades it's often a bit tedious to test site functionality such as creating and editing nodes. Can Simpletest perform this kind of functionality? Or do I need a solution like Selenium?

It depends of your Simpletest tests. Upgrade your site in a test environment (stagging ideally) and then run your Simpletest tests. If tests are ok you can be sure that everything covered by your tests is ok.

If your question is if Simpletest can create nodes, yes, it can. What Simpletest can't do is test Javascript. If you need to test Javascript you should use another tool like Behat. Behat is a BDD tool, so it allows you to describe the behavior of your app and test it. Behat has several drivers, one of them is the Selenium driver, that includes full JS tests (because the tests are performed by a real browser). There are otheres drivers and many posibliites.

In general Behat is better than Simpletest for integration tests, while Simpletest is better for functional testing.

If you are going to use Behat use the Behat Extension approach. Check the Drupal Behat Group too.


Dynamic base url with angularjs I have create 2 angular app into drupal 7 like

"example.com"
"example.com/app1"
"example.com/app2"

example.com is my main site. So, when I set html5 pushstate enable for removing hash in angular apps, I got nobase error from angularjs. Coz,

<base href="">

require for enable angularjs html5 pushstate.

My question is, since i have multiple angualr app in this drupal site, how can i dynamically add conditional base url for "/app1" and "app2" ?

anybody can help me?
Waiting for response. Thanx.

Add base element to your sites theme template file:

YOUR_THEME_NAME_preprocess_html(&$variables, $hook) {
    $url = 'default';// default url
    if($application1) {// your condition for app1
      $url = 'app1';
    } elseif($application2) {// your condition for app2
    $url = 'app2';
    }
    $data = array(
      '#tag' => 'base',
      '#attributes' => array(
      'href' => $url,
      ),
    );
    drupal_add_html_head($data, 'base_href');
}

Put it into your template.php

Ref: https://stackoverflow.com/a/35725528/3770000


Article page in Drupal Usually the articles in a drupal installation are published on the front page, but what I would like to do is to create a menu link to show all articles (instead of the front page)?

You need Views.

With Views you can make highly customizable lists of content. I suggest you use Drupal 7 and Views 3, because its easier to make a View in it than in the version 2. If you are using Drupal 6 try Simpleviews, which will let you create Views very easily too.

I make this suggestions because as a newcomer the full Views interface can be a bit daunting. Have a play around and good luck!


Control menu item visibility I find myself wanting to control whether a menu item is shown on certain pages, much like how I can control how blocks are only visible on certain pages.

I cloned the menu using the Menu clone module, but have already experience maintenance issues and can only see it becoming more of a problem when the site goes live...

Is there a clever way of controlling menu item visibility?

I have done something along these lines with custom blocks.  The basic approach is

Put everything you want in a menu, regardless of visibility
Make a custom block; make sure you don't cache it
In the render callback, get the menu $menu = menu_tree_all_data('menu-foo');
unset() any items in the $menu according to your visibility rules
Assign the items to $block['content']

Then you can assign the block to a region.


How to display background images from CSS included by modules I'm working to take a single page "site" built in jquery/css and convert it to a D6 module.

the code contains more than one css file which has classes like this:

background: url('images/stadium.jpg') no-repeat left top;

The question I have is:
How do I get those images recognized?

Normally, in the tpl.php files I include with my module I set up my image like this and everything is fine:

<img src="print base_path().drupal_get_path('module','my_module'); /images/my_image.png" />

I don't know how to get images call from css classes to appear, and I can't build the path out all the way manually since I don't know where, or in what theme my module may end up.

If anyone has any ideas, or docs they can point me to I'd appreciate it.
if you need any clarification please let me know.

Thanks!
Steph

Basically given:

background: url('images/stadium.jpg') no-repeat left top;

The image will be loaded from the path relative to the CSS file.

e.g:

/styles.css
/images/stadium.jpg

The image is loaded from the relative 'images' subfolder.

Presumably, if the design is all controlled by a module, you could drupal_add_css the css file and have the image files relative to that in the module folder.


How to exclude Admin Toolbar from being Translated in Drupal 8? I have enabled 3 languages, but I always want to show Admin toolbar (menu) in English, I don't want that to be translated, how can I do that ? If I want to see front end content in Arabic then I don't want to see Admin menu in Arabic.

You can set a separate language for administrator pages on the account edit page for each administrator account.

Under Language settings, set the Administration pages language.

BUT! There is a major core bug related to this feature: if admins are creating fields, the config will be screwed up.  See the issue for workarounds.

Admin toolbar module

If the question is specifically about the Admin Toolbar contrib module, you can not download the translation for it.  If no translations are downloaded, the module will always show in English.


disable date field (only update with datepicker) I am using drupal 6, im my form I put the date field as

$form['myform']['from_date'] = array(
    '#type' => 'textfield',
    '#title' => t('From date'),
    '#size' => 8,
    '#default_value' => (arg(5) == null)? '0':arg(5),
    '#attributes' => array('onclick' => 'GetdatePicker(this);'),
);

i want that user can not edit this field without using date popup(populated from date picker).
any suggestion.

Add 'readonly' => 'readonly' attribute to your field,

ie:

$form['myform']['from_date'] = array(
'#type' => 'textfield',
'#title' => t('From date'),
'#size' => 8,
'#default_value' => (arg(5) == null)? '0':arg(5),
'#attributes' => array('onclick' => 'GetdatePicker(this);', 'readonly' => 'readonly'),
);


Archive old content data in different database How can i make archive my old content and save in different db with my cron job.

I want to store in different DB because i want to increase my site performance.

In drupal 7 what's the best way to do it ?

Here's what you can do:

Add your archive database to your settings.php below your default database.

$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

In your cron script, load all nodes you want to archive. In this example I retrieve all nodes older than a month and no more than 50 at a time.

$nodes_to_archive = array();

$query = db_select('node', 'n')
  ->fields('node')
  ->condition('type', 'your_content_type')
  ->condition('created', REQUEST_TIME - (86400 * 30), '<')
  ->range(0, 50);
$result = $query->execute();

while($record = $result->fetchAssoc()) {
  $nodes_to_archive[] = $record;
}

In the same script, switch from database and add the nodes to the archive (make sure the second database has the same structure as the existing one)

db_set_active('my_other_db');

foreach ($nodes_to_archive as $node) {
  db_insert('node')
    ->fields($node)
    ->execute();
}

Still in the same script, switch back to the default database and remove the archived nodes.

db_set_active();

$nids = array();
foreach ($nodes_to_archive as $node) {
  $nids[] = $node->nid;
}

node_delete_multiple($nids);

I haven't tested any of this so you might need to improve it here and there. If anything's unclear, please ask.

Here is a list of helpfull resources:

How to connect to multiple databases within Drupal
Function db_select
Function db_insert
Function node_delete_multiple