How do I add an extra "Add content"-link to the admin toolbar dropdown I am trying to add some improvement to the workflow of the webmasters. Right now they have to click "Content", and then click once more on the "Add content" button. Since I am working with the "Admin toolbar" module, I want to add a "/node/add" link below the "Content" link in a dropdown. But no success yet.

This is fairly simple. First, create a your_module.links.menu.yml file in your custom module and add the following:

your_module.admin:
  title: 'Add content'
  parent: system.admin_content
  url: internal:/node/add

Clear cache and you're done!


How to tell Custom Breadcrumbs which vocabulary to use? In my site I have pages with a single vocabulary called "category" and Custom Breadcrumbs displays the taxonomy hierarchy and it works.

Another content types has several vocabularies, including "category". But here Custom Breadcrumbs (CB) will not use the category but other vocabulary to generate the trail.

If I exclude the vocabularies I don't want CB to use to only allow "category", then no breadcrumb is displayed.

The only difference I see between those content types is the order in which I have created fields. Category was the last field I created for my second content type

So how can I force CB to use category as vocabulary ?

I had the same problem on my site. I managed to fix it the hard way.

Edit custom_breadcrumbs_taxonomy/custom_breadcrumbs_taxonomy.inc

Add these lines after line 20:

$query->condition("v.vid", 2); // 2 is the id of vocab You want to use
$query->orderBy('v.weight');
$query->orderBy('t.weight');
$query->orderBy('t.name');

So You have:

...
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
$query->fields( $t_alias );
$query->condition("r.nid", $node->nid);
$query->condition("v.vid", 2);
$query->orderBy('v.weight');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$result = $query->execute();
$terms[$node->vid][$key] = array();
...


FAQ in Drupal, using vocabularies? Hi Drupal enthusiasts!

I am trying to design way of organizing FAQ on Drupal page.

Does anyone know about module that implements following use case?

2 vocabularies: faq categories, faq items grouping.

Example:

Faq Categories:

Application

Calculator

Paint

Notepad

Faq Grouping:

Using cursor
Printing
Saving

Now I create question, I may choose Paint and Notepad tags for categories, to show a question in both categories. Then I choose printing term to show this question next to other one, which is also printing group.

Do you think I should struggle with Views? I don't think it's gonna fulfil following use case. Probably I need to write code by myself.. Question can be assigned to as many grouping and category terms as wanted, as some questions are referring to multiple..

It turned out you can do this with Views. You list all content with some category tags, then you sort them with grouping tag and remove not needed headers (duplicates).


How do I create templates in my custom module? I've created a custom module that has a bunch of PHP functions whose main purpose is basically to output HTML. For example:

function showRecentActivity($tid, $recordStart, $count){
    //do some db_select stuff to get an array of node IDs...

    foreach($nids as $nid){
        $node = node_load($nid);

        //now that we've loaded the node, 100 lines of if, echo, etc. will follow in order to output the HTML to the page
}

Perhaps you can already see the problem. While echoing HTML is fine for small pieces of markup, constructing full pages with echo statements is horrible to code, maintain, and very bug-prone.

Obviously what is needed is a pre-defined template file, written in HTML with just small places for echoing the necessary PHP variables. Just like my theme's template files.

But I have no idea how to do this with my custom module.

hook_theme is your friend, it allows you to modularize your markup in two ways:

Allows you to define a template file for your markup.
Allows you to define a theme function.

No matter which way you go, you will call for the markup the same way. so lets say you wish to modularize markup for recent activity. You will do the following in your custom module:

function custom_module_theme() {
   return array(
     'activity' => array(
       'variables' => array('variable1' => NULL, 'variable2' => NULL),
       'template' => 'custom-module-name-recent-activity',
     ),
   );
 }

You will create custom-module-name-recent-activity.tpl.php in your module directory where you will have $variable1 and $variable2

Your custom-module-name-recent-activity.tpl.php will look something like this:

 <?php print $variable1; ?>

 <?php print $variable2; ?>

And then from your module when you have done your processing and have established $variable1 and $variable2 (you can pass as many as u want), you will simply do:

theme('activity', array('variable1' => $variable1, 'variable2' => $variable2));

Hope this helps, I wonder now if I should have linked to some tutorial. But hey its Saturday :)

(And if you are using Drupal 6, change 'variables' to 'arguments' in the code above.)


How to let users choose one role from 2 offered on their account page? I have Drupal 7 installed on my local WAMP server.

I need some simple solution to let users choose one role from 2 offered on their account page AFTER registration.

Is it possible to do it with the Rules module? - when a user follows one of the 2 links he is assigned the corresponding role. The problem is I cannot find the proper Rules Event that could initiate this process.

As the last resort I would probably have to use the Auto Assign Role module.

Using Rules, I would do it this way (untested):

Create a user field, select list (or radio button, whichever you prefer) - we will call this field_user_role_choice with the options (Role1Name, Role2Name)

First Rule:

Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

Condition: Data value is empty - selector: account:field_user_role_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
Condition: Data comparison - selector: account:field_user_role_choice, value: Role1Name key
Actions: Add User Role - whichever role is associated with Role1Name
Actions: Remove a User Role - whichever role is associated with Role2Name (this is to prevent both roles being assigned to one person)

Second Rule:

Create a new Rule, React on Event: After updating an existing user account

If you don't assign a default value,

Condition: Data value is empty - selector: account:field_user_role_choice, Negate (this is to ensure it doesn't trigger on a registration or if the user doesn't select a role)
Condition: Data comparison - selector: account:field_user_role_choice, value: Role2Name key
Actions: Add User Role - whichever role is associated with Role2Name
Actions: Remove a User Role - whichever role is associated with Role1Name (this is to prevent both roles being assigned to one person)


Template.php - Hiding Specific Element on Node Edit Drupal 7

Say I have a custom element being rendered out on my page.tpl.php (say it's named $custom_element in the below example), but this is also showing up on the Node Edit page because I want this user to not use the admin theme to edit Nodes but just same theme the front end is using to edit Nodes.

What hook do I use to hide this element when the user is editing the node? What's the best approach in this?

My template.php file

function mytheme_preprocess_page(&$vars, $hook) {
  if (in_array('page__mypagetype', $vars['theme_hook_suggestions'])) {
    $vars['custom_element'] = my_custom_element();
  }
}

Sorry if this doesn't make sense. I'm not sure I'm using the proper wording. Basically trying to figure out how to say "Drupal, while the user in logged in and editing these nodes, please don't show this element on the node edit page since it's printed in the page.tpl.php".

I know this can be done by creating a page--node--edit.tpl.php page. But isn't there a way to do this via a hook in the template.php?

As fast solution, verify the value returned from arg(2) is different from 'edit'.

   function mytheme_preprocess_page(&$vars, $hook) {
      if (in_array('page__mypagetype', $vars['theme_hook_suggestions']) && arg(2) != 'edit) {
        $vars['custom_element'] = my_custom_element();
      }
    }


References lost when a content type is renamed Actually I work in a project developed using drupal 7.
Drupal is totally new for me and sometimes something happens that leaves me stunned…
Today I have discovered something terrifying: when a content type is renamed (and his machine name change), you have to turn the whole project in the parts where the content type was used (in my specific case rules link) because when the machine name change it is possible that the references are lost!!!

You can help me to understand this comportament?

why not name it back, and then only changing the displayname, not the machinename would maybe sufficent for you ?

else do an export and import - as suggestes via features module.


Disable default site and only use multisite On my server I have drupal with a multisite sub-directory set up (example.com/www.site1.com), and do not use default for anything. However, when i go to default (example.com), I am sent to the default install.php (example.com/install.php).

How could I best prevent this from happening, and for example, show a custom index.html page when a user lands on just example.com?

You can't have an index.html in the root of your default directory, Drupal doesn't treat these directories like normal web folders. If you want example.com to go to a folder with a plain index.html file in it, you're going to need to edit your vhosts configuration. Right now, your vhost file probably looks something like this:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.site1.com, www.site2.com, www.site3.com
  DocumentRoot /var/www/YOURDOCROOT
...etc

What this is doing is redirecting all sites that match either the server name or server alias and sending them to the DocumentRoot folder specified. When it gets there, Drupal tries to map the http requests to the appropriate folder but finding none for example.com, it sends it to the default directory instead.

If you want it to go to a single-page index.html, you are going to have to remove example.com from your vhost above and setup a new one, pointing example.com to that new folder, ex.

<VirtualHost *:80>
  ServerName example.com
  DocumentRoot /var/www/EXAMPLECOMDOCROOT
...etc

and place your index file in there.

If instead you want Drupal to send all traffic to one of your subsites, you can try either of these two methods:

Remove the default directory (assuming there is nothing in there you want) and symlink it to the site directory you want it to be using instead, ex. if you want it to be pointing to site1

ln -s www.site1.com default
You could also point your primary domain there as well using symlinks, ex:

ln -s www.site1.com example


Using the Sites module with a multiligual site My multilingual site has three sets of (anonymous or logged-in) users: public, set1 and set2. They will all get the same site structure, but set1 or set2 will see slightly different content on some pages. Each group will be given a URL: http://example.com/mysite for public, and http://example.com/mysite/set1 or http://example.com/mysite/set2 for the others.

I can use the Views module with the Context module to help decide what content to show on the pages, but I need a way for the URL to retain, for example, "set1" in the URL path as they navigate around.

I tried Sites (which uses PURL), but it doesn't work with Internationalization: it prefixes the site name before the language, so when clicking the language selector back and forth, you can end up with page not found and a broken menu at http://example.com/mysite/set1/en/fr/fr/fr/en/en/en/en!

Is it possible to use Sites with i18n?

Or should I use another approach?

You cannot use the PURL "path" method with i18n (Internationalization) because it conflicts with i18n outbound url rewrites - specifically the detection and maintaining of region and language using the path.

I'm not sure if PURL domain and query string methods will still work.

I too am looking at this because I have a project where we've used PURL to maintain a brand identifier with the commerce module, but we want to also use i18n in future. I've used i18n and Domain Access modules before, both separately and together and they play well. Domain Access though is not what you want.

My suggestion would be to treat your "set1" and "set2" like regions. The i18n module lets you specify a region and language that is detected from the path. This is so you can have things like

Germany with German (DE-de)
Germany with French (DE-fr)
Germany with English (DE-en)
United States with Spanish (US-es)
United States with English (US-en)
etc.

So, in these examples we have a country-code and then a language. The i18n module allows you to detect first the country code as a region and the language code for language and then customise the settings based on both.

I would suggest you use this method to specify custom languages where you have a "set1" for region and a standard language code for language, defaulting to English where no language is defined (ie. LANGUAGE_NONE).

I'm going to give this a go myself for my project. I'll let you know how I go.


How to have on-page comments in Drupal 7? Currently, if you enable threaded comments on Drupal, the user has the ability to click on "reply". This takes the user to another page where they can write the comment. I want this functionality to happen on-page. In other words, if they click "Reply", a comment box must drop open using JavaScript or Jquery.

First prize is if there is already a module available or some setting that does this that I am missing. Alternatively, I would assume the best way is to just include the code in the Template File of the comments being generated?

It seems you're looking for the AJAX Comments module

Features:

  Provides ajax comments to Drupal sites. Features:

  Makes AJAX submits
  Allows replies to comments on the actual thread page
  AJAX comments deleting
  Works with CAPTCHA
  Cool jQuery sliding
  views integration


Drupal 7 CKEditor while replacing from textarea media files are not rendering I'm working with Drupal 7 + WYSIWYG module + CKEditor + Field Collection.

My issue is, CKEditor is not rendering the media files which is included through media browser.

Steps to reproduce:

Create field collection field with unlimited occurrence.
Add some text and audio/video/document file using media browser with media teaser setting.
Now click "Add another item" button.

That's it now new field will be added, but the previous field will only have the text you entered, the media will be gone.

When I debugged the field, I found the values in hidden textarea. When CKEditor tries to render the values, media elements are not rendering.

After a long research I found one solution from here.

The patch they provided works for me.

https://www.drupal.org/files/issues/interdiff_8413.txt

I will leave this question open, so that others can get some help from this.


May I know the difference between field_data_body and field_revision_body? As I am a beginner of this Drupal 7 I have some doubts regarding these database tables.I need  a short notes regarding all these database tables.The doubt which I had found is that when I add the content in Drupal 7 it is inserting in these two database tables i,e field_data_body and field_revision_body and in similar way when I add comment it is also doing the same functionality. I need someone's help.

In short:

field_data_body is the current body data.

field_revision_body is a historic backup, that you can revert to if necessary.

Detailed explanation of revision:

  Drupal lets you create a new revision every time a node is updated.
  This allows you to track how the node has changed over time on your
  site.

  To enable this feature you go to the default node editing form (D6:
  administer/content management/content types/edit/workflow settings;
  D7: administer/structure/content types/edit/publishing options) and
  check the box Create a new revision in the node editing form. This
  will result in a new revision being created every time the node is
  edited. (Administrators can override this when editing an individual
  node.)

  To view and manage revisions, use the Revisions tab when viewing a
  node (you must have "view revisions" or "administer nodes" permission
  to view revisions.) From the Revisions tab, you can view the
  individual revisions, revert to an earlier revision, and delete
  revisions (you must have the "administer nodes" or "revert revisions"
  and "delete revisions" permissions).

  One interesting detail of the system is the behaviour of the reverting
  mechanism. Let's say you have revisions {1,2,3,current}. If you revert
  to revision #2, a copy of #2 is made and the copy is set as the
  current revision. Thus, after reverting you'll have {1,2,3,4,current},
  where current is a clone of #2, and #4 is the previous current
  revision.

  Another useful feature of the revision system is the Log field, which
  appears near the "Create a new revision" check box on the node editing
  form. If you add a message to the Log field when you create a
  revision, that message will appear on the Revisions tab along with the
  revision. It is a good idea to add a meaningful Log message whenever
  you create a node revision, so that others (or you, months later) can
  see why you changed the node and what your changes were, without
  having to actually view the previous revision.

  You can enhance the revisions tab by installing the contributed Diff
  module. This module allows you to see the differences between two
  revisions; without this module, you can only view the entire content
  of each revision, and it may be difficult to tell exactly what has
  changed between the revisions.

  Note that the node_revisions table in the database will always have
  one record associated with each record in the node table, which it
  keeps track of as the current revision. This will happen even if you
  do not have revisions enabled. On the other hand, if you have enabled
  revisioning, you will have multiple entries in your node_revision
  table associated with each node, corresponding, not just to the
  current revision, but all past revisions too.

Source: Node revisions

Related:

How to disable the revision feature completely?
Node Revision Cleanup


Can I clone a view but keep it independent of it's content? I'm looking to duplicate(clone) of a view, so that I may reuse it on other pages and have it will not pull through the same content.

I'm using Views 7.x-3.8 on Drupal 7.34 this will be updated later when the site goes live.

Yes it is possible to duplicate a views as much as you need and edit them independently. It saves a lot of work and time.


How to set cache settings for Block I want to set the cache settings for a block that I build by module.
I know how to set the cache settings for the build array, but I am not able to find a possibility to modify the cache of the block itself. (label / twig)

The theme of the block does output a form by receiving an array. This array is language specific. I need to set the cache to "language specific" or turn if off completely. But how?

Thanks.

Everything that is render cached in Drupal is by default varied by interface language specific.

If that's not enough and you have different interface and content language for example, you need to use cache contexts. Which works exactly like anywhere else, with $form['#cache']['contexts'], see https://www.drupal.org/docs/8/api/cache-api/cache-contexts for more information.


exclude contextual filters from breadcrumb I'm having a bit of a problem here.
I have a view which contains a list of items. At the top there are some vocabulary terms which you can click. When you click you go to a next page which shows a filtered list.

The problem is, on that new page, the filters are being added to the breadcrumb which I don't want. How can I exclude these filters from the breadcrumb?

example
The page with the complete list has this breadcrumb, which is good:
Home » Opleidingen » Bijscholing

Next, if we click on 'gasten, hoe gaan we er mee om', the list gets filtered with the word 'gasten', on the next page the breadcrumb is like this:
Home » Opleidingen » Bijscholing » Gasten, hoe gaan we ermee om? » » gasten » gasten

I want to be able to exclude this part '» » gasten » gasten'

Click the "override breadcrumb" box in the settings pane for the contextual filter. You can override it with a custom value and you can use %1, %2. This won't exclude them but it will clean up the problem of the repeated words.


Open ajax dialog with JavaScript By adding use-ajax to a link we can open a modal using the Drupal ajax library as per the docs.
E.g.
<a class="use-ajax"
    data-dialog-options="{&quot;width&quot;:400}"
    data-dialog-type="modal"
    href="/node/1">
    First article displayed in modal dialog.
</a>

This will use the ajax library to fetch node/1 and then display it in a modal.
There is also a Dialog API for JavaScript which allows opening modals using JavaScript.
E.g.
var myDialog  = Drupal.dialog(ADOMElement, settings);
myDialog.show();

The problem with this API is you need to pass in a existing DOM element.
My question is can I trigger opening a modal with JavaScript and utalise the internal Drupal ajax library to actually fetch the content?
E.g Can I do something like this?
var myDialog  = Drupal.dialog('/node/1', {useAjax: true});
myDialog.show();

I could just create an html link as per my first code block, hide it with css, and then trigger a click on it with JS but this seems a bit hacky - there must be a way to trigger this action using pure JS.

You can trigger Ajax in custom javascript. See How to Trigger Existing, Non-Form Ajax from JavaScript Event
In your case an Ajax dialog:
var ajaxSettings = {
  url: '/node/1',
  dialogType: 'modal',
  dialog: { width: 400 },
};
var myAjaxObject = Drupal.ajax(ajaxSettings);
myAjaxObject.execute();


How to run alterRoutes on particular condition ? Does it run on cache clear and not on normal Request? I am trying to implement a feature where I need to run different flow than default flow while the registering user on the site.

I am trying to alter the route of "user password reset" for the for the first time logging users, Below is the code

    <?php

    namespace Drupal\developer_registration\Routing;

    use Drupal\Core\Routing\RouteSubscriberBase;
    use Symfony\Component\Routing\RouteCollection;
    use Symfony\Component\HttpFoundation\Request;

    /**
     * Listens to the dynamic route events.
     */
    class RouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
      // The Test is getting printed on only cache clear and not on URL Hit
      echo "Test"; exit;

      if(isset($_SESSION['developer_registration']['email_id'])) {

       if ($route = $collection->get('user.reset')) {
                 $route->setDefaults(array(
                 '_controller' => '\Drupal\developer_registration\Controller\UserCustomController::setPasswd',
              ));
             }
          }
       }
 }

The problem is that above alterRoute method doesn't runs on the URL hit. It only runs on cache. But my problem is that I want to  run alter route on particular condition.

I am not getting the way to do the same. Please help me.

Yes, it runs only on cache clear. You have to implement the dynamic behavior inside of the controller. By extending the core user controller you can call the parent method in case the dynamic condition doesn't apply:

class UserCustomController extends UserController {

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    if (!...) {
      return parent::resetPass(Request $request, $uid, $timestamp, $hash);
    }

    // return the redirect you want
  }

}


Unknown error: Function eregi_replace() i am using pressflow 6.25
 there is a flie views-view-field--events--block--field-date-value.tpl.php  in template theme directory

in line 5

$create_date = explode(' ',eregi_replace('<[^>]*>','', $output));

in my web site
show this error
Unknown error: Function eregi_replace() is deprecated in include() (line 5 of C:\xampp\htdocs\fiddle\sites\all\themes\sttheme\fiddle\templates\views-view-field--events--block--field-date-value.tpl.php).
how can i solve my problem?

There may be a problem with the PHP version.

See HERE

  This function has been DEPRECATED as of PHP 5.3.0. Relying on this
  feature is highly discouraged.


Display only the last submission per user of a webform in views I have a webform. I want to create a view of all submissions to the webform, but I only want to display the last submission for any particular user based on the "Webform submissions: Completed" field. i.e. I only want one row per user if they have submitted the form multiple times.

Is it possible to create a filter that will do that?

I have worked out a simple solution to this - the Views Distinct module


How to leave user profiles even when there are several pages? The profiles of my users have several fields (bio etc.) and several pages which I add with views (following, followers etc.).

I try to leave the profiles of users even when we change page, a little as here :

https://disqus.com/by/iamfrancisyo/ (when you click "followers", the information of the user remain posted at the head of page (avatar etc.)).

Yet, the profile disappears when we change page.

I tried to add the variable $tab to user-profile.tpl.php, but naturally it also disappears during the change of page.

Have you a solution?

Easiest way:

For each View (which would have User as base table no doubt and which has uid as contextual filter) you add an attachment View Display and pin it to the top of the main view. In that attachment, under 'Format: Show:' you select to show 'User' instead of 'fields', using the same view mode that is shown for the normal profile.


Custom node tpl being ignored I have created a content type called 'Home' and I also create a new file called, node-home.tpl.php.

What I understood from the drupal documentation, that when a Node has the content type it should use node-contenttypename.tpl.php as the node template file, if it exists.

But mine isen't working and its defaulting back to node.tp.php.

Any idea what I'm doing wrong?

The file has to be called node--home.tpl.php.
There always has to be 2 '-' between type and name.


Simplest way to have dynamic content (year) in field's default value? I'm looking for the simplest way in Drupal 7 to set simple dynamic content in the default value of a text field.

Specifically, I have a "Copyright notice" field, and I want the default value to be like this: "© Copyright Our Organisation [YEAR]", where [YEAR] is the current year. When the user creates a node in 2012, the form field is pre-populated "© Copyright Our Organisation 2012", and will be saved as this and stay as 2012 unless editted. When the user creates a node in 2013, the form field is pre-populated "© Copyright Our Organisation 2013" but all the old nodes made in 2012 don't change. EDIT: The field should still be editable, so users can replace it where it's not appropriate (e.g. if one piece of content they're uploading is actually "© Copyright Some Other Organisation 1981"): but the default should reflect the current year.

There seem to be a few options, but none of them seem particularly clean:

Using tokens. It seems that this requires either the token_filter module or the token_insert module. Then, the default value could include [current-date:custom:Y]. However, it's not so clean. For token_filter, the token from the default won't be translated until the user manually changes the input filter to "token filter" and hits save - bad for the user. For Token Insert, I believe the input field type would need to change to long text, and I'm not even sure it would work in the context of setting the default value.
Custom module. Something like, setting the default value to include some gibberish string like "_!YEAR!_", and then use something like hook_form_alter(); to find and replace. Or, defining some custom field that does this. Both involve fixing this specific combination of field and content firmly into code, which seems undesirable.
D7 CCK module. It exists (as a dev module) and apparently it has some feature to do with setting lists using PHP that didn't go into D7 core. Sounds not very applicable to this case however.
PHP filter. While you can set the Default Value field to use the PHP filter, in testing I found it doesn't actually apply the filter to the content you enter into the default value field. For example, putting © copyright Our Organisation <?php echo date('Y'); ?> into a default value field with PHP Filter applied just dumps that exact string, © copyright Our Organisation <?php echo date('Y'); ?>, into the field on the edit/create form, giving a user without access to the PHP filter nothing but some escaped text resembling PHP code, and giving a user with PHP filter access PHP code in the content of the field which continually processes, rather than becoming static text.

Am I missing something? Is there another way, or a variant on the above that is simpler?

you can write a module and implement hook_node_save(). If the node is new just set the value of the field (a simple text string to something like:

$node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "&copy; Copyright Our Organisation ".date('Y');

So in your own module you could do:

function MYMODULE_node_presave(&$node) {
 // Only do this for new nodes, eg nodes without a NID.
 if (!isset($node->nid)) {
     // Set our copyright text string.
     $node->field_copyright_notice[LANGUAGE_NONE][0]['value'] = "&copy; Copyright Our Organisation ".date("Y");
 }
}

// You can also hide the field for new nodes with hook_form_alter().
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_NODETYPE_add_form') {
    $form['field_copyright_notice']['#access'] = FALSE;
  }
}


How do I enable Clean urls within a migrated site? I am currently assisting a client with a Drupal 6 to 8 upgrade. After migrating a copy of the site into a development localhost environment. I noticed that I was not able to enable clean URLs. I have checked the .htaccess and found the following:

RewriteEngine on
RewriteBase /clientname
RewriteBase /
#Redirect /clientname

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

I have have checked other forums, and according to them the issue should be fixed. However, I am dealing with this same issue.

Any new advice would be much appreciated.

Did you read this:

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

Actually, you should use the original D8 .htaccess cause there are some special rewrites for core and autoloader (and more).


Is it possible to filter content  displayed by the  Views module using a regular expression? Is there a way to filter content displayed by Views 3 using a regular expression?

I have a large list (10K items) of content of a custom type on my site and I want to create preset views for my users.  The default views filter is not selective enough.  I need to select with a regular expression such as /M [0-9][0-9]?[0-9]?/ in one of the fields.

Is this possible in some other way, not using a regular expression?

I'm using Drupal 7.  Thanks!

Set up a Contextual Filter (previously know as Arguments in D6), they're hiding under the "Advanced" menu of you view. There you can put some PHP code to return a list of arguments.

Here is an example from one of my views, my PHP code return ID for a field regarding the roles of a user, it returns a string separated by "+" like 1+2+3 which is the separator for "OR" so I can select various node which have these values in this field.

This is the configuration to provide multiple arguments.


Restrict Location per Domain in OpenLayers I have Domain Access and Open Layers running on a site. Think of it as a map-based Craigslist. Each city has it's own subdomain, offering location-based content.

Users create content with a location on each subdomain, and I need to make sure that content's location is inside a radius (say, within 50 miles of a centerpoint) for that subdomain.

How can I do this?

I think you can do this with:

GeoIP API
Context
Context GeoIP
Domain Context


Add placeholder/help text to Views exposed filter? Title pretty much says it all. I am looking for a way to add placeholder/help text to a Views exposed filter. This would be text that appears in the filter (in this case, search field) before the user enters a value, and then disappears when the filed is clicked or when text is entered into it.

You can do this with preprocess functions.  Here's a tutorial on doing this for the default search box; you can do views exposed filters in a similar way.

You may also be able to use the Compact Forms module to do this, though I don't know if it is compatible with Views exposed filters.

Also, there's a module for showing helper text below a field: Better Exposed Filters

To set it up, simply enable the module and then navigate to your view edit page.  Under Exposed Form, click Basic next to Exposed form style and change it to Better Exposed Filters.  Then adjust as necessary.

However, this module will not automatically hide the text upon input.


Render Date Range on node template I'm trying to render both start and end date on a node template in Drupal 8 from the Date range field from the content type. I've tried multiple ways to no avail.

-- Only shows start date --

{{ kint(node.field_date_range.value ) }}

{% if node.field_date_range %}
{{ node.field_date_range.value|date(format='l M j') }}
{% endif %}

Here is the full solution that allowed me to separate the content into a traditional calendar mock-up on a node--events--html.twig:

{% if node.field_date_range.value %}

  {{ node.field_date_range.value|date(format='l')  ~ ' thru ' ~ node.field_date_end_range_value|date(format='l') }}
{% else %}
  {{ node.field_date.value|date(format='l') }}

{% endif %}

{% if node.field_date_range.value %}

  {{ node.field_date_range.value|date(format='M')  ~ ' thru ' ~ node.field_date_end_range_value|date(format='M') }}
 {% else %}
  {{ node.field_date.value|date(format='M') }}

 {% endif %}

 {% if node.field_date_range.value %}

   {{ node.field_date_range.value|date(format='j')  ~ ' thru ' ~ node.field_date_end_range_value|date(format='j') }}
 {% else %}
   {{ node.field_date.value|date(format='j') }}

 {% endif %}


How can I can I add functionality to my module so that the templates can be overwritten? How can I can I add functionality to my module so that the templates can be overwrittable like in drupal core. I want to be able to use my module with various themes, but change the required templates.

The only way I have seen to add is via drupal_get_path and explicitly specifiying a theme/module.

You need to declare your templates by implementing hook_theme(), and when needing them in your module uses a render array rendered with the RendererInterface::render() method on the renderer service.

Theme, or other modules, will then be able to declare override for your templates like they do for any others.

The theme system overview in Drupal documentation gives more details on this process.


Accessing values of unknown field types when using entity_metadata_wrapper I've been looking into using the Entity Metadata Wrapper classes (defined by the entity module in Drupal 7) to access field values, as this seems to be a clean way of doing so.

There a couple of things that make this a bit awkward however. Assume I have a wrapper for a content type that defines a field named field_something as such:

$wrapper = entity_metadata_wrapper('node', node_load($nid));
$value = $wrapper->field_something->value();

The first problem I have is that I have no way of knowing before hand whether what I get is an actual value (a string, an entity, etc.), another metadata structure wrapper (when fields have multiple values) or an array (when fields have multiple properties).

I have found a way to answer those questions using the info() method:

$info = $wrapper->field_something->info();
$is_multi_value = (strpos($info['type'], 'list<') === 0);
$has_multiple_properties = isset($info['property info']]);

However that is hardly practical. Whenever I want to use a field without knowing it's definition before hand, I must take into account several cases. This makes my code quite heavy.

In order to deal with this I have written some code which:

Ensures we always get returned an array, even if it's a single value field ;
When there are multiple properties, return the value of the first column.

Point 1. here will always work, unless the caller want to know whether this was a single value field or not. Point 2 works in some cases, not all, but is convenient when it applies.

Here is the code:

function entity_metadata_simple_values($field) {
  $fields = array();
  $values = array();
  $info = $field->info();
  if (strpos($info['type'], 'list<') === 0) {
    foreach ($field->getIterator() as $field_iteration) {
      $fields[] = $field_iteration;
    }
  } else {
    $fields[] = $field;
  }
  foreach ($fields as $final_field) {
    $ff_info = $final_field->info();
    if (isset($ff_info['property info'])) {
      $column = reset(array_keys($ff_info['property info']));
      $values[] = $final_field->{$column}->value();
    } else {
      $values[] = $final_field->value();
    }
  }

  return $values;
}

So my question is: are there simpler/better ways to address this problem of getting values from the metadata wrapper when the field type is not known ?

Here are a few suggestions to make this process a little easier.

$wrapper->field_something->type();

will return the type of the field, ie node, taxonomy_term, integer, text etc. You could then handle the value returned from $wrapper->field_something->value() correctly.

Also

$wrapper->field_something->raw()

will return the raw value of the field. Which will either be an array in the case of multi valued fields of just the value. For instance an entity_reference will be the nid (or entity id) of the referenced entity, or an array of referenced entity id's.


What is the appropriate way to get items from an entityqueue? I was having trouble finding API examples for entityqueue in Drupal 8.

I ended up writing a query to get the items.

$query = $this->database->select('entity_subqueue__items', 'esi')
  ->fields('esi', array('items_target_id'))
  ->condition('esi.bundle', $name_of_queue)
  ->orderBy('delta', 'ASC');

$nids = $query->execute()->fetchCol();

But I'd like to use a built in function if possible. Where's the function for retrieving items from an entity queue?

Given $sid is your subqueue id:

$entity_subqueue = \Drupal::entityManager()->getStorage('entity_subqueue')->load($sid);

Loads the subqueue object.  You can manipulate this to retrieve or update your entityqueue.

To get the items:

$items = $entity_subqueue->get('items')->getValue();

To update the items, add another item to the $items array and then save the entity object:

$items[] = ['target_id' => 69];

$entity_subqueue->set('items', $items);

$entity_subqueue->save();

Voila!

You can check in the database that your entity queue is updated:

select * from entity_subqueue__items where bundle = :sid;

I would like to also add that there is a great alternative to using entityqueue in Drupal 8: the Config Pages module.  It allows you to create entity bundles that have only one entity.  You can then add any field type you like, including entity reference fields.  I recently replaced an entity queue on a project with a config page with an entity reference field, and I preferred the user experience.


Change HTML structure of form? I want to alter the HTML structure for a particular form in my site.  Specifically, I want to add some wrapper DIVs around a few sets of form elements.  What's the "Drupal 7" way of doing this?

You can implement hook_element_info_alter() to change the theme wrappers used by the form fields.

If you look at the code of system_element_info(), you will notice the form fields are defined as in the following code.

  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['machine_name'] = array(
    '#input' => TRUE,
    '#default_value' => NULL,
    '#required' => TRUE,
    '#maxlength' => 64,
    '#size' => 60,
    '#autocomplete_path' => FALSE,
    '#process' => array('form_process_machine_name', 'ajax_process_form'),
    '#element_validate' => array('form_validate_machine_name'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );
  $types['password'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#process' => array('ajax_process_form'),
    '#theme' => 'password',
    '#theme_wrappers' => array('form_element'),
  );

You can add a new form wrapper, or change the existing one. Suppose, for example, that you want to add a theme wrapper for the textfield form field; you could use code similar to the following one.

function mymodule_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#theme_wrappers'] = array_unshift($type['textfield']['#theme_wrappers'], 'mymodule_textfield_wrapper');
  }
}

Your module then should implement the theme_mymodule_textfield_wrapper() theme function, and  hook_theme() to declare it.
You can use the code of theme_form_element() as guideline to write your code. The form element is contained in $variables['element'].

Alternatively, if the form fields you want to wrap with additional HTML use all the same theme wrapper, you can override that theme function using hook_theme_registry_alter(). Be careful, as in this case you are also altering every form field using that theme wrapper, including future form fields for which your wrapper could cause issues.


I have to remove HTML code that shows up on each page, where is it coming from? I am very inexperienced in Drupal.  I have been asked to remove commented HTML code that appears on each page of the website.  What file should I look for in the root directory to find the source of this?

The comment was added by another developer as a joke or something.  It's only wrapped in the body and appears close to the top.

The site is using Drupal 6.

It's probably your theme files then, in /sites/all/themes/[selected theme]. You can also try to change the theme and check if it is gone.

Have a look at html.tpl.php and page.tpl.php files.


How do I programatically change default values in a contact form? I have a Drupal 8 contact form where the form's placeholder values are the default values of the fields. Unfortunately, this site is multilingual and I don't think it's possible to translate default field values.

Is there a way I can set the fields' default values equal to the (translatable) field labels in either a module or preprocess function?

You can override your contact forms(both the default and the custom ones) by adding a field widget hook.
Why a field widget hook and not the usual form alter hook like D7? Because overriding the default value of the field can be done only in the respective field widget and not at the form level.

Here's the sample code:

function <mymodule>_field_widget_form_alter(&$element,  \Drupal\Core\Form\FormStateInterface $form_state, $context) {
   $field_definition = $context['items']->getFieldDefinition();
   $entity = $context['items']->getEntity();
   if(($entity->getEntityTypeId() == 'contact_message') && ($entity->bundle() == '<your-custom-form-machine-name>')) {
     if($field_definition->getName() == '<your-field-machine-name>') {
       $element['value']['#default_value'] = 'Hi there!';
     }
   }
}

NOTE This has been tested with Drupal 8.1.1.


How do I print the name of the field for a submission a value? I have a custom webform confirmation page where I am print the submission values using the following:

<?php print $submission->data[67][0]; ?>

How can I print the title of the form field for the above data?

The Webform submission object's data parameter is a keyed array of component ID's/component submission data. The object doesn't contain the component field name so you'll need to reference its value through data attached on the node.

For example:

$webform_node = node_load($submission->nid);
foreach ($submission->data as $cid => $data) {
  print $webform_node->webform['components'][$cid]['name'] . ':' . $submission->data[$cid][0];
}


re-saving users with default field collection items I wanted to post to @Clive comment on How can I quickly re-save all users on my site? and ask about how to do this for fields in a field collection but couldn't because I've never posted to this site before so I had to ask a new question. He provided the following code to run as a php script in VBO on all users:

$items = field_get_items('user', $entity, 'field_name');
if (empty($items)) {
   $entity->field_name[LANGUAGE_NONE][0]['value'] = 1;
}
user_save($entity);

This solution works great for a single field of a user. I need a similar solution for setting default field values in a field collection after importing users.

I migrated 6000+ users and have set default values for fields in a field collection after the fact that don't show up unless I re-save a user account. I want to bulk re-save all 6000+ users so that the default field collection fields are saved and are visible. It's almost identical to the original question except the field is not just a singular field associated with the entity -- the field(s) in question are part of a field collection. How do I access the fields from my default field collection to then force re-save of users?

Is the proper way to access field data through entity_metadata_wrapper? If this is the case, how do I get/set the values of fields in a field collection that I want to associate with users using this wrapping class?

This finally worked for me -- may it save someone hours of headaches:

// load the user
$userwrapper = entity_metadata_wrapper('user', $entity);
// apparently you have to create the field collection entity
$fieldCollection = entity_create('field_collection_item', array('field_name' => 'field_yourCollectionName'));
// attach your field collection to the user
$fieldCollection->setHostEntity('user', $entity);
// set the value of one of your fields in your field collection - in my case it's a boolean
$userwrapper->get('field_yourCollectionName')->field_fieldNameInYourCollection->set(0);
// save the entity
$userwrapper->save();


How do I alter the HTML outputted by an exposed filter? I have a view that pulls in content of many different types. I gave the user two exposed filters, using the Better Exposed Filters module. However, the two filters look different. I would like them to look the same.

Specifically, I would like to get rid of the "Start date", "End date", and "E.g., 2017-02-01" labels on the filter on the right hand side.

How do I do this? Is it possible to do it within the view settings? If not, I don't mind writing a custom solution. I imagine there's a relevant hook somewhere, but I do not know which one to use.

Turns out these settings can't be changed in the View (that I was able to find, and I looked pretty extensively). But, with Drupal's module/hook system, it's a pretty quick fix.

Source: How to remove format description in date_popup form field?

First, get rid of Start date and replace End date with And to match the filter on the left:

function edit_date_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] === "views-exposed-form-editable-content-page") {
    $form["field_editor_review_date_value_1"]["min"]["#title"] = "";
    $form["field_editor_review_date_value_1"]["max"]["#title"] = "And";
  }
}

Then, get rid of the E.g., 2017-02-01:

function edit_date_form_date_popup_process_alter(&$element, &$form_state, $context) {
  $element['date']['#description'] = "";
  $element['time']['#description'] = "";
}

Plop those into a module, enable it, and your output is:


Override Entire Module Page using Template I would like to override the entire page created by my custom module, I've used the hook_theme function but my template only affects the markup within the content region, I need to define the markup of the entire page inside the template file, including the header footer etc.

I know that this can be done in the theme but I need to to keep the template file within the module itself.

You want to override the deliver callback for the menu route.
https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_deliver_page/7

But notice this might be very invasive and cause you issues later on.


views related content block // show content with specific initial letter i have a content-type with this fields:

title field
starting letter // term reference -> stores term in vocab "starting letter"
car brand // term reference -> stores term in vocab "car brand"
car model // term reference -> stores term in vocab "car model"
Image field

i have created a view that hast the url: example.com/vehicles/audi (the term audi comes from the vocab "car brand" in views this looks like vehicles/%)

on this page with the url example.com/vehicles/audi i want to show a block that contains a list of other cars which name starts with the letter A like:

Acura
Alfa Romeo
AMC
Ascari

the same should be work with brand starting with B, C and so on. i need a contextual solution.

my problem and what i dont unterstand:
how do i set this thing up, because i dont have the term "A" in my url which i could filter with the contextual filter. i just have the term "audi". can anyone help me please?

Set argument for second view using hook_views_pre_view().

$view->set_arguments(array('A'));


How do I edit serialized values in "config" and "key_value" tables? While trying to switch original language of a Commerce product type I've encountered longblob serialized data in config and key_value database tables.
Is there a quick way to edit them, possibly without writing a lot of PHP code?

Don't edit the serialized config, edit the config as YAML. Try for example
drush cedit
See other options (UI and command line) here: https://www.drupal.org/docs/configuration-management


Creating a node type module in Drupal 7.x I am having some deep trouble getting around creating a node type with Drupal 7.x.
My aim is to create a node type that has some form elements within a table grid. Using any of the existing modules is coming across as a challenge because I can't find anything specific to my needs, hence I decided to explore module building and then enabling it as a node.

The tutorial I have is :
http://drupal.org/node/231019 (Create new content type for Drupal 6.x) .. .there isn't any exact tutorial available for Drupal 7.x

I have followed every step but am unable to see the content type appear in my node module.

Anybody has pointers to any resources for this?

Thanks

Download and look at those wonderful examples


Allowed range for date input - down to the day level rather than the year level? I am trying to set up a content review process for a client's site.

The desired process is this:

When users are adding content, they specify a "review date"

This date must be between today and today +365 days
A week before that date, send an email to users of a role letting them know

When I am setting up the date field, I've set "Starting year" and "Ending year" (in Field Settings -> More settings and values -> Date entry), however this doesn't behave as expected. It will let you set a date within calendar years, but not within a year of today. So I can make it work for any date in 2012, but not a specific day.

I'm fine with the rules + email bit, just the date field is holding me up.

I'm thinking it will be some custom JS, but am open to any approaches :-)

Ok, so this is our "solution". Not tidy, but we didn't want to edit the date module directly.

My module:

<?php
function modulename_form_alter(&$form, &$form_state, $form_id){
  if(substr($form_id,-9) !== "node_form" ){
    return;
  }
$jsPath = drupal_get_path('module', 'modulename');
  $jsOptions = array(
    'group' => JS_THEME,
    'weight' => 20
  );
  // Load this JS late, so that it happens after the main date module
  drupal_add_js("$jsPath/js/modulename_datepicker.js", $jsOptions);
}

My colleagues code for the modulename_datepicker.js file:

jQuery(document).ready(function(){
    for (var id in Drupal.settings.datePopup) {
        if (Drupal.settings.datePopup[id].func == "datepicker") {
            var defVal = jQuery('#'+id).val();

            jQuery('#'+id).datepicker();
            jQuery('#'+id).datepicker( "option" , {
                changeMonth: Drupal.settings.datePopup[id].settings.changeMonth,
                changeYear: Drupal.settings.datePopup[id].settings.changeYear,
                firstDay: Drupal.settings.datePopup[id].settings.firstDay,
                defaultDate: Drupal.settings.datePopup[id].settings.defaultDate,
                dateFormat: Drupal.settings.datePopup[id].settings.dateFormat,
                minDate: 0,
                maxDate: "+1Y"
            });

            if (defVal == '') {
                jQuery('#'+id).datepicker( "setDate" , "+1Y");
            } else {
                jQuery('#'+id).datepicker( "setDate" , defVal);
            }
        }
    }

});

Better solutions welcomed :)


How to delete a managed folder and its contents programmatically via hook_uninstall? My hook_update_N() implementation looks like this:

$directory2 = 'public://folder_name';
file_prepare_directory($directory2, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

How can I remove "folder_name" and its contents in hook_uninstall using drupal's API?

Drupal doesn't consider a folder to be a group of files, and doesn't have a method for bulk deleting managed files (like it does for unmanaged files: file_unmanaged_delete_recursive). So you'll need to identify which files you want to delete manually. A query with WHERE uri LIKE 'public://folder_name/%' might be sufficient in this case, for example, but you'll know you're own setup better than I can guess.

Once you have a list of file IDs, load up the objects, loop through them, and call file_delete on each. If you have the File Entity module installed, you can shorten this by using file_delete_multiple(), and just pass the IDs.

Once you're happy all the files have been deleted (you could stat the folder after running the loop), then remove the folder with drupal_rmdir().

Bear in mind that file_delete() is not guaranteed to remove the file; other parts of the system can declare their interest in a managed file by way of the file_usage table. If you want to unconditionally remove files regardless of any other entity in the system that they're attached to, you can use the file_usage_* methods in file.inc.


Multiple sites and performance in Drupal 7 I help manage a cluster of sites related to course curriculum. Each site is a separate Drupal 7 install with its own theming, modules, user list, content types, entity structure, and codebase - all of them identical (not shared, but replicated across all the sites). They all run on the same server as different Drupal instances. I'm not a huge fan of managing each individual site and its modules, libraries and theming, but this is the setup as I inherited it.

Now we are looking at adding a few sites to the cluster. This is an opportunity to organize differently, and I haven't found any adequate data on which method is better. These are my three choices as I see them.

Multiple Drupal instances (the way we have it now).

Advantages:

If code for one instance gets broken, the others will continue to run.
Opportunity for separate userlists, taxonomies, etc. (Right now we are not leveraging this, but I suppose we might in the future.)

Disadvantages:

Every upgrade has to be tested and implemented on all sites individually.
Performance hit from running all those instances (cron runs, session variables, caches, etc.)

One Drupal instance running Multisite.

Advantages:

One codebase means one set of modules to maintain.
One Drupal instance would smooth out the performance issues (maybe?)

Disadvantages:

Each site still has its own database, requiring separate userlists, taxonomies, etc.

One Drupal instance with all the content in one place. (This is the way I'd really like to go.)

Advantages:

Much, much easier to maintain.
Performance savings? (This is what I really want to quantify somehow)
Only one site to upgrade when we finally go to D8...

Disadvantages:

Lose flexibility among sites' user lists and access levels. (I can get some of this back using taxonomy terms, but for now it's immaterial.)
Lose flexibility with content types and structure. (The sites are very nearly identical as it is, and the differences can be smoothed out in development.)
If one site gets broken, they're all broken. (Already true to an extent because all the sites are on one server.)
Performance hit from all that content being in one database?

What I'm wondering is, what are the performance savings for each option over #1 (the status quo)? Quantitative data is great, but even an explanation of where the savings come from would go a long way.

My recommendation is to go with a multisite.

Multiple Drupal instances and multisite are about the same in terms of performance (multiple databases). One Drupal instance will not scale as well and thus will not perform as well. The database layer is a bottleneck of Drupal that is hard to work around.

You can create custom code for taxonomies to make them shared across all multisites; users can use something like https://www.drupal.org/project/bakery. Doing this for multiple Drupal instances is a little harder to pull off in comparison to a multisite.

To do a shared taxonomy you'll need a new database connection in your settings.php pointing to a new db. This will hold all of your taxonomy_* tables; or you can designate one already existing db to be the master record. Then using  hook_taxonomy_term_presave() and hook_taxonomy_vocabulary_presave() write the master taxonomy info into the correct db or if it already exists have it use that tid/vid. Then in hook_taxonomy_vocabulary_insert()/hook_taxonomy_vocabulary_update() and hook_taxonomy_term_insert()/hook_taxonomy_term_update() write the taxonomy info to the rest of the databases in your multisite. See taxonomy_term_save() and taxonomy_vocabulary_save() and use the drupal_write_record code to write. Use db_set_active() to change database connections. Have all multisites use the same settings.php file (symlink or include), and in there have a big array containing all your database connection info; create a path lookup function that uses conf_path() and readlink() if needed for knowing what db to connect to. You'll need to migrate all taxonomies before so they all match. This took a little while to code, about 2 weeks. The code I have is for D6 so it wont work for D7.

We used the shared taxonomy on around 80 databases using https://www.drupal.org/project/domain to give us 1300+ domains. It scaled very well.


How to disable webform Results tab in webform without uncheked Access all webform results? I'm using D7, i like to hide web form result tab, i try with tab tamer module,but it doesn't work i still got access to submission results,when i unchecked Bypass views access control and Access all webform results permissions, results tab become disable but in this case i couldn't change my webform workflow submissions anymore. Could any one suggest me an idea how to disable result tab without disabling the possibility to change my webform worflow state

The Webform access callback, webform_results_access(), for the submissions tab is structured so evoking the built its hook hook_webform_results_access() can't override Access all webform results permissions check.

However, a custom module could override the tab's access callback with your own custom logic:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%webform_menu/webform-results']['access callback'] = 'MYMODULE_webform_results_access';
}
function MYMODULE_webform_results_access() {
  $result = FALSE;
  // @TODO: Add access logic
  return $result;
}


Which method to set up pay to register? I am building a site that requires payment, from paypal for instance, as part of the user registration. What approach should I take?

Does it have to be registration? You might find it easier to set up one or more roles with the privileges you want to grant to paying users and then use Ubercart to grant these roles to users who buy the appropriate products.

If this sounds good, look at using the uc_roles module that comes with Ubercart. The Ubercart documentation contains a pretty good overview: on selling site access with role assignment.


Missing bundle entity, entity type paragraphs_type from field_instance.yml file I'm currently trying to migrate my D7 site to D8 and one of the things migrating is field_collections to paragraphs. I have a field_collection call "field_sidebar_callouts". I want to migrate that to paragraphs.
Everything is migrating correctly until it reaches to field_instance.yml file. It throws an error call this:

Missing bundle entity, entity type paragraphs_type, entity id r_callouts

Is the instance.yml file importing half the id? How come the entity id is only "r_callouts" and not "field_sidebar_callouts".
Did my field_instance.yml get auto-generated incorrectly?
Any help would be amazing!
Here's my instance file:
uuid: 295c39a9-1857-4d53-a342-92a16ae71223
langcode: en
status: true
dependencies: {  }
id: upgrade_d7_field_instance
class: Drupal\migrate_drupal\Plugin\migrate\FieldMigration
field_plugin_method: alterFieldInstanceMigration
cck_plugin_method: null
migration_tags:
 - 'Drupal 7'
 - Configuration
 migration_group: migrate_drupal_7
label: 'Field instance configuration'
source:
 plugin: d7_field_instance
 constants:
  status: true
process:
 type:
  -
  plugin: process_field
  source: type
  method: getFieldType
 entity_type:
  -
   plugin: get
   source: entity_type
  -
   plugin: static_map
   map:
    field_collection_item: paragraph
    paragraphs_item: paragraph
  bypass: true
field_name:
  -
   plugin: get
   source: field_name
bundle:
 -
  plugin: static_map
  source: bundle
  bypass: true
  map:
    comment_node_forum: comment_forum
-
  plugin: paragraphs_process_on_value
  source_value: entity_type
  expected_value: field_collection_item
  process:
    plugin: substr
    start: 6
label:
 -
  plugin: get
  source: label
description:
 -
  plugin: get
  source: description
required:
 -
  plugin: get
  source: required
status:
 -
  plugin: get
  source: constants/status
allowed_values:
 -
  plugin: sub_process
  source: allowed_vid
  process:
    -
      plugin: migration_lookup
      migration: upgrade_d7_taxonomy_vocabulary
      source: vid
settings:
  0:
   plugin: d7_field_instance_settings
   source:
    - settings
    - widget
    - field_definition
field_collection:
  plugin: field_collection_field_instance_settings
default_value_function:
 -
  plugin: get
  source: ''
default_value:
 -
  plugin: d7_field_instance_defaults
  source:
    - default_value
    - widget
translatable:
 -
  plugin: get
  source: translatable
settings/title:
 -
  plugin: static_map
  source: settings/title
  bypass: true
  map:
    disabled: 0
    optional: 1
    required: 2
destination:
 plugin: 'entity:field_config'
migration_dependencies:
 required:
  - upgrade_d7_field
optional:
  - upgrade_d7_node_type
  - upgrade_d7_comment_type
  - upgrade_d7_taxonomy_vocabulary
  - upgrade_d7_field_collection_type

I believe you need to change the expected_value: field_collection_item to match your field_collection_items


Menu not showing for 1 server of two cloned servers After cloning an existing server instance and pointing the new one to the same database I've modified my hosts files to load the 2nd server with the same URL as the first one.

All is well except for the fact that on the 2nd server the navigation menu is missing!

Any insight onto what may cause two otherwise identical servers to behave differently in this fashion?

update: the menu in question is generated by the superfish module.

After a heavy duty migration like that, I would try going through the standard Drupal debugging steps first:

Clear caches.
Re-save theme settings (admin/appearance/settings/mytheme).
Rebuild permissions (admin/reports/status/rebuild)
If you are using the Features module, double check that things are identical to the old instance. You may need to revert some features components.
Check the status report and error log at admin/reports.

Good to cover your bases before you start digging deeper.


Output same content type in different format I need to output a same content type in 2 formats : html and xml. How can I do that and what url to use o access these different outputs?

The easiest would be to use Views Datasource which allows you to output any data in XML, JSON, XHTML with different schemas. You can the set your own URLs and can have fine control over the output.

Another, rather primitive way is to use the RSS feed with full content on, but I take it that may not be what you are looking for, yet when all else fails — it is better than nothing.


Set the search index and the field_revision_body empty I'm not using the core Drupal search engine and I'm not using any revisioning on my nodes.  I noticed that the {search_index} table and {field_revision_body} table are occupying 50Mo of my database space.

Does emptying these tables cause any problems?

You shouldn't empty field_revision_body as it will break the content, but search_index is ok to empty.

Regarding search, please review the settings at: /admin/config/search/settings

e.g uncheck the Node and User search under "Active search modules"


Retrieve Taxonomy Term by Field in D7 I have a vocabulary with a field "legacy_id" which is a primary key another related system.  I am building a routine to update the data in the drupal system based on changes in the related system.  Other then hitting the DB directly, is there a way to retrieve the tid or the entire term from the field?

You can use EntityFieldQuery,

Here is the sample code,

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', 1) // change 2 to any vocabulary ID
  ->fieldCondition('field_test', 'value', 'test');
$terms = $query->execute();

First param to fieldCondition is the field name, second one will be the column name for example for text fields column name is value and for term reference field tid, then the final one is to specify the value. Hope this helps.


Views body field pop-up not loading and preview not working Recently we have moved our website from our own hosting to Pantheon. Since we've made the move the Views body field pop-up won't load anymore. Pop-ups for other field may or may not load. Also the Preview function in Views isn't working either. Because this may sound vague I've made a screencast display the problem. Also no errors are shown or created in the logs. I suspect it has something to do with AJAX.

This happened to me when I used the jQuery Update module with newer versions of jQuery (specifically 1.7). It causes several administrative oddities that you can get around, but the Views admin bug is pretty much crippling.

Here is a great patch that will allow you to choose a different version of jQuery for administrative pages, so for example, you can run jQuery 1.7 for the front end, but still use 1.4.4 for the administrative areas.

http://drupal.org/node/1524944


How to modify module output via another module - whois module? In drupal 7, can we access and read return value of a specific module via another module?

Specifically, I am using the whois module, and would like to access its output from a custom module, with the goal of modifying the output.

How can I do this?  What is the suitable hook function? How can I access the output from whois before it gets rendered.

Please guide me.

Thanks a lot.

You can change the output through preprocessing, for example in your theme's template.php file, or in your custom module (see also: https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess_HOOK/7).

The $variables['content'] variable contains the content of the block to be displayed. The individual elements come from $variables['elements']. If you add:

debug(array_keys($variables['elements']));

to the script, you get the following output:

array (
  0 => 'whois_form',
  1 => 'whois_lookup_data',
  2 => '#block',
  3 => '#weight',
  4 => '#theme_wrappers',
  5 => '#children',
)

When looking at these in detail, you see that $variables['elements']['#children'] is comprised of $variables['elements']['whois_form']['#children'] and  $variables['elements']['whois_lookup_data']['#children'].

Ultimately, $variable['content'] is comprised of $variable['elements']['#children'] (see also https://api.drupal.org/api/drupal/modules!block!block.module/function/template_preprocess_block/7)

So, there are two options:

Alter $variables['elements']['whois_lookup_data']['#children'], and
recreate $variable['elements']['#children']
Alter $variable['elements']['#children'] directly.

I chose the second option below.

To use the hook_preprocess_block hook, as shown below, the core module "Block" needs to be enabled.

If used in a module, in yourmodule.info:

name = Whois Alter Module
description = A module to change the output of whois.
core = 7.x
package = Drupal 7 Misc
files[] = whois_alter.module
dependencies[] = block
dependencies[] = whois

In whois_alter.module:

<?php
// $Id$
/**
* @file
* A module to demonstrate hook_preprocess_block to alter the output of another module
*
* This module alters the output of the whois module
*/

/**
* Implements hook_help().
*/
function whois_alter_help($path, $arg) {
  if ($path == 'admin/help#whois_alter') {
    return t('A module to alter whois output.');
  }
}

/**
* Implements hook_preprocess_block().
*/

function whois_alter_preprocess_block(&$variables, $hook){

  if (isset($variables['elements']['whois_lookup_data'])) {
     $whois_modified = whois_alter_modify_whois($variables['elements']['#children']);
     $variables['elements']['#children'] = $whois_modified;
     $variables['content'] = $variables['elements']['#children'];
  }
}

function whois_alter_modify_whois($content) {
   // do what you want to do to modify the output
   return $altered_content;
}

For Theme preprocessing, just use the functional part of the module in template.php:

function yourtheme_preprocess_block(&$variables, $hook){

  if (isset($variables['elements']['whois_lookup_data'])) {
     $whois_modified = yourtheme_modify_whois($variables['elements']['#children']);
     $variables['elements']['#children'] = $whois_modified;
     $variables['content'] = $variables['elements']['#children'];
  }
}

function yourtheme_modify_whois($content) {
   // do what you want to do to modify the output
   return $altered_content;
}


How can I create block for my custom form? I create a custom form module. Now I want show my form in a block. How can I do this ?

Note: I create MymoduleBlock.php in /modules/my-module/src/Plugin/Block path with this code but not work:

<?php

namespace Drupal\my-module\Plugin\Block;

use Drupal\Core\Form\FormInterface;
use Drupal\Core\Block\BlockBase;

class MymoduleBlock extends BlockBase {
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\my-module\Form\MymoduleForm');
    return $form;
   }
}

The code in MymoduleBlock::build() is correct, and it is what Drupal core does in UserLoginBlock::build().

  $form = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');
  unset($form['name']['#attributes']['autofocus']);
  // When unsetting field descriptions, also unset aria-describedby attributes
  // to avoid introducing an accessibility bug.
  // @todo Do this automatically in https://www.drupal.org/node/2547063.
  unset($form['name']['#description']);
  unset($form['name']['#attributes']['aria-describedby']);
  unset($form['pass']['#description']);
  unset($form['pass']['#attributes']['aria-describedby']);
  $form['name']['#size'] = 15;
  $form['pass']['#size'] = 15;

What the block definition is missing is the annotation (the comment before the class) which allows Drupal to identify that class as plugin. See what Block API says. (Emphasis is mine.)

  Blocks are a combination of a configuration entity and a plugin. The configuration entity stores placement information (theme, region, weight) and any other configuration that is specific to the block. The block plugin does the work of rendering the block's content for display.

  Block plugins use the annotations defined by \Drupal\Core\Block\Annotation\Block. See the Annotations topic for more information about annotations.

In the block class I used as example, the annotation is the following one.

/*
 * @Block(
 *   id = "user_login_block",
 *   admin_label = @Translation("User login"),
 *   category = @Translation("Forms")
 * )
 */

Also, the machine name of module should not contain hyphens, which aren't allowed in PHP functions. That creates problems when you implement hooks, since the hook name is derived from the machine name of the module. For example, the implementation of hook_page_attachments() for your module would be my-module_page_attachments(), which is not an acceptable PHP function name.
If you think your module is not going to implement hooks, keep in mind that the majority of modules implements at least hook_update_N(), for which is also preferable not using capital letters in the module machine name.


webform submission details not getting displayed i have multiple nodes each per language and the default is English(node/1).
For french node(node/2) after submitting the details of the contact form, the details not getting displayed in Webform-Confirmation.tpl.php page, however when i do the same in default English node, it is getting displayed. any configuration should i do for this please help

You should set Redirection location of webform in form settings.

Edit your webform node.
Click on webform tab in top of page and it will redirect you to webform configuration of the node.
Click on form settings link in webform
Checked Confirmation page radios in Redirection location field-set and save the form.


How do I use the Password Policy module? I just installed and configured the Password Policy module, but the constraints like password length should be minimum 8 characters is not reflecting when an administrator user adds a new user and creates an one time login password.
The constraints/plugins provided in Drupal 8 by the Password Policy module aren't working in any scenario. Can anyone suggest the possible cause or the right way of using this module?
This module also doesn't modify the default recommendations on /admin/people/create.
Recommendations to make your password stronger:

Make it at least 12 characters
Add lowercase letters
Add uppercase letters
Add punctuation

Please see the reference link below which has information about how to use this module for Drupal 8

https://opensenselabs.com/blog/tech/drupal-password-policy-module

There might be other modules like PRLP (Password reset landing
page) or other relevant password setting modules that might not be allowing the policy to be enforced.
You can check by uninstalling them and see if the created policy is
being enforced on the default user form.


is it possible to index a hidden field? i have a newsletter content type which consists of a link to a file (pdf) and a summary field.  the idea behind the summary field is that it will contain a list of keywords and when a search hits one of these keywords the newsletter item (and so the pdf file) will be highlighted.

the issue is that i don't really want the summary text to be displayed, but if i set it as hidden in the display it doesn't seem to be indexed.

anyway that i can persuade drupal to index this field?

using 7.12 by the way if that's important.

Dave

The best way should be implementing the search_api module , with this module you can index anything and set the importance of the indexed field .

Here is a screen cast that shows how to implement here

Note that the screencast must be updated because facet_api works now without apachesolr

Enjoy!


add and remove preassign role to user on completion of user profile I have created user through admin. Admin Assign specific role to user. But On first time login we want user to complete user profile and then only it will able to access anything else on site. So I want to remove role from user profile if any of field in user profile is empty. And add Pre-assign role again to user after completion of user profile.

Please help. Thanks in advance

I never did something similar before, but I guess, rules module suits you like nothing else.

First of all you need 2 roles: users who just created and users who filled some profile fields. When admin creates a new user he set first (just created) role.

Then you create a new page view event (in rules core):

Create action load entity by id using site:current-user token (so you can access user profile fields in condition section);
In condition section, Check user role (only for just created);
In condition section, create condition for each profile field you wanna check (not empty or something similar);
Create action to redirect user to edit profile page.

So, each time when new user will load any site page, he will be redirected to edit profile page until he doesn't fill profile fields.

The second event is after profile save, assign new role "Fills some profile fields".
There is no difficult conditions, so I'm sure you can handle this event yourself.

If you need more complex solution, redirect on profile if only user load specific page you can try rules page. If you would like to redirect only once per session, you have to write your own rules condition through rules API or try out this one (never use this before).

I hope this could be helpfull for you, anyway wish you luck to find what you are really looking for.


Drupal installation creates innoDB tables even though myIAM is set as default in my.ini Drupal installation creates innoDB tables even though myIAM is set as default in my.ini

whenever i install a new Drupal 7.26 on my XAMPP (ApacheFriends XAMPP Version 1.8.2) running under Windows 7 I get innoDB tables in my database.

I put the following line in my my.ini file under [mysqld]

default-storage-engine=MyISAM

But still - after installing Drupal the tables are all innoDB?

What is is that i do wrong?

Drupal overrides the default to set it to innoDB because innoDB is a better choice for Drupal in many cases. Two main reasons for this:

InnoDB supports transactions; MyISAM doesn't.
When a row in a MyISAM table is being updated, the entire table is locked, so no other process can write to it. InnoDB locks rows in tables, rather than entire tables. For example, on this site, if many people are writing to the comments table at the same time, they would have to wait in a queue if the table were myISAM, but with innoDB, multiple writes can happen simultaneously, provided they're not to the same row in the table. This has obvious performance ramifications.

If you absolutely have to, you can edit the information schema table in mysql to set all the tables to MyISAM, but make sure you know what you're doing...


How can I tell which Feature something belongs to? I am working on a site that has maybe 100 different Features. I am editing a block, which I assume is attached to a Feature.

Without looking through each Feature individually, how can I tell which Feature this block belongs to (or even if it is Featured at all?

You can search in your editor or your repository for your 'block_machine_name'. It must have been referenced in the respective feature.


When to use list(text) or taxonomy? This may be a silly question, but I'm curious what the benefit is of using a list (text) multiple select field over a taxonomy term reference field. They both seem to fill roughly the same function of giving predetermined multiple choice options, but taxonomy has the added benefit of allowing you to add terms after content has been written to the database.

So is there any good guideline for one to use one or the other? (And particularly when list(text) makes more sense than taxonomy term reference?).

Structure and dynamic are IMO the keywords for choosing taxonomy.
I recently had this question come to me when tagging companies with geographical regions. My first choice was to prepare taxonomy with list of regions. Soon it turned out to be over-complication. The regions almost never change their names and almost never change their structure/parents. So I tossed out the taxonomy and decided to use a flat List (Text). It's now also much easier to maneuver the regions in a View. So - if your list is static and flat - go for a list.


How to add an 'if' statement for a content type in a custom views-view.tpl.php? Is it possible to add an 'if' statement for a content type in a custom views-view.tpl.php?

This is just so I can add text to show if the post in the view is either an 'episode' or an 'announcement'. The content type is called announcement.

I want to do this because I need to identify and style differently based on the post type:

If it's from an episode, it displays the episode number.
If it's an announcement, it says announcement.

So basically something like so:

<?php if (content_type='whatever') {... code goes here ...} ?>

If this is possible, can you provide an example?

Note: I have a custom theme called views-view-field--first-post--block--created.tpl.php and all it has is <?php print $output; ?>. It's called a field content date.

Also, this is what the output of the entire view looks like: stdClass Object ( [node_created] => 1434783086 [node_title] => CTRL Daily Episode 11 [nid] => 11 [node_type] => ctrl_daily ). [node_type] is what I want.

You can access it by adding Node Type field to views and access it using $row variable in views-view.tpl.php.

$rows: The results of the view query, if any

Or $views is also accessible in each and every views template file.


How to add_js per content type in my module? I'm looking for a way for my module to evaluate the content type in a preprocess hook and conditionally add some javascript.

Theme_preprocess_page() makes the content type accessible plus some other useful things (I could differentiate between nodes & views & such), but I can't use it because it is likely to have already been declared by the theme.

*My_module*_preprocess_page() doesn't appear to provide the content type anywhere.

What is a good option here?

Here's how to add content type specific javascript to a node using hook_node_view and #attached

/**
 * Implements hook_node_view().
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {

  // Add content type specific JS on full page node view
  if($view_mode == 'full'){
    switch($node->type){
      case 'article':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/article.js');
      break;
      case 'page':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/page.js');
      break;
    }
  }

}


PDOException when saving node with AudioRecorderField Occurs on client's computer but not mine. Does not appear to be a user-related problem. Using SoundCloud recorder.

PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid
input syntax for integer: "NULL" LINE 4: WHERE (base.fid IN ('NULL')) ^:
SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri
AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS
status, base.timestamp AS timestamp FROM {file_managed} base WHERE (base.fid
IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] =>
NULL ) in DrupalDefaultEntityController->load() (line 196
of /Users/Shared/Server/HTTP/chinese/includes/entity.inc).

Looks like the problem was with the PHP upload limit. Seemed to be a computer problem because I always used short recording files when testing, while my client tested with a full recording.


Subscription to User-saved searches Required functionality:

User can filter nodes based on certain relevant custom fields.
User can save filter criteria as a named set.
User can view and edit these sets of filter criteria.
User can "subscribe" to changes based on his saved sets of filter criteria and get email notifications containing links to only the newly matching nodes.

Can I build such subscriptions with mostly out-of-the-box functionality of Rules and related modules?

Subscriptions depending addressfield field is a related question, but the poor lad did not get an answer.

Conceptually the business logic you want to complete is possible using Drupal. Finding a way to make this scale to a very large website -- I leave as a project for you.

Start by looking at Saved Searches and Views Saved Search or Views Save. These modules let you save a search with a simple name for later re-use. Some of these modules allow per-user saved searches.

You could then create a Queue using the Queue API in Drupal to periodically process the resultsets of these searches. Or even use the Relation module to store heuristics on these resultsets.

Create a cron task using hook_cron or Rules Scheduler to periodically process the resultsets and have Rules to send off emails about new changes in the saved searches. Functions like views_get_results (if you use views_saved_searches) can help you to get these results.

So in general yes it's possible with Drupal -- scaling all this to a very large amount of  users is either an infrastructure problem or something (i think) "Drupal" shouldn't do in the long run ...


How do I display a message after redirecting users from the logout page? I'd like to show a message via drupal_set_message() after redirecting users from user/logout?destination=user.

I tested this code but it doesn't work.

if ($find) {
  drupal_set_message(t('This entry is ignored.'), 'error');

  $form_state['redirect'] = array(
    'user/logout',
    array('query' => array('destination' => 'user')),
  );

  drupal_redirect_form($form_state);
}

How do I display a message after redirecting user from the logout page?

Reading your code, it appears to me that you want to redirect /user/logout to /user.

If that's what you actually want, then you could use the Rules module for this, using an approach that is similar to my answer to the question "How to create a redirect to point to the user's id?", in which you use values for the_old_path and the_new_path that fit your needs here, i.e.:

Change all occurences of the_old_path to user/logout.
Change all occurences of the_new_path to user.
Adapt the message being displayed to fit your needs, so that the user will also receive an informational message, e.g. similar to something like this one:

  The path /user/logout has been redirected automatically to path /user.

If you don't want such message to appear, then just delete the line containing drupal_message in the rule.

Use the value of the [destination] variable in the redirect

In case you want to make the value  (user in this case) of the URL argument (destination in this case) available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

PS: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.


How would I insert one item into the user-edit page with templates? I'm looking to insert a button into the user edit page. I've seen examples of how to edit the entirety of the user-edit page, but I want to keep everything intact and only make one small change.

Is it possible to do this without building the entire user-edit page all over again from scratch?

Although you could add a button into the template, this is done better with the forms api using a custom module. You can use hook_form_FORM_ID_alter to alter the user_profile_form and only make the small change you want while leaving the rest of the form untouched.

As an example, you could add a button "My cool action" to the use profile form with the following code. You just need to replace MODULE with the actual name of the module you put it in.

function MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['newaction'] = array(
        '#type' => 'submit',
        '#value' => 'My cool action'
    );
    $form['actions']['newaction']['#submit'][] = 'my_newaction_callback';
}

function my_newaction_callback($form, $form_state)
{
    // this function is called when your button is pressed
    // do whatever you want here.
}

Update #2

You could place the button in the middle or top of the page using the following code and figuring out which weight places it where you want. Try a weight of 0 to have it near the middle.

$form['newaction'] = array(
    '#type' => 'submit',
    '#value' => 'My cool action',
    '#weight' => -3,
    '#submit' => ['my_newaction_callback']
);


How to create add custom style to specific view in drupal Please check this site

I am trying to create rounded corner rectangle on right hand side where products are listed. This is currently working because I modified view-view-grid.tpl.php. Doing this has changed everywhere wherever I was using grid. I want to add this style only to a particular view. How can I achieve this in views.  I also want to modify style of each category displayed within the box eg. Product category should be bold or some different color.

I am beginner so please let me know steps or some good references.

This is actually really easy with views. I am going to assume you are using Drupal 7 with Views 3. But this works almost the same in previous versions of both as well.

First, go into your view. On the far right expand the "Advanced" fieldset if it isn't already expanded. Then click on the "Information" link next to Theme at bottom of the list.

This will popup a modal that will display how to name your template files to replace the default template. It specifically allows you to modify different levels of the template. Find the level you want to modify. Then, while reading the list from left to right (right being the most specific) pick the name that is specific enough for your uses.

Next, go into the views module and find a copy of the bolded template file and copy that into your theme folder into a templates folder or into a custom module. Then give it the name you found above and make your changes.

Finally save it and flush the Drupal cache. Now when you go back to that information page it should show your new template file highlighted. This may require a few refreshes.

Now on another note, if you use the built-in field controls you can add custom CSS classes to help target the specific view and thus a specific button underneath it. You can also add specific classes to the view in the advanced section.

Though keep in mind drupal already gives us a ton of classes to each element, so you shouldn't need any of this just to target that view and a specific button within it.


multilingual nodes architecture issue Is it possible that node translations aren't new nodes? For example if I translate /node/1 I get /node/2 and this is problematic in some cases (comments are not shared between #1 and #2, and entity references are not reused).

Detailed walkthrough:

I'm using locale, translation, variable and i18n. I've got 2 languages configured: EN, FR. I have content types News and Event. Both have Multilingual support: "Enabled, with translations". The News has fields:

title
body
reference to a Event (implemented with entityreference)

I create 2 node instances:

/node/1 (#1) Event (EN)
/node/2 (#2) News (EN) with reference back to #1

I edit #1 and add a translation (FR) and #3 is created. I then translate #2 and #4 is created. The problem is that I have to respecify that the reference from #4 is #3 and not #1. If I use the "Synchronize translations" feature of the content type the workflow is a bit better but still not exactly what I want since on the FR front end when viewing #4 the reference to #1 will be displayed in EN and not FR.

Is there any way to have translations not creating new nodes but instead just translating some fields only?

Also, is the module i18n the "defacto standard" for implementing multilingual sites in Drual 7? Or is there something better out there?

Did you try Entity Translation ?

I find it very much easier and efficient than i18n (which is needed for some other parts of the site anyway).

There you get exactly what you're looking for : translations stored in one node only.


Drupal says "e-mail sent" but I don't receive I have installed my webserver from a computer at home. On Ubuntu Server, LAMP, everything works fine except email sending.

First I was getting:

  Unable to send email

then I followed these directions.

Then I still got same error. I checked Apache logs and I found

sendmail: fatal: file /etc/postfix/main.cf: parameter myhostname: bad parameter value: myservername.{null}

I changed the file and wrote my website domain like domain.com

At last, Drupal says "Email sent" but I receive no email. What is the problem?

Have you used a devel php input to do a sendmail test?
there is a question already answered here.
How to programmatically send an email?

Also here is a great article on debugging emails...
http://www.drupalcoder.com/blog/how-to-debug-outgoing-mails-in-drupal


Views Search API with Search API database, sort handler I need to have a views handler for Views Search API that will allows empty (i.e. NULL) values in fields to be sorted last.
For the simple views there is a solution: Views Sort Null Field but I'm totally lost,  How to implement the same functionality for Views Search API?

More specifically - Views Search API provide only $query->sort() method that not allow you to add sort formula like $this->query->add_orderby(NULL, "ISNULL($this->table_alias.$this->real_field)", $this->options['order'], $alias)

In case you are using Search API Database Search as a backend for the Search API you can solve the problem by using hook_search_api_db_query_alter hook:

/**
 * Implements hook_search_api_db_query_alter().
 *
 * Preprocesses a search's database query before it is executed.
 *
 * @param SelectQueryInterface $db_query
 *   The database query to be executed for the search. Will have "item_id" and
 *   "score" columns in its result.
 * @param SearchApiQueryInterface $query
 *   The search query that is being executed.
 *
 * @see SearchApiDbService::preQuery()
 */
function custom_module_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  $db_query->orderby('ISNULL(field_field_name)', 'ASC');
}

This solved it and moved items with NULL values to bottom of the view. Cheers!


Get a contextual filter for a View in Drupal 8 I'm converting a module from D7 to D8 for a client. Some of the code is working programmatically with views - something I haven't done that much in D7, since I just write my own queries.

In the code is this line:

$contextual_filter = method_exists($view, 'get_items') ? $view->get_items('argument', $display->id) : 0;

I need to convert this to D8, but I'm not sure entirely what I'm working with here.

What I do know:

In D8, $view is an object of type Drupal\views\ViewExecutable
In D8, there is no get_items() method, nor a getItems() method on ViewExecutable
ViewExecutable has a property, args, and also a property argument

My questions:

How can I get the items from ViewExecutable
How can I get the contextual filter from ViewExecutable
Do I even need to do #1 to get #2?

Further down the code, I can see that $contextual filter is used as follows:

'contextual_filter' => !empty($contextual_filter) ? 1 : 0

So it would appear I'm just trying to get a boolean indicating whether or not a contextual filter exists.

Can anyone who has worked more with D7 Views more than I give me some insight as to what is happening with this code, and ideally how I can update it to D8? (Though insight as to what is happening in D7 may be enough for me to figure it out in D8).

In D8 the settings of a view are stored in a configuration entity. You can load the entity with View::load() or get it from the view executable directly and then load a display and check the contextual filters (stored in the key arguments of the display options):

$storage = $view->storage;
$display = &$storage->getDisplay('default');
$arguments = $display['display_options']['arguments'];

'contextual_filter' => !empty($arguments) ? 1 : 0