Make certain pages available to logged-in users only I need some help and here is the issue:

I am building a site using Drupal 7.

I need to make certain pages only visible to logged-in users (each having their own username/password), other users should be simply redirected or shown an error message. Is this functionality maybe included in Drupal 7 itself or is there a module that does this (something simpler than Organic Groups)?

You need to use Content Access module for fine grained node view permissions.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


SMTP Vs. elastic_email From my understanding, smtp just changes the smtp server you use to send your mail, while elastic_email is a web service. Do I still need smtp if I'll only be using elastic_email for all emails? Thanks.

First of all, I'm assuming that you are referring to the SMTP Authentication Support and the Elastic Email modules. The answer to your question is rather straightforward: you only have to use one of the 2 modules. So, if you are sending all your emails using the Elastic Email module, you can pretty much disable the SMTP Authentication Support.

The reason is that the 2 modules are actually doing the exact same thing: they give you a way of bypassing the default PHP mail() function. If you have decided that you want to use Elastic Email, you don't need the SMTP Authentication Support module (and I'm not sure how they interact with each other so, it's better if you disable SMTP just to be on the safe side on this).


Using arrays when setting values in defaultConfiguration() of BlockForm in BlockBase I'm writing a block plugin that allows you to specify certain values for the block in the panel pane editor.
I'm able to defined the default values using

public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        );
}
public function blockForm($form, FormStateInterface $form_state){
    $form['plugins_string_text'] = array(
      '#type' => 'text_format',
      '#title' => $this->t('Block contents'),
      '#format' => 'full_html',
      '#description' => $this->t('This text will appear in the block.'),
      '#default_value' => $this->configuration['plugins_string'],
    );

    $form['layout'] = array(
        '#type' => 'details',
        '#title' => t('Layout'),
        '#open' => FALSE,
        '#group' => 'layout',
        );
    $form['layout']['pane-type'] = array(
        '#type' => 'select',
        '#title' => t('Pane Type'),
        '#options' => array(
            'standard' => t('Standard Panel Pane'),
            'box' => t('Box Layout'),
            'column' => t('Column Layout'),
        ),
        '#description' => 'Choose what type of pane this is',
        '#default_value' => $this->configuration['layout']['pane-type-submit'],
    );
}

I see how to generate the default configuration['plugins_string'] but I'm not sure how to load a default when it is in an array. Like configuration['layout']['panetype-submit']

I have already tried

public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        array('layout', 'pane-type-submit') => 1,
        );
}

and

public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        'layout', 'pane-type-submit' => 1,
        );
}

Both of these were not successful

Are you looking for this?

public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        'layout' => array('pane-type-submit' => 1),
     );
 }


How to increase the speed of SQL Views queries? I have a View with two relationships, and a few displayed fields. It has a COUNT (use aggregation). The database contains just about 10.000 rows. It takes 4 seconds to complete. A similar query to the very same tables takes 0.002 seconds, i.e., 2000 times faster! It is supposed that the Views module is smart enough not to get involved in a burocracy of tables that will take forever to load the data, but it happens. How can I solve it?

I put the example. Essentialy, they do the same (I need to take a little extra info, but essentialy to get the list of products and number of products in a category, the SQL is working. See the SQL query in one case, and in the other). And I was just very carefully adding the two relationships and the fields, so either I did something very wrong or Views SQL UI needs a very lot of improvement.

Quite fast query:

SELECT SQL_NO_CACHE field_familia_tid, COUNT( DISTINCT node.nid ) AS total
FROM field_data_field_oem_ubicacion AS ubi, field_data_field_oem_ref AS oem_ref, field_data_field_familia AS familia, field_data_field_marca AS marca, node
WHERE ubi.field_oem_ubicacion_value = oem_ref.entity_id
AND oem_ref.entity_id = familia.entity_id
AND oem_ref.entity_id = marca.entity_id
AND field_marca_tid =69440
AND node.nid = ubi.entity_id
GROUP BY field_familia_tid

A similar query, done carefully with the Views UI. Extremely slow, 1000 times slower:

SELECT taxonomy_term_data_field_data_field_familia.tid AS taxonomy_term_data_field_data_field_familia_tid, COUNT(DISTINCT field_oem_ubicacion_field_collection_item.nid) AS field_oem_ubicacion_field_collection_item_nid
FROM
{field_collection_item} field_collection_item
LEFT JOIN {field_data_field_familia} field_data_field_familia ON field_collection_item.item_id = field_data_field_familia.entity_id AND (field_data_field_familia.entity_type = 'field_collection_item' AND field_data_field_familia.deleted = '0')
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_familia ON field_data_field_familia.field_familia_tid = taxonomy_term_data_field_data_field_familia.tid
LEFT JOIN {field_data_field_marca} field_data_field_marca ON field_collection_item.item_id = field_data_field_marca.entity_id AND (field_data_field_marca.entity_type = 'field_collection_item' AND field_data_field_marca.deleted = '0')
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_marca ON field_data_field_marca.field_marca_tid = taxonomy_term_data_field_data_field_marca.tid
LEFT JOIN {field_data_field_oem_ubicacion} field_data_field_oem_ubicacion ON field_collection_item.item_id = field_data_field_oem_ubicacion.field_oem_ubicacion_value
LEFT JOIN {node} field_oem_ubicacion_field_collection_item ON field_data_field_oem_ubicacion.entity_id = field_oem_ubicacion_field_collection_item.nid
WHERE (( (field_data_field_marca.field_marca_tid = '69440') ))
GROUP BY taxonomy_term_data_field_data_field_familia_tid

Note: Afterr careful inspection of SQL and also from suggestion by user tenken, I replaced the LEFT JOIN by WHERE-AND in the SQL. The result was almost identical, and fast, so now the question is: why does Drupal uses by default the LEFT JOIN, and where can I change it (if possible, not programmaticaly, in order to have the logic inside the View).

Take the query from the Views admin and from the mysql command line, or phpmyadmin add the EXPLAIN keyword in front of it. Assure it's using indexes on query criteria and that the query is optimized.

If it's not a fully optimized query then simply add an index to your SQL schema as needed until it's as optimized as it can be.

You can either add the index directly to tables through phpmyadmin, or create a module to index the necessary db fields (and then drop indexes if the module is disabled).

Drupal ships with a db that is not fully optimizted for any query you could generate with views. Module creators make general assumptions in the table they make to provide primary keys for example -- but they don't index every column of their schemas as taht would be wasteful. How you use Fields on your site is different from how I would use fields on my sites ... etc.

1 module that may help you index your Drupal fields (after evaluating the EXPLAIN output is) Field Index:

  Field modules don't always add indexes for its columns (value column
  of text field for example), this leads to poor performance in views
  when we would like sort or filter views using the unindexed columns.
  We can check the query executed by views and add custom indexes
  manually, but it's not easy to deploy.

  With field_index module, we can create custom indexes for fields. The
  indexes are exportable.


How many times each value was selected? I have a content type with 6 select-list fields.
Each field has several available values, multiple selections allowed via checkboxes. A group of users each submit the content once.

Select List Field 1

user001 answered     | user002 answered     |user003 answered
1|oranges            | 1|oranges (x)        | 1|oranges (x)
2|apples (x)         | 2|apples (x)         | 2|apples
3|bananas (x)        | 3|bananas            | 3|bananas
4|mangos             | 4|mangos (x)         | 4|mangos (x)

Select List Field 2

user001 answered     | user002 answered     |user003 answered
1|eggs               | 1|eggs (x)           | 1|eggs (x)
2|fish (x)           | 2|fish (x)           | 2|fish (x)
3|nuts (x)           | 3|nuts               | 3|nuts
4|berries            | 4|berrries (x)       | 4|berries (x)

Views, showing Content of type, contextually filtering on the group id, displays selections from each user in the group. A list of all selected values is shown, including many duplicates.

Apples
Bananas
Fish
Nuts

Oranges
Apples
Mangos
Eggs
Fish
Berries

Oranges
Mangos
Eggs
Fish
Berries

Instead of showing this list (above), I would like to display the number of times each value was selected in total by that group of users.

Fish     (3)
Apples   (2)
Berries  (2)
Eggs     (2)
Mangos   (2)
Oranges  (2)
Bananas  (1)
Nuts     (1)

I have tried Views aggregation, but so far have only been able to count how many values were chosen for a given field, instead of counting how many times each specific value was selected.

It seems like this should be easy to accomplish, like I am missing something simple. How can I achieve this?

I ended up:

Creating a Content Pane for each question.

Added a duplicate set for each field result in the that pane.

For instance one, I set aggregation to "Group results together", which gave me the labels.

For instance two of that same field, I set the aggregation to "Count", which gave me the number of times that value has been selected.

Excluded the above fields from display.

Added a Global Text field for styling, using the tokens from the above fields for Label: (Value)


How do I change the Default Query of a Views Exposed Filter with hook_form_alter()? I searched for an entire day on this issue and found no working solutions that affect the "initial query" of an exposed form in Drupal 7.

I have a simple checkbox exposed as a select list; the options are All, 1, or 0. It defaults to All on default. I'm trying to change it to 0. With that said, I was able to successfully set the default value of my exposed form (doesn't affect the initial query) and rename the options with a custom module:

function MODULE_form_alter(&$form,&$form_state,$form_id) {
//dpm($form);
  if($form_id == 'views_exposed_form') {
    $form['field_checkbox']['#default_value'] = '0';
    $form['field_checkbox']['#options']['All'] = t('Both');
    $form['field_checkbox']['#options']['0'] = t('Unchecked');
    $form['field_checkbox']['#options']['1'] = t('Checked');
  }
}

I tried to interpret merlinofchaos' advice in the only relevant advice I could find on this (9 year old thread) and might not even be relevant to D7.

function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
    //print $form['#id'];
    if($form['#id'] == 'EXPOSED_FORM_NAME') {
        if (!isset($_GET['EXPOSED_FILTER_NAME']))  {
            $form_state['input']['EXPOSED_FILTER_NAME'] = '0';
        }
    }
}

Though the above code changes the $form_state['input']['EXPOSED_FILTER_NAME'] variable from "All" to "0", it doesn't change the default query. I have dpm'd both $form and $form_state, but I don't know what needs to be changed. Any advice would be extremely appreciated!

Try this out with hook_views_pre_build

/**
 * Implements hook_views_pre_build().
 */
function MODULE_NAME_views_pre_build(&$view) {
    if ($view->name == 'VIEW_MACHINE_NAME') {
        //- Set the exposed filter to new value
        $view->filter['EXPOSED_FILTER_NAME']->value = '0';
    }
}


How to enable IMCE in a field of a custom block I have module that generates a plugin block with a field of type managed_file.

public function blockForm($form, FormStateInterface $form_state){
    $config = $this->getConfiguration();
    // todo make this IMCE
    $form['background'] = array(
      '#type' => 'managed_file',
      '#title' => $this->t('Background'),
      '#description' => $this->t('Enter background image'),
      '#default_value' => isset($config['background'])?$config['background']:'',
      '#upload_location' => 'public://backgrounds',
      '#weight' => '2',
    );
}

I guess I have to create a module.schema.yml file to do that but I don't know how to enable the IMCE.

block.settings.stingray_basic_block:
  type: block_settings
  label: 'Stingray basic block'
  mapping:
    body:
      type: text
      label: 'Body'
      translatable: true
    background:
      type: managed_file
      labe: 'Background'
      ??? MAKE IT IMCE ???

Usually this boolean appears in the core.entity_form_display...yml file as a third party settings structure:

content:
  field_background:
    weight: 1
    settings:
      preview_image_style: thumbnail
      progress_indicator: throbber
    third_party_settings:
      imce:
        enabled: true
    type: image_image

...but I don't know if it can be set in the schema.yml file nor how.

Anyone has info on this?

ref: https://www.drupal.org/node/2821710

You can provide an alternative URL input(type=text) for IMCE integration.

You just need to include drupal.imce.input library and set the input class name as "imce-url-input". Also see imce.input.js file

if (\Drupal::moduleHandler()->moduleExists('imce') && \Drupal\imce\Imce::access()) {
  $form['background'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Background URL'),
    '#attached' => array('library' => array('imce/drupal.imce.input')),
    '#attributes' => array('class' => array('imce-url-input')),
    '#default_value' => isset($this->configuration['background']) ? $this->configuration['background'] : '',
  );
}


'Page not found' but hook_menu() is correct! This is my hook_menu:

$items['events/%event'] = array(
  'title' => 'Event',
  'title callback' => 'entity_label',
  'title arguments' => array('event', 1),
  'page callback' => 'events_view',
  'page arguments' => array(1),
  'access callback' => 'entity_access',
  'access arguments' => array('view', 'event', 1),
  'file' => 'events.pages.inc',
);

return $items;

But when I navigate to events/2 there's a 404 error waiting! Here's the page:

As you can see, my Event has been successfully created (it exists in database and its id is definitely 2) but the requested page could not be found and Shortcuts menu and Navigation block has disappeared.
What possibly could I mistaken?
Feel free to ask for more information.
Thanks.

EDIT:
I'm using Drupal 7.12

If you're getting a 404 it's due to one of the following:

You haven't cleared Drupal's cache since you implemented the menu item, OR
Your event_load() function is returning FALSE/NULL for the provided ID, OR
The function event_load() doesn't actually exist

Judging from the rest of your function/file names (events_view, events.pages.inc) your module is called events so your router load function will probably be called events_load() (note the additional s).

If that's true then you need to change your menu item to match that:

$items['events/%events'] = array(
  // ...

And clear Drupal's cache to pick up the change.


How to COMPLETELY limit access to Views pages? I've got a content type that has attached to each of its nodes a calendar (e.g., node/123/calendar); this is generated by fullcalendar via Views.  I'm setting up node access rules on that page so that some users can see the calendar and some can't.  The node access is handled through the "Access:" field in Page Settings for the view, in what I think is the usual way (I'll admit to being something of a Views newbie).

This works, but (to my eyes) only sort of.  If a restricted user tries to get to the page, they get the same page structure, generated by a page--node--calendar.tpl file, that they'd get if they were allowed to see the page, except that the content is the "You are not authorized to access this page" message.  Thus the user is able to get some information about this restricted item, like the fact that there is a node that has a calendar attached to it.  I'd prefer to have a more empty 403 or 404 error page come back, without the node-related wrappings.

Is there any way to do this?  I suppose my page template could check the content it's about to display and see if it matches the access denied message, but that's a little more hackish than I'd like to get...

That is because Drupal, when users access a page to which they don't have access, it draws the page using its template file, and replaces its content with the error message.

What you can do is setting a page to use for the access denied page, and use a different template file for that page. In Drupal 7, that is done in admin/config/system/site-information, under Error pages.

Keep in mind that, when an access denied error is returned, the URL of the page is not changed; this means the users would still know the node has a calendar attached, if they try to access the page using the URL directly. The Calendar tab is not shown to users who don't have the permission to access it, though; they can only try using the tab URL, and see if they get an access denied error.


Fetch data from database and show in custom block I have created my own simple block.I want to show some data from user table of database of logged in user to the block.I want to show it programmatically and not want to use any module. How can I do that?
One more question related to block is, can I add my custom theme to my custom block (like .tpl.php file for custom module)?If yes how can I do that?

depending on the information you want to retrieve, Views is probably your simplest option:

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

Views allows you create a block or a page in order to display formatted data.


Separate drupal view filters from the results I implemented a search index using Drupal Search API, and then created a view using that search index. In my view I added filters on searchable fields. My search is working very well.

However, my clients want to have the search filter controls in the sidebar and the search results in the main content region. But my filter controls and results are part of a single view. It is possible to separate them?

Drupal version : 7.26

I haven't used the Drupal Search API but if you are creating a View with exposed filters, you can have them put in a Block instead of being part of the View.  Then you can put that Block anywhere you want.  To do this, you go into the Advanced Settings of your View:

and in Exposed form in block: select Yes instead of the default No.  Then you can go into the Block UI and place the newly created block wherever you want.

One interesting effect:  If you don't restrict this block to the page of the View in the Block UI, it will show up on all pages, and if your users then select any of the filters in it and hit apply, that will take them to the View page and results.


Views exposed filter using Solr only returning results for exact phrase We're using a Views exposed filter (using the Search API Solr) that searches a Solr index to search for node titles, but only seeing exact phrases matched.

For example, if we have a node titled 'Trees of the Eastern Seaboard,' and do a search for 'Trees,' the node is returned. If we search for 'Trees of' the node is also returned. However if we search for 'Trees Seaboard,' no results are returned.

The Solr search index is using the 'Fulltext' setting. I've tried switching it to 'String' but that setting returns no results at all for the view.

The default search is also configured to use Solr, and returns results correctly for 'Trees Seaboard.'

Is there a way to allow the Views exposed filter to return the correct results for not exact phrases? (keywords?)

Is there a way to allow the filter to accept a 'contains any' setting for the search?

This is a screenshot of the basic search view that we setup for our Search API + Apache SOLR configuration:

The settings for the filter can be shown here:


How to disable access to a node What I want is whenever a registered user saves a page type node - that specific node should be made inaccessible to the user.

So if a registered user has save node/122, node/122 should be made inaccessible to the user.

How can I do it?

Easy! When a new Page is created, just change its owner to a different user with appropriate role and permissions. In our case, let's say to admin.

First, install the Rules package, enable Rules and Rules Admin modules.

Navigate yourself to the Rules | Triggered rules | Add a new rule page:

Label: Detach page from creator
Event: After saving new content

Make sure the new rule is active. Save changes and on the next page Add a condition:

Select the condition to add: Content has type
Content types: Page

Save and Add an action:

Select an action to add: Load a user account
User id: 1

Save and again, Add an action:

Select an action to add: Set the content author
User, who is set as author: Loaded user

Done! This changes the node creator and the original author has control over it no more.

As you will see, this is just the quickest solution to your problem. Rules module enables you to go wild and achieve heaps of stuff that you would normally expect separate modules to be put together for. To get the idea, have a look at how I used Rules (in conjunction with Flag) to keep track of Recently viewed nodes in Drupal.

Note that the node creator always has view permission to the node, as long as they have access content, without which CMS wouldn't make much sense. Anyway, to keep track of the original creator, for display or so, you can use the CCK's User reference module.


Prevent sites from receiving modules installed by other sites in a multi-site instance Can I prevent a site from receiving modules installed by a different site in a multi-site instance? In other words, can site A in a multi-site instance not receive a module installed by site B?

I am aware that in a multi-site instance, modules that are installed for one site is installed for other sites. For other sites to use said module, it must be enabled in its respective site. In my scenario, I do not want a module to appear at all for a given site, even if it was installed by a different site.
I am aware that configuration can take place to install site-specific modules. My question is the reverse: preventing modules for a specific site rather than installing modules for a specific site.

Yes, the multisite system can do that out of the box. From the Site-specific modules and themes section of the multisite docs:

Each site configuration can have its own site-specific modules and themes in addition to those installed in the standard 'modules' and 'themes' directories. To use site-specific modules or themes, simply create a 'modules' or 'themes' directory within the site configuration directory. For example, if sub.example.com has a custom theme and a custom module that should not be accessible to other sites, the setup would look like this:
sites/sub.example.com/settings.php sites/sub.example.com/themes/custom_themesites/sub.example.com/modules/custom_module

So just make sure you don't put modules that shouldn't be shared in /sites/all/modules; put them in /sites/SITE/modules instead.

Can site A can "block" (for lack of a better term) a module installed by site B, in which site B installs to sites/all/modules?

You could implement hook_system_info_alter in site-exclusive modules to prevent certain ones from ever being displayed to the user on those sites, but as there's no record anywhere of what site downloaded/installed a module to /sites/all/modules, you'd have to keep those modules up to date manually. Unless you supplement that with an API exposed from each site that let each other site know what it had installed and what should/shouldn't be available to install.

Is best practice to configure specific modules per site rather than trying to prevent the transposition?

I think it's fair to say an inclusive rather than exclusive approach is better practice here, any other approach is a bit awkward. It gets more complicated the more automated/robust you want an exclusive approach to be, whereas doing it the other way round just works.


Why are responses for AJAX POST calls in admin UI so delayed Just in the past day or so, something has happened to my site.

For some reason, all AJAX calls from Drupal's admin UI are now taking about 50 seconds a piece.

This is absolutely maddening because there are so many areas in Drupal's admin where one field change will result in an ajax callback.

I've been reviewing my network traffic in Chrome Dev Tools and Firebug and see that all pages and site resources are loading at an average of .2 seconds to 1 second.

Then, when I trigger a Form update in the UI, the POST to /system/ajax takes about 50 seconds

The same is true in /ctools/content/ajax/* -- when I am in the Panels screens, AJAX callbacks are averaging around 50 seconds of wait time for the server to respond.

I'm on a shared AN Hosting environment, D7.

Any thoughts?

EDIT --

I've found that some smaller AJAX requests (particularly those made by Inline Entity Form) do make it through without the delay... I can't see any correlation or pattern between those that do and then those that don't get through.  It can't just be one module as I see problems with core Fields UI's and cTools that are totally separate from eachtother

EDIT --

The consistency between failing calls seems to be the size of the POST -- even the basic Field UI has a post size of 252B -- smaller posts seem to not have an issue.

It was apache's mod_security

I'm not sure exactly what was going wrong, but my host (ANHosting) was able to fix the problem.


How can I replace "English" with "EN"? I have 3 languages in my Drupal 8 site. All works fine, without the language switcher.
Replacing German with DE worked, but replacing English with EN didn't work.

How can I replace English with EN in Drupal 8?

I use this, it's a little bit more dynamic then if you would hardcode the language code yourself. Hope it helps. This example works with the language switcher block.

function theme_preprocess_links__language_block(&$variables) {
    foreach(array_keys($variables['links']) as &$code){
        $variables['links'][$code]['link']['#title'] = $code;
    }
}


Not all the buttons are displayed I installed CKEditor plugin ver. 1.16. In configuration page for editor appearance I selected "Full":

But when I open "Add content" page I see the different picture:

When I changed the appearance from "Full" to "Advanced", the appearance doesn't change. But when I switched to "Basic" appearance, it worked.

What's the issue here? Why not all the buttons are displayed?

On 'Add content' page, please check which 'Text format' you have selected in drop-down below the CKEditor.

Make sure that you have selected the Full HTML or Filtered HTML according to your field settings.


How to replace text in many nodes? We're upgrading from Bootstrap 2 to 3. Now I need to replace CSS classes in the body fields of many nodes. This needs to be done in at least 5 sites. What is a good way to replace text in all nodes of a site?

Ideally I'd do it with something like drush replace old_str new_str. Found one thing from 2009 that didn't work at all and then I found drush sar, which didn't do the job either.

The Drush Search and Replace plugin may be of some use

This drush plugin performs a text search & replace on all content and content revisions in all text fields and all custom blocks on a Drupal site.
It does this directly in the database, not by loading, editing and then saving entities, so it is very fast. This also means you should clear the Drupal caches after you run this command.

Hopefully it goes without saying you should give this a dry run before applying it to a live site, how well it works will depend on exactly what data you have in the fields.


Jquery animate in Views slideshow Is there any way to add some jQuery animations in each slide of a slider created with Views Slideshow module?

You might want to try the Views Slideshow Xtra module

  Views Slideshow Xtra is an enhancement module for Views Slideshow, providing the ability to create overlays for a Views Slideshow. HTML elements are placed in  overlays, with overlay visibility controlled by toggling the CSS display property, so that overlays are displayed with their corresponding slide. Animation of the overlay displays is also supported.


Template preview not working properly I've got a huge problem with my template preview. For all of my post (page, article and so on), I have not the good region in my page.

My theme is extended Classy.

If I go to see the page (not from the preview), I have the good page.
But if I want to see the preview of this page, I've got some missing region (I guess this is a region).

See my page--post-type.html.twig

        {% include '@theme/layout/header.html.twig' %}
    {% include '@theme/includes/page-head.html.twig' %}
    {% include '@theme/includes/page-breadcrumb.html.twig' %}
    {% include '@theme/includes/page-entry.html.twig' %}

 {{ some displayed data }}

{% include '@theme/layout/footer.html.twig' %}

My included files a working (for both preview and view), but the preview isn't in this page is guess.

The last included block is this for the preview :

  BEGIN OUTPUT from 'themes/theme/templates/block/block.html.twig'

And for some reason, after I have this :

  BEGIN OUTPUT from 'core/themes/classy/templates/content/node.html.twig'

if it helps, my .theme file :

    /**
 * Implements hook_theme_suggestions_page_alter().
 */
function theme_theme_suggestions_page_alter(&$suggestions, $variables) {
//    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node = \Drupal::routeMatch()->getParameter('node_preview')){
        $node = \Drupal::routeMatch()->getParameter('node_preview');
//        if ($node instanceof \Drupal\node\NodeInterface) {
//            $suggestions[] = 'page__' . $node->bundle() . '_preview';
//            $suggestions[] = 'page__node_' . $node->bundle() . '_preview';
//        }

    } else {
        $node = \Drupal::routeMatch()->getParameter('node');
        if ($node instanceof \Drupal\node\NodeInterface) {
            $suggestions[] = 'page__' . $node->bundle();
            $suggestions[] = 'page__node_' . $node->bundle();
        }
    }

//    dump($suggestions);

}

And I have also this function alstef_preprocess_node() which I took from this : Place block region in node template

I've been stuck for hours, any help you be appreciated.

PS : I'm working on drupal 8 with a custom Theme (here called 'theme').

EDIT : I've just made a dump of my node, and the node is null is i'm on my page--post-type.html.twig or page--post-type-preview.html.twig with the preview (change thanks to suggestions)

While previewing a node, the node parameter is not "upcasted" from an integer to a node object. But you can easily do this yourself in the preprocess function, just add those lines before:

  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  //now you always have "real" node object (instanceOf Drupal\node\NodeInterface -> true),
  //no matter if preview or normal viewing


Placing a drupal menu on an external site I have a drupal install (latest 7.x version at the time of writing). It is in the root directory of my domain.

In a non drupal sub-directory, called 'member' so at /member, I have 3rd party script which enables my site to have membership functionality.

The script inside of /member is not drupal, although it does connect to the drupal database to write to the users table to enable single sign-on.

I was wondering if it is possible to display a drupal menu (the main navigation) inside the script in /member? I want to be able to alter the menu in drupal and then have those alterations automatically updated in the /member script.

I would certainly appreciate any advise as to whether this is in fact possible, and some advice about how I might get started.

Thanks.

Yes, it is possible.
In your drupal website:

Render the main menu block on a custom made (module) page for example /main-menu-external
Strip all the sections but the content section, so that no header, footer, ... is rendered, only the menu.
With context load a blank theme on the page "main-menu-external"
At this point "main-menu-external" will be a blanco page with only the main menu rendered on it AND will use a different theme from the rest of your website so you can configure it for that page only.

In your /members website:

Just put an <iframe> with source "yourdrupalwebsite.be/main-menu-external"

Et voila, there is your drupal menu on an external website :)


How to create features for site configuration in drupal 7 I have one requirement where all admin configuration need to be converted in to features eg caching must be enable

Strongram module will allow to export system configurations and settings through features.


Views exposed filter - Replace '-Any-' by Select All I have a view with an exposed filter of taxonomy terms. Because I'm using charts, when I select the option '-Any-', the chart gets messed up. I noticed that, if I select all terms available instead of '-Any-', the chart looks ok.

So my question is, it is possible to replace the '-Any-' with a select all or, in some way, force the any to select all?

This question is already answered. Please find the answer in below link
https://stackoverflow.com/a/5975294/5093173

or use this code

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view name') {
      $form['filter_name']['#options']['All'] = t('select all');
}

}


how to properly show MENU LOCAL TASK Hoping to get some advises from experts here regarding the Menu Local Task on user/uid/edit page. You see, I'm taking over a project at the brink of death. I have no idea why they hide all the local tasks tab.

I know that showing it on page.tpl.php is as simple as "print $tabs", however the fact that i am using splitting User/uid/edit pages into two (using EditProfile modules) complicates thing a bit.

My objective here is to show that local tasks (View/Edit Profile/Account Settings/Notification Settings) on templates/edit/edit-acct-settings.tpl.php page.

So far I could make that happen by this line on that template page.

if ($tabs = render(menu_local_tasks())): print $tabs; endif;

But, I'm sure there's a friendlier way to do this.
Again, I have no idea how they made the tabs disappear.

And it came rendered as normal list, not tabs. And I dunno how to exactly theme it if it's the current page. Hoping he "Edit Profile" would go bold or something when I'm on Edit Profile page.

Any advise appreciated. TGIF!

Managed to find my solution! This thread here is my saviour:
Print primary and secondary tabs separately

In templates/edit/edit-acct-settings.tpl.php page

<?php if ($primary_local_tasks): ?>

<?php print render($primary_local_tasks); ?>

<?php endif; ?>

In my_theme/template.php

function mythemename_preprocess_user_profile_form(&$vars) {

  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();
}

Hope this helps any other newbies who encounter same issue!
Thanks all~


Bootstrap level error When I attempt to use Drush 8.0.3 on a clean Drupal 8.1.1 install, I receive the following error:

  Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

This is on a Digital Ocean server running Ubuntu and nginx.

Drush status:

root@*********:/var/www/html/drupal/sites/default# drush status
Drupal version         :  8.1.1
Site URI               :  http://default
Database driver        :  mysql
Database hostname      :  localhost
Database port          :
Database username      :  drupal
Database name          :  drupal
PHP configuration      :  /etc/php5/cli/php.ini
PHP OS                 :  Linux
Drush script           :  /usr/local/bin/drush
Drush version          :  8.0.3
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /var/www/html/drupal
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default
Sync config path       :  sites/default/files/config_JYMyTTYRsOD-Wxu0fI7lfugHI6rk2DbhO5g-jrfjsPyy46mmesB1aTpSuq2RAUIOUC4N2q_IkQ/sync

Oddly (to me, at least) I can clear caches:

root@***************:/var/www/html/drupal/sites/default# drush cr
Cache rebuild complete.

I don't know if this always is needed, but I recommended keeping Drush in sync with Drupal - the same version or newer. The current (stable) version of Drush is 8.1.2.


add a repeatable autopopulate node title select list to custom block I'm going to develop a new block that user can select 4(or more) node with 4(or more) autopopulate node selection list but i couldn't find any documentation or tutorial on how to build those select list.

Any suggestion?

You can use form select options

put the list of your nodes in to an array and pass them into the form function

function mylist_form($form, &$form_state, $args) {
$mylist = array();
foreach ($args as $node){
$mylist[$node->nid]= $node->title;
}

$form['mylist'] = array(
  '#weight' => '1',
  '#key_type' => 'associative',
  '#multiple_toggle' => '1',
  '#type' => 'select',
  '#options' => $mylist,
  '#title' => 'Select nodes',
);
 return $form;
}

after in the block view function you can render the form

$mylistform = drupal_get_form('mylist_form' , $nodes );


"Cannot declare self-referencing constant database.inc line 2101" Suddenly, I got this error when I was configuring rules; the entire Drupal site is not accessible, not even update.php.

  Fatal error: Cannot declare self-referencing constant '' in I:\My Documents\web\xampp\htdocs\mysite\includes\database\database.inc on line 2101

The last thing I remember was configuring rules with custom PHP.

I suddenly got this same error on a Windows workstation.

It does not have anything to do with the content of the database (including cache); it occurs before it even connects to the database.

The only fix that worked for me was restarting apache.

Notes

The character within quotes is "EOT" ("end of transmission"), which looks empty in the error message.
The line 2101 in database.inc is the start of the DatabaseStatementBase class.


How can I stop a Rule action from being executed, programmatically? How can I stop sending an email, for example? Assume the event is before_sending_an_email.

Once happened, you can't stop an action.

The only thing you can prevent from happening is executing the action at all. In case of e-mails, you can only stop an e-mail with rules if it has been sent by a rule. Then you need to add a condition to that rule to prevent it from executing the action that sends the mail.

To prevent a mail that is sent directly in the code, you need a custom module, implement hook_mail_alter() and redirect it to a dummy address, you can't really stop it there either.


how to know this query related to which block I have a website with a very large number of blocks, some of them have been created using Views module. now i am seeing in slow query log some queries generated by Views like

SELECT DISTINCT(node.nid) AS nid,
  node.type AS node_type,
node.vid AS node_vid,
node.title AS node_title,
node.language AS node_language,
node.created AS node_created
FROM node node
LEFT JOIN term_node term_node ON node.vid = term_node.vid AND term_node.tid = 193
LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid AND term_node2.tid = 194
LEFT JOIN term_node term_node3 ON node.vid = term_node3.vid AND term_node3.tid != 194
WHERE (node.type in ('article')) AND (node.status = 1) AND (node.language in ('ar')) AND (term_node.tid IS NULL) AND (term_node2.tid IS NULL) AND (term_node3.tid = 0) GROUP BY nid ORDER BY node_created DESC ;

Now, is there any way to know this query related to which block? i couldn't figure it out by checking in preview query of views!!

There is some hint on last line. the block in showing Article(node type) which are published to site and created in arabic language.

So, remind that where u seen this kind of content block in the site.


Open Menu links in new browser window I have created various menus, via the menu structure->menu page in Drupal for various pages in my site.  I want to have some, if not all, of these menu links to open in a new page. You can not add target="_blank" to the path in the menu screen and I don't want to add a new module right now.

I am trying this:

Drupal.behaviors.externalMenu = function (context) {
  if (jQuery().attr) {
$(document).ready(function(){
  $('.page-node-166 a', context).attr('target', '_blank');
});
}}

My Steps: created a new js file, added the above code, went into my themes .info file, referenced this js file in the scripts section, refreshed, a few times, nothing works.  Links still open in current window.

What should be happening in this code snippet is, find this class[page-node-166], which is the page, then for any link on that page, open it in new window.  My first time attempting this so I don't know if I am missing a step.

How can I have menu links open in new window in drupal 7?

=====================

Update:

You don't really need a drupal behavior to do this.  Instead just simple do this:

;(function($){
  $(document).ready(function(){
    $('.page-node-166 a').attr('target', '_blank');
  });
})(jQuery);

or

jQuery(document).ready(function(){
  jQuery('.page-node-166 a').attr('target', '_blank');
});

By default drupal uses jQuery.noConflict() so that it does not interfere with the $ that may be used from other libraries.


Cron drupal 8 for my module? I am doing a module in drupal 8, I would like to know how to execute a function automatically every month. I think it's done with Cron, but I only get to do it every week. as I edit it from my function.

A modified example from cron_example module. This doesn't concern the interval the cron tasks are set in cron.

This is important, as you will probably set another cron tasks sooner or latter with different interval requirements. Also, many system tasks require more frequent cron runs.

function cron_example_cron() {
  $interval = 30*24*60*60; // Approx a month of interval

  // We usually don't want to act every time cron runs (which could be every
  // minute) so keep a time for the next run in the site state.
  $next_execution = \Drupal::state()->get('cron_example.next_execution');
  $next_execution = !empty($next_execution) ? $next_execution : 0;
  if (REQUEST_TIME >= $next_execution) {
    // This is a silly example of a cron job.
    // It just makes it obvious that the job has run without
    // making any changes to your database.
    \Drupal::logger('cron_example')->notice('cron_example ran');
    if (\Drupal::state()->get('cron_example_show_status_message')) {
      drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
      \Drupal::state()->set('cron_example_show_status_message', FALSE);
    }
    \Drupal::state()->set('cron_example.next_execution', REQUEST_TIME + $interval);
  }
}

Also, for more fine-tuned approach, you can use the Ultimate Cron module, which provides more fine-grained control for the cron jobs.


Commerce Allows User to Edit Cart After Completion of Checkout I recently found a problem where a customer can edit their cart and re-checkout after checkout has been completed and payment has been made. This results in a single order record (the latter one) and two payments.

Re-creation of this issue:
1. Start a cart
2. Open the cart in a second window (You should have two windows/tabs open with the same cart)
3. Checkout on the first screen
4. Once checkout is completed and payment has been made, remove or update an item in your cart using the second screen

This places the cart back in a Shopping Cart status (per Drupal Commerce rules) and you have the same order/cart number since they share a table (which is another problem for another day). You can now checkout again and you will have two order confirmation emails with the same order number. Drupal Commerce will show only one order (the second order) but two payments. There is no way to recover the first order.

This only happens when the customer leaves the shopping cart open in multiple window(s) and tries to edit it after checkout.

Is there a fix to dis-allow editing of a cart after it changes over to an order? I would like it to throw an error and force a refresh of the page causing it to create a new shopping cart.

Hmmm, this is definitely something that deserves to be fixed in Commerce itself. I'm going to open an issue there and outline a strategy that essentially adds a form alter hook to the Cart module to redirect back to /cart in the event that the shopping cart form is being built / submitted for an order that is in an unsupported status. I can't say exactly how I'd do it yet, but I suppose it would involve iterating through the checkout pages to allow shopping cart form submissions for any order that hasn't yet passed a checkout page that doesn't have back buttons (e.g. the Payment and Completed pages).


clickable links in revolving banners I am a newbie to Drupal 7.21.
I have got as far as creating a rotating banner for my front page.  Now I want to have a clickable link from each banner to a new page that gives more information about each banner topic.  The banners automatically pause nicely when the mouse hovers over them, but I can't find a way to get the link attached to the image.
Can anyone help?
Thanks
Andy

There is a combination of modules listed on the site HOW TO INSTALL & SETUP VIEWS SLIDESHOW MODULE ON DRUPAL7? that will allow you to do that.

Effectively the modules work together to give you:

A content type where you can store your banner and the URL
A view that has some nice JQuery slideshow options for displaying rotating banners that will link to their included URL


Show English tabs regardless of current site language A localised Drupal 7 site has four languages. Three non-English languages are for the site content, and English is the admin language. Most users won't be logged in. The only logged-in users will be admin or editors.

For logged-in users, the View/Edit/Translate/Devel tabs ($tabs in page.tpl.php) are shown in the current site language. But as these are only intended for admin, it makes more sense to show these in the admin language (English).

How can I always show the tabs in English (or the admin language)?

(One workaround is to remove the translations for the strings in the tabs, but that would have to be repeated if any new tabs or languages are added.)

In the end I just used the workaround: removed the translations for the strings in the tabs. There weren't too many.


Invalid form POST data - ajax for Authenticated users I have a Drupal form using ajax. When I submit the form I am getting the following being displayed:

When I check the Drupal log I have the following entry.

I have Googled the error and found this post but it applies to anonymous users. I am only using this with authenticated users.

Searching for the error in the code returns the ajax_get_form() function in ajax.inc

 $form_state = form_state_defaults();

  $form_build_id = $_POST['form_build_id'];

  // Get the form from the cache.
  $form = form_get_cache($form_build_id, $form_state);
  if (!$form) {
    // If $form cannot be loaded from the cache, the form_build_id in $_POST
    // must be invalid, which means that someone performed a POST request onto
    // system/ajax without actually viewing the concerned form in the browser.
    // This is likely a hacking attempt as it never happens under normal
    // circumstances, so we just do nothing.
    watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
    drupal_exit();
  }

$form is not an object. I am not sure why.

In the ajax_get_form() function I am doing ado a dd() of $form_build_id. This returns me something like form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE.

If I perform the following SQL in the database I get a result.

select *  from cache_form where cid like '%form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE%';

The cid in this instance is  form_state_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE.

In form_get_cache() the code is as follows:

function form_get_cache($form_build_id, &$form_state) {
  if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
     //code missing
  }
}

From cache_get() we are looking for form_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kEbut what we have stored in the database is form_state_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE. Of course we do not match so nothing is returned.

I am unsure why this is happening.

My form code is as follows

  $form['welcome'] = array(
    '#markup' => //some html markup,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#ajax' => array(
      'callback' => 'myform_js',
      'wrapper' => 'message_container',
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'click',
    ),
  );

  $form['result'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
  );

The function myform_js() is not being hit as when dd() is added to the top it is not called. I can't see anything obviously wrong with this so not sure if there are any environmental issues that could cause the issue.

I have also tried changing the type of $form['submit'] to button.

It looks that the part that is failing is the call to cache_set(). I am unsure as why at the moment.

OK think I have it.

As form_form-ymw-BN0Zhp9j2CZf82mZzslbUBiLo8kZbreXhB1y8kE was not being set I looked at form_set_cache().

/**
 * Stores a form in the cache.
 */
function form_set_cache($form_build_id, $form, $form_state) {
  // 6 hours cache life time for forms should be plenty.
  $expire = 21600;

  // Cache form structure.
  if (isset($form)) {
    if ($GLOBALS['user']->uid) {
      $form['#cache_token'] = drupal_get_token();
    }
    cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
  }

  // Cache form state.
  if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
    cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
  }
}

I dug into cache_set()

function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  return _cache_get_object($bin)->set($cid, $data, $expire);
}

I then looked into set()

  /**
   * Implements DrupalCacheInterface::set().
   */
  function set($cid, $data, $expire = CACHE_PERMANENT) {
    $fields = array(
      'serialized' => 0,
      'created' => REQUEST_TIME,
      'expire' => $expire,
    );
    if (!is_string($data)) {
      $fields['data'] = serialize($data);
      $fields['serialized'] = 1;
    }
    else {
      $fields['data'] = $data;
      $fields['serialized'] = 0;
    }

    try {
      db_merge($this->bin)
        ->key(array('cid' => $cid))
        ->fields($fields)
        ->execute();
    }
    catch (Exception $e) {
      // The database may not be available, so we'll ignore cache_set requests.
    }
  }

Here an exception is caught and not reported. I added a dd() into catch. Looking in drupal_debug.txt

[message:protected] => SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes

I have now increased the value of max_allowed_packet in MySQL. It has fixed things.

With this information I did some more googling and found this post. They have had the same problem that I had.


Should user input be able to cause an unhandled exception? Drupal 7's user login form (and I dare say others) can be tampered with client-side, to cause Drupal to throw an unhandled exception.

All you need to do is change the input fields, appending [] to the name of the name field, and Drupal will create invalid SQL and throw that at the database.

Is this considered a problem? Surely it's Drupal's job to ensure user input is sanitised to the point that it won't generate invalid SQL - is it a DOS risk/security issue?

e.g. Visit drupal.org's login page. Open firebug. Change the <input name="name".../> to <input name="name[]" .../> and add another one just like it. Put some values in both name fields and the password and submit. You get the "This website has encountered an error." page of death.

(I can vouch for this under Drupal 7.35, and on drupal.org which I presume is 7.36)

...

No, user input shoulnd't cause and unhandled exception. Not only because is a nasty reponse form server but it reveals an error condition not handled so it may head to security issues. A non-handled error means that developers are not aware of that error (or they are too lazy, what may be worst).

All error conditions should be handled to minimize problems related to that uncontrolled error.

I've tried to reproduce the bug (with two input name fields with name="name[]" as you have shown in your images) without getting reported error. So I think this
particular case you mention seems to be a drupal.org bug or a module bug of a module used in the Drupal site. You can report the bug in the Drupal.org infrastructure issue queue


Difference between DRUPAL_CACHE_PER_PAGE and DRUPAL_NO_CACHE What is the difference between DRUPAL_CACHE_PER_PAGE and DRUPAL_NO_CACHE?

I'm developing a module that will generate 2 blocks for menu and it's sub-menu in different blocks and can't decide between those two options for the blocks.

links:
https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL_NO_CACHE/7
https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL_CACHE_PER_PAGE/7

DRUPAL_NO_CACHE doesn't cache the item, ever.
DRUPAL_CACHE_PER_PAGE caches the item per page url -- this is useful for example if the block changes with a url context.


CSS not working after Commerce AJAX processed on field I have got a problem with css after Drupal processes radio buttons on Drupal Commerce product page. Radio buttons are formatted (images instead of typical radio)

Formatted radios

After clicking any of radio buttons:

The HTML:

    Pack size

            <input type="radio" id="edit-attributes-field-pack-size-50-grams" name="attributes[field_pack_size]" value="50 grams" checked="checked" class="form-radio ajax-processed">  50 grams

            <input type="radio" id="edit-attributes-field-pack-size-100-grams" name="attributes[field_pack_size]" value="100 grams" class="form-radio ajax-processed">
            100 grams

The SCSS is:

    #edit-attributes-field-pack-size {
        overflow: hidden;
        input {
            opacity: 0;
        }

        label[for|="edit-attributes-field-pack-size"] {
            display: block;
            width: 102px;
            height: 102px;
            background: url('/sites/all/themes/blissout/img/radio.png') no-repeat;
            text-indent: -1000px;
            overflow: hidden;
        }
        label[for|="edit-attributes-field-pack-size-50-grams"] {

        }
        label[for|="edit-attributes-field-pack-size-100-grams"] {
            background-position: -102px 0;
        }
        label[for|="edit-attributes-field-pack-size-500-grams"] {
            background-position: -204px 0;
        }
    }

And it works perfectly until the ajax is "preprocessed" on radios. That Ajax calculates the price depending on the size of selection (it's drupal commerce code). It's different product variation but the classes doesn't change.

I have tried putting CSS into html.tpl.php. If the trigger('create') is solution could someone describe me step by step how to write js/jquery code for it?

The problem is you're relying on an ID for your CSS selector, but when Drupal's Forms API refreshes a form via #ajax, it appends a numeric suffix to the ID to maintain a unique ID prior to replacement. Your CSS no longer applies because the selector no longer matches any element on the page. You should switch this to some class based selector instead.


Replacing the updated module in drupal 7 without effecting the database from previous module? I have seen that whenever we apply patch to a module, without reinstalling the module, new updates of the module won't be reflected.
The problem is reinstalling the module will truncate the module related tables in the database. Is there any other way, so that we can replace the updated module without effecting the data from previous module?

Thank you in advance.

That's what hook_update_N is used for:

  For each change that requires one or more actions to be performed when updating a site, add a new hook_update_N(), which will be called by update.php. The documentation block preceding this function is stripped of newlines and used as the description for the update on the pending updates task list. Schema updates should adhere to the Schema API.

e.g. Adding a new column to a table:

function MYMODULE_update_7100() {
    db_add_field('foo_table', 'bar_col', array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'description' => 'My new integer column.'
    ));
}


How to use data in a content type from another content? Is it possible to use data in a content type from another content?

I will create a website for a football club. I want to add a content type for clubmembers (approx. 250 members) with personal information.

The members could order clothes from the club through a board member, who will keep the orders per member through a page.

To not have to re-enter some data, is it possible to establish a link with the personal member page? For example, I want to use some fields that are contained in another content type.

If it's possible, how can I do that?

I will suggest to use Entity reference module.

  Provides a field type that can reference arbitrary entities.

Also you can take a look References module.

  This project provides 'node_reference' and 'user_reference' field
  types.


Does anonymous can access current node? How to check it in my module? I need to do something witn current node by my module only if anonymous users can view this node. How to check it?

By default I use $node->status == 1, but some other modules can change anonymous access rights also for published nodes.

The check if the anonymous user has access to a given $node, you can use the node_access() like this: node_access('view', $node, user_load(0)).

As a side note, $node->status == 1 will check that the node is published. An unpublished node is usually not visible by anonymous user. Which users are allowed to view unpublished node depends on the granted permissions and node access module enabled on the site.


Access callback for blocks We have "access callback" and "access argument" for defining the access to pages.

What is the way to restrict showing blocks? Can "access callback" also be defined in hook_block_info(), or through any other way?

The array returned from the implementations of hook_block_info() doesn't contain a property equivalent to the access callback for the menus. If you have a module that implements a block, then you can implement hook_block_view() using code that checks if the user has a specific permission. The following code is used from a Drupal module; as you see the block is "rendered" only when the user has the "access content" permission.

case 'recent':
  if (user_access('access content')) {
    $block['subject'] = t('Recent content');
    if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
      $block['content'] = array(
        '#theme' => 'node_recent_block',
        '#nodes' => $nodes,
      );
    }
    else {
      $block['content'] = t('No content available.');
    }
  }
  break;

You can use similar code, but checking a different permission, even a custom one your module uses for checking if the user can see the block.


How to choose between classic SQL query and Drupal 8 technic? I have a custom content entity (amap_distributions_inscriptions) linked to 2 entity_reference 'datedistributionid' (which is basically the date of distribution plus other fields) and 'amapienid' (which is mainly the people who can attend to the distribution).

I want to create a form allowing people to enroll to the distribution, i.e. choose a date among all possible and their role.

In the past (a module I wrote for Drupal 6), I had a db_query joining the three tables, sorting by date, name of the people, etc. I processed the result of the query with a while ($record = db_fetch_object($result)) to build a tabular form with all dates and already enrolled people and so on.

What would be the "Drupal 8" way to do that?

I started with a

$storage = \Drupal::entityManager()->getStorage('amap_distributions_inscriptions');
$ids = \Drupal::entityQuery('amap_distributions_inscriptions')
  ->execute();
$inscriptions = $storage->loadMultiple($ids);
foreach ($inscriptions as $id=>$inscription) {my code here}

but I'm struggling with retrieving 'date distribution' and 'amapien', then sorting the results before starting to build the form rows...

Any guidance?

Trying to use @ssibal's advice, I assume I should write something like

$database = \Drupal::database();
$result = $database
  ->select('amap_distributions_dates', ???)
  ->fields('ddate', 'iid', 'pid', 'irole', 'nom', 'prenom')
  ->condition('dnumber', 0, '>')
  ->execute()

My D6 query ('amap_distributions_dates', 'amap_distributions_inscriptions' and 'association_personnes' being the 3 tables):

$query = "
SELECT
    amap_distributions_dates.ddate,
    iid,
    amap_distributions_inscriptions.pid,
    irole,
    nom,
    prenom
FROM
    amap_distributions_dates
    LEFT JOIN amap_distributions_inscriptions ON amap_distributions_inscriptions.ddate = amap_distributions_dates.ddate
    LEFT JOIN association_personnes ON association_personnes.pid = amap_distributions_inscriptions.pid
WHERE
    dnumber > 0
ORDER BY
    amap_distributions_dates.ddate ASC,
    iid ASC,
    irole ASC,
    nom ASC,
    prenom ASC
";

Finally, this worked:

$database = \Drupal::database();
$query = $database->select('amap_distributions_dates', 'amdd');
$query->leftJoin('amap_distributions_inscriptions', 'amdi', 'amdi.datedistributionid = amdd.id');
$query->leftJoin('association_personne', 'ap', 'ap.id = amdi.amapienid');
$query->fields('amdd', ['id', 'datedistribution', 'nombreproduits'])
    ->fields('amdi', ['id', 'datedistributionid', 'amapienid', 'role'])
    ->fields('ap', ['id', 'nom', 'prenom'])
    ->condition('nombreproduits', 0, '>')
    ->orderBy('datedistribution', 'ASC')
    ->orderBy('role', 'ASC')
    ->orderBy('nom', 'ASC')
    ->orderBy('prenom', 'ASC');
$results = $query->execute()->fetchAllAssoc('id');
foreach ($results as $row) { some code here }


How do I bulk delete all content posted prior a chosen date? How can I bulk delete all content posted prior a chosen date? Let's say I want to delete every node posted before/up to year 2012, but keep the ones after 2012.

How can I achieve it in Drupal 6?

Using the Views Bulk Operations (VBO) module, you can:

Create a VBO view
Add a filter (could expose it) for content "Post date" less then required date
Add a bulk operation to "Delete item"
Save the view

With the view you just created, you can then bulk delete the selected nodes.


Override module's template in theme Suppose i have this hook_theme() in my module, choosing a template inside the module:

/**
 * Implements hook_theme().
 */
 function module_theme($existing, $type, $theme, $path) {
   return array(
     'module-output' => array(
       'template'  => 'output-template',
       'variables' => array(),
   ),
 }

If i put the same output-template.tpl.php inside my active theme, Drupal picks up the module's template.

Is there a way to make Drupal understand that if a template with the same filename exists somewhere in the theme, to pick the theme's template and not the module's (like an override)?

You can override tpl files defined in modules inside your active theme (under the templates directory). But Drupal will look for a file name using the defined theme key name and not the defined template file.

In your case, you should create a module-output.tpl.php file within your theme. Maybe a good practice to name your template file the same as your theme definition.


Managing custom theme translations file How to add a translation file to a custom theme?

I did

my_theme.info.yml

'interface translation project': my_theme
'interface translation server pattern': themes/my_theme/translations/my_theme-%language.po

twig template:

 {% trans %}
  status
{% endtrans %}

{{ 'status'|t }}

/my_theme/translations/my_theme-fr.po:

msgid "status"
msgstr "statut"

msgid "statut"
msgstr "status"

followed by a

drush cr

The output is not translated when I am on the fr page (the default language being english).

The .po file is not imported by being placed in the themes directory, you need to import it. To do that go here:

Home > Administration > Configuration > Region and Language > Import


Commerce : products with 2 prices In a Commerce project, the customer should be able to choose between 2 options with a radio field, for some products only, with a different price for each option. When a customer selects a radio option, the unit price should be changed accordingly and with ajax, and the line item updated I guess.

We also need that the admin enter PRICE A, PRICE B in 2 commerce_price fields when he creates new products, not by rule calculation neither  +90 or -100 as in Commerce Pricing Attributes (because prices vary a lot and having to calculate each price difference would be a source of errors).

At the moment the lone idea I got to configure this is :

set a line item field with these radio options, shown in the add to cart form.
Then or a pricing rule which detects if the 2nd price exists, and is selected ; sets the 2nd price as the unit price ?

Or programmatically, with some hook ? Any suggestion would be really helpful.

Pricing rules was the right track. In order to configure 2 main prices for a single product :
Add a 2nd price field to the product type:

Add a boolean field to the corresponding line item type:

In the Add to Cart form settings of this field (admin/commerce/config/line-items/CUSTOM-line-item/fields/field_avec_aerien), check  Include this field on Add to Cart forms for line items of this type.
Finally, in admin/commerce/config/product-pricing/rules/manage/, create (or clone & edit) a new pricing rule which set the unit price to 2nd price amount, when the boolean is checked by the customer in the add to cart form.

Pricing rules are very powerful, indeed !


How can I create two distinct sets of exposed filters for use in a single view? I am wondering if there is a way to create two distinct sets of exposed filters to use on a single view. The reasoning is that I have a view for content of a given type. I have a set of views exposed filters placed in the header of the site that is used as a search form, which displays its results within this view. However, once the user submits a search, I would like them to be able to further filter their results based on aspects of the resulting nodes. This would somehow require a second set of exposed filters for the same view. As far as I can tell, as long as I have my exposed filters in a block, all filters that I add are placed within that block. Is there some way to get around this, and display two sets of filters, in different places, for a single view?

It looks like what you are describing is faceted search. In Drupal, a good solution for faceted search is using Apache Solr along with the Apache Solr module. Here's a video tutorial on how to install Solr for Drupal. Here you can see an example of faceted search working on a site I built for the company I currently work for.


How do I get a double top boostrap nav with bootstrap template? I want a secondary bootstrap navbar on my site, a black one on top of the blue one.

Now when resizing, there is a hamburger menu and so on, so stacking 2 bootstrap menus on top of each other, even of different colors may cause problems.

How do I have a double bootstrap menu with 2 colors?

You can create a region in yourtheme.info or use Block Group Module.
If you're using Bootstrap theme for Drupal, you can simply write code for your Top Links Navbar in page.tpl.php and use CSS to design it as you wish. Now in the template code, include your navbar if not empty:

if (!empty(primary_nav)||!empty(top_links)||!empty(user_nav)||!empty(navigation))
{ //..Code to include your top_links navbar .. /}

You can also hard-code your menu in page template of your theme but it's not the best practice.

Plus: Always use the child theme.

If you want to add hamburger menu then use JQuery pluggin for same and remove the default responsive behavior of bootstrap from the menu you want to display hamburger on smaller screen. I advice JQuery plugin as it's open source, clean and very beautiful.

Play here.


How to display unpublished contents in views for all the users? I need to display published as well as unpublished content for all the authenticated users. Also, site also has workbench moderation module enabled.

I have tried by pass access control permission, view unpublished contrib module.

Please suggest.

Add Permission - Workbench Moderation : View all unpublished content.


How do I diagnose a unstable installation on ubuntu 16 server? I'm deploying a site to a Digital Ocean Ubuntu 16 server. I'm using PHP 5.6, but otherwise using the default versions of the necessary database software. The site functions; however, I frequently have database related errors, specifically, the following one:

  PDOException: SQLSTATE[HY000] [2002] Connection refused in lock_may_be_available() (line 167 of /var/www/html/phisigmarho.org/includes/lock.inc).

I usually get that error, but I also get "the website experienced an error" errors when I to do anything database or process intensive (updating modules through the UI, etc). I'm relatively new server administration, so I'm not sure what could be wrong or which logs I should be looking at for clues to what's wrong. For the moment, restarting MySQL from the terminal is letting me move forward with setting up the site, but I can't let anyone use the site the way that it is now.

How do I figure out why MySQL keeps going away?

Unless you are using Drupal 6, I suggest you start again from scratch and use/install PHP 7.

Drupal 8 and 7 (since 7.50) support PHP 7, which is twice as fast as PHP 5.

sudo apt-get update
sudo apt-get install apache2
sudo apt-get install curl
sudo apt-get install mysql-server
sudo mysql_secure_installation

Would you like to setup VALIDATE PASSWORD plugin? n

Change the password for root ? n

Now, for the rest of the questions put y

sudo apt-get install php php-cli php-curl php-gd php-mbstring php-mcript
a2enmod rewrite
sudo service apache2 restart

Now, Install and Secure phpMyAdmin and create a database with and a user with privileges. Do a fresh Drupal install and make sure you get no errors in the install screens.

Once all ok, dump all your DB tables and import your site. Make sure your Drupal directory contains all your modules and the files folder contains all your images and files of your importing site.


Creating a custom registration page I would like to modify the look of a user registration page that I am creating. It contains content profile fields and a recaptcha area. I have created a user-register.tpl.php file and updated my template.php file so that this template file is recognized.

I would like to pull out the pieces of the registration form and place them with specific divs for styling. The problem I am having is that I cannot get the fields. I have tried using

print drupal_render(drupal_get_form('user_register'));

but that creates a white page. When I try to just print drupal_get_form('user_register') I get nothing as well. So I am stumped as to what I am doing wrong. It would appear that the drupal_render command is not returning anything so I can't figure out why that would be.

Here is my modification to my template theme:

function mytheme_theme($existing, $type, $theme, $path) {
  return array('user_login'=>array(
    'template'=>'user-login',
    'arguments'=>array(
        'form'=>NULL),
    ),
    'user_pass'=>array(
        'template'=>'user-pass',
        'arguments'=>array(
            'form'=>NULL),
    ),
    'user_register'=>array(
         'template'=>'user-register',
         'arguments'=>array(
            'form'=>NULL),
    ),
  );
}

This would seem it should work but it doesn't. It is almost like that form does not exist.

I am using Drupal 6.26. Any help would be appreciated!

Thanks

I found what was causing the problem with not being able to display form elements as described above. The issue was this line in my templates file:

function mytheme_preprocess_user_register(&$variables) {

   $variables['intro_text'] = t('some text.');
   $variables['rendered'] = drupal_render($variables['form']);
}

It looks as though you can only call drupal_render once. Any subsequent calls to drupal_render are ignored as Drupal as already marked the code as rendered. There should be a way to force a re-render if necessary or be able to get the already rendered results. If someone knows how to do this please reply to this post.

The solution was to remove this line from the templates.php file and everything worked.


Why don't all pages of content show up in the pagination beneath main content? On a Drupal 7 site, I have several pages' worth of content, articles that are set to "published" and "promoted to front page". The page numbers underneath the main content part of the block show pages 1 through 5, and the "next >" and "last >>" links. However they do not show pages 6 and beyond. Why not?

I can go to the content that's on pages 6 and beyond, by going directly to the node. I can even enter the URL manually for page 6 and it loads fine, so the articles are there, published, and promoted. However, the pagination does not show links for pages beyond 5. Clicking on the "last >>" link only goes to page 5. In the image below, you can see that I've manually opened the URL for page 6, which loads the content, yet the pagination only shows it on page 5 of 5.

Is there a setting somewhere to choose how many pages Drupal shows? Or is there some other issue?

Note: I'm using the default Drupal front page. I haven't configured a different view. Should this be necessary?

This appears to be a bug in Drupal 7 or in some configuration. After migrating the site to Drupal 8, the full pages display correctly.


Where can I find where this content is being loaded from? Helping out a friend with a Drupal based site. On one page, he has a series of images with a lightbox displaying info once clicked.

This however doesn't function, and instead shows as an image title.

I was just wondering where I'd find the file with the descriptions?

Thanks

That's not a simple question, it depends on the site. For your case you will first want to check Nodes (Content items) as that could be a WYSIWYG field. Otherwise if it's hard-coded it would most likely be in the theme folder that's currently enabled.

You can also check Views for the page that's showing all of them as a series of images. That could give you information on what type of Content they are.


In the specific page.tpl.php adding an include file I was recently asked to create a blank page without a header and footer. I implemented that following this comment.
Now the issue is that the team for whom I've created it do not want the html, body tags either that show up in view source! They have directly included a php file in the specific page-simple.tpl.php . I know this is not the right approach. If someone could point out the issue doing it this way and another approach if possible. I'd really appreciate it.

Thanks.

Try create a custom module and use module_load_include() it might be a better approach than the standard PHP include() then include the custom php.


Email sent using rules chops characters off email from address I'm sending out an email using rules. I'm leaving the from field blank, so that it just uses the site-wide address.

For some reason it seems like Drupal is cutting characters off the from address. This is on my local dev machine so the email looks like this: admin@website.meeples

When the email is supposed to get sent, I simply get a message saying "Unable to send e-mail. Contact the site administrator if the problem persists." so I checked my syslog, and all the from headers say "someone@website.meep" and the email can't send because my machine can't resolve that domain.

What the hell? Why has it modified the from address? I've tried changing the site email to "admin@test.com" and when I do that nothing gets modified (IE I see admin@test.com in my syslog). So why is it changing my website.meeples domain?

I tracked the problem down to the mimemail module.

In mimemail.inc there is a function called mimemail_headers which contains this:

  if (preg_match('/[a-z\d\-\.\+_]+@(?:[a-z\d\-]+\.)+[a-z\d]{2,4}/i', $from, $matches)) {
    $headers['Return-Path'] = "<$matches[0]>";
  }

The {2,4} at the end of the regex caused it to chop the les off of meeples. Changing it to + fixed the problem.


Where are the field variables in a block template? How can I access the variables of the fields in a block template?

They're in the content variable, e.g.

<div{{ attributes }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content.field_foo }}
    {{ content|without('field_bar') }}
    {{ content.field_bar }}
  {% endblock %}
</div>

For reference, these are the default core variables you have available (from the core template:

  plugin_id: The ID of the block implementation.
  label: The configured label of the block if visible.
  configuration: A list of the block's configuration values.
  label: The configured label for the block.
  label_display: The display settings for the label.
  provider: The module or other provider that provided this block plugin.
  Block plugin specific settings will also be stored here.
  content: The content of this block.
  attributes: array of HTML attributes populated by modules, intended to be added to the main container tag of this template.
  id: A valid HTML ID and guaranteed unique.
  title_attributes: Same as attributes, except applied to the main title tag that appears in the template.
  title_prefix: Additional output populated by modules, intended to be displayed in front of the main title tag that appears in the template.
  title_suffix: Additional output populated by modules, intended to be displayed after the main title tag that appears in the template.


Adding a suffix to a form element I have a form which has an input field for which i want to add a suffix.
function myapp_preprocess_form_element(&$variables) {
  if ($variables["element"]["#attributes"]["id"] == 'edit-keys') {
    $variables['#suffix'] = '
Some text
';
  }
}

I've looked into the form-element.html.twig file and it does have a suffix varaible, but it's not rendering.
Any ideas?

/**
 * Implements hook_form_FORM_ID_alter() for login.
 */
function MYTHEME_form_user_login_form_alter(&$form, &$form_state) {
  $form['register_user']['#prefix'] = "
 " . t("Don't have an account?") . "";
  $form['register_user']['#suffix'] = "
";
}

This is how I've added a wrapper to a form element using prefix and suffix. Hope it helps.


Full path in the menu I've trying to setup a Drupal 7 site where I already have some content added. The content is bound to a multi-level menu, but the path's for nodes in the submenus show only the actual node's alias, omitting the parent nodes. I wish to have url's where the path contains the content structure, no matter how many levels are?

I have tried a few pathauto settings:

[node:menu-link:parents:join-path]/[node:title]
[node:menu-link:parent:url:path]

After each try, I have rebuilt the paths and cleared cache, but I am still not getting the paths that I need, and they haven't actually changed.  All of my nodes have the "Generate automatic URL alias" setting checked on the node edit page.

How can this be achieved?

I would try the following.

Take a backup of the database. Backup and Migrate makes this easy.

Make sure core and modules are up to date, especially Pathauto and Token.

Browse to admin/config/search/path/patterns, and set the path pattern to [node:menu-link:parents:join-path]/[node:menu-link].  Credit to Menu path in Pathauto.

Browse to admin/config/search/path and delete the bad aliases, or admin/config/search/path/delete_bulk and just delete all the content aliases.  Be careful here, and make sure you have a backup.

Spot check a few nodes, and make sure the "Generate automatic URL alias" is set.

Double check that the nodes have a menu entry set on the node edit page, and that the parent is correct.

Double check the menus and make sure that the links have the paths set to node/XXX.  You need to click the EDIT link to see this.

Browse to admin/config/search/path/update_bulk to create all of the aliases for the existing nodes.

Clear Drupal cache from admin/config/development/performance

That should work.


Adding namespace to s3 module I have a drupal 7 codebase which I downloaded from a production server and set up locally (using PHP version 7). There is this amazons3.module file in which I have to add an extra namespace Drupal\amazons3 to get it running. If I remove the line, the code throws an error stating : Error: Class 'Drupal\amazons3\StreamWrapperConfiguration' not found in amazons3_upload_location() (line 345 of /xxx/yyy/sites/all/modules/amazons3/amazons3.module)..

Why am I having to add this code when it is not there in the production version and nor in the github codebase ?

I solved this by linking to the correct path where the composer was placed (as suggested by Japo).

EDIT:

In another server setup, the same issue was fixed by adding php-curl module.


Sum up views custom text field using aggregation Would it be possible to set the custom text field value in views? I have a simple calculation in custom text field. It gives me the correct calculation, but when I'm trying to aggregate the views to calculate the total sum from custom text field it returns 0 value.

I'm thinking that custom text field has no value in the first place and it's only output an HTML. Would it be possible to set custom text field value from the calculated output? Or is there any other way to achieve this without using the hook system?

Please note that I'm also attaching another view into custom text field which returns a total sum from another field.

Yes short Answer have a look at creating a custom twig extension:

the idea would be to pass the details required  as an "exclude from display" field (or fields) to the custom global text field. Note excluded from display fields can be accessed in the "REPLACEMENT PATTERNS" section under view text.

then basically in the text field
you would do something like:

{myCustomTwigFunctionToCalculate( add_REPLACEMENT_fields_here)}
// or example ...
{myCustomTwigFunctionToCalculate( entity_id, nid, uid)}

  namespace Drupal\YOURMODULE\Twig;

  class CustomTwigToCalculateTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'myCustomTwigFunctionToCalculate';
  }

  /**
   * {@inheritdoc}
   */
 public function getFunctions() {
    return [
      new \Twig_SimpleFunction('myCustomTwigFunctionToCalculate', [$this,
      'myCustomTwigFunctionToCalculate'], [
      'is_safe' => ['html'],
    ]),
  ];
 }

 public function myCustomTwigFunctionToCalculated($param1 , $param2 ) : string {
 // Do the stuff you need to to calculate prams you pass.

  $output = '';
  $output = $param1 + $param2 + 42;
  return (string) $output;
 }

}

you will also need a service file ... see below examples.

Links to custom twig extension for Drupal 8:

https://www.openaccess.fr/la-veille-du-web/create-twig-extension-drupal-8

https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae

https://www.youtube.com/watch?v=9PeAfExNSDk


Do not want store credit card details I am using Drupal 8 Commerce 2 Onsite payment gateway with USAepay payment gateway. I do not want to store credit card details in the database, even it should not save last 4 digit last of card number. Is there any way?

There is a reason that they have made it like that.
Take a look at this page, it describes why.

Onsite Payment Gateways always store credit card info
Payment gateways have different capabilities. Some support storing a user's card in the gateway. Others have an "offsite" flow, sending you to their site to collect card info and then returning you back to the commerce site when done.
An "Onsite" payment gateway is one that keeps the visitor on the site, collects the card numbers and posts it from the site to the gateway. In Drupal Commerce 2, the payment flow for onsite gateways is completely different than in Commerce 1, Ubercart, or many other shopping carts: it now stores the credit card in the gateway first, and creates a "Payment Method" associated with the user that contains the token from the gateway. It can then use that token for any future charges (as long as the gateway continues to honor it).


Why should you use theme(), rather than calling the theme functions directly? Why should you use theme(), rather than calling the theme functions directly?

theme('box', $title, drupal_get_form('comment_form', $edit, $title));

Why doesn't the code call the theme function directly, as in the following code?

theme_box($title, drupal_get_form('comment_form', $edit, $title));

You have to use the theme() function for the override system to work. For example, your theme may override the theme function for a module, or a template (.tpl.php) file might be used instead.


See what path aliases are set up with Drush? Ive installed Drush and my local system is a Mac. It seems to have worked as when I type drush into the terminal a long list of commands comes up.

When I type drush cc all I get the message 'drush' cache was cleared . Does that mean my path aliases are set up? Or could I be getting a false success message? I have a number of Drupal sites locally and I dont know which (if any) is having its cache cleared.

You have to either be within a drupal doc_root (aka apache verbiage) or have properly configured drush site aliases for commands to work:

Eg, if your site lives at /var/www/

cd /var/www/
drush cc all

Or if you have setup a drush site alias of @local, then from anywhere on your system:

drush @local cc all


Eliminate Views Entity Reference Duplicates. I have some titles the same on purpose I have a view with an entity reference pulling in what I need from a content type. There are, on purpose, titles that are the same.

Is there a way to compare what is output and then only show one of the titles?

I am showing these in a select list.

This is not duplicates, as they are separate entries... so using the Query Settings > Distinct isn't the correct solution in my case.

You can use hook_views_pre_render to get at the results array before it is output to the screen.

e.g.

function my_module_views_pre_render($view) {
  if ($view->name == 'the machine name of the view') {
    foreach ($view->result as $result) {
      // do some kind of comparison and de-duplification
    }
  }
}


load node_type_form form I need to load and print drupal 'internal' form on the page, which id is "node_type_form"
I have:

$form = drupal_get_form("node_type_form");

$html = drupal_render($form);

echo $html;

it only prints "Menu settings" and "Save and add fields" button.

I get:

Notice: Undefined index: node_type_form in drupal_retrieve_form()

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_type_form' not found or invalid function name in drupal_retrieve_form()

Notice: Trying to get property of non-object in menu_form_node_type_form_alter()
Notice: Undefined index: #node_type in menu_form_node_type_form_alter()

node_type_form() lives in modules/node/content_types.inc, which the system only includes when it needs to (to fulfil menu paths etc).

If you include it manually before your call to drupal_get_form() it should work...

module_load_include('inc', 'node', 'content_types');
$form = drupal_get_form("node_type_form");
// ...


Errors when installing Token I installed the Token module, and it produced a bunch of errors. I accidentally navigated away from the page displaying the errors, and now I'm left wondering what future problems these errors might cause.

Is there any way to find out what went wrong with the install?

I am using Drupal 7.

admin/reports/dblog will show you the last messages logged by Drupal. To see the menu, you need to enable the "Database logging" module, which is a core module present also in Drupal 6.


How to use sprintf in Url::fromUri? I am trying to convert this from D7 to D8:

l(drupal_strtoupper($field),
sprintf('http://finance.google.com/finance?q=%s',
$exchange . ':' . $field),
array('attributes' =>
array('target' => '_blank',
       'title' => (drupal_strlen($title)) ? $title : $field)
)
);

I am doing this and it produced error:

return Link::fromTextAndUrl(Unicode::strtoupper($field), Url::fromUri(sprintf('http://finance.google.com/finance?q=%s'),$exchange . ':' . $field))->toString();

  InvalidArgumentException: The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core/lib/Drupal/Core/Url.php)

It doesn't really make sense to use sprintf (or any other string formatting/replacement functions) here - the API can already accommodate what you need in a much more structured manner:

$options = ['query' => ['q' => $exchange . ':' . $field]];
$url = Url::fromUri('http://finance.google.com/finance', $options);
$link = Link::fromTextAndUrl(Unicode::strtoupper($field), $url);


Modify Override the Views Filter Criteria Programaticly I have the following view being called in my code with views_get_view() and I then try to modify the filter called usershare to admin instead of the default that I have set in my view. But it doesn't seem to override my view output. What am I doing wrong here? I noticed that some examples use pre_execute() and some just use excute(). I'm not sure if that has anything to do with it.

      $view2 = views_get_view('flag_lists_user_lists_public', FALSE);
      $view2->set_display('default');

$view2->display_handler->display->display_options['filters']['usershare']['value'] = 'admin';

      $view2->pre_execute();
      $output .= $view2->render();

You can use hook_form_views_exposed_form_alter() :

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form['#id'] == 'flag_lists_user_lists_public') {
    $form['usershare']['#value'] = 'admin';
  }
}


Auto import Facebook page photos as nodes for views display I have some experience using feeds and views, and I've looked at a few modules designed to integrate Drupal with Facebook. But I'm unable to figure out how to set up an importer to automatically pull Facebook photos from a page and turn them into nodes. I'd also like to map three fields for views display: image, description and FB album title to Drupal taxonomy term.

Suggestions on how best to approach this?

JSON parser did the trick with a feeds importer properly mapped. Once I figured out how to get the data from Facebook, it was really just a matter of configuring the importer properly with the right expressions. I was pleasantly surprised to find that I could get the data without any token because the data comes from a public page, rather than a private profile. The url structure: http://graph.facebook.com/[album id]/photos.


How to implement facebook feed which shows the latest facebook wall post I would like to display latest facebook wall post on my website. I found the Facebook Pull module; but it doesn't work for me. I have add the appropriate app id and App Secret and nothing is showing up. Any ideas?

Do you know how  I can accomplish it? I never have a similar problem with a twitter_pull module which does the same but for the twitter.

Why not use the facebook like box plugin? If you're just looking for a widget like capability on your site, this is the easiest and pushes the heavy lifting on to Facebook's servers without any more modules or extra PHP:

http://developers.facebook.com/docs/reference/plugins/like-box/

Play around with the options, you probably just want to show the stream. There are other options below to customize the output of this as well.


Context select submenu I'm trying to enable a submenu item through context rules.

However, the Context is consistently trying to select only the top parent item, and not the submenu. I tried few times on completely clean installs with the same results.

Am I doing something wrong or it should be working this way?

How can I otherwise open a submenu item with context rules?

Thanks!

I am using a Menu Block module and Context to achieve a similar thing.

For conditions, I have this fire on a Content Type of Instructor Profile. I add Menu Block's blocks to region's One and Two accordingly.

And I use Context to automatically select the menu level for me


What are the major differences in building an install profile for Drupal 8? There is a good guide for drupal 7 which explains how to build a install profile for drupal 7. I built an install profile using it.

But I want to build an install profile using Drupal 8. What changes do I need to make to my Drupal 7 install profile to make it work for Drupal 8.

PS: I know Drupal 8 is not ready yet but I'm doing this for learning purposes.

Apart from specific code changes like converting the .info file to a .info.yml, the biggest conceptual change is that most of what an install profile will contain are configuration files.

Basically, you can take the configuration directory of in installed site, copy it into the config folder of an install profile and then you're already pretty close to building an install profile that will at the end look like the site.

There will still be a few challenges, for example dependencies between configuration and content. Lee Rowlands (@larowlan) is working on a default content module that allows to import content entities from .yml files too https://github.com/larowlan/default_content, but you can't just stuff all of it into an install profile.

Take a custom block for example. You have a block configuration, which depends on  a custom block content, which in turn depends on a custom block type (bundle of the custom block). I'm guessing the way to solve that will be to split an install profile in a set of modules, that depend on each other.


Delete user and change Content Author Is it possible to Delete the user and keep its content as created by the one who deleted the user.

Suppose, abc is a user as content creator/editor only and have created 2 contents.

abc got fired as editor and his boss xyz wants to delete his user account.

xyz not only wants to delete abc but while deleting abc transfer all the content created by abc to his name, so that it'd be like created by xyz.

Drupal has only 4 options while deleting user account which doesn't satisfy this need.

If it is possible then how? please elaborate how to achieve that....

While canceling user account choose either Disable the user account and keep its content or content belong to anonymous user

To bulk Update author for node you could use Views Bulk Operation

Create a view listing the content that you want to edit.
Add a bulk operation in fields

Select change the author of the content

Go to your view to select the nodes for which you want to change the author

Select the author who should be made the new other for all these content.


How to edit a webform block (not the webform itself) I have one webform block I would like to edit. I know I can use hook_form_alter, the problem is that any changes I make using it are affecting the actual webform plus the block.

How can change stuff just on the webform block? It's just a captcha component I want to disable, thanks.

probably the easiest way is to create a separate form for that block (a copy of what you have now, but dedicated to that block), and disable Captcha for that form name