Creating a custom field with dynamic/virtual computed property value I’m working on a custom field (Drupal 8) where the author selects a taxonomy term from defined list, but the display is of, or includes, a node that references said term. I already have a service that can retrieve the desired node based on the term id. I started with a custom FieldFormatter for entity references, and that does a reasonable job of displaying the node information as desired.

However, what I really need is to get that node information included in a jsonapi response. I’ve made a custom FieldType extending EntityReferenceItem figuring all I would need is to add a computed property value (See https://www.drupal.org/node/2112677, e.g.). The examples keep pointing to the use of a specialized class extending TypedData, but the EntityReferenceItem treats the main property as computed, and doesn’t use that.

I also read How to properly define and return simple array computed field property but I'm not sure it's addressing the same kind of thing nor is there quite enough detail there to help me implement a solution.

class MyField extends EntityReferenceItem { ...
    public function getValue() {
        $values = parent::getValue();
        $values['computed'] = 'foobar';
        return $values;
    }
}

my_module/config/schema/my_module.data_types.schema.yml -

# Schema copied and modified from the configuration of the Entity reference field type
# in docroot/core/config/schema/core.data_types.schema.yml
field.storage_settings.my_field:
  type: mapping
  label: 'My field storage settings'
  mapping:
    target_type:
      type: string
      label: 'Blah blah blah'
field.field_settings.my_field:
  type: mapping
  label: 'Another label'
  mapping:
    handler:
      type: string
      label: 'Reference method'
    handler_settings:
      type: entity_reference_selection.[%parent.handler]
      label: 'Yet another label'
field.value.my_field:
  type: mapping
  label: 'Default value'
  mapping:
    target_id:
      type: string
      label: 'Value'
    target_uuid:
      type: uuid
# This part is new:
field.computed.my_field:
  type: mapping
  label: 'Hello World'
  mapping:
    target_id:
      type: string
      label: 'Computed Value'
    target_uuid:
      type: uuid

Any pointers out there?

My understanding is that I can set things up so that the computed value shows up in the $items parameter passed into my custom Formatter's viewElements() method, and, at least as important, will be part of a JSONAPI response when my_field is part of the include query parameter. As of now, neither of those things occurs.

UDPATE

I think the new part of your configuration is not necessary. I recall that there is a module called entity_reference_uuid which does something like you want: extends from core ER field type, adds an extra column target_uuid and uses the entity property which is computed from the reference.

In their schema they only have these keys definition:

field.storage_settings.entity_reference_uuid
field.field_settings.entity_reference_uuid
field.value.entity_reference_uuid

If you look here you will see the entity is computed (like the one you want to add). Further down you can see they kept sync between the entity property during ::setValue  ::getValue methods and implement ::onChange to notify any changes on the property. This all are entity lifecycle logic, nothing to do with rendering.

Until here everything is more like your code.

Later on the formmatter they just iterate over the referenced entities which are obtained from the $items. The thing is I think that your problem comes from not implementing the \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::prepareView:

/**
 * {@inheritdoc}
 *
 * Loads the entities referenced in that field across all the entities being
 * viewed.
 */
public function prepareView(array $entities_items) {
  ...
  // Fragment fromt line 142 and on.
  // For each item, pre-populate the loaded entity in $item->entity, and set
  // the 'loaded' flag.
  foreach ($entities_items as $items) {
    foreach ($items as $item) {
      if (isset($target_entities[$item->target_id])) {
        $item->entity = $target_entities[$item->target_id];
        $item->_loaded = TRUE;
      }
      elseif ($item->hasNewEntity()) {
        $item->_loaded = TRUE;
      }
    }
  }
}

As you can see there is where the entity key is populated for the formatter to use.

ORIGINAL ANSWER

By default all (most) pieces of data in Drupal 8 are typed data or get composed by it; means that fields are complex typed data which are like maps or mappings. EntityReferenceItem extends from \Drupal\Core\Field\FieldItemBase which extends from \Drupal\Core\TypedData\Plugin\DataType\Map. As explained in both of your renferences you should override the ::getValue method from EntityReferenceItem. Here is an example

/**
 * {@inheritdoc}
 */
public function getValue() {
  $values = parent::getValue();
  $values['computed_value'] = $this->myAwesomeService->getJSONApiData();
  return $values;
}

There on your formatters (and view's field) can use the computed_value key from your field.


Passing Settings from Drupal Module to Javascript: Uncaught TypeError: Cannot read property In my module I have the following code.

$my_settings = array(
    'basePath' => '/',
    'my_locs' => $my_locs // Array of numbers
);

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

In the JavaScript I am supposed to retrieve settings as follows.

var my_locs = Drupal.settings.my_module.my_locs;

From Goggle Chrome console, I get the following error.

  Uncaught TypeError: Cannot read property 'my_locs' of undefined google_elev.js

These are the various output I obtain from the console.

>my_locs
undefined

>Drupal.settings.my_module.my_locs
[41, 9, 42, 9]

>my_locs = 2
2

>var my_locs
undefined

>my_locs = Drupal.settings.my_module.my_locs
[41, 9, 42, 9]

 >my_locs
[41, 9, 42, 9]

All the rest in the JavaScript file works perfectly; variables are readed, computed, snd used. Settings are loaded in Drupal.settings before loading the JavaScrip file with drupal_add_js().

I don't know what to try. I don't understand if it is a syntax problem, if I must define the var to be an array before, or if something tricky in the order of callings have to be accomplished.

For future readers who will have the same problem.

My call for retrieving Drupal settings variables was made in the declaration part of the JavaScript:

var my_locs = Drupal.settings.my_module.my_locs;

I supposed this would be correct, since the Drupal settings object is already created, and since Javascript allows, like Java, the creation of new objects at declaration time.
But for some reason it didn't work.

I solved leaving the declaration

var my_locs;

and passing the object inside an initialize() method.

function initialize() {
    my_locs = Drupal.settings.my_module.my_locs;
    [...]

I hope it can be useful, since I lost lot of time on this.


How to override form id of Webform? I want to override form_id of webform in Drupal 7. Example my webform form id is webform_141 and I want to override it to webform_en or webform_uk.

Is it possible?

Note: I need to override it for multilingual site.

You can simply do following way, using hook_form_alter, paste following code in your template.php file, save and clear cache. Change the THEME with your themeName in code or if you are doing with costume module then with module name.

In your case the code will be,

function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_141') {
    $form['#id'] = 'webform_en';
  }
}


Views and Panels URLs I am trying to understand how URLs work in D7 with Views and Panels. When setting up a new view or panel it asks you for a URL.

I am setting up a panel that will embed a few different views. This panel will be for the homepage. I have a view with the URL featured-items. I have successfully embedded it into the front page panel. However, it is also accessible at /featured-items. How do I prevent this from happening?

When you select a Views "Page" type display, it must have a URL. And that URL is where this page will be accessed from.

There's a separate views display that's dedicated to be inside Panels, and that one is called "Content Pane" display inside views. This display doesn't take URL, but also has a lot more options for panels configuration such as argument input from panel, settings overrides such as pager, fields, items per page, base URL etc (need to explicitly allow each from the Views display "Pane settings").

So to answer the question, either use Content Pane display, or you can also use a Block display (as suggested by @JayendraKainthola) which is less flexible inside panels.

Once you've created the display Content Pane, it will be available in the "View panes" category when you're adding it to the panel.


Model view and labels are not displayed correctly I created a model view and labels are not displayed correctly when I export with the module: "Views data export".

Here are the contents of my model views-view-field--sitemap--views-data-export--field-image.tpl.php :

<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>';

echo $fields["field_image"]->content;

the result is :

&lt;image:loc&gt;http://www.domaine.com/xxx.jpg&lt;/image:loc&gt;

instead of :

<image:loc>http://www.domaine.com/xxx.jpg</image:loc>

You're trying to change the content of your XML to provide structural changes to the XML document. This content is escaped so it doesn't break the XML document.

If the whole goal of theming is set your XML image field to a image:loc element, you should just change add a Label to your field with it set to "image:loc". This will render the XML document image field as an image:loc element.


Inline block confirm messages I have a contact (web)form in my sidebar on my site and I would like to display a custom confirm message when a users submits the form. However, this message should replace the contact form.

I've tried with Inline Messages or with the form-settings (no-redirect), but every solutions just redirects the entire website to the node and displays the message inline. So, that not what I want, obviously...

So, is there a solution where the content of the page remains unchanged, but when submitting the form in the sidebar, only the sidebar refreshes and shows the confirmation message?

The Webform Ajax module will give you the functionality you describe. Here is a quote about it (from the module's project page):

... adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.


Change text-format through the theme Is it possible to change the text-format (display output only) of a long-text field through the theme in Drupal 7? Similar to the way you can override the imagecache output for an image. The reason I don't want to change the database value is because the user role doesn't have permission for the desired output (full_html), but I'd like to have this output on a specific content-type - benefit 2 is that the user doesn't have the input/text format options on the form.

First of all you should be aware that if you were to display the input of a input like is was full HTML, it would be the same thing as giving the user who created the content access to using the full HTML filter. The only difference is that you wont tell the user that he can type full HTML. This could potentially open your site to exploits, if people write harmful HTML. You should instead give users access to the filters that you want to use for their input.

Now if you want to display any text through any filter, you can do that by using check_markup. You simply pass the text and filter id to the function and it will return a text you can use on your site.


Automatically Create View I'm not even sure I know enough about Drupal to ask the question properly, but here goes.  I've managed to make a drupal view that displays submitted locations on a map of people who all received the same physical card. Under the map, anecdotes etc of how people received that card appear. I'll spare you the rest of the details.

You can see what I mean here:
http://www.wwghosting.com/sevendeg/final-leaf-test

Anyway, what I would like now is: if someone searches the site, for say card 2701, they will be shown a page that looks like that.

The problem is, I had to manually make that view with a filter that filters out card #2701 and anyone who submitted that card.

If I had to do it that way, I'd have to make 5000 views manually if we had 5000 cards. Also, the map there is just shown in the header of another view, so really, it's two views in one page.

What I want is for a display similar that to be automatically made if someone searches for card 2701. Or once they submit a card, I want them to be redirected to that page.

I think somewhere I read that it is possible to render a view from URL info, but not sure if that's the way to go about things.

Thanks in advance for any help/guidance.

-Todd

What you're looking for is Contextual Filters. Rather than creating many views, you create one view that accepts an argument to change the value of one or more filters. In your case, the filter is the card number.

There are many ways to do this. One way is to pass the value of the card to the view by URL argument. This can be done with query string parameters at the end of the URL (which you can set as hard links in HTML that the user clicks on. Another option is using a very specialized configuration of Panels module, where it will pass a URL argument to a view which is contained in one of its panel panes. See https://drupal.org/node/1584046

Those options are only necessary if you need the value to be pre-populated when the user visits the page. They are a bit tricky to implement, but something that Drupal does very well once you know how to configure it.

The other option is to set an exposed filter on your view. On the view configuration page, click on your filter and check the box to expose the filter. Then, there will be an input area when you load the view on your page, which will accept any valid values for your filter.


Is it possible to post video on Facebook user timeline using Facebook Autopost module? I need to upload videos to Facebook and I'm using Facebook Autopost and Rules module.

I've followed the video tutorials from:

Facebook Autopost
Drupal & Facebook : How to Post Drupal content on Facebook P 2/2
Drupal & Facebook : How to Post Drupal content on Facebook - Drupal 7, Drupal 8.

They teach how to post images and text but none mention videos. How can I upload videos with this module?

No. Not without building upon it. While the version of the FB PHP SDK (3.2.3) that the module relies on supports uploading video, there is no support for it in the module.

Looking at the current module, it looks possible to build in support. For example, take the scenario where the module supports uploading an image to the user timeline:

The rule action triggers rules_action_publish_to_facebook_timeline() which retrieves (in facebook_autopost_entity()) a FBAutopostEntityPhoto object which is extended from the FBAutoPostEntity class.
When FBAutoPostEntity::publishEntity() is called to publish the entity, it calls a parent method FBAutopost::publish() which checks a list of types that does include a video type.

Presumably, one could extend another class (e.g. FBAutopostEntityVideo) from FBAutoPostEntity that would add the various details for base classes that would allow it to plug in to the underlying SDK.

To sum it up, the existing module doesn't support however there's some support at lower levels in the code. That comes with the caveat that there might be more overhead to add (e.g. is there more to defining a Video entity than just extending the FBAutoPostEntity class) than what I mentioned here.


how to bring Core forum discussion with comment on front page I am using core forum in drupal 7. my requirement is how to bring forum discussion question with comment on front page.

You can create views of type Forum topic. and put the views page on your sites front page.

navigate to [your-site]/admin/config/system/site-information  change the default front page to your views page link.


How to create a Content Type that reuses data from existing Content Type? I have a specific use case that does not seem to be covered by existing Drupal 7 modules. I need to be able to create a "content type" that is created by choosing from a list of existing content.

Use Case:
A company that trains new pilots needs two content types:
Type 1: Schedule a training flight.
Type 2: Post training flight details.

Type 1 has the following fields:
(flight_id,trainer_name, plane_name, new_pilot_name, date, airport, flight_status)

IMPORTANT:
Type 2 is created when an admin clicks on the flight_id from a list of scheduled flights.

Type 2 is required to contain the following data/fields:
(content from type 1, trainer_notes, new_pilot_grade)

You can use Entity reference:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

And the Inline Entity Form module:

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

Others similar modules to Inline Entity Form:

Entityreference Autocreate

  A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

  Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

  Node Reference Create is an enhancement to the nodereference
  autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

  It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.

  The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

EDIT: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.


How restrict a constraints to a content type? I would like to create validation for a several fields on a content type to check if they each have unique values from each other. The part I'm struggling with is how to add the constraint for just my content type, and not all node entities. So far I'm using hook_entity_type_build() to add: $entity_types['node']->addConstraint('UniqueSizes', []); Is there a way to restrict this to only my content type?

No, it's not directly possibly when adding the constraint.

But you can always check the bundle or existence of certain fields (in some places preferable, if you ever need another node type with those fields and the same logic) within your constraint when it is run.


How to programmatically remove a field from a node? How does one remove a field from a node programmatically? I have a migration in hook_update_N that moves the contents from a a field into a custom table. After that migration, I want to remove the field in that same function.

Are there any field API's that cater removing fields?

Edit, Solution: Because the answers lack actual code, here is what I did to move fields from the $users into my own records and subsequently remove the field from the database;

function my_module_update_7005(&$sandbox) {
  $slice = 100;
  //Fetch users from database;
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_uid'] = 0;
    // We'll -1 to disregard the uid 0...
    $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')->fetchField() - 1;
  }
  if (empty($users)) {
    $sandbox["current_uid"] += $slice;
  }
  $users = db_select('users', 'u')
    ->fields('u', array('uid', 'name'))
    ->condition('uid', $sandbox['current_uid'], '>')
    ->range(0, $slice)
    ->orderBy('uid', 'ASC')
    ->execute();
  //Loop trough users;
  foreach ($users as $user) {
    $foo = new Foo();
    // Warning: drupal's fields return mixed values; e.g. NULL versus an int.
    $foo->debits = (int) $user->user()->field_credits["und"][0]["value"];
    $foo->save();

    $sandbox['progress']++;
    $sandbox['current_uid'] = $user->uid;
  }

  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  // Remove the field.
  field_delete_field("field_credits"); //note that the name for Foo is field_foo
  field_purge_batch($sandbox['max']+1);//Drupal seems to have an offbyone problem.
}

field_delete_field($field_name) will mark the $field_name for deletion on next cron run.

You could use field_purge_batch to do the deletion, if you don't want to do it on cron run.

EDIT: field_delete_field() should be used when you need to delete the field from other bundles as well. If you only wish to delete the field from a particular bundle you should use field_delete_instance() as mentioned by @Clive.


IIS problem with Drupal - Update manager: Update failed! Directories are locked by php-cgi.exe I have some problem when using the "Update manager" on the GUI. Some directories get locked by php-cgi.exe, and thus the replacement of the original directories with the newly downloaded ones (which are fresher) is not successful.
BUT I have to mention that it's not a permission issue, because the modules can get installed via "Install from a URL" on /admin/modules/install, and work without a problem.

Let's take an example:

Available updates page (/admin/reports/updates/update):

Now I check Select (or other) module to be updated (it doesn't matter which module I choose, the results are the same!! so it's just an example).
I hit "Download these updates" button.
OK, the module's updated instance gets downloaded without a problem:
"Updates downloaded successfully":

Now I click on Continue.
Here comes the error. The result:
"Update failed! See the log below for more information.
select_or_other

Error installing / updating
File Transfer failed, reason: Cannot copy D:/Projects/web/drupal-7/tmp/update-extraction-6d8993ac/select_or_other/LICENSE.txt to /Projects/web/drupal-7/htdocs/sites/all/modules/select_or_other/LICENSE.txt."

OK, I'm starting to try to inspect the possible reasons.

Here's what my Drupal directory structure looks like: . I set ../tmp to be the temporary directory (in /admin/config/media/file-system), the Drupal files are in htdocs. This is correct, as I can install modules via the GUI, as I mentioned above.
When I try to enter the htdocs/sites/all/modules/select_or_other directory, I can't, because I get an "Access denied on file ......sites/all/modules/select_or_other!" when opening in Total Commander, and "...sites/all/modules/select_or_other is not accessible. Access is denied" when opening in Windows Explorer:
,
OK, I right click the folder, and open Unlocker via its assistant in the context menu. It says this directory is locked by php-cgi.exe:

I click on "Unlock All", and the folder can now get deleted of itself (as it's not locked anymore by php-cgi.exe), so it simply
I can find the updated select_or_other module's directory in tmp:

so I have to manually move it to sites/all/modules directory.

What can be the possible reasons of the lockup of the directory by php-cgi.exe? (Maybe Windows Cache Extension 1.1 for PHP 5.3 installed via Web Platform Installer? But if yes, why is that for example the deletion of images or similar via the GUI works correctly?)
What can I do to avoid this problem, and let "Update manager" work?

The reason for php-cgi for having the Lock is because of the "peculiar" way windows handles file access, and php/iis handles "caching".
Basically you just created the directory and tried to access it, but the handle that created it was not released (so it was still locked).
This is not a drupal issue, its an IIS/PHP issue
And there is no known workaround that I could find.

Basicly, do the base advise of not using IIS is the best, I have seen this problem in more than just drupal with IIS that I solved by moving to apache HTTPD (on win32).
Mind you that was for back at school, with a project where I was required to use windows 2000.

the best way I know of running drupal on windows is through apache (because of the internal handling of php).


How do I attach a CAPTCHA when adding the contact form to a node? I am embedding the Drupal contact page in a node. I added the following code in template.php.

function sakura_preprocess_node(&$variables) {
  $node  = $variables['node'];
  if (!empty($node)) {
    $variables['template_files'][] = "node-" . $node->nid;
  }
}

Then, I created the node-24.tpl.php template file (for the node where I add the contact form).

require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';

//no need to maintain two version of node.tpl.php
include "node-page.tpl.php";

function local_contact_page() {
  $form = contact_mail_page();
  // override default values here if you want
  // next one will select a different category
  //$form['cid']['#default_value'] = 0;
  $form['submit']['#value'] = 'Отправить';
  unset($form['copy'], $form['subject']);
  dpm($form);
  return($form);
}

function local_contact_page_submit($form_id, $form_values) {
  return(contact_mail_page_submit($form_id, $form_values));
}

function local_contact_page_validate($form, $form_state) {
  return(contact_mail_page_validate($form, $form_state));
}

print drupal_get_form('local_contact_page');

drupal_set_message($form_id);

I also enabled the CAPTCHA module with the math method. On /contact it shows the CAPTCHA, but it doesn't show it on the contact form I embebbed in the node.

How can I make the CAPTCHA appear on the node page with the contact form?

Webform module is best for creating forms and still having options that come with regular nodes. It also integrates with captcha.

What is the reason you are embedding the form in the node like that?


How to append classes for dynamic terms in jquery? I have installed a rating module, there I want to change the style. for that what I need is
there is a css class called

$('.rate-widget-fivestar)

there are totally 3 widgets. the value of five star increses to 1,2,3 for three widgets respectively.

I want to add a class for each widget.
(ie)

if($('.rate-widget-1))
 {  //class 1
 }
 if($('.rate-widget-2))
 {  //class 2
 }
 if($('.rate-widget-3))
 {  //class 3
 }

how can i acheive that in jquery??

I hope below code works for you.

if ($('.rate-widget-fivestar').hasClass('rate-widget-1')) {
  $(this).addClass('class1');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-2')) {
  $(this).addClass('class2');
}

if ($('.rate-widget-fivestar').hasClass('rate-widget-3')) {
  $(this).addClass('class3');
}


Is it possible to use standard tokens in a views field? I am using Drupal 7.38 and Views (7.x-3.11) to show fields. I can't seem to get standard token replacement working for text fields, e.g. [node:created] is not replaced with the relevant value.

This seems to work fine if I set views to show content rather than fields. Am I missing something obvious?

If you want to display the date the node was posted or created when showing fields, you don't need to use a token. Simply add the field Content: Post date to the fields of the view.

If you want to include this date in a Global: Custom text field in your View, be sure to have the field Content: Post date above the Global: Custom text field. The replacement pattern for the post date will appear by clicking on Replacement Patterns inside the custom text field (usually named [created]). You can also select Exclude from display in the post date field if you don't want it to show.

EDIT:
Re-read your question, and I guess you are using Token Filter to insert tokens like [node:created] in a Long text field in your node, right? If this is the case, I'm afraid Views will not do a token replacement when rendering the field. There may be a way to modify the Views formatter to do this, but that's beyond my skills. See this post for a similar situation - you are able to use token replacements in your Views Header or Footer custom text, but not in a Field.


How to cache block for logged in user? I have a block, created with a custom block plugin (extending BlockBase),  that shows on every page, and I want to cache its data, to speed up  performance.

I have added cache tags to the build() function:

$build['#cache']['tags'] = $cache_tags;

But the build() function is still executing on each page load.  I guess because the cache tags are for render cache, not data cache.

Is there a built in way to cache the data in the build() function for a block for logged in users?

Or do I have to add custom caching in the build function, like this:

if ($cache = \Drupal::cache()->get($cid)) {

https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x

Blocks are cached by default. A block class with this build method:

public function build() {
    return [
      '#markup' => 'Block content',
    ];
  }

gets cached indefinitely or as long as you set in cache max-age.

If you add cache tags to the block that doesn't change whether the block is cached or not. The cache tags are used to invalidate cache items, not to store them. That is what cache keys are used for.

If the block gets cached, this is for logged in users, because the cache for anonymous users doesn't cache blocks, only pages.


How to noindex on paginated pages in Drupal 7? This question is almost a copy of: How to noindex comment/reply in Drupal 7

However in this case i would like to know how to add noindex,follow on paginated pages. For example I want to add noindex,follow on domain.com/artiklar?page=7 but not on domain.com/artiklar

How can I do this? Thanks!

You can use Metatag module and Metatag Quick module to add a "noindex" meta tag to the artiklar content type for pagination pages (you will use the path based metatags part of metatags_quick).


How to install OpenLayers in drupal? I have been trying this for a while without success. After installing the OpenLayers module in drupal 7.14 and trying to configure it i get the following error:

Cannot establish a connection to the server:

I have tried all permutations including downloading the openlayers library in the local machine, giving it a local path in a number of different ways.

The second error that is seen suggests that i am installing an incorrect version of the openlayers library when in fact i have been installing the recommended version i.e. version 2.11.

It has been a frustrating experience getting Openlayers, Geoserver , PostGIS and Drupal 7 working together on Windows 7. The number of combinations are many and there are many issues that are difficult to solve if you are not a webmaster.

There is a patch for the '?q' URL problem which occurs using openlayers-7.x-2.0-beta1, apply the openlayers-fix-marker-lang-path-1404912-3.patch (http://drupal.org/node/1404912) it should fix this for you.


Different logic in Facets functionality what I am trying to achieve is to filter the site's search results and produce results of 5 content types. Search API has helped me do that and very well I must say. There is one more thing though that I need to do and I am wondering it already supports such behaviour and/or if it can be solved by theming OR if I have to create a custom solution; so here it is:

Say my aforementioned content types are: Alpha, Bravo, Charlie, Delta, Echo. I want my facets to be produced in this manner:

All (23)
Alpha (10)
Bravo (4)
Charlie (0)
Delta (1)
Echo (8)

So what i need furthermore than the options your module provides is the "All" option as long as showing Facets which yielded no results.

Apart from that, I also need to bypass the "filter-like" functionality the module provides by default, where I have to click the "-" sign next to the link to go back to the main selection, and make clicking the link filter the results while leaving the other options there for clicking. So if I was to switch from "All" to "Bravo" i'd just had to click Bravo, something like a contextual filter of Content Types in a View, oh and yes, my results are in a view-page.

Thanks in advance.

In the end I did all of this with jQuery alone.

I created a block that contains the

All (23)
Alpha (10)
Bravo (4)
Charlie (0)
Delta (1)
Echo (8)

options, I add the number with jQuery by counting the grouped results, and by JQuery again, I hide the appropriate grouping blocks. So the Facet API block was of no use to me and neither was the View's exposed filter.


Are old nodes automatically archived over time? I just went to a site that I haven't touch in a while and I see this on the homepage:
The requested page "/" could not be found.

I went into Administration » Configuration » System
and saw that the Default front page was set as: /node/1
When I tried to pull up that node, I got a page not found error:
The requested page "/node/1" could not be found

I suppose it's possible that someone else who has access to the site deleted this node accidentally, but I'm just wondering if it may have been auto-archived or something instead.

Are there hackers that gain access to sites and then just delete their front page? Or should I be pointing the finger at the other people who have access to the site?

Drupal does not archive or otherwise delete or modify content automatically over time. There are a few possibilities as to what happened to node1 including:

An administrator or someone with permission to delete nodes of that content type deleted it
there is a rule or other module configuration that deletes nodes after a certain amount of time
Node 1 was deleted a long time ago and someone changed the front page after the fact (not likely as I think drupal verifies the path when you save that setting)

Drupal does keep a record of when nodes are deleted in the watchdog table. The watchdog table has a UI which can be found at /admin/reports/dblog. You can filter this list by type, but note that Drupal only stores a finite number of rows in this table with First In First Out as a rule. So it's possible that the record of node 1 being deleted has also been deleted.


Where is $form_state stored between form build, and form submit functions? I assume that $form_state data can normally be stored either in the database, or in the session.

In this code:

function _module_name_main_form($form, $form_state) {
  $form_state['random_extra_data'] = some_func();
}

function _module_name_main_form_submit($form, $form_state) {
  $important_data = $form_state['random_extra_data'];
}

I trust that there are limits to how the user can manipulate $form_state, which isn't true if $form_state['random_extra_data'] is stored in the session.

Is that safe to do?

The cache_form table stores $form_state, so except for the values passed on by the client, which should be validated anyway, it is safe to trust the content in $form_state.


How to post xml data in drupal_http_request? I have curl code of it This is following curl code

    $ch = curl_init(); //initiate the curl session
    curl_setopt($ch, CURLOPT_URL, $url); //set to url to post to
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // tell curl to return data in a variable
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlrequest); // post the xml
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // set timeout in seconds
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $result['xml'] = curl_exec($ch);

How do I change the following code to use drupal_http_request()?

Seeing how drupal_http_request() is used in _xmlrpc(), something like this should do it.

// The path to send the request
$url = "http://example.com/API_PATH_HERE";
// Example of valid xml code;
$xmlrequest = "<showId>0</showId><tag>123</tag>";

$response = drupal_http_request($url, array(
  'headers' => array('Content-Type' => 'text/xml'),
  'data' => $xmlrequest,
  'method' => 'POST',
  'timeout' => 10
));
// If there is no error return data
if (empty($response->error)) {
  $result['xml'] = $response->data;
}


Similar module to splashify? I'm looking for alternative modules to create splash pages, similar to this: https://drupal.org/project/splashify

This is the only one I've found but I'm sure there should be more of this.

To make the search I used the "splash" keyword.

Does anyone know any other?

The idea is to popup a "colorbox" frame when the user log in, then the user would be able to check "I don't want to see this information anymore?

Try out tinybox simple splash

  TinyBox module uses TinyBox, a lightweight and standalone modal window
  script. The main purpose of this module is to provide Splash
  Screen/Window as simple as possible.


Print variable views template I have created a view with table format but i am not able to print field variables in twig template of view suppose machine name of eck field is field_large,field_quote_source and so on.

 <ul class="bxslider">
  {% for row in rows %}
<li{{ row.attributes }}>
  {% for key, column in row.columns %}
        {% for content in column.content %}
          {{- content.separator }}{{ content.field_output -}}
          {{ content.field_large }}
        {% endfor %}
  {% endfor %}
</li>
 {% endfor %}
 </ul>

This is the path for accessing single fields in a view table template, for example in the first row:

rows.0.columns.fieldname.content.0.field_output

In your code example, to get all field names available, use this in the first loop:

{{ dump(row.columns|keys) }}

The naming of the fields depends on how you have configured the view and is not necessarily the machine name of the field in the entity.


Access denied to all users after migrating site to new server Please don't consider this as a duplicate post. I have tried all the solutions that worked for others, but still struggling to fix the problem (all users including admin taken to 403 page). This is a Windows server running Drupal 7.

Things I have tried -

No base_url value given
No cookie_domain value given
Session table truncated
Cache tables truncated
No file permission differences
Tried Reset password email but the link takes to 403 page
Deleted browser cache

Please let me know if anyone has experience with a similar issue or what else I could try.

This is what I can see in watchdog table.

Thanks

I finally figured it out!

We are enforcing secure flag on our cookie and therefore had to disable the corresponding rewrite rule from IIS, as we didn't have a SSL certificate in new server.


Views slideshow pager as menu tabs I wondering if this is possible.
I can not find any information on this topic, but I am trying to make my pager that is in a Views slideshow into the menu tabs of my navigation, so that if I scroll over the "home" menu button, the image would change, or if I scroll over "about us," the image would change to the "about us" image. Can anyone give me some suggestions on what I can do to achieve this?

Views Slideshow Menu. Only works with 2.x at the moment.


Best settings for xml sitemap, cron time and submission time? i have news site for about 7 months.

The site get new feeds every hour but google take about 1 day to index them and only few of them.

I see other sites that instantly index. "1 hours ago etc". Mine newest in google says "19 hours ago"+. And after some errors with sitemap, now i have 0 links last 2-3 days.

So, i wan't to share my configs and you tell me if something is wrong:

Feeds module import feeds every hour
cron runs every 3 hours
xmlsitemap sumbission time to search engines is every 3 hour

I want to notice that i have arround 130.000 links. I have many feeds who import content. Maby are too much to index? idk

So, what im doing wrong?
PS: Also, every time i submit xml sitemap, i must ping google? if yes, i ping home page or xmlsitemap?

The indexing you are having is moderate / typical indeed. Only a small percentage of sites (from the 100% existing in the web right now) are being indexed every hour or so (some sites are indexed once smaller times like 20 minutes or even less - Wikipedia for example could be indexed in 10 minutes or less in some cases).

You should use various Drupal modules to raise the both PageRank and PQS (Page quality score) of your sites pages.

Use wisely the modules MetaTag, AdvAgg, xml sitemap, pathauto, search404, redirect and others to insure you achieve that targets.

More ways to handle that many 404's - Either your could redirect all the nodes to the homepage or groups of them to some nodes with suitable context).  Moreover, if you have the spare timenergy or resources you could make redirects to NID's 1x1 for all or most of your links. You could also delete some via WMT and than via robots.txt. It is recommended by some to make redirects not in Drupal but rather directly in the main .htaccess file for better performance.


How do I reference (what is the syntax I have to use) to get the data of my Profile2 custom fields? I have used the Profile2 module (D7) and created some custom fields for my users. One of those fields (for example) is "field_company" with the label "Company."

Now I am using a computed field (Company) on a content type (Games). When user creates a Game, I want my computed field Company to be computed/populated automatically, based on the "field_company" field I have set in my profile2.

I am trying to find how to get that information. This is as far I got, so far, but it doesn't work.

$entity_field[0]['value'] = "";
$name=$profile2->field_onoma[LANGUAGE_NONE][0]['value'];
$entity_field[0]['value'] = $name;

You should use the field_view_field() function. Have a look at the follwing page for more information:
http://coder1.com/articles/printing-or-rendering-node-field-or-profile2-field-drupal-7


How to save node form data in form_values using drupal_execute I want to save $form_values in the session table in the submit handler when a node type (eg page) is saved.

How can I reuse this $form_values to create this node again using drupal_execute after some time (say tomorrow)?

I've tried creating it but it isn't working out:

function abcdonations_entry() {
  if (isset($_SESSION['form_id'])) {
    $fs = $_SESSION['form_id'];
    $form_id = $fs['values']['form_id'];
    module_load_include('inc', 'node', 'node.pages');
    $node = array('type' => 'person');
    drupal_execute($form_id, $fs,(object)$node);
    print "Written successfully";
  }
}

Then I save it in this function:

function anu_general_form_person_node_form_submit(&$form, &$form_state) {
  $_SESSION['form_id'] = $form_state;
}

If I understand right you basically want to clone a node later? If this is the case than you can just:

$nid = $the_nid_of_the_old_node;  //get the $nid of the old node
$new_node = node_load($nid);      //load the old node object
$new_node->nid = NULL;            //unset nid to tell node_save that this is a new node
// do what ever you need to the new node
node_save($new_node);             //save the new node

That should do it.


How to get work the hook_form? I try to hook the node form by hook_form(), but I can't modify the base form.
I try to do this like below

function products_form($node, &$form_state) {
  $type = node_type_get_type($node);

  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE,
    '#weight' => -5,
  );
  return $form;
}

What's is wrong? My module name is 'products'.

hook_form() is only meant to be used by a module that provide content type:

This hook, implemented by node modules, is called to retrieve the form that is displayed to create or edit a node. This form is displayed at path node/add/[node type] or node/[node ID]/edit.

Emphasis mine.
It provides the form, and does not do alterations.
If you want to modify base form created by another module, you need hook_form_alter():

Perform alterations before a form is rendered.
One popular use of this hook is to add form elements to the node form. When altering a node form, the node object can be accessed at $form['#node'].

Again, emphasis mine.


Cookies for a webform using page breaks I'm using the Webform module in a Drupal 6 installation. This webform is appearing in an iFrame, and can be found on every page. The website that contains the iframe is static, the Drupal installation with the Webform module is the only thing being loaded in the iframe. This webform is a quiz with 20 questions. The rest of the site is kind of like a handbook, and I want my users to be able to use the static handbook website as a guide while taking the quiz. Each quiz question is on its own page; I am using webform's pagebreaks to split each question up.

Is there a way to set a cookie that takes the user back to the question they left off at, should they choose to leave the form and return?

You can find some well written answers on using cookies in Drupal here.


How would I use DATEDIFF(), NOW(), and BETWEEN in a db_delete() query? Is the something like the following possible?

db_delete('note_dates')
    ->condition("DATEDIFF('start', NOW()) BETWEEN 0 AND 30")
    ->execute();

You can use DeleteQuery::where(), e.g.

$args = array(':arg1' => $foo, ':arg2' => $bar);
db_delete('note_dates')
  ->where("DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2", $args);
  ->execute();

That'll give you

DELETE FROM {note_dates}
WHERE  (DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2)


Set a condition for one field to be unique in all the content types. I am working with Drupal 8, and have a custom post type called: chapter. This content type is connected with a taxonomy term called: Book.

Now, I have a field called: number, for specifying the chapter one, two or three. this field should be unique. For example, if I say chapter 1 I can not repeat it ever again in the same book, but I can upload the chapter 1 for another book. I also can upload all the chapters for the same book in a different order.

So the rule is: Just add a unique chapter number per book.

The final goal is to create a view and be able to order my chapters by the number.

Do I have to use the rules module for that? Or maybe, there is a better approach?.

You can implement a custom validation constraint and a hook_entity_bundle_field_info_alter to set the new constraint to your field.

Check: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint


How to return a specific value when using entity_load? I want to loop through Paragraph bundles and return a string (image path uri string).

I can view the Paragraph arrays as such:

foreach ($variables['field_paragraphs'] as $i) {
  $entity = entity_load('paragraphs_item', array($i['value']));
  dpm($entity);
}

This returns each Paragraph bundle as an multidimensional array. I want to take the value of each uri key and place them in their own array.

To that effect I have tried $image_path = $entity['ParagraphsItemEntity']['field_image']['und']['0']['uri'];, but it returns nothing.

I've also tried making a function.

  function array_column_recursive(array $haystack, $needle)
    {
        $found = [];
        array_walk_recursive($haystack, function ($value, $key) use (&$found, $needle) {
            if ($key == $needle) {
                $found[] = $value;
            }
        });
        return $found;
    }
    print(array_column_recursive($entity, 'uri')[0]);

This gives me an error message.

  Fatal error: Cannot redeclare array_column_recursive();

(It doesn't seem to matter what the function is named; it will always have this error.)

Would anyone know how to simply get a value from a multidimensional array in Drupal?

OK, here's what I did, after discovering Entity Metadata Wrappers:

//FORMATS ARRAY TO SOMETHING EASIER TO HANDLE
$entity_wrapper = entity_metadata_wrapper('paragraphs_item', reset($entity));
//RETURN THE VALUE OF THE IMAGE ARRAY
$image = $entity_wrapper->field_image->value();
//RETURN THE (FULL) URL OF THE IMAGE
$file_url = file_create_url($image['uri']);


How do I save and retrieve CKEDITOR media (images and video) on a CDN? I am using CKeditor, and I need to add media in content. I have enabled the media in the CKeditor configuration.

Then I upload an image:

The image is being added:

Checking the path for the image :

It gets saved in the local server, while I want it to be saved in a CDN.

I am also using the Media module and CDN old S3 module. which saves all the media in the CDN, but the images for CKeditor are saved on the local server.

Currently, it is saved in the base path (eg. https://drupal.stackexchange.com/). I want it to be saved and retrieved from my CDN.

I did find the  Uploadcare : Add media from anywhere plugin, but I don't understand how to use it; I  think it has its own CDN, but I want it to use my own CDN.

Modifying the core is not recommended and it is not the best practice, how do I achieve it in efficient way.
How do I save images added from CKeditor on a CDN instead of the local server?

Until CKEditor developers implement the functionality, you could create a custom module that:

on node add/edit you loop thru all fields using CKEditor and crawl each images/videos
detect if the images are already on the CDN
if not, upload the images/videos on the CDN
replace the images links with your new CDN links
save the node

I hope it will help you.


How to map a URL to an attachment I'd like to have a simple and clean URL for a PDF file, such as

http://www.examples/file1

that maps to an attachment in a Drupal node, rather than using something like

http://www.examples/sites/default/files/files/file1.pdf

I've tried using URL Aliases, but Drupal complains and won't let me create the alias.  I can obviously do this with Apache redirects (with mod_rewrite) or (gasp!) with a meta tag refresh, but both seem inferior to being able to manage it from within Drupal.

You can use File Aliases module for this.


How to login to my site again after all users were deleted? I was inside /admin on my site looking at users. I noticed a lot of what looked like robot made users and I decided to delete them. I clicked the box for delete all on this page. What happened then is that all users were deleted and now I cannot login at all.

All clients linked with whitelabel show error message.

What can I do?

If you have backups then restore from backup then delete users again without deleting the ones you want to keep.

If you don't have a backup then you will need at least user 0 (anonymous) and user 1 (superuser).

I am assuming Drupal 7 because you didn't specify version.

You will have to add those back into the database either via database access in your hosting administration area or from the command line.

Note: I am adding the basic MySQL queries here but you should read these whole linked pages for more information.

The process is similar for both users.
You should read Restore user 0 for more detailed information but here are the SQL queries:

User 0 (anonymous):

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('', '', '', '', '', '', '', '');
UPDATE users SET uid = 1 WHERE name = '';

User 1 (superuser): You can change "admin to whatever user name you want to use. I recommend not using "admin" because attackers will try that first if trying to work out your password.

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('admin', '', 'youremail@example.com', '', '', '', 'youremail@example.com', '');
UPDATE users SET uid = 0 WHERE name = 'admin';

Then you will need to do a password reset for the user 1 account.

Other users
Other users can be added just with the first insert statement without the update statement after however you will lose settings like user picture, signature etc. if there is data in those fields (or unless you know what the data should be and ad it back in).

Those users would also not get roles so you would have to assign roles to them after.

They also wouldn't have the same UID as before so in the uncommon case that you have code that specifically references a user ID that will need consideration.

Note that some modules that change the behavior of Drupal users may change the way you need to add these users back.

For example if you user the "User revisions" module then there is also a user_revision database table that needs to be considered when doing these queries.


Red Herring Error : Class name must be valid object or string After just having spent two days trying to get to the bottom of a particularly weird bug I thought I'd post up what my question would have been — if I had taken the time to write it — and then post my answer also, just in the hope of helping other people avoid the headache.

  PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522

This was the starting point. I got this error — along with a typically pleasant WSOD — after creating a new install of my site on a localhost. The strange thing about it was that I had almost exactly the same setup working on another machine. The code was served by GitHub and so was identical, the database was a direct dump from the original site, php was configured as expected and versions were only a 0.0.5 out (5.3.15 and 5.3.10), both Drupals were version 7.9 ... everything should be working.

What made this weirder still was the fact the site would work directly after a drush rr, however, it would break immediately after a drush cc all, or on refresh.

This led my collegue and I traipsing in circles, debugging common.inc and modules.inc trying to find a clue as to what was going on. What we discovered was that after the reset registry the correct entity_info array was built, but after the clear cache, we only got part of the full entity_info array.

Investigating further we found rather ridiculously that the following code — taken from module.inc — could not find particular functions in particular module files that we knew to exist.

foreach ($list as $module) {
  $include_file = isset($hook_info[$hook]['group']) &&
    module_load_include(
      'inc', $module, $module . '.' . $hook_info[$hook]['group']
    );
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }
}

This could only mean that at the point this code was being executed certain files that should have been included by now, weren't. What made this even more baffling was that if we called the following outside of any of the caching code, it returned the correct entity_info array.

$entity_info = module_invoke_all('entity_info');

This meant that there wasn't anything wrong with the files, it just seemed to be the caching system. To cut a rather long story short, because we didn't have anything modifying the core drupal caching system, we decided to resort to the good old trial and error disable all modules and enable one by one. Great.

This took some time but we managed to whittle everything down to one bespoke module, which we then trial and errored function by function call. Until we got the culprit:

/**
 * Helper function to redirect an actual submit to the ajax handler
 */
function microsites__admin_settings_submit(&$form, &$form_state) {
  return microsites__admin_settings__ajax_button(&$form, &$form_state);
}

So I guess my question — apart from being, what can cause PHP Fatal error: Class name must be a valid object or a string error — would be what out of the above function could cause such a disastrous error, and in such a weird manner?

For those who have been using PHP a while, it should be obvious what is causing the issue, although what wont be obvious is why Drupal didn't make a song and dance about it.

Basically the cause of the WSOD were the two ampersands denoting call time pass by reference. Something that has been deprecated in PHP for a while. The reason why they were there at all was just a copy and paste typo.

return microsites__admin_settings__ajax_button(&$form, &$form_state);

The above should have been:

return microsites__admin_settings__ajax_button($form, $form_state);

With the above change made, everything magically started working again.

Now I might get some people assuming that we just hadn't been keeping track of our errors, but we had as much logging enabled as possible... at no point did either PHP or Drupal complain about the call time pass by reference. Instead what Drupal seemed to do — and only after clearing cache I might add — was fail to include other files once it had hit this illegal / deprecated syntax, which then went on to create malformed entity_info arrays.

I have since tested this on other files, and all it takes is to add a call time pass by reference and it breaks Drupal, at least for all my localhost setups anyway... that is, unless the following has been specified in the php.ini:

allow_call_time_pass_reference = On

If anyone can ascertain as to why the silence (considering all other PHP errors and warnings are shown), why it broke other files loading, and why the problem only affected when running after a cleared cache, I'd be interested to hear.

Maybe upgrading to 7.22 would fix a few of the above... but in future I'll make sure I double check coherence between my entire php.ini(s) I think; rather than spend a few days trying to bash through a brick wall using only a toothpick.

update

Just to answer Clive's question, this was the output in the apache error log after I've just tested the same problem again:

[Thu Apr 11 11:15:29 2013] [notice] Digest: generating secret for digest authentication ...
[Thu Apr 11 11:15:29 2013] [notice] Digest: done
[Thu Apr 11 11:15:29 2013] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6 configured -- resuming normal operations


Get Contacts from social networking sites I am trying to import contacts from Social networking sites to Drupal using OpenInviter. Its working fine with Web mail Providers but when i am trying to get contacts from Social networking sites it is throwing error as

Unable to get contacts.
No contacts could be retrieved from your account.

Any help is appreciated.

I would use Contact Importer in conjunction with OpenInviter.  It could be that you do not have an app for the specific social network to give permissions to allow access to users' data.

While I was configuring HybridAuth, there were options to allow your site to access contacts of users.  This requires you acquire an API key for each social network you want to access, which means creating an app.  If you're still having issues I could set up an app on the social networks you would like to access, then configure hybridauth and see if you can access the contacts through its API.


How do I share configuration between custom admin form and node type edit form? I have a module that requires some settings per content type. The module is to also provide one admin page where all the settings can be applied across content types at once.

Essentially I'm trying to share configuration information between a custom Admin Settings form and the node type edit form. I had this all working with Drupal 8 Beta 10 or something like that, but I'm trying to get it working with the latest stable release (8.0.4).

I originally used the method described here for my custom Admin form using the following code:

$config = $this->config('mymodule.settings');
'#default_value' => $config->get('my_setting'),

Similarly, for the node edit form alter function, I used:

$config =  \Drupal::config('mymodule.settings');
'#default_value' => $config->get('my_setting'),

But the above stopped working for the node type settings form at some point, so I started looking at using Third Party Settings:

$node_type = $form_state->getFormObject()->getEntity();
'#default_value' => $node_type->getThirdPartySetting('mymodule', 'setting', 'default_value'),

This works great for the node type edit form, but I don't know of a way to pull the third-party settings into my custom Admin form partially because getEntity() method isn't available.

So my question is, what is the best practice for sharing configuration settings between a custom admin form and the content type edit form?

So the bottom line appears to be that Third Party Settings is a great way to handle content type settings without really caring which content type you're dealing with, but there doesn't seem to be a way to get this working with a custom admin settings form for the reason described in the question.

If I didn't want to have a separate configuration form that handled the content type settings for all content types on one form, I would definitely have used Third Party Settings. However, since I had this extra requirement, I wound up fixing whatever broke along the journey from D8 beta to stable release.

Now the node type gets included with each of the desired settings using the following code:

function mymodule_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $node_type = $type->get('type');
  $config = \Drupal::getContainer()->get('config.factory')->getEditable('mymodule.settings');
  $config->set('my_setting_'.$node_type, $form_state->getValue('my_setting'));
  $config->save();
}


Input formats and WYSIWYG editor problem I have install 2 editor: YUI and TinyMCE

But wysiwyg settings are:

Why I can't setup editor on this input formats?

Check your permission page, and make sure you have the right permissions.  Also make sure there is no conflicting permissions


Restricting view to content associated with user profile On my site some users have the permission to see others' profile.

I'm looking to show a view in a block containing a food content type. It will be displayed on the profile page of the users (user/*). The block will contain content associated with that user (somehow I need to tell that when I am creating the content).

For example: Content "rice" belongs to user1; content "potatoes" belong to user2.

When I enter the user1's profile I see "rice"; when I enter user2 profile I see "potatos". It's the same block with the information changing according to the user profile I am seeing.

What you're wanting is a contextual filter for your view. Create a node view with a block display and in the Advanced section under Contextual Filter click the Add button.

From there you can add Content: Author uid which will tell the view to filter by author UID. On the popup modal, under the WHEN THE FILTER IS NOT.... fieldset, select Provide default value with Type of Raw value from URL and Path component of 2. This essentially tells the view to pull the UID from Drupal's internal path (i.e. the XXX in /user/XXX when viewing a user page).

After saving the view, you should be able to place it your region to display against user profile pages.


How to Uninstall/Reinstall a custom module whithout losing the content? As we know : it's impossible to unsintall a module whithout being forced to remove all the data that's belongs to it.
The problem is, if we want to update a module we are obliged to uninstall it and then reinstall to get the changes work.

At developpement phase, it's ok , but what about being in a production site and having a big amount of data we don't want to loose, by just adding a field , or changing a type ....

Is there any best practises? Is there a process that could be advised? Is there any feedbacks of your own experience?

For example, I would guess : export data and then import data after the reinstall?

Thank you so much!

You can update your database with

  hook_update_xx

if your module define hook_shema

https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8


"Add to Cart" button/from in template (form ID from Node ID)? I'm working on a website made with D7 and the Commerce Module, with a "Products" view (for the Product content type) having this relationship field:

(Products referenced by field_info_prodotto) Commerce Product: Add to Cart form

I want this "Buy Now" button/form to also be inside each products' page (= in the template for the Product content type).

I can create a template for single nodes (see code), but how should I edit the general template (node--product-display.tpl.php)?

# node--181.tpl.php
<form class="commerce-add-to-cart commerce-cart-add-to-cart-form-24" autocomplete="off"
action="/en/products" method="post" id="commerce-cart-add-to-cart-form-24" accept-charset="UTF-8">

<input type="hidden" name="product_id" value="24">
<input type="hidden" name="form_id" value="commerce_cart_add_to_cart_form_24">
<input name='form_token' type='hidden' value='<?php print drupal_get_token('commerce_cart_add_to_cart_form_24'); ?>'>

<input type="hidden" name="quantity"
value="1">
<input type="submit" id="edit-submit--9" name="op" value="Add to cart" class="form-submit">

</form>

(In the template there is already the code to show a "Buy Now" field - field_tab_5 - but that's just an empty text field and I suppose it's not what I'm after).

Found a solution!

Add a field of type "Product reference" to the Product content type ("Inline entity form - Multiple values" as widget)
Use "Add to Cart Form" to its display format
Field API in node--product-display.tpl.php:

print render($content['field_info_prodotto']);


HTML5 custom data attributes in Drupal I want to use the "data" attribute in some of my tags, and I have been searching for a way to include it.

For Example: I am adding JavaScript code to my form. I use hook_form_alter() and the #attached property.

$path = drupal_get_path('module', 'mymodule');
$form['#attached']['js'][] = array('data' => $path . '/js/custom_values.js','type' => 'file');

How do I add a "data" attribute to the <script> tag generated? I want to use it for arguments to the JavaScript code.

If you mean how to add the data- attribute to the <form> tag it would be as easy as this:

$form['#attributes']['data-foo'] = 'bar';

The same goes for any element within the form:

$form['foo']['#attributes']['data-bar'] = 'baz';

For more info have a look at the documentation for #attributes.


Views Exposed Filter Sort on Entity based on Term Reference Field from Entity Reference Relationship I've been playing around with Views exposed filters on an entity. I have so far been able to create a relationship to another entity through an Entity Reference, and exposed the fields belonging to that entity.

What I needed to sort my entity by was a term reference field on the referenced entity (this is a one to many relationship, the sorted entity can have any number of reference entities). I was able to get a multiselect field to do so, but this is really not ideal. Using Better Exposed Filters I was hoping to get a checkbox list. But it seems that the nature of the relationship doesn't open that possibility up.

So the question is, if I needed a View that allowed sorting an entity by an exposed Term Reference Field filter on all of its Entity References, what method would I use, if not Better Exposed Filters?

So you have two relationships. One to the referenced entity to pull it in, and another on the term on that referenced entity to pull in data such as term names (to sort on term names).

This immediately brings to my mind an issue whereby you will have what seems like duplicate entries coming in. To avoid that you will have to use aggregation, and in the aggregation settings you will have to do a count on one of the fields (which will collapse the result set) and then do an exposed filter.


Content access based on the content author's role I have a content type named "Files". I have given access for users with roles editor 1, editor 2 and editor 3 to update and delete their own content.

Now If a user with editor 1 creates a files content. I need to allow other users with same role (editor 1) to update and delete the content.

I tried Content Access Module but it doesn't helps.

Can anyone give me a working example for this scenario.

The permission on "own content" is connected to the node's author's uid and only relates to role in that a user with the role holding that permission can edit a node they created.

How I would solve your use case is with a hook_node_access in a custom module.
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7
WARNING: I just threw this together as an example, I did not test, and you need to put in the right role values.

hook_node_access($node, $op, $account) {
  if( $op !== 'update'){
    // not my use-case
    return NODE_ACCESS_IGNORE;
  }

  $author = user_load($node->uid);
  if( in_array( 'role1', $author->roles) && in_array( 'role1', $account->roles) ) {
    // the user editing has the same role as the author
    return NODE_ACCESS_ALLOW;
  }
  // repeat ... etc.

  // we did not find what we were looking for, continue with normal access check
  return NODE_ACCESS_IGNORE;
}


Group node from OG membership doesn't work I want to create some views to display Group information on Group content pages. E.g. Display contact info from the group in a block/pane in the sidebar.

I did this before, by using the default OG Content view and add the relations.

I add the relationship OG membership: Group Node from OG membership, and sets its relation to (OG membership from node)
Set the contextual filter to provide a default value (Current OG group from context) and keep relation set to the default OG membership from Node.
Add fields and set their relation to Group node from OG Membership.

This isn't working though, it gives no results when viewing on Groupcontent-pages. It gives only results when viewing the Grouppage itself. I do not know why this is not working the way it should. As I recall I never had this problem before.

I used Organic Groups 7.x-2.7 with Panopoly 7.x-1.30. I have this on 2 separate installs (one on Acquia site, and one in my VM). The VM has only Panopoly and OG (and dependencys) installed as extra so it's almost vanilla.

I have enabled OG Context of course.

How can I solve this? Without these views it's a pain for the user to see in which groupcontext they are browsing.

EDIT:
I installed a vanilla drupal (Not Panopoly). Installed OG + dependencys.
Then I created an empty view and added the following:
1. Relationship: OG membership: OG membership from Node group (required)
2. Contextual: (OG membership from node group) OG membership: Og membership ID
and Current OG group from context

This works! However, this doesn't work in Panopoly... Is this the new way to work with OG and Groupinfo on groupcontent pages?

The SQL-querys views does are exactly the same. Though on Panopoly there are no results. On Vanilla Drupal there is.
How can I debug this?

Solved it. The panel needed the relationship. This can be added on the contexts-page of the panel. The relation I added was:
 Node from Node (on Node: Groups audience [og_group_ref])

When this is added it can be chosen instead of "This node" when Views panes are added to a page-layout.

This works with the default OG Content-view with the relation OG membership: Group Node from OG membership added to it. (on groups without content this gives No content in this group however.)


How to give access to delete his own comments I am using Drupal 7 and want user should be able to delete his own comment. I know that is it not supported by drupal 7 due to threading.
You can provide edit permission from "admin/people/permissions" but there is no option to provide permission of delete.

Thanks in Advance

Ref : https://www.drupal.org/node/777696

Are you familiar with coding? You can try this tutorial.

edit: and i ran into this site, wich is a patch to the module 'Comment Goodness'. There's also some extra info about flat comments (the default structure is nested, not flat).


How to correctly use cookies? (Twig and cache context) In my current project I need to alter node templates depending on previously visited landing page. My idea is that, when a visitor visits one of these landing pages, a cookie will be set, and subsequent node templates will be altered depending on that cookie.

I've got three view pages serving as entry points for my visitors:
myproject.com/tv
myproject.com/mobile
myproject.com/infopoint

In theme preprocess I'm checking/setting a cookie and assigning a template variable. The Twig templates do minor modifications depending on that variable:

function MYTHEME_preprocess(array &$variables, $hook) {
  $router = \Drupal::routeMatch();

  if ($route = $router->getRouteObject()) {
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    $view_display_plugin = $route->getOption('_view_display_plugin_id');

    if ($view_id && $view_display_plugin === 'page') {
      if ($view_id == 'slide') {
        user_cookie_save(['device' => 'tv']);
        $variables['MYTHEME']['device'] = 'tv';
      }
      elseif ($view_id == 'tile' && $display_id == 'mobile') {
        user_cookie_save(['device' => 'mobile']);
        $variables['MYTHEME']['device'] = 'mobile';
      }
      elseif ($view_id == 'tile' && $display_id == 'infopoint') {
        user_cookie_save(['device' => 'infopoint']);
        $variables['MYTHEME']['device'] = 'infopoint';
      }
    }
  }

  // user_cookie_save prefixes all cookie names with 'Drupal.visitor.'
  if (isset($_COOKIE['Drupal.visitor.device']) &&
    in_array($_COOKIE['Drupal.visitor.device'], ['tv', 'mobile', 'infopoint'])) {
         // I'm doing design modifications in my Twig templates depending on this variable
        $variables['MYTHEME']['device'] = $_COOKIE['Drupal.visitor.device'];
    }
  }
}

In services.yml I've activated the cookies cache context

parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site', 'cookies:Drupal.visitor.device']

In my Twig templates I've got multiple code pieces like this:

{% if MYTHEME.device == 'tv' %}
   <!-- code here -->
{% else %}
   <!-- other design here -->
{% endif %}

Sadly the code doesn't really work. On the entry pages, the device theme variable is always correct, but the cookie is not updated (seems as if only first uncached hit sets the cookie. I even have the weird situation that cookie and twig variable aren't equal.). On node templates the theme variable isn't set correctly at all.

Any ideas how to get the code above working?

PS: Due slow views with geo-distance calculations disabling cache is not an option, I need to provide cached pages also for anonymous users.

I've updated the code in the question, the code is now working. It was almost complete, I had made some simple mistakes though:

Even when providing a proper cache context, you still need to disable the Internal page cache module. Only Internal dynamic page cache module is allowed.
user_cookie_save() prefixes the cookie name with Drupal.visitor. This is  the real name you'll also see in your browser's dev console. But when checking for cookie names in PHP, dots and spaces are converted to underscores. That means using user_cookie_save(['mycookie' => 'some_value']); creates a cookie with a "real" name of Drupal.visitor.mycookie, but in PHP

your template/module code needs to check
if ($_COOKIE['Drupal_visitor_mycookie'])
and you also have to use the underscore name in services.yml
required_cache_contexts: ['cookies:Drupal_visitor_device', '...other_stuff...']

Don't set the cookie value and check that updated cookie value in the same request:
user_cookie_save(['mycookie' => 'new_value'])
will immediatly update the cookie in the client browser, but PHP code in the same request like
if ($_COOKIE['Drupal_visitor_mycookie'])
will still return the original value from the previous request.


How do I save username and password using a "Remember me" checkbox in the login form? I want to save username and password using a Remember me checkbox. If I click it, the username and password should be save for future. In Drupal I am using Persistent login module to do this but I am not able to save the username and password.

I think Remember me module doing the same job which you wants.


Find an entity that most recently referenced a particular entity Scenario
A content type - Wardrobe references another content type Product via Entity Reference field - field_product.
Problem Statement
I need to find the Wardrobe content which most recently referenced a particular Product content.
Question
Could this be accomplished through Views alone (by playing with available options in views) or do I need to write a customised query in php? I cannot figure out the way with either of these options :/
P.S.
Alternative suggestions are welcome :)

I am afraid, it's impossible to achieve what you want with a simple entity reference field alone.

The problem is that while the wardobe content saves the date of its most recent edit, you can not tell which (if any) product was added during that editing session (unless you use versioning consistently and compare the products saved in different versions manually). To complicate things further, an entity only saves the date of its most recent edit (saving over the previous edit date) which makes it very inadequate to track when a particular product was added to a wardrobe.

The biggest issue you face is that the information you need (when an item is added) is not directly tracked at all. While you could probably figure it out if you use versioning, this data would still be very hard to access in views.

What you can do is make a list of wardobes a particular item is part of and order them by most recently updated wardobe (though this most recent edit may or may not have actually added that product). If that's not what you want you need to find a way to track the missing date information yourself.

Possible starting points which come to mind:

Custom compound field with joined reference + date fields: https://www.phase2technology.com/blog/compound-fields-in-drupal-7/
Custom module which adds a db table with columns for wardrobe id, product id and date. You can access these data on node save, during which you can still access the old version of the wardobe, check which (if any) products were added, and add those entires to the db.


Pre populate a text field when creating node Say I'm creating content into a text field. Instead of inserting text by typing into text field, how could select text from a drop down list to pre populate the text field?

I would suggest you create a content type called "Text Templates". Then add a reference to this content type in the content type that you are using.

In hook_node_submit you can get the value from the body fields of the Text Template node using the node-reference and then pre-populate in your current node.

If you want the body to be filled during the node edition then you will have to write an ajax call to fetch the body based on the drop-down value and fill it in the body.


Constantly getting "The website encountered an unexpected error. Please try again later." I wondered if I can get some advice regarding working with Drupal 8. I've tried installation after installation and sooner rather than later I'm effectively bricking the installs by just installing third party modules.

Can someone please advise how I can debug effectively? I'm not a dev but can do some basic dev tasks.

I used to use for Drupal 7 in settings.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

However, I have no luck with this in Drupal 8.

It's getting incredibly frustrating when trying out new modules for this constantly to be happening.

Log file reads (which I've Googled) prior to asking.

  [proxy_fcgi:error] [pid 15594:tid 139919129229056] [client
  79.70.230.243:47902] AH01071: Got error 'PHP message: Uncaught PHP Exception
  Drupal\Component\Plugin\Exception\PluginNotFoundException: "The
  "file_type" entity type does not exist." at
  core/lib/Drupal/Core/Entity/EntityTypeManager.php line 125\n'

A second site outputs:

  [pid 15594:tid 139919154407168] [client 79.70.230.243:49570] AH01071:
  Got error 'PHP message: Uncaught PHP Exception
  Drupal\Component\Plugin\Exception\PluginNotFoundException: "The
  "file_type" entity type does not exist." at
  core/lib/Drupal/Core/Entity/EntityTypeManager.php line 125\n',
  referer: http://domainname/user/login

Despite me having the above information, I really don't know what is causing this. Furthermore, I never do as reading the log files and following those error messages (like the above ones) doesn't clearly illustrate which module is causing the problem.

That exception is thrown by EntityTypeManager::getDefinition() when it doesn't find any definition for the entity with the ID passed as argument.

  if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
    return $entity_type;
  }
  elseif (!$exception_on_invalid) {
    return NULL;
  }

  throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));

The ID of that entity could confuse: It's not the File entity Drupal core implements because its ID would be file, not file_type. That is the entity defined from the File Entity (fieldable files) project, in its FileType.php file.

I take you installed the module, and uninstalled it, but your site still have some instances of that configuration entity. I would try cleaning Drupal cache, and if that doesn't work, I would re-install the module, go to /admin/structure/file-types, delete any entity listed there, and uninstall the module again.


change FILTER CRITERIA for display (in views) I want to have different filter criteria for one display in my views. I added it and when i hit "Update preview", the data shows up as expected in the bottom area of my views window. But then, when I surf to the url or when I hit the link specified at Path, I get data that appears without that filter applied. I have hit the save button on top, too. What else am I missing?

edit 1
Also, I have realized that my second display also shows the title of my first display but I can reach it on the alternate path url...

edit 2
see screenshot in better resolution at: http://www.tiikoni.com/tis/view/?id=5c2a5fe
screenshot: On the left screen, you can see the view settings and on the right screen, in the April 2014 & May 2014 sections, you can clearly see that the filter Content: Title (contains Brunch) doesn't get recognized

The Filter criteria didn't get applied properly because both Displays had the same name. It is required that both View displays have different names to be able to apply filters to only one Display.


Add a role to a user during MailChimp subscription I'm sorry, I'm a beginner in Drupal 7, and I don't really understand the roles behaviors. I arrive in a website which is already done, and I have to add a functionality : a newsletter for another entreprise but on that website.

So I used Mailchimp to create a list, and the subscription is possible on the website.
But I don't really understand how to send a mass contact to these people because they're not put in a specific role.

So my question is, how can I put people who subscribe to this newsletter in a specific role (Which I already created) ?

I'm sorry, maybe this is a bit difficult to understand, and there can be a lot of mistakes in my message because I'm French.

I read some of the answers in that website and I looked for some others on the internet, but really, it's extremly complicated, I don't even know where to put those php codes I found.

Thank you really much for reading it, if you can help me, I would really be pleased !

Try using rules you can add a condition and put action to it.
condition -> when to activate your rule: when a person subscribes
action-> add user role.
Hope this solves your problem


eu cookie compliance With the new EU cookie compliance law coming into force Friday (26/05/12), does anyone have any suitable advice for those of us who not only develop in Drupal and other frameworks? I myself have a degree in Business (and use to teach Business at FE level and had numerous limited companies), the ICO website is not helpful for those who developing, but those who have 'netpreneur' aspirations, may have second thoughts now the full weight of the ICO is behind the EU law. Personally, I would be quite happy to see the cookies option removed from all visitors on my future portal developments.

Would anyone care to shed some light on this in how we can ensure end users perceptions of 'privacy' theft are reduced to the lowest possible point. I don't believe the answer is merely to 'seek professional advice' as some Drupal developers simply cannot when starting out, even though I would argue that that should always be the case from a organsizational legal standpoint.

What would be the simplest answer to ensure compliance across Drupal?

The simplest way to ensure compliance for Drupal is to install the Cookie Control module, which has been created for exactly this purpose:

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.

There's also the EU Cookie Compliance module:

This module intends to deal with the EU Directive on Privacy and Electronic Communications that comes into effect in the UK on 26th May 2012.

This second one does a better job in my opinion.


File in /sites/default/files/ gives 404 error my page is trying to load this file /sites/default/files/languages/it_Et3NQJm4afZYHEnSM9oq5ylZkAw2ExqC8PQtEYrxXDU.js but it gives 404 error.
This error is spamming my log page with errors messages. If i check the ftp the file is there but if i try to load it from the url it gives 404 error. Is it a permission issue? How can i fix? Thanks

Yes, it is a permission issue. Did you move the website to a different server? Sometimes, after you change the server (maybe from localhost to production) some files can have permissions issue.

That's a Drupal generated file, so you can make a backup of it, remove it, flush all caches, cross your fingers and load the page again. Hopefully Drupal will create the file with the correct permissions and the issue is solved.

If this doesn't work, check the watchdog again and check what's the problem again. Maybe there is a different problem... like that your Temporary directory is not writable.

If you still receive the same error. Try to flush all caches. Then, try to flush CSS and JS cache (this can be done with administration menu module in the first link in the left).

If that doesn't work, you must check the file permissions directly, so lets check if the user and group are configured to what they should be.

Then lets check if the file is accesible, maybe modify the permissions to 644 and check again. If this doesn't work, then change it to 664, If still doesn't work, 666; it should work now, but the user and group of the file are not well configured.

EDIT: Permissions updated as suggested by @Clive.


How to restrict each user to making only 1 comment per node? Does anybody know if there is any way I can restrict each site user to making only one comment per node on my Drupal 7 site? I haven't found anything yet.

I've just tried a complicated setup with flags and rules and triggers and actions and redirects. This didn't work too well.

Implement hook_form_alter() in a module. If the form is the node comment form, check if the currently logged-in user has commented on this node earlier. (You might have to write a custom function for this.)  If the user has commented on the node, disable the submit button and the textarea.


What is the best order of content deletion on Drupal sites? Whenever I try to clean up a site.

I delete stuff in the wrong order, and then the site breaks.

Any guidelines on how to do this?

Content first, then content type? Blocks, views, what to delete first and in what order so things don't break?

Yes, delete content first, before you delete the content type. It won't actually break anything in core Drupal if you do delete the type first, but you'll end up with orphaned content; which can be a pain.

Beyond that it comes down to what custom/contrib modules you have installed, and how they're being used. There are hundreds of modules that make use of nodes/content types, all in different ways, so whether or not you would need to do anything specific for each of those depends on the module itself, and what it's expecting.

For example, deleting content and content types may or may not break a particular View, depending on how it's configured (maybe there's a custom preprocess function relying on the content type field not being empty).

Deleting a content type provided by a Feature might break something in that feature if there's custom code relying on it.

Blocks don't have any relation to nodes/content types by default, so if you have something installed which connects them, you might need to do something specific to avoid that module producing errors.

TLDR; there's no single answer - list out the modules you have installed, work out which ones of those have interaction with nodes and content types, and come up with a basic plan of action for each that you follow before deleting.

If that's too much work, then just make sure you remove everything in your site that relates to those nodes or content types before deleting them.


Rendering field cases unexpected error Hey guys I tried to render a field on to the page template and it works fine on all pages except login/registration/profile pages.

Here's the code:

    <h3>
     <?php print render(field_view_field('node', $node, 'field_introduction', array('label'=>'hidden'))); ?>
    </h3>

Here's the error:

You need to load the node to render it if the page you are viewing is other than node page... In node page page.tpl.php contains $node object.. See page.tpl.php documentation for more details...

  $node: The node object, if there is an automatically-loaded node
  associated with the page, and the node ID is the second argument in
  the page's path (e.g. node/12345 and node/12345/revisions, but not
  comment/reply/12345).

If other than node page you need to load the specific node from which you want to render the field in your login/registration/profile pages.. You can override page.tpl.php for specific pages.. For more details see Template suggestions..

To load the node specifically you can use node_load API function...

$node = node_load($nid); // Where $nid is node id


is there api for After rate_save_vote? I want do something after the eventAfterRate in php,
and I have use the rate rules http://drupal.org/project/voting_rules  ,the result turn out not after,and the same as implement the hook_rate_widget_insert.
so is there api for  After rate_save_vote?

Rate relies on the Voting API module, which exposes hook_votingapi_storage_add_vote():

  Save a vote in the database.

function hook_votingapi_storage_add_vote(&$vote) {
  _mongodb_votingapi_prepare_vote($criteria);
  mongodb_collection('votingapi_vote')->insert($vote);
}

I don't know of a Rate-specific hook but you might get somewhere using that one (all depends what you need to do I guess).


Are there any benefits/caveats with using Entity Reference over Term Reference? Pretty simple question really, but is there any benefit to using a core term reference field over an Entity Reference field?

Obviously tagging is not really an option with Entity Reference, but I've used the Inline Entity Form for creating new terms from a node page and it works fine (I prefer it over tagging if my terms have fields).

tl;dr

Apart from tagging are there any benefits/caveats with using Entity Reference over Term Reference for referencing taxonomy terms?

Swings and roundabouts really, it depends on your use case...

Behind the scenes there's essentially no difference - both field types relate one entity to another by way of an ID, so it really comes to down which type provides you with the 'frills' you need/want.

As you mentioned Taxonomy has the open tagging widget, which is nice, but then Entity Reference has Views integration (by way of Entity Reference View Widget) which means you can define as complex a view as you like for your selection widget. Also very nice.

And then there's Inline Entity Form which you also mentioned. That's a superb tool obviously, but only really useful if you need it in your project.

What Taxonomy has going for it is that it's part of core, and doesn't require a bunch of other modules installed to work. But then in a normal Drupal build a lot of those modules will probably already be there. It also maintains a term index table for nodes which can help with performance, but obviously only if you're relating your terms to node types.

I think your choice is going to come down to what widgets/formatters you need for a particular situation to be honest, it's too tight to call :)


Remove "submitted by" How can I remove "submitted by"? I already try to remove it on admin/structure/types/manage/page, but i still see "Submitted by...".

You need to check your node and page level twig templates to make sure it is not outputting the submitted by information, despite what the setting is here. There could also be a Views block outputting this information in one of the regions, which would ignore the setting as well.


Links displaying as plain text, and html tags not applying, no matter which text format is selected I have a text field type, that I'd like to be able to include links within. It appears that all of the formatters should be able to do this by default, and that the full/filtered html formatters should be able to handle html tags. However, for some reason, my text field is not doing either of these things. Links are simply appearing as plain text.

I think that they did work before, although I can't exactly remember where else in the site these filters are used to double-check, but they are no longer honoring links or html. Additionally, if full/filtered html is selected, then any html tags are hidden from view but are not being applied to the text. This leads me to believe that the formatter is recognizing the tags, but for some reason is failing to process them. Any suggestions?

So, just in case I wasn't clear at all:

Links are displaying as plain text (e.g. typing in http://www.google.com simply renders as http://www.google.com - plain text, no link). This is occurring with all formatters, including the "Plain Text" formatter, even when "Convert URLs into links" is selected. This is occurring with email addresses as well.
All html tags are being ignored (e.g. entering Google or Local Link displays only as Google or Local Link, without rendering the link. Additionally, something like Bold renders as Bold, without the style applied).

It's hard to suggest a solution without examples, but I'd suggest you check the order of your text format filters (/admin/config/content/formats/full_html) and see if:

Convert URLs into links is still turned on
There are no additional filters acting on links or <a> tags that would cause them to be killed or hidden
Make sure your links look like links! Obscure ones like bit.ly/4321 or even google.com won't get picked up. If they aren't getting picked up, adding http:// to the front of it normally triggers the auto URL filter.

If that doesn't work, see if you can post some example code. If we can see how they are being hidden, we might be able to assist better.


Creating a poll inside a content type I need a poll inside my content types.

Sometimes the users create an article and like to create a poll directly into the node they created. They don't want to create an extra poll with no connection to the original article.

So how can I get the poll functionality inside a different content type?

Possible solution 1: The Pollfield module seems to be a good starting point. This should do what you need for Drupal 6. However, it might not be a stable solution for Drupal 7.

Possible solution 2: It seems the Poll Improved module might be fit your requirements seeing that provides a field for polls. Though it also doesn't have a stable D7 release.

  They don't want to create an extra poll with no connection to the original article.

You can use references (or entityreference) to have your article nodes reference a poll node. Though that would require another step for your content creators.