How do I override/theme Views REST Export display field? I have a REST Export view display setup in Drupal 8, delivering node fields.

The challenge: I want to theme/tweak/alter the output of JSON or HAL_JSON for and image field. Currently, it's rendering this in JSON:

"field_feature_image":"  \n\n<\/a>\n"

I would prefer it to look like this (taking out all the HTML):

"field_feature_image":"http:\/\/mysite.com\/app\/sites\/default\/files\/images\/feature\/huygens.jpg"

Where's the best place to start? I don't see any views theme options when specifying a REST Export display. Should I create a module of some sort? Is there a theme option?

Here's one option:

Add a new relationship in the view for the field (field_feature_image in your case)

Add new field for "File: URI" using this new relationship

Use the File URI formatter, and also enable the "Display the file download URI" option

This method may not be ideal for fields with multiple values. I am still working out the best method to do that using the core tools in Drupal 8.


Allow users to edit the list of CCK allowed values for "select list" I have a CCK field ("City") that is a select list, and has manually entered cities in the allowed values list. I added these cities (as the administrator of the website) but I would like to hand control over to the client.
However, changing their permissions, and allowing them full access to the CCK content types would be potentially disastrous; I need a way to give authenticated users permission to add values to this select list.

Is this possible?

A simple solution would be to use taxonomy.

Taxonomy has it's own permission system.
Drupal adds a lot of nice features for taxonomies.
Categories such as cities is a perfect match for a taxonomy.


How to use group audience in drupal 7 views filters How to use the Group audience field in our drupal 7 views filter. I have to fetch the values for the appropriate groups node. So i want to add the group audience field in the views filter. By default the filter having the fields of Groups audience (group_audience:gid), Groups audience(group_audience:delta) likewise. Please suggest me some ideas how to fetch the values based on the group audience field in the views filter.

Thanks, Sathish

Please check the screenshot.Basically you need to add a relationship as in screenshot.


How to change order of taxonomy terms related to specific node field? As in question. I have multivalued taxonomy field. Is this possible to control terms weight,  which are belongs to specific node field?

As a term weight, I mean weight inside single node. It's just a field value delta.

I found one way to do this. We need to change the taxonomy field widget to autocomplete. Then you can swap the words there, thus changing the delta.


Count entitys dependent om field value and as entity reference I have two node types, Apartment and Building.

Apartment has two fields:
- "Building" a Entity Reference field that reference to the node type Building
- "Rooms" a Text List with values 1 room, 2 rooms, 3 rooms etc...

I want to have a View, that lists all Buildings and under each Building it displays how many Apartments WITH specific amount of rooms. Like this:

Building 1
1 x 1 room apartment
5 x 2 rooms apartment
6 x 3 rooms apartment

Building 2
7 x 1 room apartment
3 x 2 rooms apartment
2 x 3 rooms apartment

Is this possible to do with Views, and then HOW to do it?

In general Views Aggregator Plus and Views Calc can both generate tally reports like these.

Unfortuntaley by making rooms a text list you've basically made it (nearly) impossible for you to easily generate these types of reports. You're question isn't really a Views question, but 1 of how to write a tally report in SQL.

Since rooms is a simple string, its hard(er) to SUM the values to make your report. If the room was a reference to a room ID in another table then SQL, and Views and aggregation functions could more easily generate these reports.

  Is this possible to do with Views, and then HOW to do it?

TLDR; Yes, it's possible. It's easier if you make your data into non-string values for aggregation. It's a futile effort to show you how because it's simply too messy in code to work with the data structures you've created.

EDIT

If these were numerical numbers for the number of rooms, or room IDs, you could easily use SUM aggregation to find the total. Then you would simply use a Views rewrite substition to show the output as something like the string [node-room-sum] x [node-room-size] room(s) aparament and use tokens derived from your View.


How to load the required modules only on Drupal site? I have a site which contains more than 100 modules. So, for each page every module is getting loaded.

Is there any way to load only required modules to that particular page?

No, there's no such way. Or may be answer is: Yes, it's done automatically. Keep in mind that Drupal loads only the .module file always, and other files (includes, classes, etc) are only loaded when needed. Is true that that 'when needed' may be always for some of the files, but not all.


Override theme function for menu callback What I am looking for: I have a custom node link which, when clicked, displays a custom HTML content (option selections) in a lightbox. I need to pass an argument to the HTML content to generate the HTML code.

What I did: I created a menu callback with one argument, and a template file for this "page" that does the processing and display the HTML content in the lightbox. I guess it's a little bit overkill and it takes quite some time for the whole render to be computed.

Would it be better (faster) to override the render with theme function? If that's the preferred solution, how to do? Create a my_theme_page() function in template.php file?

Or can I generate the HTML in the callback function?

Any help would be appreciated.

After a lot of googling, I found a nice solution to my problem.

First, one needs to register its menu with callback (in a custom module):

function MY_CUSTOM_MODULE_menu() {
  $items = array();
  $items['my_link_url_path/%'] = array(
    'title' => 'content title',
    'page callback' => 'MY_PAGE_CALLBACK',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
   );
   return $items;
}

Then the HTML content you want to be in the lightbox has to be printed in the callback function (you can define this function in your custom module file) as follow:

function MY_PAGE_CALLBACK($MY_PASSED_ARGUMENT = NULL) {
  print 'This is my HTML content displayed in the lightbox: Arg = ' . $MY_PASSED_ARGUMENT ;
}

The trick comes from the fact that you do not return, but print directly the output. No theme layers will be processed.

Just add your link somewhere (with the lightmodal rel attribute if you are using Lightbox2 (http://drupal.org/project/lightbox2):

Click me

This will display 'This is my HTML content displayed in the lightbox: Arg = 345' in a lightbox.

Note: don't forget to empty the cache when changing your menus...


Inserting field or field collection into body field I've created a content type called "News" with the following fields:

Body
Image (using Insert module to allow user to insert picture into the body)
Body Sidebar (a field collection, surrounded by a  with the following fields)

Body Sidebar has two fields:

BS Title
BS Text

I want to be able to give the content creators an easy way to insert the sidebar into the body in a similar way they can with the image field. As far as I know the Insert module can't be used to do that.

Is there any way to allow users to insert the Body Sidebar div into the Body field? If not, is there a way to do this programmatically?

Apologies if this is elementary, I'm very new to Drupal.

You might be able to use the EVA: Entity Views Attachment module to attach the data to the node, but I'm not sure.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.


Is it possible to declare a Javascript library dependency at Hook.info? Below is my module.info file:

name = myid
description = Creates an ID template, Inputs ID form, Prints an ID and View System Statistics .
core = 7.x
package = CSU

;Jquery Library
dependencies[] = jquery_update (>=7.x-2.5)

;Needed to create text editors.
dependencies[] = imce (>=7.x-1.9)
dependencies[] = wysiwyg (>=7.x-2.2)
dependencies[] = imce_wysiwyg (>=7.x-1.0)

I know required module of my custom module can be declared in my module.info file to inform module users that it depends on it. How about javascript library like TinyMCE? Is it possible to declare it at hook.info? How will I inform that the user must also download TinyMCE.

I was thinking of including it using drupal_add_js but Tinymce is always stored at drupal\sites\all\libraries\. Please enlighten me in my problem. I'm a bit lost.

You can define library dependency using hook_requirements(). Then if the library is missing, drupal will automatically shows the error message in status report(admin/reports/status).

Also it will show the error message, when trying to install module without having required library.

You need to define hook_requirements() in your youmodule.install file like below:

/**
 * Implements hook_requirements().
 */
function yourmodule_requirements($phase) {
  $requirements = array();

  if ($phase == 'runtime') {
      $t = get_t();
      $library = libraries_detect('tinymce');
$error_message = isset($library['error message']) ? $library['error message'] : '';

if (empty($library['installed'])) {
  $requirements['tinymce'] = array(
    'title' => $t('TinyMCE Library'),
    'value' => $t('Not installed'),
    'severity' => REQUIREMENT_ERROR,
    'description' => $t('!error Please download !tinymce, and extract it into the %directory directory.', array(
        '!error' => $error_message,
        '!vimeo.ga.js' => l($t('TinyMCE'), $library['vendor url']),
        '%directory' => 'sites/all/libraries/tinymce',
      )
    ),
  );
}
else {
  $requirements['tinymce'] = array(
    'title' => $t('TinyMCE Library'),
    'severity' => REQUIREMENT_OK,
    'value' => $t('Installed'),
  );
}
  }

  return $requirements;
}


How to show a list of students: pairing entity references? I'm working on a drupal page for an academic department, and I've created content types for Faculty, Students and Alumni.  Both the Student and Alumni content types have a field for "Advisor", which is an entity reference to a Faculty member.  In the student and alumni display, the advisor field then links to the advisor's page.

Now, I'd like to have the advisor page show a list of all their students (current and former).  Is there a simple module that will do this?  I don't want to write my own module - if there isn't a relatively simple way to do it, I can just have an entity reference in the Faculty content type and do manual entry.

EVA: Entity Views Attachment can help you doing this task.

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

See this tutorial: https://www.torontowebsitedeveloper.com/drupal-video-tutorials/drupal-7-node-reference-tutorial

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.


How can I set node/entity references automatically using rules? Use case: On my site, when a user registers, four nodes of four different content types are automatically created using rules.  I would like references to these nodes to be stored using node/entity reference* fields in the user profile.  I want to use rules to assign each node to the respective field in the user profile automatically.  Is there a way to configure a rule to do this?

I tried using the rules "Set a data value" to set the user profile field to the created node but that didn't work-- it doesn't give an error, but after the rule is triggered the reference is still unset.

I wrote "entity/node" reference because I am happy to use either the entity reference or the references module, so long as I can get a solution.

For what it's worth, you can do this with entity references & rules alone. Nodeone.se has a video covering exactly this scenario.
Relation has great potential, and is a much more intelligent way to go about relationships, but it can be tough to use (especially for non-devs) because it lacks a strong way to make new references.


Newbie Taxonomy and Content Question I'm new to Drupal (having used Perch CMS and PHP for years). Forgive me if I bumble the terminology a bit. I've been furiously going over documentation and tutorials. Sorry in advanced for being verbose.
Using Drupal 9 with a Bootstrap 5 template I'm developing -  I'm looking to create a page that has a listing of downloadable PDFs that are categorized into groups and subgroups - these will eventually be placed in nested accordions on a page:
DOCUMENT LIBRARY
== Category A
==== Sub Category AA
====== Content: Has title, image and file link
==== Sub Category AB
====== Content: Has title, image and file link
== Category B
==== Sub Category BA
====== Content: Has title, image and file link
====== Content: Has title, image and file link
==== Sub Category BB
What I've done so far: I've setup a vocabulary tree that matches the structure I need. I also created a content type that meets the needs of each content item and have added taxonomy to the content form display. Created a view that show the content type.
What I need to do: Cycle through the taxonomy tree structure to create the accordions, showing the taxonomy term name and then nest each content item that matches the taxonomy term.
What I need from the community: Make sure I'm going down the right path and that I'm not misusing Drupal in this way. Also, any tips and/or things I should search for would be helpful. I'm pretty comfortable with theming (twig).

One way to implement this, assuming that you will show the entire document library as a block.
I'll build this in reverse order because in Drupal, there is no "tree" structure; philosophically, Drupal adopts a "tag" (multivalue) structure, so you have to nudge the tags into a tree structure.
This can seem like a disadvantage coming from a tree-based system, but it's one of Drupal's strengths because tags allow for multiple parents.
So first, for each sub category, create a view mode called "Show documents".
View mode creation path: /admin/structure/taxonomy/manage/MY_VOCAB_MACHINE_NAME/overview/display, scroll down and choose "Manage view modes" under "Custom settings."
After adding the view mode, go back to /admin/structure/taxonomy/manage/MY_VOCAB_MACHINE_NAME/overview/display, check the box for "Use custom display settings for the following view modes" and press Save.
Now you can edit this view mode to get the display of content you want.
For that, I would create a view.  This view should use a contextual filter to get the current taxonomy term, and then it should use fields to list the title, image, and file link.  The display mode should be block.
After you create the view, enable the Layout Builder module. This will allow you to completely customize the layout per view mode.
Now, you can go back to the view mode page and attach the block showing the content to the term.  Depending on how you implement the accordions, you should be able to adjust the CSS classes in Layout Build and the Views UI (for the block) to get what you want.  Using a view mode will also let you target a theme template specifically to that view mode.
Finally, you can make another view (block) of the sub categories, this time grouping them by parent.  And then set the view to show the display mode of the sub categories to the view mode that you created earlier, which will automatically bring in all the accordions.
This is not the only way to do this; another way is to use the embed feature of views, which lets you embed one view inside another.


image style (imagecache) images are not being created Currently i am unable to create images that get resized automaticaly according to the different image styles.

This includes the default styles such as thumbnail as well as the custom created styles.

I have checked the "Public file system path" as well as the "Temporary directory" (under Configuration > File system).

Both of the directories exist.
The file permissions are good on the directories (777).

The original file that's uploaded gets created.
It's just the scaled images that aren't getting created.

Any help with this problem would be very welcome.
If there is already a solution somewhere (which means i searched for the wrong terms), a link to that would be very appreciated.

edit:

I can't find anything in the logfile either, except for messages like :

type : page not found

message: sites/default/files/styles/thumbnail/public/fotoslider/slider_images/testbeeld20130103005.jpg

The problem was fixed when I changed the theme to another one, and back, as per @MPD suggestion.


Entity Reference Field: How to filter a View entity reference Using Drupal 8 I want to create a field that references certain Views that the user should be able to choose from when editing a node. Creating this reference is possible using the reference field type and choosing "View" as the type to reference.

The problem is I also want to filter which views should be selectable. This does not seem to be possible.

When referencing for example nodes, there's an option to select which bundles should be referenceable. Is there any way to do something similar for views, or for config entities in general? Or is there any contrib module available for this? Maybe there'a a hook / plugin I could implement to filter the referenceable views programmatically?

Yes, the options you can select from there are plugins.

As you found out, you can't use views with config entities, but you can implement one yourself.

There are two ways to do that, one is to define your own plugin that you can select there, like ViewsSelection does it. Or, it is possible to provide a version of the default plugin (DefaultSelection) that is automatically used for a specific entity type, see for example TermSelection.

I would however only use the second pattern if it is your own entity type, and otherwise define a separate plugin (you can still extend from DefaultSelection and re-use the code there).


Installing and loading google client php api I am developing a php module that uses the Google Client class from the google client php api. I have downloaded and unzipped the latest google client php api at sites/all/libraries, and put my module at sites/all/modules. The code loading the library is this:

if (($library = libraries_load("google-api-php-client")) && !empty($library['loaded'])) {
    print "success";
}

$client = new Google_Client();

However, I am getting "Class 'Google_Client' not found" when I try to access it. Also, the print is not showing, as if the library never loads. However when I use libraries_get_path() I do receive the correct path: sites/all/libraries/google-api-php-client

I have tried the checks here but they all fail. I am using the Libraries API 7.x-2.1 and drupal 7.22

My hook_libraries_info() implementation:

function hook_libraries_info() {
    $libraries['google-api-php-client'] = array(
        'name' => 'Google API PHP Client',
        'vendor url' => 'https://code.google.com/p/google-api-php-client/',
        'download url' => 'https://code.google.com/p/google-api-php-client/downloads/list',
        'version arguments' => array(
            'file' => 'README',
            'pattern' => '/Version (\d+)/',
            'lines' => 5,
        ),
        'files' => array(
            'php' => array(
                'Google_Client.php',
                'config.php',
            ),
        ),
        'integration files' => array(
            'calendarVis' => array(
                'php' => array(
                    'Google_Client.php',
                    'config.php',
                ),
            ),
        ),
    );
    return $libraries;
}

Other than that, I have tried creating an .info file, which worked on my initial wampserver setup, but I cannot make it work anywhere else. Here is the .info file:

name = calendarVis
description = Google Calendar Visualization for P-space
core = 7.x

dependencies[] = libraries

Also, after accessing the page that uses the module and returning to administrator menus, I am getting this error message:

"Warning: Invalid argument supplied for foreach() in libraries_invoke() (line 161 of drupal-7.22/sites/all/modules/libraries/libraries.module).
Notice: Undefined index: installed in libraries_load() (line 621 of drupal-7.22/sites/all/modules/libraries/libraries.module)."

Here's an updated answer (the version of the client library I'm using is  "google/apiclient": "1.0.*@beta")

    function hook_libraries_info() {
     $libraries['google-api-php-client'] = array(
     'name' => 'Google API PHP Client',
     'vendor url' => 'http://developers.google.com/api-client-library/php',
     'download url' => 'http://developers.google.com/api-client-library/php',
     'path' => 'src/Google/',
     'version' => '1',
     'files' => array(
      'php' => array(
        'autoload.php'
      )
    )
  );
  return $libraries;
}

Note, the 'autoload.php' file in the files array.  This will automagically load all the classes you might want, and seems to work well for me; rather than manually selecting each file the library includes that I might need.

I load the library and then use it like this:

$library = libraries_load('google-api-php-client');
module_load_include('inc', 'page_speed', 'page_speed_client');

My inc file contains the logic I want for defining a new client and service (see the Google docs) and does a Pagespeed Insight query, and (for now) simply dumps the returned data onto a page.

Final caveat, remember to clear cache if you edit your files array, otherwise the library won't load properly, that caught me out a couple of times.


How to Invalidate cache for views by user's location My site using Drupal 8 last version (8.2.5) and we have the views which contains the filter based on user's location (time-zone). For example, the users are coming from UK will get the time in UK timezone, and the Users are coming from the US, will get the time in the US. The problem is, when anonymous users from UK accessing to the site, it's display as US time instead, because the page has cached from US when the users from US visited.

On Drupal 7, I had implements DrupalCacheInterface and set custom cache for APC. And it's working fine.

How can I customize Drupal 8 cache for this requirement? My web server enabled the opcache and I and a custom module already.

Updated:

After reference from Cache API from drupal.org, I tried to use Cache Context for TimeZone.

Inside default.services.yml, I modified:

# @default ['session', 'user']
  contexts: ['timezone']
  # Tags with a high invalidation frequency.

For make it filter by context request, when detect difference timezone will render cached pages according. But seems it's not working on Anonymous page cache.

Anyways for resolve my issue?

I resolved it by copy the Core Page Cache Module to my owner module, then disable Page Cache Module.

getCacheId(Request $request)

this function should be return a custom key is reach my goal.


Use calendar to display anniversary I've a site that collects historical events.
I would to use calendar to display a block with events of actual the months (that, obviously, could be events in every year, also in XIX century).
How should I set the contextual filter to do this?

Generically I need a calendar of anniversary..

Thanks,
Sergej

The date module can be used to set up recurring events. An event on a specific date can occur multiple times. There's a basic tutorial at http://www.bentedder.com/recurring-calendar-setup-in-drupal-7/


List of all active modules used in a site Is there a way of having a list of all the used (active) modules on a site ?

I am in the process of documenting a site and would like to list all the active modules, I know I can take them from admin/modules but there must be another way.

You can use drush pm-list --type=Module --status=enabled command for getting a list of all installed modules.

If you want to exclude the core modules use drush pm-list --type=Module --no-core   --status=enabled


How to determine if request will result in a successful HTTP request? Two part question here.

What is the proper way in a module to determine if a page request is resulting in a HTTP 200 OK?  Looking through static $stored_headers for a 30x/40x/50x seems wrong.

What is the earliest hook that you can reliably do this from?

When I was developing the code for Nodewords, I used the following code, to verify if Drupal was serving an error page:

  $headers = drupal_get_headers();

  if (preg_match('@HTTP/1\.[01]\x20+403@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 403);
  }

  if (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 404);
  }

The function containing that code is called from nodewords_preprocess_page(), the implementation of hook_preprocess_page().


Is it possible to set a role specific value for "allow_insecure_uploads?" I want to override the value for "allow_insecure_uploads" which is in system.file config, but only for specific roles. Am I going to need to do this in a module / does one already exist?

Module suggestions are usually frowned upon on DA, but regardless the answer is yes; role-specific config values are possible via the D8 config override system.

The Drupal 8 docs has a section on the config override system with a relevant example in the Providing overrides from modules section. After you've declared the override class in your module's .services.yml & created the override PHP class, you'll do something like this in the loadOverrides() method:

 public function loadOverrides($names) {
    $overrides = array();
    // @TODO: define a hasRole($role) class method that checks Drupal::currentUser() for a given role
    $has_role = $this->hasRole('my_role');
    if (in_array('system.file', $names) && $has_role) {
      $overrides['system.file'] = ['allow_insecure_uploads' => TRUE];
    }
    return $overrides;
 }


How to create 3d charts using Charts module and Highcharts library? I want to create 3d charts using the Charts module and with Highcharts as its charting engine (library).

How can I create such 3d charts?

In the latest -dev version of the Charts module (D8), there is a checkbox to enable 3D for Highcharts and Google.


Bootstrap subtheme does not recognize stylesheets I'm trying to use a custom (LESS) build of Bootstrap in my Drupal project. I have a subtheme in the proper folder and have compiled a style.css file. However, Drupal does not recognize this file. So far I have

Edited the .info file to switch of the CDN and switch on the local .js files
Cleared the cache
Switched off the aggregation of CSS
Restarted the server
Added a foo.css to the .info file for testing

Nothing of this works. The subtheme does not recognize my custom css files.

What could have gone wrong here?

I forgot to turn the subtheme on in the theme settings.


How to disable cache for a specific content type? I use Drupal 8 and I want to disable caching for a specific content type in full view mode.

I've found how to disable caching for all view modes, but I want to disable it for only a specific content type.

How can I do that?

You need to set max-age 0 in e.g. hook_node_view().

function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

That said, I recommend you find a way to make caching work. There are concepts like lazy_builder that allow you cache most of a node and only dynamically build a small part in it.

Also note that this does not disable the page cache for anonymous users. If you need that too, which I would recommend even more to try and avoid, then you also need:

\Drupal::service('page_cache_kill_switch')->trigger();

Update, answer is getting too long to post in a comment:

Ah, flag. How do you hide the flag for the author? Are you using the latest D8 and flag version?

If you look at flag_entity_view(), you can see that flag is already doing exactly that. It registers a so called lazy builder and enables a thing called placeholdering. It does that to show a flag/unflag link depending on the user. You probably just set #access on that element right now.

Flag is supposed to have access hooks but I think they don't work right now. See https://www.drupal.org/node/2584299. Follow that issue, once that is resolved, you can just implement that.

But for now, you can just switch out the lazy builder callback there with your own for now that does your additional check and then does what the existing one does. And it will just work.


How do I alter the entity type class? In Drupal 8 you can load an entity with:

$node = \Drupal::entityManager()->getStorage('node')->load(123);

This looks for the entity definitions and finds that node is defined by Drupal\node\Entity\Node - so (I guess) Drupal\node\NodeStorage will instantiate a new Drupal\node\Entity\Node instance.

What I'd like to achieve is subclassing Drupal\node\Entity\Node and being able to instantiate this subclass when it's appropriate. For example if I have a node bundle article, there would be a class:

namespace Drupal\my_module\Entity\Article;
class Article extends Drupal\node\Entity\Node {
}

And I'd call:

$node = \Drupal::entityManager()->getStorage('node_article')->load(123);

And the return would be my Article subclass.

I can achieve this by creating a new entity type and wiring it back to another existing entity definitions, for example the node-article example would be this class:

namespace Drupal\my_module\Entity;
use Drupal\node\Entity\Node;
/**
 * @ContentEntityType(
 *   id = "node_article",
 *   label = @Translation("Content"),
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     "storage" = "Drupal\node\NodeStorage",
 *     "storage_schema" = "Drupal\node\NodeStorageSchema",
 *     "view_builder" = "Drupal\node\NodeViewBuilder",
 *     "access" = "Drupal\node\NodeAccessControlHandler",
 *     "views_data" = "Drupal\node\NodeViewsData",
 *     "form" = {
 *       "default" = "Drupal\node\NodeForm",
 *       "delete" = "Drupal\node\Form\NodeDeleteForm",
 *       "edit" = "Drupal\node\NodeForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
 *     "list_builder" = "Drupal\node\NodeListBuilder",
 *     "translation" = "Drupal\node\NodeTranslationHandler"
 *   },
 *   base_table = "node",
 *   data_table = "node_field_data",
 *   revision_table = "node_revision",
 *   revision_data_table = "node_field_revision",
 *   translatable = TRUE,
 *   list_cache_contexts = { "user.node_grants:view" },
 *   entity_keys = {
 *     "id" = "nid",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "title",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid",
 *     "status" = "status",
 *     "uid" = "uid",
 *   },
 *   bundle_entity_type = "node_type",
 *   field_ui_base_route = "entity.node_type.edit_form",
 *   common_reference_target = TRUE,
 *   permission_granularity = "bundle",
 *   links = {
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
 *   }
 * )
 */
class Article extends Node { }

// Results my Article sub type.
$node = \Drupal::entityManager()->getStorage('node_article')->load(123);

This works fine (as much as I can see); however, it smells. It adds a new entity type, which is not true, and might cause other troubles in the future.

How do I define a subclass for an entity bundle so that loading the entity would return an object of that class?

Create a new class in your module that extends \Drupal\node\Entity\Node.

use Drupal\node\Entity\Node as BaseNode;

class MyNode extends BaseNode {
}

Implement hook_entity_type_build().

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * @param EntityTypeInterface[] $entity_types
 */
function my_module_entity_type_build(&$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->setClass('Drupal\my_module\Entity\MyNode');
  }
}

Remember to rebuild the cache.

It works fine when loading nodes via the entity type manager service and the node storage. It even works when you just use Drupal\node\Entity\Node::load($nid) thanks to the fact that this load() function it is just a static wrapper for the entity type manager service call provided by the Entity class which is extended from the Node class.

// Part of Entity class for reference
abstract class Entity implements EntityInterface {
  /**
   * Loads an entity.
   *
   * @param mixed $id
   *   The id of the entity to load.
   *
   * @return static
   *   The entity object or NULL if there is no entity with the given ID.
   */
  public static function load($id) {
    $entity_manager = \Drupal::entityManager();
    return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
  }
}

This also works fine with the soon-to-be-removed entity_load_multiple() function, so I guess this covers all standard use cases for loading nodes.

Of course, if your module does this and another module does the same, you'll have a problem, but I guess it's not common scenario, and it makes sense only for very specific use cases.


is it possible to add a class to header found in page.tpl based on a node id? first off, i’m using Adaptive Theme so maybe this won’t make sense using a different theme. but here i want to add a class to

<header id=“main-content-header” class="someclasses">

which is found in page.tpl but based on node id. this would have to be done in mysubtheme_preprocess_page(). i have part of the code working.

 $variables['content_header_attributes_array']['class'][] = 'about'

but don’t know how to ascertain the node id that is contained on the page. is it possible? my pseudo code would read something like

if (nodeId == 1){
 $variables['content_header_attributes_array']['class'][] = 'about'
}

by the way, i find myself needing to do this constantly so i can style these headers differently, at least for this project i do. maybe there’s a better way to accomplish,..?

i can use conditional stylesheets but then there’s the issue of adaptive design and you’d have to put media query’s in these conditional stylesheets. don’t know if that’s such a good idea or not.

You probably already have a specific class for the page on the <body> tag.

For example :

<body class="html not-front not-logged-in page-node page-node- page-node-5 node-type-page">

Then a css should work for you :

body.page-node-5 #main-content-header { ... }

or

body.node-type-page #main-content-header { ... }


Edit Block body content directly in database I've used some php code in a block that appears on all pages and now receive a fatal error and cannot access the site. In what table and field can I find the Block body content in the database for a Drupal 7 site? I plan to edit the Block body content directly in phpMyAdmin.

block_custom table is what you are looking for.

Regards


Import the data into view I want to import data from excel to created view how can I do this? using what module I can achieve? I found some user import tutorial but in views how to import the data?

Your suggestions are valuable thank you.

You can never import to created view. View is to create, manage, and display lists of content. So first you have to import the data from excel sheet to the content type which you are using into your view as a content type filter.

To import the data, install Feeds module.

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.


Kernel Base Test: Create node content types and taxonomy vocabularies via configuration? Does anybody know, how the mentioned entity types can be setup via configuration Yaml files? Right now I am setting up my entity types for a Kernel Base Test like the following:

Vocabulary::create([
  'name' => 'Kreise',
  'vid' => 'districts',
])->save();

$stringFields = [
  'field_district_number',
];
$this->saveFields($stringFields, 'string', 'districts', 'taxonomy_term');

$booleanFields = [
  'field_searchable'
];
$this->saveFields($booleanFields, 'boolean', 'districts', 'taxonomy_term');

Is it possible to quickly load the entity type configuration by an existing site configuration to save time? Because I already have configured entity types in my site configuration. It seems like an not necessary additional step, to code the entity configuration for my test.

Here is documentation for using the configuration.
So for example, if you want to load Tags Vocabulary you will do:

$config = \Drupal::service('config.factory')->getEditable('taxonomy.vocabulary.tags');
$description = $config->get('description');

$description contains the description of the vocabulary. In this way, you can load what you want from the yml file.


Is it better to start a Drupal theme from scratch or extend an existing one? I am new to Drupal and am curious if it is better to start a theme from scratch, or extend one that is already out there. Also, are there any resources out there that someone could point me towards?

I am using Drupal 7.8.

I've done both many, many times and my experience has led me to say: I would start a theme from scratch every time.

Most of the starter/base themes for Drupal contain massive amounts of superflous HTML code (because they have to allow for every possible eventuality) which introduces more DOM complexity than there ever needs to be in a page. This is bad for your page load time, which in turn is bad for SEO. It's also bad for code readability and Javascript performance on the client side.

The other thing is that (rightly or wrongly) you won't always agree with the decisions the developer(s) of the theme have made with their HTML/CSS/JS and it can be very time consuming to fix an existing theme to conform to your own standards.

Why not create your own base theme? It would be a good exercise to learn how to do it and you'll be 100% sure that the code is as streamlined as you want it to be. From then on you can just use your own base theme each time you want to create a new one.

The link to the theming guide in alastair's answer would be the perfect place to start.


Using "Rabbit Hole nodes" and "Facebook Like Button" I am busy developing a Drupal 7 website. All nodes of content type "X" are displayed on my front page as well as on (possibly) multiple taxonomy term pages. But that is it, users are not allowed to access the single node page directly.

I have restricted the user's access to example.com/node/* pages using the plugin "Rabbit Hole nodes", redirecting them to example.com/#node-[node.nid] using the "Token" module.
I have also implemented the "Facebook Like Button" module to provide
a Like button for each node.

Each of these Like buttons are placed inside a generated iframe with following iframe Src.:

//www.facebook.com/plugins/like.php?href=http%3A%2F%example.com%2Fnode%2F1&layout=button_count&show_faces=true&width=450&font=arial&height=80&action=like&colorscheme=dark&locale=de_DE&send=false

Note: Look at the "href" value that is passed along. It uses the exact URL pattern (../node/*) that I am restricting access to.

I asked myself these questions:

Does the Facebook crawler (user agent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php) actually have access to this?
Will "Rabbit hole nodes" not break this like functionality?
Where will users from Facebook land when clicking on the Facebook
"like" notification of their friend? I mean, it's restricted..

[Update] How it should actually work:

When accessing the URL example.com/node/1 the following should happen:

Normal User (everyone except Facebook's crawler): Should be redirected to example.com/#node-1.
Facebook's crawler: Should not be redirected, instead it should just stay on the single node page example.com/node/1.

Possible solution:

One solution that I considered implementing is altering "Rabbit Hole nodes" module code and checking for the Facebook crawler user agent like this:

if (in_array($_SERVER['HTTP_USER_AGENT'], array(
  'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)',
  'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
))) {
  // Don't execute Rabbit hole functionality
}
else {
  // Execute Rabbit hole functionality
}

What are your opinions, ideas and solution approaches?

Perhaps consider using Page Manager (part of Chaos Tools) to redirect users instead of the Rabbit Hole nodes module.

On the Page Manager admin page (Structure -> Pages) edit the node/%node page
Make a an HTTP response variant that redirects the user to site/#node-NUMBER when they are trying to reach site/node/NUMBER.
Set the selection criteria for that variant depending on the user agent (i.e. don't use this variant when facebook is looking).  This will  require a custom php rule.

There is an excellent Page Manager tutorial here.


D8 Prepopulate webform full_address value field from url? I am able to prepopulate the name, date, body etc they are single value elements.  The full_address.value field wont accept the address city state value in the url.
from views rewrite link I have tried full_address.value (changes to full_address_value in url), full_address by itself and full_address-value.
None of those work. I see the value in the url however, it doesn't prepopulate the full_address.value element.  Ideas? Syntax issue in rewrite?

Thru trial and error I made the composite element full_address prepopulate using
&full_address[value]= {{ field_address }} as the receiving field/element name.
putting the brackets in made it work. Ahhh...


Custom space types in Open Atrium I have seen the OA webinar on extending Open Atrium that documented how to make custom content types for sections and have them be recognized and tie in to the OA hierarchy. I would like to do the same but with spaces.

I can clone the space content type to get different ones like "department" or "project" with different custom fields but I want them treated separately in the navbar/breadcrumb.  In other words, the label "space" isn't useful - can't sell that to my client.  Having departments and projects all lumped together as spaces is awkward and too generic.

As far as I can see spaces are OG groups and you can make custom OG groups, but OA builds a complex hierarchy with permissions inheritances and such so not sure if it's possible.

The label "space" and such are hardcoded into the oa breadcrumb module so it appears there's no flexibility and this may require substantial rejiggering of the architecture.

Is there a way to override the default breadcrumb toolbar using the Panels Breadcrumb module (part of the OA distro)?  Can I just roll my own navbar and disable the oa specific module?

This has been addressed here: https://www.drupal.org/node/2295541

Short answer: You can't create your own space content types because it breaks the architecture set up by organic groups. Better to use the stock space content type and add a term reference field where the terms delineate different space "types", or make use of the standard "space type" term reference field.


How do I create translation without default language content? In Drupal 8, my default language is English, but I also have German. How can I create a content item that will only be available for German, and not in English? In other words, how do I created "translated only" content?

When I add new content, I can use the Language select box, but it still creates content available in the English language.

It used to take several contributed modules to make even a small multi-lingual Drupal 7 site. Now, you can translate everything using just the Drupal 8 core.
Step 1: Enable the translation modules
You need to enable these four core Drupal modules in order to translate your site.

Step 2: Translate the Drupal core
First, let's translate of the core language inside the Drupal. In this example, I'm going to add Spanish as an option on my site:

Go to Configuration > Languages

Click "Add language"

Choose your language and click "Add language".

Click on the percentage area, under "Interface Translation".

You'll be able to search for and manually translate all the language strings in here:

Step 3: Translate your own site set-up

Go to Structure > Content types, you'll see a "Translate" option for your content types:

Inside the next screen, you'll see similar "Translate" links for all your fields:

Step 4: Add content
Now we can add content to your Drupal site.

Go to Configuration > Content language and translation.
Click the box next to "Content":

Note: This is an important step as you can set a specific translation for your content type. That means, the content type default language will be set to a particular language(like German).

After this step, all content of "Biography" type will be by default translated to german.


How do display a secondary menu within a drupal node without the node displaying as a actual menu item I have created a menu with a teaser view with the teasers linking further to nodes.  The problem I have is I would like the secondary navigation to continue to persist with the node that the teaser page links to.  The secondary navigation always drops when I go to the actual node. However I don't want these nodes to be menu items. How do you keep a node within the secondary navigation structure without making it an actual menu item?

I found a great module that seems to work great!  It's called menu position found here: http://drupal.org/project/menu_position and it's super easy to use.


Strange Drupal behaviour after update After updating Drupal from 7.15 to 7.16, I noticed a strange behavior.

If my custom module is enabled, the website design is broken in Internet Explorer. I don't see some parts of website: The front page shows only slideshow, I don't see filters or even the whole pages. If a custom module I am using is disabled, everything is OK. I tried to downgrade again to 7.15, but I still have the same error.

I really don't understand why it happened, as I didn't have any problems with Internet Explorer, and my module before the update.

Can anyone help me with my problem?

This is the code used from my custom module.

/**@file This module provides custom functions    */

/** Unset these form elements from the comment_form using hook_form_alter */

function custom_module_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['name']['#access'] = FALSE;
  return $form;
}

/** Implements hook_block_info(). This hook declares what blocks are provided by the module.*/
function custom_module_block_info() {
  $blocks['contact_block_form'] = array(
    'info' => t('Contact Form'),
  );

  return $blocks;
}

/** Implements hook_block_view(). This hook generates the contents of the blocks themselves. */
function custom_module_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'contact_block_form':
      $block['subject'] = t('');
      // Load contact pages inc as the form definition sits there.
      module_load_include('inc', 'contact', 'contact.pages');
      $block['content'] = drupal_get_form('contact_site_form');
      break;
  }

  return $block;
}

/** Views - Exposed Filter Form Theming  */

function custom_module_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'location') {
    $form['field_location_tag_tid']['#options']['All'] = t('- choose region -');
    $form['field_poselok_tag_tid_option_limit']['#options']['All'] = t('- choose city -');
$form['field_poselok_tag_tid_option_limit']['#states'] = array(
      'disabled' => array('select[id="edit-field-location-tag-tid"]' => array('value' => 'All')),
    );

    $form['type_1']['#options']['All'] = t('- choose gallery type -');
    $form['field_author_tid']['#options']['All'] = t('- choose gallery author -');
    $form['field_author_tid']['#states'] = array(
      'invisible' => array('select[name="type_1"]' => array('value' => 'gallery')),
    );
  }
}

I placed <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> in  and now my website looks fine in IE.


How to set automatically meta tag from node content? I use the Nodewords module and in the Readme file it talks about ability to automatically create metatag from node content but I don't find how to do.

  Each content type should be configured to control whether certain meta tags
  should be automatically generated, e.g. the "description" tag can be
  automatically taken from the node teaser.

Do someone know? Do I need additional module?

Log into your Drupal 6 backend and go to sitename.com/admin/content/types

Edit content type you wish to set auto generation of meta tags.

In this example I am editing Basic Page so I hit edit and ended up at

sitename.com/admin/content/node-type/page

Select "Meta tags settings" and on that page you can set various meta tag generation options.

One you probably want to set is:

Generate meta tag content when the meta tag content is empty
(default)

AND

Generate meta tags content from the node teaser (default)

Both of these are default so they should be working out of the box.


How to know the "name" of an input field of a commerce checkout form? I need to find the name of an input field of a commerce checkout form to use in:

form_set_error('NAME-HERE', t('Field cannot be left blank'));

The html of the field is:

             CIF/NIF/ID *
             <input class="text-full form-text" type="text" id="edit-customer-profile-billing-field-cif-nif-id-und-0-value" name="customer_profile_billing[field_cif_nif_id][und][0][value]" value="" size="20" maxlength="20">

I tried with all of these, but it didn't work.

customer_profile_billing[field_cif_nif_id][und][0][value]

customer_profile_billing_field_cif_nif_id_und_0_value

customer_profile_billing-field_cif_nif_id-und-0-value

customer-profile-billing-field-cif-nif-id-und-0-value

customer_profile_billing_field_cif_nif_id

If I use

dpm($form_state['values']);

I get this:

Give a try to this:

  form_set_error('customer_profile_billing][field_cif_nif_id', t('This field failed validation'));


Any better popup modal framework in drupal I use the Chaos tool suite module for modal popup in Drupal 7; I am unable to open popup from within a popup using ctools. Can it be done using ctools, or is there any better popup modal module in Drupal 7 which can do this? (I am using forms in popups and not only pages.)

Could the Colorbox module be useful for you?

  Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.3 through 1.6. This module allows for integration of Colorbox into Drupal.


Is SimpleNews Cron Neccessary? I'm running the latest stable version of SimpleNews 7.x.

I realise there is an option to disable sending via cron tasks and set a throttle. The description underneath this option advises it should only be used for testing purposes.

My SMTP server relays through Amazon SES. The SMTP server itself throttles email sending by default to 20 messages per connection.

So I'm wondering, is the cron task email sending really necessary if the messages just get queued up and throttled by my SMTP server anyway?

If I disable the cron sending are there any substantial problems I might encounter?

The throttle value you're mentioning is specific to cron jobs, not to a single send event. There's no easy way to throttle the number of mails delivered in a single send event.

In general, the main reason someone would want to use cron in this case is when your subscriber base is large enough that a single "Send" action will time out, due to the time taken to send the total number of emails exceeding your server's PHP maximum execution time directive.

Cron is utilised in this case to break up large subscriber bases into chunks your server can better manage.

In your case, you have a limitation of 20 outgoing mails imposed on you by your service provider. To ensure you can send mail to more than 20 people at a time, you will have to use cron to get around this limitation.

The throttle you refer to is the number of messages sent PER cron. Removing cron isn't advisable for a substantial list, as your server will connect to Amazon, attempt to deliver all the mails, of which only 20 would be accepted.

Without knowing the inner workings of Simplenews, one of two possible (and undesirable) scenarios would unfold:

1.) Any mail in excess of the first 20 would be ignored by Amazon, and sending would fail. Your site would ignore the errors, and of your entire "Send" event, 20 mails would go out.

2.) Simplenews might cache the remaining mails that Amazon doesn't accept in your DB. These would wait around to be sent at a later stage (next cron run), but because you're not running cron, Simplenews wouldn't be invoked during cron, and that queue would never be properly addressed. This would result in you sitting with a large number of unsent mails clogging up the Simplenews spool table.

Bottom line, disable cron at your peril. The second your subscriber base goes over 20, your newsletter sending process will start to give you issues.


Are hooks indexed when Drupal loads? Wondering how Drupal manages hooks outside of the core in modules. Seems like parsing the code in modules would add a lot of overhead, and that it's more likely that the code is doing something else to manage the calls; for example, indexing or compiling the code when Drupal boots for the first time.

If there's a difference between how 6 and 7 handles this, please explain how each handles it, or clearly state which version you've explained.

I can't speak for Drupal 6 (haven't used it in a while), but in Drupal 7 the standard method used to invoke a hook is something like the following:

$modules = module_implements('some_hook');
foreach ($modules as $module) {
  // Call the hook
}

module_implements() caches the hook implementations, and as such the index is only rebuilt when the caches are cleared (or more specifically, the bootstrap cache).

As for parsing the code in modules, this falls outside of Drupal's jurisdiction; PHP will parse all of the code in any included file. Since hooks must reside in a .module file (or at least a file that's explicitly included from a module file), and all enabled module files are included on each page request, the whole file will be parsed every time.


Kickstart Price slider in front page Can any one say that how will i show my kickstart price slider in front.

I read many reference but still at no where . I use the multiblock module but the block produced is only shows in the search page.

Then I also try through view . I create another facet block using facet api but there is no option for changing the display widget.

is there any way or i am missing something .

Any help is most appreciable . thank you in advance.

got it myself
i create a facet block with price field and a search block of index type which will show the facet in every where the search page will shown .i restricted it for only front page .Then it works for me.


Imagecache preset is missing in field configuration I have all the modules that could have to do with imagecache enabled.
It's the user: picture field that I want to use an imagecache preset on. Normally if you want to configure that field in views, there should be a drop-down list at the very bottom of the configuration form right under the 'link to user's its profile'-checkbox.

I remember I had it there but now it's gone and I can't find out why.

Do you have the ImageCache Profiles) module installed and enabled? Here is a quote about it (from the module's project page):

  ... allows you to set user profile pictures that are consistent throughout your site and allows avatars on the user profile pages, nodes and comments to be a different size.


Define a specific page.tpl for a page create from a module I have a module witch generates a custom page:

function my_module_basket_menu() {
  $items["my-basket"] = array(
    "title"=>"My basket",
    "page callback" => "_my_basket_page",
    "access arguments" => array("access my_module_basket content"),
  );

  return $items;
}

function my_module_basket_theme($existing, $type, $theme, $path) {
  return array(
    'my_module_basket_page' => array(
      'template'  =>"my_module_basket_page",
      'render element' => 'page',
      'arguments' => array("listeProducts" => NULL, "key" => $key),
    ),
  );
}

function my_module_basket_theme_registry_alter(&$theme_registry) {
  $hooks = array('page');

  foreach ($hooks as $h) {
    // Add the module path on top in the array of paths
    array_unshift($theme_registry[$h]['theme paths'], drupal_get_path('module', 'my_module_basket'));
  }
}

function _my_basket_page() {
  // ...some treatment

  return theme("my_module_basket_page", $liste_produits, $key);
}

All works fine, but the problems start here: I want also to have a specific page.tpl, for example page_my_basket.tpl.php.

I tried to create a function my_module_basket_preprocess_page and change the theme there but the URL path I catch is the node of the page 404. Impossible to catch "my-basket". Any ideas? A different suggestion on how i can make it work?

EDIT

As suggested, i changed the name of my registry_alter function. From here when i look at the url (with a dsm()), i catch the good one, not the 404. So that part is ok.

So now i have to theme two page tpl, one for the page create in the module and a second one to replace  the page.tpl.php The problem is this second page i add a function preprocess in my module :

function my_module_basket_preprocess_page(&$variables, $hook){

    $alias = drupal_get_path_alias($_GET['q']);

    if ($alias == "my-basket") {
      $variables['template_files'][]  = 'page_my_basket';
    }
}

In my hook_theme function, i have that :

function oxo_wedze_basket_theme($existing, $type, $theme, $path){

  return array(
    'my_module_basket_page' => array(
      'template'  =>"my_module_basket_page",
      'arguments' => array("listeProducts" => NULL, "key" => $key)
    ),
    'page-my-basket' => array(
      'template'  =>"page_my_basket",
      'render element' => 'page'
    ),
  );
}

And that don't work, i still get the standard page.tpl.php

Page templates have overrides already available based on path.

If you see template_preprocess_page() it has this code:

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

and you can see that theme_get_suggestions() looks at the path and generates the template suggestions.

This means that if you have hook_menu() generate the path "my-basket" then you will be able to override its page template in your theme by naming it page--my-basket.tpl.php without having to do anything else, like use hook_theme() or manually add a template suggestion in the preprocessor, or alter the theme registry.


How should I structure a node migration that has three locations? I have a situation where I need to migrate a D6 node that has three location fields.  The example code shown in the drupal module documentation (  https://drupal.org/node/2018113  ) isn't working.  I either get no addresses or four copies of the node.

I used the following code to join to the location tables for each lid field in the d6 content.  Whee!

$address_arguments = array(
        'administrative_area' => array('source_field' => 'hq_province'),
        'locality' => array('source_field' => 'hq_city'),
        'thoroughfare' => array('source_field' => 'hq_street'),
        'premise' => array('source_field' => 'hq_additional'),
        'postal_code' => array('source_field' => 'hq_postal_code'),
);
$this->addFieldMapping('field_company_address','hq_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'leg_province'),
        'locality' => array('source_field' => 'leg_city'),
        'thoroughfare' => array('source_field' => 'leg_street'),
        'premise' => array('source_field' => 'leg_additional'),
        'postal_code' => array('source_field' => 'leg_postal_code'),
);
$this->addFieldMapping('field_company_legal_contact','leg_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'inc_province'),
        'locality' => array('source_field' => 'inc_city'),
        'thoroughfare' => array('source_field' => 'inc_street'),
        'premise' => array('source_field' => 'inc_additional'),
        'postal_code' => array('source_field' => 'inc_postal_code'),
);
$this->addFieldMapping('field_company_inc_state','inc_country')
->arguments($address_arguments);

$this->addUnmigratedSources(array('field_company_twitter:title','field_company_twitter:attributes','field_company_linkedin:title','field_company_linkedin:attributes','field_website:title','field_website:attributes'));

}
protected function query() {
$query = parent::query();
$query->leftJoin('location_instance', 'hq_i', 'hq_i.lid = f.field_hqaddress_lid AND hq_i.vid = n.vid');
$query->leftJoin('location', 'hq_l', 'hq_l.lid = hq_i.lid');
$query->addField('hq_l','street','hq_street');
$query->addField('hq_l','additional', 'hq_additional');
$query->addField('hq_l','city', 'hq_city');
$query->addField('hq_l','province' ,'hq_province');
$query->addField('hq_l','postal_code', 'hq_postal_code');
$query->addField('hq_l','country' ,'hq_country');

$query->leftJoin('location_instance', 'leg_i', 'leg_i.lid = f.field_legal_contact_address_lid AND leg_i.vid = n.vid');
$query->leftJoin('location', 'leg_l', 'leg_l.lid = leg_i.lid');
$query->addField('leg_l','street','leg_street');
$query->addField('leg_l','additional', 'leg_additional');
$query->addField('leg_l','city', 'leg_city');
$query->addField('leg_l','province' ,'leg_province');
$query->addField('leg_l','postal_code', 'leg_postal_code');
$query->addField('leg_l','country' ,'leg_country');

$query->leftJoin('location_instance', 'inc_i', 'inc_i.lid = f.field_incorporation_state_lid AND inc_i.vid = n.vid');
$query->leftJoin('location', 'inc_l', 'inc_l.lid = inc_i.lid');
$query->addField('inc_l','street','inc_street');
$query->addField('inc_l','additional', 'inc_additional');
$query->addField('inc_l','city', 'inc_city');
$query->addField('inc_l','province' ,'inc_province');
$query->addField('inc_l','postal_code', 'inc_postal_code');
$query->addField('inc_l','country' ,'inc_country');

return $query;
}


Why do my custom elements not get rendered? I've tried to create custom Webform elements of type radios and checkboxes. The element is available in the Webform UI for admin, I can add it to my webforms from build section but it is not getting rendered in webform frontend. I have no idea what I'm missing.
(Note: I have created another custom elements of type textfield, selectbox, autocomplete and they all are working fine.)
Below is my custom src/Element code and src/Plugin/WebformElement code: (Do I need to add/modify any other files to get this elements rendered on frontend form?)
--> src/Element/MyCustomRadio.php

<?php

namespace Drupal\my_custom_element\Element;

use Drupal\Core\Render\Element\Radios;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;

/**
 * @FormElement("my_custom_element")
 *
 */
class MyCustomRadio extends Radios {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#size' => 60,
      '#process' => [
        [$class, 'processMyCustomRadio'],
        [$class, 'processAjaxForm'],
      ],
      '#element_validate' => [
        [$class, 'validateMyCustomRadio'],
      ],
      '#pre_render' => [
        [$class, 'preRenderMyCustomRadio'],
      ],
      '#theme' => 'input__my_custom_element',
      '#theme_wrappers' => ['form_element'],
    ];
  }

  public static function processMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }

  public static function validateMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add custom validation logic.
  }

  /**
   * @param array $element
   * @return array
   */
  public static function preRenderMyCustomRadio(array $element) {
    $element['#attributes']['type'] = 'checkboxes';
    Element::setAttributes($element, ['id', 'name','value']);
    static::setAttributes($element, ['form-text', 'my-custom-element']);
    return $element;
  }

}

================================================================================================
--> src/Plugin/WebformElement/MyCustomRadio.php
<?php

namespace Drupal\my_custom_element\Plugin\WebformElement;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformElement\Radios;
use Drupal\webform\Plugin\WebformElementBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Provides a 'my_custom_element' element.
 *
 * @WebformElement(
 *   id = "my_custom_radio_element",
 *   label = @Translation("My Custom Radio"),
 *   description = @Translation("Provides a webform radio element."),
 *   category = @Translation("My Custom elements"),
 * )
 */
class MyCustomRadio extends Radios {

  /**
   * {@inheritdoc}
   */
  protected function defineDefaultProperties() {

    return [
      'multiple' => '',
      'size' => '',
      'minlength' => '',
      'maxlength' => '',
      'placeholder' => '',
    ] + parent::defineDefaultProperties();
  }

  /**
   * {@inheritdoc}
   */
  public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
    parent::prepare($element, $webform_submission);

  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    return $form;
  }

}

================================================================================================
I have also attached image so that it can help oneself to understand the problem clearly. This module is made in fresh drupal 8 instance. Please let me know if any specific detail is required.
In admin panel: (i have option to add custom radios in my form)

In frontend: (Custom Radios is not rendered, only drupal&contrib radios and checkboxes is rendered)

For radios or checkboxes to work you need to call
\Drupal\Core\Render\Element\Checkboxes::processCheckboxes

or
\Drupal\Core\Render\Element\Radios::processRadios

Your example code, is extending Radios but trying to render checkboxes. I recommend extending Checkboxes and gradually override the default methods including \Drupal\Core\Render\Element\Checkboxes::processCheckboxes.
Below is an example
<?php

namespace Drupal\my_custom_element\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

/**
 * Provides a form element for a set of My custom element.
 *
 * @FormElement("my_custom_element")
 */
class MyCustomElement extends Checkboxes {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $properties = parent::getInfo();
    // My custom properties.
    $class = get_class($this);
    $properties['#process'][] = [$class, 'processMyCustomElement'];
    $properties['#element_validate'] = [[$class, 'validateMyCustomRadio']];
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function processCheckboxes(&$element, FormStateInterface $form_state, &$complete_form) {
    // You can override and extend this method.
    $element = parent::processCheckboxes($element, $form_state, $complete_form)
    return $element;
  }

  public static function processMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }

  public static function validateMyCustomRadio(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add custom validation logic.
  }
}


How to find the image cache url for images I want to get the url to a specific image from image cache. I have the image file name (my_image.jpg), file path (site/default/files/my_image.jpg). From this value I want to get the url to a certain image cache folder (sites/default/files/imagecache/240x135/my_image.jpg). I cannot use any drupal methods/modules to get this because I am using external scripts to directly access the back-end database, from where I can get the image name, actual image path, but couldn't find the table where the url to image cache is stored.

How can I do this?

You can use the imagecache_create_url() function:

$path = imagecache_create_url($presetname, $filepath);

$presetname: String specifying an ImageCache preset name.
$filepath: String specifying the path to the image file.


Duplicate entry/Contraint violation 1062 in file_managed on browser crash I'm using Drupal 7.28. Today when I tried to upload some 100 image files in Image field type, it aborted in the middle saying that "20 MB" limit reached. Now it wouldn't even show me way to delete the files.

Since then I'm getting the following error (below). when I try to upload the same files.

I've run cron and also cleaned all caches but this error does not go.

I can see that these orphaned files are still stored in the file_managed table.

How can I resolve this problem?

Related post: https://stackoverflow.com/questions/8809010/pdoexception-on-duplicate-filename-in-drupal-7

Another solution comment here on Drupal.org which says that such files should be cleaned by 6 hours by Cron run.

Error on repeat uploads

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'public://wsgallery/DSC00441.jpg' for key 'uri':
  INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize,
  status, timestamp, type) 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); Array ( [:db_insert_placeholder_0] => 1
  [:db_insert_placeholder_1] => DSC00441.jpg
  [:db_insert_placeholder_2] => public://wsgallery/DSC00441.jpg
  [:db_insert_placeholder_3] => image/jpeg [:db_insert_placeholder_4]
  => 305012 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1413799461 [:db_insert_placeholder_7]
  => image )

Check whether the file is being used by another part of the system with the file_usage_list()

$file = file_load($fid);
$usage = file_usage_list($file);


How to add an id element to a field in Drupal 7 I am try to find out a way that I can add in #ID element to a link field in Drupal 7. When you Edit the field it give you a chance to create a CLASS (Additional CSS Class) for it, however I want to add an #ID element so that I can use it to trigger an event for google analytics. I actually was able to add and #ID to that panel display but it is 2  above and not triggering it.

Is there a way to do this without code, if not what approach would I take to handle through code(not my specialty).
Here is an example of what I have...

      Print

and I want this...

          Print

First of all are you using the Link module? Just so we know.

I would create a template to the field:

You can copy the /modules/field/theme/field.tpl.php to your theme, change the name to field--field-print-link.tpl.php and customize it in any way wanted.

Don't forget to flush your caches!

Or, of course, you could add the id with JS using a bit of jQuery (as Drupal already uses it):

$('element').attr('id', 'value');


XAMPP localhost - admin access denied Does anyone has issue with mac Xampp localhost? Everything seem fine after I imported online Drupal site and database to Xampp(1.8.2-4) localhost. However, after I hit the login button on the login page( [https://localhost/user][1] ), it gave me "access denied". That's mean I cant login at all.

Best,
CocoSkin

it gave me the error message after i run drush upwd admin --password=YOURNEWPASSWORD

~ here is the error message ~

HH5765-122A-M1:~ cocoskin$ cd /Applications/XAMPP/xamppfiles/htdocs
HH5765-122A-M1:htdocs cocoskin$ drush upwd admin --password=MYNEWPASSWORD
Command user-password needs a higher bootstrap level to run - you    [error]
will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'upwd admin' could not be executed.                [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.26
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  test_drupal
 Database name          :  test_drupal
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  6.0-rc4
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/XAMPP/xamppfiles/htdocs
 Site path              :  sites/default
 File directory path    :  sites/default/files

If you are sure that your password is correct go to the Data base and empty( truncate) Sessions & Flood and all cache(I mean all tables has prefix cache_) tables,finally  clear your browser cookie then try to login otherwise(If you are not sure about password) try to reset password programmatically


Why does my rule have no effect on a VBO list of unpublished nodes but does work for published nodes? I set up a rule that is supposed to delete some unpublished nodes. I created a view with VBO for the rule to work with. The rule is triggered by cron, leads a list of nodes provided by the view with VBO. The rule loops through the listed item and has delete content as action.

The problem is that the rule has no effect on unpublished nodes, even though I found out that the rule and view as they're set up can delete published nodes. Could someone give me a pointer here, why the rule works on published nodes but not unpublished nodes?

Anything about Rules that uses the Rules Scheduler, runs for sure with "Anonymous" authorizations. There are cases (Rules Actions) for which that auth is insufficient of course.

So a possible explanation for the cause of your issue, is that your unpublished nodes are not included in your VBO views result. To verify if this is indeed the reason that causes your issue, just check the views results you get by looking at the Views results without being logged in (so as Anonymous user). If those unpublished nodes are included anyway, verify if Anonymous users are authorised to delete those nodes.


Delete node without Confirm I need to delete node for specific Content type without confirm message

function _node_delete_function($node) {
  if ($node->type == 'bills') {
    node_delete($node->nid);
    drupal_goto();
 }
  else {

   return drupal_get_form('node_delete_confirm', $node);
  }
}

Any help?

You can use hook_menu_alter().

Example :

/**
 * Implements hook_menu_alter().
 */
function Module_menu_alter(&$items) {
  $items['node/%node/delete']['page arguments'] = array('_custom_node_delete', 1);
}

/*
 * Custom delete.
 */
function _custom_node_delete($form, &$form_state, $node) {
  node_delete($node->nid);
  cache_clear_all();
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(
    t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title))
  );
  $form_state['redirect'] = '<front>';
}


How can I print a block (the language switcher) without the block-related classes? I'm not sure if this question is phrased correctly; I'm happy to accept any solution that accomplishes my aim.

GOAL: I am trying to print the language switcher block in the header of my theme without the block-related classes, because the theming for these classes assumes that the block will be printed in the main content area of the page.

Usually, I've been adding the language switcher block as a widget using the Panels module.  When I do this, no block-related classes are printed, and it's much easier to style the CSS.  However, I can't add the widget in the header because I'm not using Panels Everywhere and Panels only overrides the main content area of the page.

I looked in locale.module and tried calling the block directly via local_block_view(), but this still adds the CSS classes that I don't want.

Is there a way to print the block without the block classes?  Or, barring that, how can I remove the classes for this specific block?

Digging locale_block_view() out of locale.module:

/**
 * Implements hook_block_view().
 *
 * Displays a language switcher. Only show if we have at least two languages.
 */
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

shows that it is "just" theming up some links.  So, you have a couple options here that may work depending on what exact divs/CSS you want/don't want:

Override theme_links() to use "links__local_block" and wrap it in some divs that you can apply CSS to.
Stuff all the guts above in a custom module's block_view() so you can override its block CSS.
Add different or additional classes to the $variables[class'] array,
Include, or override in your theme, a different locale.css file,
Override the block.tpl.php for this specific block, eg, block--locale.tpl.php (see: http://drupal.org/node/1089656) (copy it out of .../modules/block/block.tpl.php and into your theme and change the classes)


How to use views to make queries on the webform (or entityform) results and show in a node? Do you know how to use the Views module (or any other "query builder") to filter/query the submissions made either by webform or entityform?

The newest version of webform (7.x-4.0-alpha10) allows views to display webform submissions right out of the box. Although you cannot revert to an older version after upgrading to 4.x, so it's important to back up your database. But after you have 4.x installed, you will see an option when you create a new view to show content of type "webform submissions". You can also read up on how to accomplish the task in older versions of webform here: https://drupal.org/node/1658784


How can I change tag separator from "," to "+"? I want to change tag separator in a Term reference field of my content type (using Autocomplete term widget (tagging)) from "," to "+" or maybe something else (in Drupal 7) because this field needs to be filled in Persian.
What shoud I do ?
thanks.

you can use a hook_form_FORM_ID_alter. I used this validation to make sure users use commas instead of spaces:

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

function custom_form_validate($form, &$form_state) {
  $tags = $form_state['values']['field_MYNAME_tags']['und'];
  foreach ($tags as $tag) {
    if ((strlen($tag['name']) > 15) || (substr_count($tag['name'], ' ') > 1)) {
      form_set_error('field_MYNAME_tags', 'Please enter tags separated by commas');
    }
  }
}


How do I add conditional shipping cost to an order? I am building an e-commerce site. When a shippable item is added to the cart I have to add some fixed shipping cost to the order which I am able to do with flat rate. But I have to
add an option "Residential Delivery Fee" while showing shipping cost on checkout page. If user select this option during checkout then I have to add another shipping cost to the order.

I am unable to figure out that how to add this conditional shipping cost.

Here the idea,

Using hook_checkout_pane() include your option Residential Delivery Fee as checkbox
Then while saving order check if user selected this option. Use hook_order
If user chose this option, you can add your shipping charge as line item with the function uc_order_line_item_add().

foreg:

function hook_order(){
switch ($op) {
.....................
case 'save':
if($arg1->residential){
//if the checkbox was selected, we add the line item to the order. the following function  will add 100 to order total as shipping charge
uc_order_line_item_add
    (
      $arg1->order_id,
      'shipping',
      t('Residential Delivery Fee'),
      100,
      NULL,
      array ()
    );

 }
}


How to render a paragraph 'Text (formatted, long)' as full HTML, not escaped I'm trying to create a custom paragraph template that displays as an accordion. I am able to correctly reference most of the other variables, except for the Text (formatted, long) field types as whenever I do .value for the field, it returns the escaped value so it looks like

text

text2

instead of the actual bulleted list.

I am able to get the value using .value|raw, but I read that I should be avoided and I'd like to get this perform correctly.

Please let me know if any further information is required.

The following code is under paragraph--rn-accordion.html.twig. I have two paragraph types, rn_accordion and rn_accordion_section(which houses all the different fields). I tried to mirror this from the bootstrap module to get this working.

The troublesome fields are: {{ item['#paragraph'].field_rn_acc_1.value }} and {{ item['#paragraph'].field_rn_acc_2.value }}

            {# Prints Accordion template. #}

                  {# Loop through all of the accordion sections. #}
                  {% for key, item in content.field_rn_accordion if key|first != '#' %}

                            {# Print the accordion section title. #}

{{ item['#paragraph'].field_rn_acc_title.value }}

                                {{ item['#paragraph'].field_rn_acc_link.value }}

                            {{ item['#paragraph'].field_rn_acc_1_btn.value }}

                            {{ item['#paragraph'].field_rn_acc_2_btn.value }}

                    {{ item['#paragraph'].field_rn_acc_1.value }}

                    {{ item['#paragraph'].field_rn_acc_2.value }}

                  {% endfor %}

If you want to render a formatted text field you have to use the render element processed_text:

  {% set paragraph =  item['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_rn_acc_1.value,
    '#format':  paragraph.field_rn_acc_1.format,
  } %}

  <div id="{{ paragraph.field_rn_acc_abbr.value }}-1" class="panel-collapse collapse">
  {{ body }}
  </div>


Execute a custom function on 'user register' or 'login' I am new to Drupal. I want to execute my custom function every time when user registers or logins to my site. How can I do this?

You can do this using the following hooks in your module.

hook_user_login
hook_user_register (In D7 we had user_insert hook.)

Examples:

User Login Hook:

function mymodule_user_login($account){

   //your code here
}

User Register Hook:

function mymodule_user_insert(Drupal\Core\Entity\EntityInterface $entity){

   //your code here

}


Sending an email to everyone with a certain role Me: Small business owner with no coding or Drupal background who wants to learn by doing instead of hiring a developer for every small thing.

Goal: I have a Drupal 7 website and would like to send different types of emails to users of specific roles using the Rules (or an easier way if you care to suggest it). I've explored using Rules to accomplish this with some success by cloning similar ones and making small changes, but making one from scratch is more challenging. I've wrapped my head around scheduling the event and creating the email in the action, but specifically editing the condition is a barrier. I assume that the element "User has role(s)" is what I should use, but I'm confused on how to drill down the "data selector" under the USER area. I'd like the system to evaluate all members of the site and email everyone with a specific role...I don't see an appropriate option. Maybe I'm looking at the wrong condition element. Little lost - I'm sure it is a painfully obvious to someone who knows what they're doing.

All constructive suggestions and guidance welcome on how to accomplish this - trying to learn!

If all you want to do is send emails to users of a certain role, you can use the Mass Contact module.  It enables a user to send an email to users by role or taxonomy. It is very easy to use, without any coding knowledge necessary. I have used it on a couple of business-related sites.

The other alternative is to use Simplenews. This is used mostly for sending email newsletters to lists of subscribers, if that is the kind of email you want to send.

But if you really want to use rules, I suggest you go through some documentation like this. Under the "Add a new action" of your rule, under the "System" section, there is a "Send email to all users of a role" action. That may be what you need.


Making a radios form element required How can I make which_option required so that users are forced to select an option?

$options = array(
  'Design1' => t('Design 1'),
  'Design2' => t('Design 2'),
);

$form['which_option'] = array(
  '#name' => 'which_option',
  '#id' => 'which_option',
  '#type' => 'radios',
  '#required' => TRUE,
  '#options' => $options,
  '#default_value' => isset($which_option) ? $which_option : NULL,
  '#prefix' => '

If you&apos;re a lucky winner, tell us which bag you would like

',
  '#suffix' => '
',
);

Looking at the code used from Drupal core, I found that book.admin.inc uses the following code, to define a require radios element.

$types = node_type_get_names();

$form['book_child_type'] = array(
  '#type' => 'radios',
  '#title' => t('Content type for child pages'),
  '#default_value' => variable_get('book_child_type', 'book'),
  '#options' => $types,
  '#required' => TRUE,
);

The code you shown doesn't work because #default_value is set to NULL.

'#default_value' => isset($which_option) ? $which_option : NULL,

You don't show how $which_option is initialized; either that variable is never initialized, or it is not initialized when you tested the code. In both the cases, isset($which_option) returns FALSE and #default_value is set to NULL.

Instead of that, the code should avoid setting #default_value, which is what form_test.module (a module for testing form elements) does. (See the first form element in the following code; the other form elements are shown to make a comparison.)

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Radios',
  '#options' => $options,
  '#required' => TRUE,
);
$form['radios_optional'] = array(
  '#type' => 'radios',
  '#title' => 'Radios (optional)',
  '#options' => $options,
);
$form['radios_optional_default_value_false'] = array(
  '#type' => 'radios',
  '#title' => 'Radios (optional, with a default value of FALSE)',
  '#options' => $options,
  '#default_value' => FALSE,
);

Notice the first radios element, which is required, doesn't have any #default_value property set.


View item list ranking I have a view with a list of nodes of a certain type sorted by a custom field.

Is there any way to put a ranking number on the output of a view?

Thanks!

I Assume you just want a row counter (1, 2, 3…). Just add the field "Global: View result counter".


How to get the active #comment-cid when a comment permalink is clicked? I am trying to get the comments on my website to change color when they are active. More specifically, I am looking to do something very similar to what StackExchange sites do when you click on a notification in your inbox (like this). So what I initially tried to do, was to wrap the comment class in another div class called comment_active using an if statement to see whether the current page url contained the string "#comment-". (being that the permalink for a comment is /node/nid#comment-cid I am trying to get drupal to know what the current cid is) I am having some problems figuring out how to do this. Is placing, for example #comment-1 even part of the url? or does it just bring you to the part of the page that contains that element id? is there a way that I can have the comment.tpl.php know whether a comment is active? Or should I be doing it some other way entirely?

Try to add a custom javascript file to in theme.info file

 jQuery(document).ready(function() {
    //get the current path
    var pathname = window.location.hash;
    jQuery(pathname).next().addClass('active-comment');
    //here add your custom animation
    jQuery('.active-comment').fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();

});

here is a plugin to animate the background color of the wrapper :here

Hope this will Help You


Add a button in user orders view requesting info about current order Drupal Commerce 7 I have an automated e-shop in Drupal 7 and drupal commerce.

I am trying to add an action button in user orders view, which on "pressing" by every current user is sending email(alert with replacement tokens about current selected order) to administrator of eshop.

Any ideas to implement action button?

I tried VBO and Views Send modules but i didn't succeded.

You can use the Rules module.

Create a component with the Action Send mail. Use tokens to customize the subject and message body as you like.
Edit the view and use VBO to trigger the rules component.


Will this php code (field_view_field) work if i put this inside body field of a node with php filter? Will this work if i put this inside body field of a node with php filter?

<?php echo "
How are doing? Rate this site
" ?>
<?php print render(field_view_field('node', $node, 'field_fivestar_rating')); ?>

I tried in there but its displays an error.

Notice: Undefined variable: node in eval() (line 2 of C:\ssatempsite\modules\php\php.module(80) : eval()'d code).

EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7562 of C:\ssatempsite\includes\common.inc).

Use the following code.

  $node = node_load(1);
  print render(field_view_field('node', $node, 'field_fivestar_rating'));


Taxonomy term title as page title in custom view I have a custom view where I show a list of nodes by taxonomy term. Since there are many terms in dictionary, I can't describe every view page manually. Is there any way to set the page title as a taxonomy term title?

You can use the argument added into the filter and there will be option to override the title, there  you can pass %1 which will automatically replace the title with the Taxonomy term title.


Don't import users in Database Just to be sure, which solution is better when I export / import DB ?

just exclude Users table from my dump export ?
keep exporting users
table but exclude users table content from my dump export ?

Because I would to to have different access code between production and developpment websites.
Thanks

EDIT: to @sanzante
just a test on a dev website, and I get an error:

drush @pfdevd6mg sql-sanitize --sanitize-password=newpassword
PHP Warning:  Module 'curl' already loaded in Unknown on line 0

The following operations will be done on the target database:
 * Reset passwords and email addresses in users table
 * Truncate Drupal's sessions table

Do you really want to sanitize the current database? (y/n): y
Sanitize query failed.

does alias aren't possible ?

If your only concern is to have different passwords you can use drush sanitize to change all passwords afer importing the DB into dev environment.

drush sql-sanitize --sanitize-password=devpassword

This changes all users password to 'devpassword'.

The command also sanitizes all user emails (so your dev site will never send mails to real users).


Programmatically get menu block & alter classes I'm invoking a menu block programmatically using:
    module_invoke('menu_block', 'block_view', 13);

What I want to do is change and add classes to the wrapper & ul tags of the menu block, is this possible? I can't seem to find a class_array to add  & have spent a significant amount of time looking through documentation & online but not come up with a solution.

borrowed from here:

add the following code in your template.php file.

<?php
  function THEME_menu_tree__main_menu($variables) {
    return '
' . $variables['tree'] . '
';
  }
?>

this would update the
 for main menu, adjust as necessary. You can adjust further up the chain within the page.tpl.php file.


Why I can upload only one file at a time with multi upload widget? I have installed the multi-upload widget module to be able to upload several files at once. I have set a file widget to multi upload, which has enabled the ability to choose several files at once however only one files uploads are there any necessary module to install for the module to work ?

Thanks for any help on this

Probably you are using APC for upload progress:

Check your status report to see. If so, do what it suggest. Or ask / pay your sysadmin to do it.


Problem with "content access" (module) and permission "View own unpublished content" I have a problem since few days and i didn't find my answers.

When i install content access, the permission View own unpublished content doesn't work anymore.

Some explanation about my configuration:

I use workbench and workbench moderation to create a simple workflow (i didn't change any setting: so draft, in review, published)

I have 2 roles who manage all the content (editor, manager and another role admnistrator who has all the bypass etc.)

And now, i've juste discovered that i have a problem when i need to see nodes that are not published. Editor and Manager can't see them event if they have created this content.

They can't see unpublished content everywhere in the site (in workbench administration and in content section so it's not a views problem)

I made another installation in local to make some test. I re-created my role with a basic configuration (permissions):

Access administration menu
Access the content overview page
View own unpublished content
View the administration theme

So when my manager creates a content type and it's unpublished it works fine. But when i install content access, it doesn't work anymore.

I don't know what's going wrong in my site but the only way for the user to see unpublished content is to have that permission : Bypass content access control

Problem, if i give them that permission, an editor can published content. It's override the workbench permission (he can just use draft and in review, only manager can published)

The only setting for content access i saw are in the content type section.

I think i made a stupid mistake, forget a setting but i didn't see where.

Thxs for your help :)

I've just found some interesting information about my problem. Maybe it will help someone else.

In fact, it's seems impossible to resolve this problem in a proper way.

There is a very good article about that: Access Control module prevents View of user's own unpublished content, and an issue on drupal.org

If we want to see our own unpublished content in workbench, we have to go in view and make:

Go to query settings
and check Disable SQL rewriting option

It's not very good solution like he said but we can't do anything else for now.


Page as homepage of subdomain I have View page like example.com/abc and I need to create subdomain abc.example.com that will show this page, but not like abc.example.com/abc.

I need to looks like it's the homepage of this subdomain.

How I can do this? Do I need some additional configuration on hosting or htaccess? What is the best way to go?

Install and enable domain module
Enable the submodule named Domain Configuration
Add a subdomain abc.example.com by clicking Create domain
Go to admin/structure/domain/ and click on edit domain for abc.example.com
click the Settings tab
Set the value of the Site frontpage field to abc


Is it possible to translate image Title and Alt fields and sync images between tranlations? Since it would be much easier to manage site with images synchronized. But I have to translate Title fields too.

Assuming you're talking about images uploaded to the site by users and administrators (and not static images that are integrated into the site as parts of a theme or a module), and you're talking about Drupal's core locale framework for translation and the built-in extensions available through the i18n module, the answer is "no".

Like everything else, it is of course possible to create a custom module to manage translation of image title fields (preferably as a submodule of some popular image management module), but I am not aware of anything like that already exists.