drupal_goto ignored in custom form submit handler I'm working on a site at the moment where some nodes are hidden behind a login. You can see a list of them, but to view them you need to sign in.

The sign in is done by showing the user login block in a lightbox.

Now the problem I'm having is the submit handler for the form isn't working properly. In my template.php file, it looks like this:

function fisita_redirect_after_login(&$form, &$form_state) {
   drupal_set_message($form['hidden_paper_url']['#value']);
   drupal_goto("http://www.google.com");
   //$form['#redirect'] = $form['hidden_paper_url']['#value'];
   //$form_state['#redirect'] = $form['hidden_paper_url']['#value'];
}

The Drupal set message, works fine, and it is outputting what I want (the URL we're trying to redirect to), but any attempt at changing the page isn't running. Either redirect or drupal_goto.

Does anyone have any clues?

Thanks

I had a problem like this and I used this as a workaround to get the page to redirect:

$url = url("node/$nid");
header("Location:$url");
drupal_set_message(t('Message to be displayed in the next page'));
drupal_exit();


To get a table in drupal 7 same as content_type_[your_field_name] in drupal 6? In the Drupal 6 database, for every content type, there is a  table that's called content_type_[your_field_name]
Now I have a database query as follows in drupal 6 :

db_query("SELECT n.nid FROM {node} n INNER JOIN {content_type_field_abc} s ON n.vid = s.vid
                          INNER JOIN {def_table} sts ON s.nid = sts.nid
                          WHERE n.type = 'trans' AND s.field_study = '%s' AND sts.status = 1", $account->name);

Then how can I use db_query in drupal 7 to get a table containing all the fields of the content type as columns same as drupal 6 ?

Or Simply, how can I write the above given query in drupal 7 ?

That depends what fields you have defined in your content type.

An easier way is to load the node object and fetch your data from it.

$node = node_load($nid);

If you install the Devel module you can do dpm($node); and find how to access all data attached to your node.


Is there a way to output the machine name of a taxonomy term? I've been to figure out how I can output the machine-name of a taxonomy term on my entity field to my twig template. using .label prints out the name of the taxonomy term. .id get a numerical value, was actually hoping to get the machine term instead. Using kint I can't seem to find it

{% for themes in node.field_themes %}

        <span>{{ themes.entity.id }}</span>
{% endfor %}

I see, the output I'm looking for somewhat like the key value of a
  list field. For example Taxonomy term it becomes taxonomy-term

As discussed the correct way is

{{ themes.entity.label|lower|replace({' ':'-'}) }}

It's suitable for other entity types as well


Storage API + Services 3: How to work together? I am trying to set up a site that will be storing a large amount of images. I am using Storage API module for that and It is working fine through web.

Now I need a REST Service to upload images.
I am trying with the default file POST endpoint of the Services module:

--> POST http://example.com/api/file http/1.1
Content-Type: application/json
Content-Length: 343901
Cookie: ..............
X-Csrf-Token: .........
{"file":"iVBOR.......Jggg==","filename":"myimage.png","uri":"storage-field-images://myimage.png"}
--> END POST (343901-byte body)

<-- 200 OK http://example.com/api/file (888ms)
Content-Type: application/json
{"fid":"81","uri":"http://example.com/api/file/81"}
<-- END HTTP (74-byte body)

But http://example.com/api/file/81 is responding me:

{"fid":"81","filename":"myimage.png","uri":"public://myimage.png".........

(Not the same uri that I sent in the request)

Am I missing something in the resquest? Or do I have to develop a new endpoint to manage that?

replace uri with filepath
--> POST http://example.com/api/file http/1.1
Content-Type: application/json
Content-Length: 343901
Cookie: ..............
X-Csrf-Token: .........
{"file":"iVBOR.......Jggg==","filename":"myimage.png","filepath":"public://storage-field-images/myimage.png"}
--> END POST (343901-byte body)


Make the order available in checkout pane callback when viewing I've overridden the payment pane callback in the checkout page (using hook_checkout_pane_alter), and I want to modify the form inputs in the pane based on the order total. However, the order object is empty when the callback is called with the "view" operation parameter.

How do I make the order available in the callback function?

You might need to use an order pane instead.


Errors to Display: None - Settings won't save I've got my site developed and I'm preparing it for production. There are some errant warnings that appear every once in awhile (I've checked them, they aren't actually a problem, just something dumb in one of the php libraries I'm using). I'd like to hide all warnings and errors on the production site.

I, as an administrator, go to /admin/config/development/logging and I change Errors to Display to None, then I click Save. It says my changes have been saved, but the option is still set to "All Messages" and the errors and warnings are still showing on my site.

What's wrong? Why can't I change this setting?

I'm logged in as user 1, with administrator permissions, but I can't change this setting. Can you help me?

Found it!

This is my first Drupal site I'm pushing to production. I still had the following lines of code in my settings.php as suggested on this site: http://drupal.org/node/1056468

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Those lines were forcing it to ignore the value in the database and always set it to Show All Errors. I commented those lines out and it's respecting the form value I choose now.


Benefit of loading JavaScript in template.php rather than the theme info file? The title says it all really. Whats the benefit of loading JavaScript files in the template.php file over the theme info file?

For the sake of simplicity lets assume there is no condition to them being loaded. As a themer my instinct is to want to load things with the info file, but this isnt the standard practice on my current project.

No real advantages.

There are two reasons to add Javascript : to make some elements work, or to make them look cool.

JS to make something work

These should be #attached to the element they make work. Preferably in the module that created said element. Or they may be written in unobtrusive way and put in info file of this module. Either way, they should never be put in theme, makes no sense to have them there. So these should be out of your question's scope.

Eye candy

These belong to theme all right. And because they do, they shouldn't depend on any script that's in module. If you have a rare situation when they do, then you need to add them in PHP for conditionals that'll cache and not waste browser's resources. But you told no conditions, so this is moot. Or should be, if your theme just assumes presence of modules without checking you have serious bug there, problems waiting to happen.

Having them added in PHP allows some reordering etc. In my experience it was always easier to write my JS in a way that didn't require this. Drupal Behaviors are good for this. If for some reason you can't write your scripts in order independent way, ie you have to use external scripts or have no time for rewrite, then #attached is the way to go.

Other "advantage" would be to attach them only to elements that are supposed to get their cool effects. But this rarely is an advantage. If all you need is to make sure JS is included, include it always. Better for caching and it'll act only on elements with specific id or class anyway, no real harm for browser. Exception here is when you need to take some php variables and make them avaliable to Javascript. Then info file will obviously not suffice and you need to add it via php.

TL;DR

Your intuition is generally good.


How to determine where the CCK fields are stored in database? When a content type is created, there is a new table for it. For example, there is a content_type_claim table, for content type claim. Content fields are defined within the table.

However, when a content field is shared (used more than once) in different content types, there will be another table created for this field. For example, there is a content_field_claim_no table for claim no, if claim no is also used in another content type.

My question is, in which table Drupal defines whether a content type field is stored inside the content_type_??? table (when used once), or in its own conten_field_??? table (when used more than once), for a particular content type.

You want the content_node_field_instance table. As that table defines each "instance" of a field on different content types. For the field configurations (global configs, independent of instance configs) you want the content_node_field table.

Similarly in Drupal 7 there's field_config table for global field configurations, and field_config_instance table for each instance of a field with content types.


How does the Drupal template engine work? I've just started learning about Drupal 7's theme system. I need to know how the template engine handles php, html, and css inside its template files and how it interacts with Drupal core to make its final output onto the page.

Basically, when we load a Drupal page in browser, what does the template engine do?

The Theming Guide is a good place to start.  Also the Theming Drupal 6 and 7 pages should be of some help to you (more specifically, How the Drupal theme system works).

Theming guide:

  This handbook is about customizing the look and feel of a Drupal site.
  We'll show you how you can modify the appearance of your Drupal site
  without requiring expert knowledge of programming. And if you wish to
  go further, we cover that too.

  This guide assumes some knowledge of HTML and CSS but no PHP
  programming knowledge is necessary. It also assumes you have
  administrator's privileges to a Drupal site. You might also want to
  familiarize yourself with some of the terminology used in Drupal. We
  concentrate on Drupal 7 with notes for Drupal 6 where applicable.

How the Drupal theme system works:

  Pages in this section describe the way the Drupal theme system
  operates, theme components and settings, .info files and page
  templates. This section is a starting point for creating a new custom
  theme.


When to use the Flag module versus a boolean field? In terms of performance, maintenance, and future expansion/migration, what are the advantages and disadvantages of using the Flag module versus a boolean field?

In my case I would use the module to mark articles in a newspaper website that will be featured on the front page.

For this particular use case, you could go with the field. There is no need to install a contrib module for something that a field can do fine.

Flags create a new entity for each new flag you create. This adds an extra layer of complexity when you are need to migrate or deploy.

It would make sense to use flags, if for example, you wished that your each of your users could mark this article (eg mark it as favorite)

Drupal also offers the 'promote to front page' functionality that you could use.


Redirect timer on successful WebForm submition I'm asked to introduce auto-redirect (to the home page) on the confirmation page of WebForm (i.e. when user sends data, he gets on the page saying "Thank you! You submition has been received, etc..." ). And I'm asked to make a redirect after some time having past, let,s say, 10 seconds.

Seems that I have to introduce some js altering but I don't know how to do this properly.

Thank you!

Add this code in webform-confirmation.tpl.php

$(document).ready(function() {
  var delay = 10 ;
  var url = "http://google.com";
  function countdown() {
  setTimeout(countdown, 1000) ;
  $('.webform-confirmation').html("Redirecting in "  + delay  + " seconds.");
  delay --;
  if (delay < 0 ) {
  window.location = url ;
  delay = 0 ;
  }
 }
countdown() ;
});


How to get current path for user profile field? On the user profile page, I want to add link field which will link to a view page.

For example,
if the current path is:

sitename/user/1 (profile page of user-1)

The link should be:

sitename/user/1/view-page

It should take the user-id from the current-path. It should redirect to sitename/user/1/view-page, in general sitename/user/%/view-page, which is my contextual view path.

How can build this link field for the profile page?

One way to go about this is a theme override of the user profile page:

Copy over core/modules/user/templates/user.html.twig over to your theme's template directory.
Have your theme implement template_preprocess_user() in your MYTHEME.theme file to inject a custom URL variable.
Modify your theme's user.html.twig to contain the HTML for the link.

For example, in your MYTHEME.theme:

use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_user() for user.html.twig.
 */
function MYTHEME_preprocess_user(&$variables) {
  if (\Drupal::request()->get(RouteObjectInterface::ROUTE_NAME) == 'entity.user.canonical') {
    $variables['view_page_path'] = Url::fromUri('base:' . \Drupal::service('path.current')->getPath())->toString() . '/view-page';
  }
}

In your user.html.twig:

{% if view_page_path %}
  MY VIEW PAGE
{% endif %}


Drush command to show aliases? Is there a drush command to show existing aliases? Some Googling didn't turn up anything.

You can use this in the terminal

drush sa

For example on my dev server:

- drush sa
@8080
@commons_3_dev
@none
@w2

The aliases are set in file called aliases.drushrc.php. For me this is located in /usr/local/share/drush/. Depending on how you installed Drush and on which distro you're on this may differ.

You can set up aliases in this fashion inside that file

$aliases['8080'] = array(
'uri'=>'server.com:8080',
'root'=>'/var/www/html_webtest2',
);

$aliases['w2'] = array(
'uri'=>'webtest2.server.com.edu',
'root'=>'/var/www/html_webtest2',
);

$aliases['commons_3_dev'] = array(
'uri'=>'yourserver.com/c3d7/',
'root'=>'/var/www/html_commons_3_dev',
);

For more fun, you can chain these together for server wide backups. For example, I do a big back up to all aliased sites like this

 drush sa | egrep "(@|default)" | egrep -v "(@none|@self) | xargs -L1 drush arb

Taken individually

 drush sa  # list site aliases
 | egrep "(@|default)"  # include default and any line containing a @ mark
 | egrep -v "(@none|@self)" # remove any lines with @none or @self
 | xargs -L1 drush arb # with each line run drush archive-backup

To find path and other info, use a bit o' pipping:

drush sa | xargs -I {}  sh -c "echo {}; drush {} st"

To narrow it down to finding paths:

    drush sa | xargs -I {}  sh -c "echo {}; drush {} st" | egrep "(@|path)"
@8080
 Site path                     :  sites/8080.webtest2
 File directory path           :  sites/8080.webtest2/files
 Private file directory path   :  /var/www/drupal_private_files
@commons_3_dev
 Site path              :  sites/default
 File directory path    :  sites/default/files
@none
@w2
 Site path              :  sites/default
 File directory path    :  sites/default/files

update

A bit late but I wanted to say don't forget about drush @sites st. I believe the @sites parameter will act on everything found under the sites folder. Think

drush @sites cron -y # runs cron on each root/sites/site
drush @sites rf


How to create View with Full Content and Teaser Can I create a View of nodes which has 'Full Content' for one node and 'Teaser' for the others ?

My page consists of a node containing full content followed by summary nodes which link to their pages.

I have a workaround but it not ideal:

I selected 'Teaser' Show:Content | Teaser in the View for all my nodes and increased 'Summary or Trimmed length' to 60000. That way, nodes with summary will show up and nodes without summary will display 60000 chars from body.

First, list only the full node in a Views display, then add a second display of type "Attachment". This attachment view will then list all the teasers, and can be configured so that it always "attaches" to the bottom of the primary one.

This way you can get both Views, but they always render together.


How to set different paths to different images on the same views block I have a situation where I have a block with 3 Images and links in the front page set in a block (drupal 7)
and I am trying to make each image and link to point to a different section in the site
but I can't :( I only managed to make them all point to the same page or to divide each to its own block (with views)
but then it doesn't look so good visually...

is there a solution for that?
Thanks

Ok, so here is a step by step "how to manage this" ;)

Step 1: be sure to have the content type for your images containing a field "link", where you can add the link to your specific page section.

Step 2: Add some content with image and URL to page section (e.g: node/13)

Step 3: Make sure you have some nodes like this:

Step 4: Create a new view for the block you want to fill with your content-type:

Step 5: Add the fields you want to show to the view: (here: the field for the image and the field for the link). If the link should be shown seperate from the image as well, you'll have to add the field for the link twice, because we'll "pass over" one link to the image)

Step 6: Now re-arrange the fields so that the order is the following. This is important, because the image field will hold a replacement pattern of the above Link field (which is excluded from display, because we don't want the link to show up, we only need its data).

Step 7: Now configure the first image field "excluded (mylink)" so that it is excluded from display and rewrites the output of the field with the replacement pattern for the "Raw url" value:

Step 8: Now configure the image field like this. Mark "Output this field as a link" and use the replacement pattern for the above link field "[field_mylink]".

That's it. Now you have a view that pulls the URL from the content type and puts it on the image of it.


single exposed filter for two displays in same view I have three displays in same view. Every display has exposed form filter and in every pages ajax was set yes. How to use a single exposed filter for these three displays in same view?

I placed these three displays in to three quick tabs. For example, the three quicktabs names are test1, test2, test3. If I apply filter in test1, it should apply all other displays (test2, test3) also.

Under Advanced > Other You have to set the "Use AJAX:Yes" for both the views.
At the Quick tab setting page select the following radio button -
Yes: Load only the first tab on page view".


Created a development/test server from an existing site, struggling with permissions errors on Cent OS 6 server I am hoping a I can get a little help on a problem that I continually struggle with and that seems to impact a number of places on a site that I have copied over from a production version.

So I have a site for which I created a development environment for on an Amazon EC2 instance (original site is not on Amazon EC2). So far everything is loading up and showing for the most part. But it is becoming clear that in handling administrative tasks I am running into file permission problems.

For instance, If I go to *Administrator > Site Building > Themes > My Custom Theme* to configure the favicon, I get the error:

  The directory sites/default/files is not writable

I have tried chmod 775 and that does not work. If I do chmod 777 the css files don't load and the site is without styles. I have tried chown 6226 (which seems to be the default user from when I did a fresh install of drupal 6.20 on the new server). And have tried chown ec2-user (the default ec2 instance user) as well as chown the user from the production server (for which there is a user with the same name on the new server).

So far nothing works and the directory is still not writeable. Where can I go just to see what the new server expects for write permissions to the files it needs permissions to access? These are not problems on the production server.

The best to fix the permission issue is run the fix-permission script available at https://drupal.org/node/244924

First download the script from here and than run the script as:

sudo bash fix-permissions.sh your/drupal/path your_user_name

Note: The server group name is assumed "www-data", if it differs modify it in the script code

Drupal official doc for file permission is available at https://drupal.org/node/244924

Generally Recommended Permissions for Drupal Files and Folders is following:

drupal/sites/default                                        750
drupal/sites/default/files (including sub folders & files)  755 or 770 *
drupal/sites/default/settings.php                           400 or 440 *
drupal/sites/default/default.settings.php                   400 or 440 *
drupal/sites/all/themes (including sub folders & files)     755
drupal/sites/all/modules (including sub folders & files)    755

* depends on system setup. Some extra modules and/or server rules may require different permissions.


How to build a module which calls a JS file on one certain node? There’s one site (A) which via an API of one other Drupal site (B) gets an already rendered views block displayed on one node - finally with hook_menu() and hook_block_view(). So now I have that node (/stuff) here with it’s views rows and views fields containers.

Since these things really have nothing to do with (B) (where I also don’t have access to) I want to build a module (button) on (A) which calls a JS to manipulate the DOM only on /stuff. Which hooks and syntax will I need?

I think you're looking for something like hook_page_alter() + drupal_add_js(), e.g.

function MYMODULE_page_alter(&$page) {
  // Check that we're on the right page.
  if (arg(0) == 'stuff' && !arg(1)) {
    // And add some JS.
    drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/MYMODULE.js');
  }
}

This could also be done in hook_preprocess_page(), hook_init(), and probably a bunch of other places. I chose hook_page_alter() at random out of those, each should be equally effective.


How to use language-specific menu items in URL aliases I'm working on a site with internationalization from the source language, English, into a few other languages. Translating the pages has worked out fine; however, I'm running into trouble with URL aliases.

Some of our pages have different menu labels vs. page titles (e.g. Terminals as the menu label vs. Terminal Information as the page title), and since the client wanted the shorter menu labels in the URL, my default path pattern (set using the Pathauto module) is [node:menu-link:parents:join-path]/[node:menu-link:title].

Menu items are also set per language – so while Terminals is the English version of the menu item for that page, when viewing the site in French, I have a menu item labeled Aérogares that's used only when the site is translated into French. This means that when the URL is constructed for a page called Maps in English and Plans in French whose parent is Terminals/Aérogares, the English URL alias is /terminals/maps, but the French alias is /fr/aérogares/plans.

Another part of the problem I'm facing is that when I save a translation of the page, this menu pattern ignores the source language and resaves every language's alias as that of the language of the translation (when saving a French translation, the English alias becomes /aérogares/plans, the Arabic alias becomes /ar/aérogares/plans, etc.).

I've tried a few different tokens as part of the URL alias options to see if they'd work, but without success:

[node:source:menu-link:parents:join-path]
[node:source:menu-link:title]
[node:source:title_field]

There are a few different options that would be acceptable in the end, listed here from most to least desirable:

Foreign-language URL aliases use that language's menu structure, e.g. Terminals/Maps is /terminals/maps in English and /fr/aérogares/plans in French, and saving one language doesn't affect the others
Foreign-language URL aliases use the language code followed by the full English path, e.g. Terminals/Maps is /fr/terminals/maps in French
Foreign-language URL aliases use the language code followed by the current page's English title, e.g. Terminals/Maps is /fr/maps

I'm running Drupal core version 7.61. Here's a list of relevant translation- and menu-related modules I currently have in use:

Entity Translation 7.x-1.0
Entity Translation Menu 7.x-1.0
Internationalization 7.x-1.26
Menu translation 7.x-1.26
Pathauto 7.x-1.3
Token 7.x-1.7
Translation Management (tmgmt) 7.x-1.0-rc3

How can I accomplish one of the desired URL structures and keep them language-independent when saving revisions to content?

Your configuration is too complex to be able to say with certainty, but your menu tokens seem to support "languages", so it may be the Path that needs some extra support.

Have you enabled Path translation or tried Pathauto i18n?


How to fix my SQL Group By issue? I have a problem with MySql request on Drupal 8.
I want to translate this request to Drupal:

SELECT x.camp AS camp, x.code AS espece, y.des AS designation, x.pf AS pf,
ROUND( SUM( x.pn - x.qte ) , 3 ) AS qte
FROM apport.apport x, apport.cereale y, apport.operation z
WHERE x.code = y.code
AND x.ope = z.code
GROUP BY x.camp, x.code
ORDER BY x.camp, x.code

This request works on PhpMyAdmin.

So, I do this:

    $query = $db->select('apport.apport','x');
    $query->join('apport.cereale','y', 'x.code = y.code');
    $query->join('apport.operation','z', 'x.ope = z.code');

    $query->fields('x', array('camp', 'code' ,'pf'));
    $query->fields('y', array('des'));

    $query->addExpression('ROUND(SUM(x.pn-x.qte),3)','qte');
    $query->groupBy('x.camp')->groupBy('x.code');
    $query->orderBy('x.camp','ASC')->orderBy('x.code','ASC');

    $result = $query->execute();

    $tableau = array();

    foreach ($result as $record) {
        $row['camp'] = $record->camp;
        $row['code'] = $record->code;
        $row['des'] = $record->des;
        $row['pf'] = $record->pf;
        $row['qte'] = $record->qte;

        $tableau[] = $row;

        print_r($tableau);
    }

But it doesn't work. The problem comes probably from here:

    $query->addExpression('ROUND(SUM(x.pn-x.qte),3)','qte');
    $query->groupBy('x.camp')->groupBy('x.code');

Because when I comment the above two lines, I do get a result.

Any help please ?

By default, Drupal use "Full_ group_by" so that why you need to Group all your fields.

If you want disable it and group only on one field, you have to update setting.php

Add this :

$databases['default']['default'] ['init_commands'] = [
'sql_mode' => "SET sql_mode = 'STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
];


#value or #default_value missing from field in $form array I made a custom content type with a couple of fields. If i go to node/add/custom-content-type
I have a dsm of $form in my .module file which shows the array in a krumo just fine. In the krumo the array shows the custom fields made in field UI, and each field has an array of 6 elements. Here's where the key #value and #default_value are missing.

Instead, the 6 keys are:

#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 1 characters ) 1
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 13 elements)

So obviously the question is how do I get those keys/attributes of that field in that array?

See Why is hook_form_alter() so messy? for a bit of background, but basically you need to drill further down into the array.

Assuming it's a standard text field you would set, for example, the default value like so:

$form['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = 'foo';


Views Slideshow Cycle doesn't re-initialize properly after an AJAX content update I have a Views Slideshow on my site that works perfectly until I try to reload only part of the page (containing the slideshow among other stuff) via AJAX (using Ajax links API module). The content itself is reloaded properly but:

If the new content contains different blocks than the old content, I'm getting the following error:

Uncaught TypeError: Cannot set property 'targetId' of undefined

It's the following lines that cause the error:

var fullId = '#' + $(this).attr('id');
var settings = drupalSettings.viewsSlideshowCycle[fullId];
settings.targetId = '#' + $(fullId + " :first").attr('id');

An inspection of drupalSettings.viewsSlideshowCycle in Chrome DevTools shows that it doesn't contain the current block id ($(this).attr('id')) but contains the old block id, already gone, so drupalSettings.viewsSlideshowCycle[fullId] returns null. In other words, the AJAX-driven content update doesn't seem to update drupalSettings - is it supposed to? I checked the AJAX response and it contains correct settings but for some reason the script doesn't see them and uses the original settings that came with the initial page load.

If the new content has the same structure as the old one (same block name for the Views Slideshow) then I don't get the error and the slideshow sort of works but the slide counter shows funny numbers in funny sequence (like 6 of 2, then 2 of 2) and at funny times (not when the slides change but when they stand still too). It looks like there are two scripts running simultaneously interfering with each other.

I would expect the behaviors mechanism to somehow kill the old scripts and settings and replace them with new ones upon processing an AJAX response but it doesn't seem to happen and I can't find any documentation on this particular aspect.

Sorry for a possibly fuzzy description (must admit I don't know the inner workings of AJAX all too well) - will be happy to provide more info if needed!

I would expect the behaviors mechanism to somehow kill the old scripts
  and settings and replace them with new ones upon processing an AJAX
  response but it doesn't seem to happen and I can't find any
  documentation on this particular aspect.

The D7 Managing Javascript docs explains this well:

  Drupal.behaviors will often be called multiple times on a page. For
  example, every time a form performs some Ajax operation, all Drupal
  behaviors will be executed again after page load, in order to attach
  any relevant JavaScript to the newly loaded elements. This can have
  the undesired affect of applying JavaScript to elements each time
  Drupal behaviors are executed, resulting in the same code being
  applied multiple times. To ensure that the JavaScript is applied only
  once, we can use the jQuery $.once() function. This function will
  ensure that the code inside the function is not executed if it has
  already been executed for the given element.

The D8 Javascript Overview docs tells you how to use $.once() in D8.

If your code is not recognizing the ajaxed in divs, then you need to attach the behaviors to the ajax wrapper, with drupal.attachBehaviors($('.ajax-wrapper'));

Ex:

$.ajax({
    url: '/some/url',
    type: 'GET',
    success: function (data) {
        var result = $(data).find('.some-wrapper').html();
        $('.ajax-wrapper').html(result);
        Drupal.attachBehaviors($('.ajax-wrapper'));

    }
});


Alternative to .htaccess compression with Boost My hosting provider doesn't support mod_deflate directives in .htaccess to provide compressed HTTP responses.

I am using Drupal 7 with Boost and wish to compress HTML, CSS and JS responses.

Is there another alternative to doing this with .htaccess?

Core should support .gz for CSS & JS. This requires .htaccess rules though. For core they should already be included.

Looks like I never got around to gzip for Boost for 7.x. You can follow the issue here
http://drupal.org/node/1416214


How can I run a query in the views in the context of the user access? How can I run a query in the views in the context of the user?
E.g. using EntityFieldQuery I can run

  $query->addMetaData('account', user_load(1));

is there any equivalent for $view->query?

I've found possibility to do it in hook_views_post_build:

function MY_MODYLE_views_post_build($view) {
  if($view->name == 'MY_VIEW_NAME') {
    $query = $view->build_info['query'];
    $query->addMetaData('account', user_load(47));
  }
}

I've noticed that we have SelectQuery object only after query build (in views.inc $this->query->build($this);).

After it only one hook is executed views_post_build.


How to redirect to another page using the url alias? Here is my code where I am trying to redirect to a page using its url alias:

    $url= Url::fromUserInput('/thank_you_for_your_message')->toString();
    $form_state->setRedirect($url);
    return;

and I get this error : Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/thank_you_for_your_message" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

Is the fromUserInput the correct way to redirect to an internal url alias?

Here you can see an example that works for me:

I use 'internal:url-alias'

use \Drupal\Core\Url;
...

$search_page = '/en/faith-community/find-a-parish';
$form_state->setRedirectUrl(Url::fromUri('internal:' . $search_page));


Error when running database update: "DatabaseSchemaObjectExistsException: Cannot add field redirect.status: field already exists." I'm getting the following error when attempting to run a database update:

Update #7101
Failed: DatabaseSchemaObjectExistsException: Cannot add field redirect.status:
field already exists. in DatabaseSchema_mysql->addField()
(line 336 of /var/www/sitename/drupal/web/includes/database/mysql/schema.inc).

It looks like the database update it do to some redirects I added. How do I go about solving this?

Most probably you are on Redirect 7.x-1.0-rc3 which was released back on 8 July 2015. It has been fixed on https://www.drupal.org/project/redirect/issues/2541304, so just update your Redirect module to 7.x-1.x-dev.


node_load is not working I am creating a import script, which is importing node into Drupal website from external database.

Node is inserting properly. I have added condition that node exist into Drupal website or not and I am getting the correct nid with  this condition.

When I am using node_load to load the existing node, its showing empty result.

I also checked node_load get blank, but did not get any satisfied answer.

Please forgive me if this question is duplicate.

Code Snippets:

$pricelist_query = db_query("select * from abshop_import.abshop_import_price where (result != 'I' and  result != 'O' and result != 'D') or result is NUll limit 0, 50");

$message = '';

while ($pricelist_object = db_fetch_object($pricelist_query)) {

    $product = db_fetch_object(db_query("select * from abshop_import.abshop_import_antibodies where (result != 'I' or result is NUll) and sku_model='%s'", $pricelist_object -> sku_model));

    if (!empty($product)) {

    $product_object = db_fetch_object(db_query("select nid from {content_field_pr_man_prd_numb} where field_pr_man_prd_numb_value='" . $product -> field_pr_man_prd_numb_value . "'"));

        //If product is primary antibodies
        if ($product -> primary_or_secondary == 'P' || $product -> primary_or_secondary == 'p') {

        //If there is no existing product
            if (empty($product_object)) {

                $node = new STDCLASS;
                $node -> type = 'primary_antibodies';

                //setting language of the node
                $node -> language = 'en';

                //setting the author of the node
                $node -> uid = $product -> uid;

            } else {

                $nid = $product_object -> nid;

                $node = node_load($nid, NULL, TRUE);

                print $product_object -> nid . "===>";

                print_r($node);

            }

            $node -> shippable = 1;

            $node -> model = $product -> sku_model;

            //Setting title of the product
            $node -> title = $product -> title;
            //Setting body of the product
            $node -> body = $product -> body_teaser;
            //Setting teaser of the product
            $node -> teaser = $product -> body_teaser;

            $node -> weight = $product -> uc_products_weight;
            $node -> weight_units = $product -> uc_products_weight_units;

        }

        //If product is primary antibodies
        elseif ($product -> primary_or_secondary == 'S' || $product -> primary_or_secondary == 's') {

            //If there is no existing product
            if (empty($product_object)) {

                $node = new STDCLASS;

                $node -> type = 'secondary_antibodies';
                //setting language of the node
                $node -> language = 'en';

                //setting the author of the node
                $node -> uid = $product -> uid;

            } else {

                $nid = $product_object -> nid;

                $node = node_load(array('nid' => $nid), NULL, TRUE);

                print $product_object -> nid . "===>";

                $n = node_load(array('nid' => $nid), NULL, TRUE);
                print_r($n);

            }

            $node -> model = $product -> sku_model;

            $node -> shippable = 1;

            //Setting title of the product
            $node -> title = $product -> title;
            //Setting body of the product
            $node -> body = $product -> body_teaser;
            //Setting teaser of the product
            $node -> teaser = $product -> body_teaser;

            $node -> weight = $product -> uc_products_weight;
            $node -> weight_units = $product -> uc_products_weight_units;

        }

        if ($node = node_submit($node)) {

            print_r($node);
            die ;

            node_save($node);
        }

        node_load(FALSE, NULL, TRUE);

}

}

Thanks in advance.

After perform R&D, I found that uid of the node was not matching with uid in {users} table, which mean there is no existing user which is author of the node.

As I am importing the node from external database and it was importing properly previously, so I did not noticed the same.

Now, when I changed the uid of the node, everything starts working properly.


hook_menu() and collapsable menu items with wildcard I've defined a few routes with hook_menu(), and added these routes to a menu with nesting. This works fine for all static routes, but for any route with a wildcard the 'active-trail' does (understandably) not apply to the menu, and the parent menu item is collapsed. How can I enforce that the parent menu item is open and has 'active-trail' class?

This is the hook_menu() implementation I am using.

function my_module_menu() {
  $items['parent'] = array(
    'title' => t("Parent"),
    'page callback' => 'my_module_parent',
    'access callback' => 'user_is_logged_in',
  );
  $items['parent/child'] = array(
    'title' => t("Child"),
    'page callback' => 'my_module_child',
    'access callback' => 'user_is_logged_in',
  );
  $items['parent/child/%'] = array(
    'title' => t("Child Item"),
    'page callback' => 'my_module_child_item',
    'access callback' => 'user_is_logged_in',
    'page arguments' => array(2)
  );

  return $items;
}

My menu (a custom menu) looks like the following.

Home

Item 1
Item 2
Parent

Child

So if I go to 'parent/child/123' I want the 'parent' and 'child' menu items to be active and not collapsed.

I've tried the Menu Trail by Path module, but it seems to have no effect.

I solved the problem with the Link Trail By Path module. This module add active class for 'parent' and 'child' link.


How to create structure "Author -> Book -> Quote"? I need to create structure [taxonomy_term] Author -> [taxonomy_term] Book -> [node] Quote.
I already have the following structure: [taxonomy_term] "Author name and Book name" -> [node] "Quote". Now I want to split vocabulary "Author name and Book name" into 2 different vocabularies: "Author" and "Book" and link them to each other and to node type "Quote" to get the following hierarchy:

Author [taxonomy_term]

Book [taxonomy_term]

Quote [node]
Quote [node]

Book [taxonomy_term]

Quote [node]
Quote [node]

I can create this hierarchy using Entity reference, but I don't know how to achieve the following.

On node (Quote) creation user should be able to:

choose existing "Author" term and existing "Book" term that belongs to this Author (conditional select);
choose existing "Author" term and create new "Book" term (and link this book to "Author" term);
create new "Author" and "Book" terms (using taxonomy autocomplete widget) and link them to each other.

Is there any way to achieve this using existing Drupal modules?

Please note: I need to use 2 different vocabularies for authors and books. I know that it would be much easier to use 1 vocabulary and parent-child hierarchy of terms, but that is not suitable in my case.

Complex business like this is hard "out of the box" with Drupal. Everyones custom logic like you've listed is different -- so community modules regularly dont let you define just deep nesting of logic.

I suspect you'll have to create some custom code to enforce relationships you want (form  validation logic).

Additionally, look at Conditional Fields, Entity Inline Form and perhaps the Prepopulate module.

You can use these modules to build the dependant drop down select lists, and a button to create the Book or Author for a quote as needed -- the prepopulate module could let you pass info from a book or author on creation, to the reference entity.

You may want to look at Display Suite or Renderable Elements to tweak how the node form(s) are layed out.

As I said this isn't a solution but tools to help you build your own business-logic solution.


How to exclude items from search api solr by negative keywords field Drupal 8, Search API SOLR.

I'd like to not return nodes if there are any matches between a field of negative keywords (on the node) and the query string the user has entered.

Module search_api_solr currently set up with several fields, matching in node titles, body and keyword fields.

e.g.
node titled "I can't find my elephant" with a negative keyword field containing "wallet" to not show up in a search "I can't find my wallet".

You don't need to do this in solr, you can do it in the query or with views filters.

Something like this:

$solrIndex = \Drupal::entityTypeManager()->getStorage('search_api_index')->load('global');
$query = $solrIndex->query();
$query->addCondition('title', $search_string);

$search_terms = explode(' ', $search_string);

// Don't match items where elements in the title match the stop words
// for an entity.
foreach ($search_terms as $term) {
  $query->addCondition('field_stop_words', $term, '<>');
}


Unsubscribing from mailing list for anonymous user in simplenews I use the Simplenews module for newsletters of my site. But I don't send out mails, rather use the module for subscribing and unsubscribing. Now for the anonymous user it gets difficult to unsubscribe since the user doesn't get any mail other than the subscribe mail. I read the comment in https://drupal.org/node/337628 #6, but I don't think I have an option here.

So I want to add an unsubscribe button to my block. How can I do that?

Drupal Version - 7.22
Simplenews Version - 7.x-1.0

I needed the same thing, so I thought I'd share my solution.

In hook_form_alter():

  // Check that this is a simplenews form and the user is anonymous
  // If so, add an Unsubscribe button with a custom submit handler before the
  // default simplenews form submit handler is called
  if (strpos($form_id, 'simplenews_block_form') !== FALSE && $user->uid == 0) {
    $form['unsubscribe'] = array(
      '#type' => 'submit',
      '#value' => t('Unsubscribe'),
    );

    $form['unsubscribe']['#submit'] = $form['#submit'];
    array_unshift($form['unsubscribe']['#submit'], 'custom_simplenews_form_unsubscribe');
  }

Then the custom submit handler will be something like this:

function custom_simplenews_form_unsubscribe(&$form, &$form_state) {
  // Change action to unsubscribe and exit so the simplenews handler will take over
  if ($form_state['clicked_button']['#value'] == 'Unsubscribe') {
    $form_state['values']['action'] = 'unsubscribe';
    $form_state['values']['submit'] = 'Unsubscribe';
  }
}

So, when control is passed to simplenews_block_form_submit() in simplenews.subscription.inc the user will be unsubscribed using the module's workflow.


Alter url aliases programmatically I have a pattern set up to create the URL aliases based on a field of type list text.

the field looks like this:

selection 1|selection 1

selection 2|selection 2

How can I alter the alias so it will show something like this:

www.example.com/1-was-selected rather than www.example.com/selection-1

UPDATE:
I'm using Pathauto for the patterns.

I would create a custom token and use that in my alias. I'm assuming you're using pathauto to create your aliases. This page gives a pretty good example of how to create your own token. Then you can select your token in the pathauto UI.

You can create the hook_tokens_info hook basically exactly as they've done, but replacing the "customs" with your real values. For your hook_tokens implementation, you should have access to the entity in the $data variable i.e., $data['node'] will have your node object if you're using this for nodes. From there you should be able to do something like $data['node']->field_your_list_field->getValue() to get the value of your field. Just be sure to return a $replacements array where the key is your custom_token and the value is the value to replace with, in your case this would be something like you-selected-value-X.


IMCE browser just won't work (403 error) I've installed IMCE to the CKeditor 4.54.4 in Drupal 7.41 (all in latest versions) and configured it both from editor appearance and file browser settings.

Seemingly I did all by the book and there are no errors in the status report.

I flushed all caches and switched to the full-html text editor format.

I then clicked on the CKeditor image icon, and there on "browse files" button created by IMCE.

Than I got an error (translating this from Hebrew): "The page is not reachable" (403 error). The path of the window, if it helps is:

imce?app=ckeditor|sendto%40ckeditor_imceSendTo|&CKEditor=edit-body-und-0-value&CKEditorFuncNum=155&langCode=en

Maybe you have an idea?

ן needed to configure the IMCE profile as a saparate configuration from the CKeditor-IMCE configuration.

Go to Admin > Files > IMCE and configure it.


I want to add a prefix to my database Drupal8 how? I want to add a prefix to my database Drupal8 how? I change the file  setting.php but it appears an error

Changing the $databases['default']['default']['prefix'] setting does not change your database. You'll have to either manually prefix your existing DB tables or run the installer again while placing the d8_ prefix in the Advanced Options > Table name prefix field of the D8 installer.


remove node in /node?page=1 I am using Global Redirect which automatically convert /node?page=1 to /?page=1 when click on pagination. everything working fine but i want also remove /node and just want /?page=1 when mouse hover on pagination. you can also refer my site and check its pagination.

You can use hook_menu_alter
below code not completely correct but can get you good idea about how can you do it

function mymodule_menu_alter(&$items) {
 $temp= $items['node/%'] ;
$items['page?%']=$temp;
}


send REQUEST_URI with header location redirect via settings.php I'm in predicament where I must use settings.php to do what I'd normally just do via mod_rewrite... the site is being hosted on Pantheon and I am referring to this article: http://helpdesk.getpantheon.com/customer/portal/articles/368354

I need to send the original requested path for reference. Trying to pass a the SERVER_URI as a parameter via header location in setting.php gets me an infinite loop.

My code:

if (preg_match('/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
    header('HTTP/1.0 301 Moved Permanently');

    header("Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=" . urlencode($_SERVER["REQUEST_URI"]));  exit;
}

Anybody have any suggestions as to how I might accomplish passing the $_SERVER["REQUEST_URI"] via header location from settings.php without an infinite loop?

While it's technically possible to use Drupal contrib to perform the redirect, it's faster and more efficient to redirect without having to fully bootstrap your web application.

For web only actions, like redirects, check for the existence of $_SERVER['PANTHEON_ENVIRONMENT'] - if it exists, it will contain a string with the current environment (dev, test or live).

To perform redirection for the pattern you've supplied, make sure to only match for it at the beginning of the URI in order to avoid an infinite loop problem:

// Pantheon - web only.
if (isset($_SERVER['PANTHEON_ENVIRONMENT'])) {
    // Check if you only want redirection from the live web environment.
    if ($_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
        if (preg_match('/^\/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
            header('HTTP/1.0 301 Moved Permanently');
            header('Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=' . $_SERVER["REQUEST_URI"]);
            exit();
        }
    }
}

Sources:

Configuring settings.php

PHP preg_match() Examples

preg_match


Views exposed filter Date - Year I need to create an exposed filter to a view that should handle the content's post date and more specifically the year. So I need a jump list that should contain values like '2009', 2010', '2011' etc.

I read Exposed Post date filter on views and it's all very helpful but I cannot figure out how to automate the starting date so it can be the year of the oldest content posted an the ending one the year of the newest.

Any help?

You'll need to use hook_form_alter in a custom module to set the options as the form is loaded.

Something like this:

function my_module_form_alter(&$form, &$form_state, $form_id) {

  switch ($form['#id']){
    case "my_form_id":

      //use db_select to get the oldest and newest years,
      //loop through them to end up with an array like this one:
      $years_array = array('2009', '2010', '2011');

      //set the options to your array of years
      $form_state['input'][my_form_input_name]['#options'] =  $years_array;
      break;
  }
}


How to keep a specific module on -dev version (with patches) on a Drupal8 site managed by composer? I'm trying to manage a Drupal 8 site entirely with composer. However, I need a -dev version of one module (search_api_solr) with a patch. How do I tell composer to just leave this module on the dev version for the time being and not touch it during update ?

Relevant part of my composer.json looks like this

"require": {
        "composer/installers": "^1.0.21",
        "drupal-composer/drupal-scaffold": "dev-master",
        "drupal/admin_toolbar": "^1.18",
        "drupal/bootstrap": "^3.2",
        "drupal/coffee": "^1.0@beta",
        "drupal/config_tools": "^1.0@alpha",
        "drupal/console": "~1.0",
        "drupal/core": "~8.2",
        "drupal/delete_all": "^1.0@alpha",
        "drupal/devel": "^1.0@RC",
        "drupal/facets": "^1.0@alpha",
        "drupal/imce": "^1.5",
        "drupal/masquerade": "^2.0@beta",
        "drupal/migrate_manifest": "^1.4",
        "drupal/migrate_plus": "^3.0@beta",
        "drupal/migrate_tools": "^3.0@beta",
        "drupal/migrate_upgrade": "^2.0",
        "drupal/pathauto": "^1.0@RC",
        "drupal/search_api": "1.0@beta",
        "drupal/search_api_sorts": "^1.0@alpha",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/search_api_solr": "8.x-1.x-dev"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,

I've specified the search_api_solr version according to this advice. However, when I run composer update I get:

Your requirements could not be resolved to an installable set of packages.
The requested package drupal/search_api_solr 8.x-1.x-dev exists as drupal/search_api_solr[...] but these are rejected by your constraint.

EDIT:
Meanwhile I have worked around this by removing the drupal/search_api_solr requirement completely from the composer.json, explicitly listing solarium/solarium instead and installing the patched version of search_api_solr-8.x-1.x-dev manually into the modules/unstable directory. Now composer update works as it shold without overwriting the patch.

Firstly, the 8.x- is not part of the composer version; the correct version is 1.x-dev or dev-1.x.

However, composer require drupal/search_api_solr:1.x-dev always updates to the latest revision on the dev branch. If you want to stay on a specific commit and prevent updates entirely, use something like composer require drupal/search_api_solr:1.x-dev#46e16862.


How to fetch submenu items for current page? My site nav is all in a single menu: main-menu, eg:

Home
About

Director Name 1
Director Name 2

Contact

My site navigation bar comprises two horizontal strips: the upper one lists all top-level pages (ie: Home, About, Contact, Services). The lower one should be populated with the revelant sub-menu items for the current page. So if you're on the Home page, the bar will be empty. If you're on the About page, the bar will contain links to each of the Directors pages.

My top menu is populated by the following, unchanged from the code in the default page.tpl.php:

<?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')))); ?>

To get the sub-menu items, however, I've had to add the following to my theme's template.php:

function mytheme_preprocess_page(&$vars){

    $vars['page_submenu'] = NULL;
    $main_menu_tree = menu_tree_page_data('main-menu', NULL, TRUE);
    foreach ($main_menu_tree as $menu_item) {
        if (count($menu_item['below']) > 0) {
            $submenu = $menu_item['below'];
        }
    }
    if ( !empty($submenu)){
        $vars['page_submenu'] = menu_tree_output($submenu);
    }
}

... basically, "get the main menu, find the menu item in it that has some "below" items, and return that "below" bit as a menu tree".

I can then just render that in the template:

print drupal_render($page_submenu);

This seems a bit kludgy. Returning only the submenu items for the current page would seem like a fairly common requirement - is there a better way to do it?

You are right it's a pretty common requirement. If you are not afraid of slight performance hit, you may use Menu Block module. It is able to provide you with submenu relative to your current path:

So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
Pretty simple, eh?

Of course it is a pretty big module, and it puts additional block layout between your menu and your display, so if it is too much of a performance hit, you can try to borrow some of it's code - it's GPL after all.


Checkboxes Defaulting to Selected When Not Desired This is going to be sound like a real stupid question, but for the life of me I don't know how to fix it. I have inherited some code that I need to maintain, and the issue I am experiencing is that a form containing checkboxes is displayed, and they are always all selected. The code for the checkboxes is as follows:

$license_result = db_select('licenses')
  ->fields('licenses', array('code', 'name'))
  ->execute();

foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $selected_licenses,
  ),
);

I though that by having an empty array for #default_value would deselect all checkboxes. Am I reading the form API wrong in this regard? Eventually I would like to set the default values but right now I want to make sure they start off as unselected.

Thanks.

I think you have to set the value in each checkbox, so probably this would be it :

foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
  $licensevalues[$license->code] = 0;
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $licensevalues,
  ),
);


Term order when saving a new taxonomy term By default when you're saving a new taxonomy term it's placed by the alphabetical order, how to make newly added terms to appear below the existed terms? Or even highlight it? Because i have like 200 terms and it's hard to manage it when you're adding a new term.

while I am not aware of a solution that will get you this exactly behavior without spending a bunch of time on a unique setup, there maybe a simple workaround for you to quickly identify the new term and move it to whereever it belongs to.

but first of, the definition or new terms being sorted alphabetically is not entirely true. by default, newly added taxonomy terms have a Weight of '0'.
this Weight value serves as the first sort criteria: terms with a higher Weight value will be further down, as will terms with a lower Weight value (can be negative too) appear further up in the list.
only when multiple terms share the same Weight value, they further get sorted alphabetically.

you can see the exact Weight value for every term by clicking Show row weights just above the top right-hand corner of the table.

so if you have a taxonomy vocabulary where all terms have a Weight of -1 and below, newly added terms will be found at the very bottom of the list.

while this will put new terms to the very end of a list, setting up a list this way may be rather tedious, as you might run out of negative numbers or simply because managing 200+ entries this way can  be a pain in the butt. instead, there is another approach I find myself using most of the time:

there are two View Modes managing Weights: one enables you to manually define a Weight value via a select list (the 'show row weights' mode mentioned above), and the other one lets you sort individual terms via dragging and dropping by clicking on the cross/drag cursor on the very left of each term. when you manually define a term order by dragging and dropping (dont forget to hit Save!), every term will be given a unite Weight value starting by 0.
 this means only the very first term will have a Weight of 0. the second term will have a Weight of 1, the third gets a Weight of 2 and so forth.
when you now add a new term, it will be assigned the weight of 0 as well, placing it as either the very first or second term in the list. this will enable you to find it immediately and place it wherever you need it to be.
if you find yourself wanting to place that new term at the very bottom, dragging it all the way down can be tedious as well, so a quicker way now would be to enable Show row weights again, just pick the lowest value and hit Save.

again, maybe this is not exactly what you are looking for, depending on whether you actually care about the order they are listed, or just want to identify the newest entry.


lost admin toolbar and stock file I am a total Drupal newbie so need advice.

I installed a new module commerce_shipping_postal_code_weight-7.x-1.x-dev, and tried to activate it. I was then advised a couple of other modules needed authorising. I authorised everything and then returned to my home screen.
My left hand column had disappeared which contained my login box, my stock file has disappeared, and so has my admin toolbar.
Logging in using /?q=user doesn't reveal the toolbar, but I am logged in.
I've restored all my files from 24 hours ago with no joy and now am waiting for our ISP to send me a backup database.
The only error message I get is :-

    Notice: Undefined index: search_api_views_fulltext in
 views_handler_filter->accept_exposed_input() (line 1273 of
 /homepages/11/d95668464/htdocs/drupaltest/profiles/commerce_kickstart/modules/contrib/views/handlers/views_handler_filter.inc).
 Notice: Undefined index: table in
 entity_views_plugin_row_entity_view->init() (line 20 of
 /homepages/11/d95668464/htdocs/drupaltest/profiles/commerce_kickstart/modules/contrib/entity/views/plugins/entity_views_plugin_row_entity_view.inc).

I had only downloaded and enabled the modules, and they had not been used so I have no idea of how I could have prevented it.

The fault turned out to be that a lot of modules had become de-selected. A good procedure would probably be to print off a module list with all the selected ones shown, this could then easily be checked by future webmasters.


REQUEST_TIME is in GMT eventhough site timezone is IST In admin/config/regional/settings I can see that IST timezone is set.

But when I print REQUEST_TIME constant I see GMT one.

How to get the IST time in REQUEST_TIME ?

As per the docs.

  The entries in this array are created by the web server.

Drupal has no control over this, and in fact, neither does PHP. (Though of course both of them are free to manipulate the value)


How to properly delete fields, programmatically? I have two content types on my site and I just deleted all the nodes using $node->delete().

For one of the content types, I noticed that the node body fields did not get deleted, nor did one of the custom fields I made for the content type. All the fields for my other content type were deleted .

So I researched and found the field_purge_field() function. I am not sure how to actually use the function, which is defined as function field_purge_field(FieldConfigInterface $field).
Can someone describe how I would actually load a field and then delete it in this manner (or in a better manner)?

Could I just truncate the tables?

field_purge_field() is described as follows:

  This function assumes all data for the field has already been purged and should only be called by field_purge_batch().

On Drupal, fields are effectively removed during cron tasks; in fact, field_purge_batch() is called from field_cron(), the implementation of hook_cron() done from the Field module. There is no need for you to call neither field_purge_field() nor field_purge_batch().

If you want to write code to purge fields for a node bundle, that code would be similar to the following one. (See the notes after the code, thought.)

  $properties = array(
    'entity_type' => 'node',
    'bundle' => 'Your bundle (a.k.a. content type)',
    'include_deleted' => TRUE,
  );

  $entity_manager = \Drupal::entityTypeManager();

  $fields = $entity_manager->getStorage('field_config')->loadByProperties($properties);

  $info = $entity_manager->getDefinitions();
  foreach ($fields as $field) {
    $entity_type = $field->getTargetEntityTypeId();

    // Proceed only if the module implementing the entity has not been uninstalled already.
    if (isset($info[$entity_type])) {
      $entity_manager->getStorage($entity_type)->purgeFieldData($field, 100);
      field_purge_field($field);
    }
  }

Notes

Purging the fields is thought to be ran during cron tasks; that is why Drupal::entityManager()->getStorage()->purgeFieldData() requires the batch size as argument. I used a value of 100, which would possibly allow the code to purge all the fields for that content type, but it could also cause a PHP timeout error. It would be better to run the code from PHP CLI, in order to avoid any execution time out.
You should not need to use this code; in most of the cases, you should execute the cron tasks (which is when Drupal purges the fields of a deleted bundle), or use Drush to purge the fields, either running hook_cron() with it, or executing a specific Drush command (if it exists).

As for truncating the tables, that is the wrong way to proceed. It would not allow Drupal and third-party modules to delete the data they have for the fields; even if you know which tables Drupal uses, you could forget a table used by third-party modules.


Acquia Dev Desktop, PHP 5.6 and SSL certificate issue on local MacOSX I am having problems authenticating to SalesForce using the Drupal SalesForce Suite module https://www.drupal.org/project/salesforce

Error opening socket ssl://ap2.salesforce.com:443

I am running Drupal using DevDesktop 2 (Built: Nov 22 2015 12:34:41) on my local MacOSX machine with PHP 5.6 with SSL turned on. On a Ubuntu server I can get the salesforce module to authenticate without an issue using the exact same settings as what I have on the Mac.
When I run this additional test on the Mac I get a similar error:
fsockopen('ssl://google.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);

Warning: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in test.php on line 2
Warning: fsockopen(): Failed to enable crypto in test.php on line 2
Warning: fsockopen(): unable to connect to ssl://google.com:443 (Unknown error) in test.php on line 2
DOWN:

When I view phpinfo() I can see that the setting for "Openssl default config" is  /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/openssl.cnf
This version of Dev Desktop is supposed to support SSL for local development. From the DevDesktop documentation:
https://docs.acquia.com/dev-desktop/sites#https

Using HTTPS (SSL) with local sites
The Local site URL link for local websites provides a Use https check box. When you select the Use https check box, Acquia Dev Desktop serves your site using the HTTPS protocol and uses a self-signed SSL certificate to simulate secure traffic. This enables you to develop and test secure websites locally without requiring you to duplicate the SSL certificates you use on your production site.

Has anyone encountered this before and how do we get DevDesktop to point to the self-signed SSL certificate that is mentioned?

After looking around I found kenorb's reply on a similar issue:
https://drupal.stackexchange.com/a/149456/62500

and after poking around the DevDesktop installed files on my Mac I managed to solve it.

The problem is the certificate file does not exist at the default location.

print_r(openssl_get_cert_locations());

Returns

Array (
    [default_cert_file] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/cert.pem
    [default_cert_file_env] => SSL_CERT_FILE
    [default_cert_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/certs
    [default_cert_dir_env] => SSL_CERT_DIR
    [default_private_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/private
    [default_default_cert_area] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl
    [ini_cafile] => [ini_capath] => )

So it is looking for cert.pem in the non existent directory "/Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/"

To solve this, edit /Applications/[Dev desktop folder]/php5_6/bin/php.ini

and add these lines:

[openssl]
openssl.cafile="/Applications/[Dev desktop folder]/common/cert/cacert.pem"
openssl.capath="/Applications/[Dev desktop folder]/common/cert/"

where is [Dev desktop folder] is the name of your Dev Desktop folder.


Unable to collect end date after field is saved I've been running a d7 site for a couple months and one of the content types has a date field. Initially I opted not to collect and end date but the need for it has arisen. As you may know, there's a design decision in d7's field api that forbids you from changing field settings after it's been saved.

The problem is that I have a very considerable amount of data on a fairly live site, which means it's extremely hairy to do something like deleting the field and then somehow herding all the data back in. Has anyone ran into this? How did you solve it? Any insight at all? Thank you :)

When I did this, I created a new date field and set it as hidden on the page. I configured it the way I wanted, then duplicated the existing information in the new field, manipulating the database directly. As you will have two date values (..._value and ..._value2) you should begin by setting them the same.

Once you are sure that the correct values are in place, you must then change all your views, rules etc that use the date field to use the new field.

Then set the new field to display and hide the old field. Make sure everything is working before you delete the old field.

There is no short cut that I am aware of. Best to do all this on a copy, with extensive backups. Good luck.


Image captcha module not showing in admin after updating Drupal to 7.35 I have a site with Captcha module installed and Image captcha submodule working perfectly before upgrading.

I followed the recommended steps, and even did it in a nearly identical test site. Everything worked perfectly in the test site. But when I applied the changes (updating from previous core version) in production, I realized that Image captcha is not only not working anymore: it even doesn't appear as submodule in Admin.

The folder is there but is no longer detected. I am thinking of reinstalling the complete Captcha module, but I am very worried about the rest of modules.

Going back to my backup of my database is not an option as I realized the problem after 2 days and that means losing a lot of data (if I would restore my backup).

Any tip on what could be causing this?

I discovered that the upgrade has renamed the path of submodule Image captcha to sites/all/modules/captcha0/image_captcha instead of the correct sites/all/modules/captcha/image_captcha (renamed filename value in table system of database. Physical path not changed). After that I have been forced to reinstall the module.

This is simply not serious, This seems a Drupal or a module bug and I have spent very bad hours trying to figure out what went wrong when I followed steps one by one and was very cautious.


populating field A with content of field B I have a content type with several fields, e.g. phone1 and phone2.

I would like to populate another type of field, "table_field", with values from the first two automatically, on creation of an instance of this content type.

What would be the best way? Can I utilize tokens to do this? Thanks for your time, I appreciate it. This is my first project. Huge learning curve, and am enjoying it.

In Drupal 6 you could use Computed Field for that, but unfortunately it's not completely ready for Drupal 7 yet.

You could also create a custom module in which you implement hook_node_presave to set the value of 'field A' based on the value of 'field B'. When you choose this method, you may also want to implement hook_form_alter to hide field A from the node form.


theme_debug doesn't work I wrote into my settings.php file (into default.settings.php file too):

$conf['theme_debug'] = TRUE;
$settings['theme_debug'] = TRUE;
$settings['theme_auto_reload'] = TRUE;

(These files have 777 permission.)

I have the "Theme developer" module.

I cleared all cache.

But the suggestions doesn't appear.

What else should I do?

(I have Drupal 7.)

People have been facing issues with Theme Developer module. If you installed this module just to get template suggestions, you might want to uninstall it and use theme_debug (only for d7) variable instead.

Enable this variable by adding $conf[theme_debug] to your settings.php or drush vset theme_debug 1

Then Perform a element inspect (or) view page source to get template suggestions. You may find this article on drupal and the answer in this post helpful- self promoting my answer.


Drupal 7 I need to style the title attribute Here is link to what I am trying to accomplish in drupal.

 http://70.169.1.219/hijo/css3_test.html

In order to get the mouse over to work the title tags where changed to data tags and styled by the css.

In drupal, it deletes the data tags that I put in block to render the affect.

 http://70.184.177.183/Uptown/home

If I style the title block, I get the double affect. I don't think there is a way to suppress the browser rendering of the title tag.

Looking for any suggestion.

UPDATE:

What I ended up getting to work was that in the CKEditor, I remember you use to be able to make an editor and call it PHP which would allow anyone to introduce PHP code into the block. So I created a new CKEditor profile and to my suprise it did not really offer any config. So I gave it the minimum config that it requiried and named it PHP. I went back in and switched to that profile an opened the block and was able to type in any HTML code I so choose and now my project is back on schedule. !
screenshot of the image overlay

It doesn't work because in test file you are using 'HTML5' doctype, and on other page (in Drupal) doctype is 'XHTML + RDFa' and you can't use data attribute.

Why don't you ignore data tags and use only CSS? There is an example:

a {
  color: #900;
  text-decoration: none;
}

a:hover {
  color: red;
  position: relative;
}

a[title]:hover:after {
  content: attr(title);
  padding: 4px 8px;
  color: #333;
  position: absolute;
  left: 0;
  top: 100%;
  white-space: nowrap;
  z-index: 9;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-box-shadow: 0px 0px 4px #222;
  -webkit-box-shadow: 0px 0px 4px #222;
  box-shadow: 0px 0px 4px #222;
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
  background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
}

You can play around with this CSS and stylize your tooltip as you like.

Also, you can use CSS to stylize title tooltip form an anchor tag, but it won't work on img tag title.

This is how provided example looks like on your site (of course you can set 'width' for tooltip and it will look exactly like yours at test page):

I hope that this is helpful.


Execute a rule after a countdown finishes I checked Countdown Timer Field module and some others but it seems they can't help in this issue.

I have a content type (organic group content type) I want this content type have a field for example "open until" and let the users indicate the date, once the countdown ends I want that organic group to be closed.

I want to have an event in rules like for example "countdown ends"

How to do this? thank you

You need to use Rules Scheduler. You can create a date field on you content type, and then on some event such as creating or updating the content type you :

check for an old scheduled event on that content instance and delete it
read in the date field.
schedule a new event.

The event that you schedule will be a rules component that you create that will take in the nid of the content type, and then in its action section closes it.

If you need help on this check out Johan Falk from Node One's series on Rules.


Several NFS folders for one Drupal instance I'm using vagrant & virtualbox to create drupal websites on my Windows local machine.
My actual drupal website is under a Windows folder, shared with my guest(ubuntu) by using a Windows NFS server (winnfsd).

After playing with NFS mount caching options, I understood that my website becomes really fast when enabling it.(specially files attributes caching with high actimeo parameter)

The website becomes fast, but it's almost unusable to developp at the same time:

Changes in my Windows text editor (Sublime Text) are not seen by Linux.
Sass/compass/gulp also don't see changes made in Windows if actimeo is superior to few seconds.

And when there is no NFS cache at all, I could see that lots of NFS operations are logged by my NFS server logs. Every Drupal files are accessed even several times to get attributes, nslookup, read, access...

So my idea was to make several NFS mounts, with different NFS caching options.

Drupal core files never changed => really long NFS cache
Contrib modules changed rarely => really long NFS cache
Custom modules change often => NO CACHE
My Themes change often => NO CACHE

So here is my question, is it good assumptions ?
If yes how do we make those kind of multiple NFS shares ?
I thought about Symlinks ?
Any one tried this approach ?

ini_set('opcache.validate_timestamps', FALSE);

Then when you want to push a code change out run

opcache_reset();

or restart the Apache process.

If you're working on a set of files you can use opcache_invalidate() to check if those files need to be recompiled.

// http://stackoverflow.com/questions/24783862/php-recursively-list-all-files-in-directory
function get_dir_contents($dir, &$results = array()){
  $files = scandir($dir);

  foreach($files as $key => $value){
    $path = realpath($dir. DIRECTORY_SEPARATOR. $value);
    if (!is_dir($path)) {
      $results[] = $path;
    }
    elseif (is_dir($path) && $value != "." && $value != "..") {
      get_dir_contents($path, $results);
      $results[] = $path;
    }
  }

  return $results;
}

// https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!OpCodeCache.php/function/OpCodeCache%3A%3Ainvalidate/8
function invalidate_opcodecache($pathname) {
  clearstatcache(TRUE, $pathname);

  // Check if the Zend OPcache is enabled and if so invalidate the file.
  if (function_exists('opcache_invalidate')) {
    opcache_invalidate($pathname, TRUE);
  }
  // If apcu extension is enabled in PHP 5.5 or greater it emulates apc.
  // This is to provide an easy upgrade path if you are using apc's user
  // caching however the emulation does not extend to opcode caching.
  // Therefore we need to check if the function exists as well.
  if (extension_loaded('apc') && function_exists('apc_delete_file')) {
    // apc_delete_file() throws a PHP warning in case the specified file was
    // not compiled yet.
    // @see http://php.net/manual/en/function.apc-delete-file.php
    @apc_delete_file($pathname);
  }
}

$file_path = 'sites/all/modules/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}
$file_path = 'sites/all/themes/custom';
$files = get_dir_contents($file_path);
foreach ($files as $pathname) {
  invalidate_opcodecache($pathname);
}

Put this code in your settings.php file.

If using APC the info for that is located here: Best APC settings to reduce page execution time

And apache: Adding .htaccess within httpd.conf correctly

Also see: First page load/execution slow, login slower Drupal 7


How to change Title field label and description for Custom Content Entity I've created a custom content entity (generated via drupal console), I can add custom fields just fine via the cms.

What I'm try to do now is change the default label from 'Name' to 'Artwork Title'.

I've tried the following, but I'm not seeing the changes.

class EntryEntityForm extends ContentEntityForm {

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

        $form['name']['widget']['#title'] = $this->t('Artwork Title');
        $form['name']['widget'][0]['#title'] = $this->t('Artwork Title');

        $entity = $this->entity;

        return $form;
      }
...
}

Can someone please point me in the right direction?

I managed to change the label using the following:

$form['name']['widget'][0]['value']['#title'] = $this->t('Artwork Title');

Hope this helps someone else.


Is there a way to create a Text Format on install of a Drupal Module? And enable a Filter for my module? I want to do a custom filter that replaces certain text with HTML. Essentially shortcodes as done by Wordpress.

Unfortunately, the Filtered HTML Text Format strips most HTML.

So I created my own Text Format manually and enabled only my own Filter.

Is there a way to do this programmatically in the module.install file?

Using Features you can export your Text Formats in code and have it automatically configured.

You can configure the filter used for a text format and their order. You can also configure the HTML filter used in the default Filtered HTML text format to allow more HTML elements. So by either allowing the HTML element produced by your filter, and by moving your filter after the HTML filter, you can get your custom filter to work.


How do I validate the term title in hook_taxonomy_term_presave()? How do I validate the term title in hook_taxonomy_term_presave()?

Is there a way to proceed with the validations in hook_taxonomy_term_presave()?

@Edit

I rendered taxonomy add term form via "Inline Entity Form" module and here form_alter fails when it comes to validation.

Any other way if hook_entity_presave can't do this?

I assume you should be looking at hook_form_FORM_ID_alter instead of hook_taxonomy_term_presave for validating the term title before saving.

/**
* Implements hook_form_FORM_ID_alter().
**/
function mymodule_form_taxonomy_form_term_alter(&$form,  &$form_state, $form_id) {
  // Check for tags bundle.
  if($form['#bundle'] == 'tags') {
    // Apply custom validator.
    $form['#validate'][] = '_mymodule_custom_term_validator';
  }
}

My custom validator.

/**
 * My custom validator for tags.
 **/
function _mymodule_custom_term_validtor() {
  // Check for term name is test.
  if(form_state['values']['name'] == 'test') {
    form_set_error('name', 'Title cannot be "test"');
  }
}


How do I invoke JavaScript in AjaxResponse? I'm submitting a form via AJAX.

$response = new AjaxResponse();

It's not using the Drupal default dialog, so I can't use $response->addCommand(new CloseModalDialogCommand()); after all validation is done. It's using jQuery Modal.

Validation is working fine. After all things done I want to execute Javascript in submitForm function.

Which function should I use? I need to check for example alert(1).

I have to close window using Javascript & Alert message as well. I tried AlertCommand but not working.

Following this example: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x
But not working

I have below code

modules/demo_test/src/Form/DemoTestForm.php

namespace Drupal\demo_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;

class DemoTestForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['firstname'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#required' => TRUE,
    ];

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

    $form['actions']['submit'] = [
      '#name' =>'submit',
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'callback' => '::ajaxSubmitForm',
        'event' => 'click',
      ],
    ];

    $form['#attached']['library'][] = 'demo_test/demo';

    return $form;
  }

  public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) {
    drupal_get_messages();

    $response = new AjaxResponse();
    if ($form_state->getErrors()) {
      unset($form['#prefix']);
      unset($form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new HtmlCommand('#demo-test-modal-form', $form));
    }
    return $response;
  }

  public function getFormId() {
    return 'demo_test_form';
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new InvokeCommand('html', 'trigger', array(
      'triggerName',
      array(
        'foo' => 'bar',
      ),
    )));
    return $response;
  }
}

modules/demo_test/js/demo.js

(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.demo = {
    attach: function (context, settings) {

      $(document).on('triggerName', function(e, data) {
        alert('data.foo'); // alerts string 'bar'
      });
    }
  };

})(jQuery, Drupal);

jQuery(document).on('triggerName', function(e, data) {
    alert(1);
    alert('data.foo'); // alerts string 'bar'
});

It's not going in JS file & alert. JS file is loading fine.

Best way is probably to add your own custom command :

<?php
namespace Drupal\demo_test\Ajax;
use Drupal\Core\Ajax\CommandInterface;
class DemoTestJsCommand implements CommandInterface
{
    public function render(){
        return [
            'command' => 'demoTestJsCommand',
        ];
    }

}

And JS :

Drupal.AjaxCommands.prototype.demoTestJsCommand = function (ajax, response) {
    alert(1);
};

Then, you just have to add

$response->addCommand(new DemoTestJsCommand());

in you form's response.


Add Publishing options to custom entity How do you add publishing options to a custom entity or it's bundles?
Currently when I create a new Entity entry I only have a save option. I would like to add published and unpublished states.

In 8.3 there is now an interface for this:

  Content entities that need a published/unpublished flag base field are
  now able to declare a "published" entity key in their entity type
  annotation. Such entities should implement the new
  \Drupal\Core\Entity\EntityPublishedInterface and use the
  \Drupal\Core\Entity\EntityPublishedTrait trait. The interface can be
  implemented directly, by the entity class, or by the entity
  specialised interface.

use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use ...

/**
 * @ContentEntityType(
 *   id = "custom_entity",
 *   ...
 *   entity_keys = {
 *     "id" = "id",
 *     "published" = "status",
 *     "label" = "label",
 *   },
 *   ...
 * )
 */
class CustomEntity extends ContentEntityBase implements CustomEntityInterface, EntityPublishedInterface {
  use EntityPublishedTrait;
   ...
}

  Entities defined in this way can benefit of the new provided methods
  to set the published status ON/OFF and are able to inspect the status
  of the published flag field:

$storage = \Drupal::entityTypeManager()->getStorage('custom_entity');
$entity = $storage->load(123);

// Reverse the published status.
if ($entity->isPublished()) {
  $entity->setUnpublished();
}
else {
  $entity->setPublished();
}

$entity->save()

Source: https://www.drupal.org/node/2830201

If you are developing for 8.4 you can use the base class

  EditorialContentEntityBase - a new base entity class for revisionable and publishable entity types

  Drupal 8.4.0 increases its usage of the revisioning and publishing
  features from Entity API by converting some if its most widely used
  content entity types: Taxonomy terms, Menu links, Comments, etc.

  In order to reduce code duplication and boilerplate, a new content
  entity base class is now available for entity types that want to
  support those features by default: EditorialContentEntityBase.

  If you are defining a content entity type in a contributed module or
  in your project's custom code, it is recommended to extend the
  \Drupal\Core\Entity\EditorialContentEntityBase base class in order to
  get out-of-the-box support for Entity API's revisioning and publishing
  features, which will allow your entity type to be used with Drupal's
  editorial workflow provided by the Content Moderation module.

Source: https://www.drupal.org/node/2870643


Views Filters: show published items from the last week or minimum number of items The homepage on our local newswebsite "Zee-Online" has a view that shows al published content from the last week. How can i change this, to show at least a fixed number of items?

I want a view that gives me all the nodes from the last week OR at least 12 items (if the first filter-criteria doesn't result in at least 12 items)

Since you're trying to create a Views filter using an "OR" relationship, you might want to consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

Does this help?


View Render output in bootstrap tab style I have an Unformatted list style view with 2 grouping:

Grouping field Nr.1: Allestimento.
Grouping field Nr.2: Descrizione

(allestimento and descrizione fields are excluded from display.)

Now I want alter the output of the tpl files to render the 2 groupin like bootstrap tabs (group n1) and nested pils (group n2).
http://getbootstrap.com/javascript/#tabs

But i have no idea how can i do this... I made this by jquery but something the page not render this so I prefare do it by php...
I hope you can help me.

Thanks

In my opinion it's better to create two seperate view (display blocks). One shoud be grouped by Allestimento and other one by Descrizione. Create for the page custom template and add tabs there.


How to use t() function for a text with anchor links? I have a text that I must show in 5 languages. I am using t() for that. The text is:

  In case of any issues, please Contact Us for assistance.

I want the phrase "Contact Us" to be a link. So this is what I have done:

$text = t('In case of any issues, please ')."".t('Contact Us')."".t('for assistance');

I suspect that this might not be the correct way to do this as this will break the translation. I fear that the sentence will not be translated as a whole but in parts.

Am I right?

And if I am, what could be the correct way to do it?

You're absolutely correct; you should never concatenate strings with t(), the whole point is that it uses placeholders so you don't have to. Specifically:

// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => ''. t('the Drupal Handbooks') .''));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at the Drupal Handbooks.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

Instead of those you should use the following:

// Do this instead.
$external_link = t('Look at Drupal documentation at the Drupal Handbooks.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to the Administer screen in the main menu.', array('@administer-page' => url('admin')));

See Dynamic or static links and HTML in translatable strings for full details.


Is there any way to number Paragraphs rendered so as to have a numbered list rendered? I’m putting together a project that requires a content type that has a numbered “How To” list in Drupal 7.5.x.

I am using the Paragraphs module and so far the basic concept of having paragraph blocks of how to “steps” is working as expected. Users are able to “Add another Paragraph” to add each additional step and the steps render correctly on the front-end display as expected.

But while that’s all fine, I’m having a heck of a time understanding how I can have Drupal/Paragraphs automatically number each paragraph so it would look like—for all intents and purposes—something like this; literally I just need that number to the left of each Step …: item and that’s it:

Step One: Do this.
Step Two: Do that.
Step Three: Do something else.

I have been playing around with the Custom Formatters module and it almost seems like that might be my solution: I could use a custom formatter that uses PHP to do something like this. Let’s assume this is what outputs the title for each paragraph field_title value with a PHP custom formatter:

return $variables['#object']->field_title['und']['0']['value'];

So I should be able to do something like this to get a number/order prepended:

return $count . ': ' . $variables['#object']->field_title['und']['0']['value'];

Of course $count is just some arbitrary pseudo-code I am placing for example’s sake, but is this the right approach? Or am I barking up the wrong tree. FWIW, I am poking around the values of the output via the Devel module and don’t see anything useful that would related to count/order.

I’d take a look at overriding the paragraph template file in your theme and doing the work there. Paragraph’s uses the following template names:

paragraphs-item--[VIEW-MODE].tpl.php
paragraphs-item--[BUNDLE-NAME].tpl.php
paragraphs-item--[BUNDLE-NAME]--[VIEW-MODE].tpl.php

The source code of the paragraphs-items.tpl.php is as follows:

<?php

/**
 * @file
 * Default theme implementation for a single paragraph item.
 *
 * Available variables:
 * - $content: An array of content items. Use render($content) to print them
 *   all, or print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity
 *   - entity-paragraphs-item
 *   - paragraphs-item-{bundle}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened   into
 *   a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php print render($content); ?>

You could use a preprocess hook to set an $attribute or other variable that would provide the Step identifier for the paragraph being rendered, although, I’d be suprised if you couldn’t figure that logic out at this level with data available on either $content or $attributes.


How do you write a drush alias for a local Vagrant box? I'm trying to write a simple drush alias to connect to a Drupal site running on a local Vagrant instance.

I have the following in a file called ~/.drush/l.aliases.drushrc.php:

$aliases['o'] = array(
  'parent' => 'l',
  'root' => '/vagrant/docroot',
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => '-p 2222 -i ~/.vagrant.d/insecure_private_key',
  'uri' => '127.0.0.1:8080',
);

The alias is found. drush sa returns:

l
l.o

However, when I drush @l.o status it doesn't connect to the remote host:

PHP executable        :  /usr/local/bin/php
PHP configuration     :  /usr/local/etc/php/5.3/php.ini
PHP OS                :  Darwin
Drush version         :  6.1.0
Drush configuration   :

I have confirmed that this command successfully connects to vagrant:

ssh vagrant@127.0.0.1 -p 2222 -i ~/.vagrant.d/insecure_private_key

Debugging output doesn't show an SSH command so far as I can tell:

SIG-106:ilob justin$ drush --debug @l.o status
Bootstrap to phase 0. [0 sec, 3.78 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.98 MB] [bootstrap]
Loaded alias @l.o from file /Users/justin/.drush/l.aliases.drushrc.php [0.01 sec, 3.99 MB]                                                                        [notice]
Cache MISS cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4 MB]                                                                             [debug]
Cache SET cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4.02 MB]                                                                           [debug]
Bootstrap to phase 0. [0.05 sec, 9.56 MB]                                                                                [bootstrap]
Found command: core-status (commandfile=core) [0.08 sec, 9.56 MB]                                                                                [bootstrap]
Loading outputformat engine. [0.13 sec, 9.6 MB]                                                                                [notice]
Calling hook drush_core_status [0.14 sec, 9.65 MB]                                                                                [debug]
Returned from hook drush_core_status [0.14 sec, 9.66 MB]

I know I must be doing something stupid but I just can't see it.

I was able to use drush alias with following configuration:

Let's assume two things:

vagrant box has some sort of static ip (can be private, for example: 192.168.56.101)
IP of vagrant is available in symbolic form (for example, we have single line in /etc/hosts with ip and hostname). (for example: test.site.local).

Step 1:
We need to copy settings, generated by vagrant ssh-config command into $HOME/.ssh/config

Host test.site.local
    IdentitiesOnly yes
    UserKnownHostsFile /dev/null
    StrictHostKeyChecking no
    PasswordAuthentication no
    IdentityFile [path to vagrant private insecure key]

Step 2:
With such configuration, my alias was in following form:

$aliases['example'] = array(
   'root' => '/var/www',
   'uri' => 'test.site.local',
   'remote-host' => 'test.site.local',
   'remote-user' => 'vagrant',
   'ssh-options' => "-i path_to_insecure_private_key"
);