List of nodes limited by last node created from each user I am using Drupal 7, and I want to create a views which lists all the nodes that match the following criteria:

Only the nodes whose content type is A, B, C
The latest nodes of those content types created by all the users, one node for each user

How do I create it?

Views 3 has the perfect new relationship type for this "Obtains a single representative node for each user, according to a chosen sort criterion."

To do this, begin with a new view which is a list of Users in fields format. By default you will see a list of usernames.

Then add a relationship 'User: Representative node (search for 'represent' when adding the relationship. You can choose the sort criteria as perhaps 'updated date' order by descending.

You can now add extra fields using the related data - such as 'Content: title' and 'Content: Updated date' using the relationship 'representative node' for each new field.


Load domain-specific CSS file on a multisite I have a Multisite Drupal 7 install.

I use one theme for all sites, and it lives at sites/all/themes.

Each domain has its own settings for the theme where you specify classes so you can target each in the css.  This allows me to not have to copy over the theme to each sites/site1/themes, and to not have to create sub themes for each one.  Less overhead.

So I have 1 giant css file, that contains all the css tweaks for each sites look.

But I would like to separate each sites css into its own file.

So I can have site1.css, site2.css, site3.css, and so on.  They would all need to be located in the theme at sites/all/themes.

How would I tell Drupal to load site1.css when on site2.com...and so on?

It's kinda messy, but you might be able to do something like the following in a custom module:

function mymodule_preprocess_html() {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

Or if you specifically want it in your theme files you could do the same in template.php

function mytheme_preprocess_html(&$variables) {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

To be honest I think you could use hook_preprocess_page in the module as well.

Many ways to skin a cat and all that jazz.


What is the best approach to write hooks? I had to use some hook functions on almost every project I worked, right now I am working on a project ( basically to collect donations and maintain organizations list ) where I need to write lots of custom code, at first I started to write all the code in theme i am developing, later I realized that its not going good with all the functions in theme because some hooks need to be written in modules so now some of the code is written in module and some is in theme which breaks the functionality when switch theme or with admin theme.

So I am thinking to write all the code again but not sure what is the best approach to write custom code in a drupal project.

if all code goes in custom module some of the theme sections needs to be rebuild and I didnt find any proper article on net on this

I think your question is more of in-general type . Please specify for what all purpose you need to use hooks .
I think this might be helpful for you : http://www.stephanemartinw.com/articles/25-theme-drupal-hooks-templates-functions

Thanks


Why Views Slideshow JCarousel plugin isn't available on view format settings? I've installed:

Views Slideshow
Views Slideshow Cycle
Views Slideshow Carousel

All required libraries are available. Status reports page is green.

I want to create slideshow view. I choose slideshow format, but on settings I have only Cycle as available slideshow type.

What can be wrong?

There is nothing wrong. jQuery Cycle is the default library used by the Views Slideshow Cycle module.

Look instead at "Widgets" on the format settings screen. The relevant configuration options will appear by selecting "Pager" under either Top Widgets or Bottom widgets.

From the Views Slideshow JCarousel project page:

  Currently provides a JCarousel pager widget.

and

  Under the Format heading, click "format" and select "slideshow". You
  should now be able to select and configure your jcarousel slideshow.
  Pager options are on this configuration screen, not under views "pager
  settings". To decide where you want your pager to go, you can tick the
  pager widget checkbox beneath the area you wish to show it. your
  choices are "top" or "bottom" of carousel.

Note: If using Views Slideshow Cycle, you will need to download the jQuery Cycle plugin.


Search API for searching in existing Solr Core I'm using Drupal 8 with Search API and Search API Solr Search.

I'm tasked with making an existing Solr installation searchable within Drupal. This core indexes PDFs and serves other systems, thus I may not edit the schema there. It can be assumed that this schema has fields like "author", "title" and "abstract".

I tried the following:

Add a server in Search API: This seems to work as I see the (correct) number of indexed documents in Solr.
Add an index with "Solr Document" as data source. I can see fields from the Solr core here.

However, in the View tab, I always see "0/0 Indexed".

Am I missing something here or is perhaps the wrong approach?

The Solr core's schema must have a field "index_id" and the value must be the same as the machine name of the Drupal index (in order for that (Drupal) index to find it). Moreover, the (Drupal) server has to use "Any Schema" and the (Drupal) index must be read-only.

Note that under "View" it still says "0/0 Indexed", however the search works.

There is a datasource.md in the search_api_solr module's folder which was helpful. I found it helpful to use search_api_devel as it shows the queries to Solr.


Auto Apply credits at checkout I am using commerce_userpoints which allows the use of credit to discount the amount at checkout of a product.

Right now the user needs to do this manually however I would like to automate this.

Any clue on how can I get this done ?

Use rules. When the order is completed, use the actions contained in the  userpoints_rules submodule to manage your userpoints. You might choose the "When an order has been paid in full" or you could just watch for orders moving in status to "Completed."


Using db_select, how can I select all nodes with any of an array of taxonomy terms and order by the number of terms it is associated with? I have this so far:

// for example, $tags = array(2, 8, 18);
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.type', 'post')
  ->condition('n.status', 1);
$query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
$query->condition('tags.field_tags_tid', $tags, 'IN');

I need to order these results by the number of "tags" associated with each node.

I've tried many things, using addExpression() with count() statements, then an orderBy(), etc, but I can't get it right.  Any help would be greatly appreciated!

You should put count as alias name in the count(*) and then groupby clause can be used on that column.

$query = db_select('node', 'n')
      ->fields('n', array('nid'));
$query->addExpression('COUNT(n.nid)', 'count'); // addExpression
   $query->condition('n.type', 'post')
      ->condition('n.status', 1);
    $query->join('field_data_field_tags', 'tags', 'tags.entity_id = n.nid');
    $query->condition('tags.field_tags_tid', $tags, 'IN');
    $query->groupBy('count', 'DESC'); //count is column name given in the addExpression


How to programmatically get webform drafts for a specific user? How to fetch all the webform drafts saved based on user id?
I tried the below query and it gives me all submission id's but how do I get just the drafts
$query = \Drupal::entityQuery('webform_submission')
      ->condition('uid', 123)
      ->condition('webform_id','test_1');

You could try this:
$query = \Drupal::entityQuery('webform_submission')
  ->condition('uid', 123)
  ->condition('webform_id, 'test_1')
  ->condition('in_draft', TRUE);

$entity_ids = $query->execute();

Or via the EntityTypeManager:
/** @var \Drupal\webform\WebformSubmissionInterface[] $submissions */
$submissions = \Drupal::entityTypeManager()
  ->getStorage('webform_submission')
  ->loadByProperties([
    'uuid' => 123,
    'webform_id' => 'test_1',
    'in_draft' => TRUE,
  ]);


Optimizing CSS Delivery in Theme I ran my site through Google PageSpeed Insights and got the following message:

Optimize CSS delivery of the following:

First it lists two CSS files I don't recognize in /sites/default/files

Second, it lists my font awesome css which I'm LINKING to from my .libraries.yml file, like so:

font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    theme:
      https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-
awesome.min.css: { type: external, minified: true }
    bootstrap/assets/javascripts/bootstrap/transition.js: {}

So my question then is two-fold:

Short of using another module such as Addvagg

1) How can I speed up delivery of the font awesome css?

2) What are those other CSS files and how can I speed up delivery of them?

download the font & css files, don't use a cdn
minify and concat your css, additionally you can use sass & gulp to
do the job for you


Problem with the body field after upgrading to 7.7 I recently upgraded to 7.7 because of the security updates, but now, when I try to add content there is no body field... and when I go check the module list I see this message on top of the list.

  Notice: Undefined index: module in _field_info_prepare_instance_widget() (line 382 of /var/www/gisele-drupal/modules/field/field.info.inc).
      Notice: Undefined index: module in _field_info_prepare_instance_display() (line 350 of /var/www/gisele-drupal/modules/field/field.info.inc).
      Notice: Undefined index: module in _field_info_prepare_instance_widget() (line 382 of /var/www/gisele-drupal/modules/field/field.info.inc).
  […]

Does anyone know what could be going on here, and how can I solve this?

Are you using OG?  Because that could be causing the issue.

Things to do

If OG is installed, but not enabled delete it.
Clear Cache
Update all modules up to their most recent versions
Run Update.php (do whenever a module is updated or deleted)
Uninstall Views and reinstall it

Issue about this problem here > http://drupal.org/node/1001060


Make Facebook comments on Facebook page show up on my Drupal site Using Drupal 7. I post some stories on Facebook and receive a lot of comments. I want these comments to also show up on the article page on my drupal site, not just on the Facebook page inside facebook. That is, when users comment on the post inside Facebook, i want the comment to show on the article page on my drupal website. Any ideas in getting this to work?

You can have a look at this Facebook Comments Social Plugin Module

  Implement Facebook commenting with settings on the level of both
  content type and node. This module comes with a Facebook Comments
  block so you can have comments anywhere on your site.

There are another modules which support your functionalities -> FB Comments Box

  This module gives your site the ability of using Facebook's Comments
  Box social plugin, i.e. comments on your site powered by Facebook. It
  provides an easy way to configure Facebook Comments parameters (like
  theme, administrators, number of posts, node types to attach to) and
  then exposes the generated code as a block for you to insert into a
  region of your choice. This module is intended for anyone who wants to
  put Facebook Comments on their Drupal site in addition to or instead
  of Drupal comments from core.


How to add comment field to custom entity I tried to add a comment field in the Basefieldsdefinitions of my custom entity but in my view the add comment form doesn't appear:

Here's the basefielddefinition

 $fields['comments'] = BaseFieldDefinition::create('comment')
  ->setLabel(t('Kommentare'))
  ->setDescription(t('Kommentare.'))

  ->setSettings(
    array(
      'default_mode'=> 1,
      'per_page'=>50,
      'anonymous'=> 0,
      'form_location'=>1,
      'preview'=> 1,
      'comment_type'=>'image_comment',
      'locked'=>false,

      ))
->setDefaultValue(
        array(
            'status'=>2,
            'cid'=>0,
            'last_comment_timestamp'=> 0,
            'last_comment_name'=> null,
            'last_comment_uid'=> 0,
            'comment_count'=> 0,
)
)
->setDisplayOptions('form', array(
 'type' => 'comment_default',
 'settings' => array(
   'form_location' => 1,
   'default_mode'=> 1,
   'per_page'=>50,
   'anonymous'=> 0,
   'form_location'=>1,
   'preview'=> 1,
   'comment_type'=>'image_comment',
   'locked'=>false,

 ),
 'weight' => 1,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);

In order to any changes on BaseFieldDefinition effects, you should uninstall/install your module.
your syntax seems Ok and I  only guest you did some changes after your module( entity) installed.


How to disable core JS aggregation and AdvAgg just for admin paths I help look after a site which uses $settings['file_public_base_url'] to serve files from a different subdomain on the frontend, but on the backend (admin paths like node/add and node/edit) this causes our JS to be loaded with absolute rather than relative URLs which seems to cause an issue with JS loaded via AJAX not executing correctly. There are no JS errors in my devtools console, but I suspect the cause is that the JS is being loaded from differing subdomains, as turning AdvAgg and core's JS aggregation off makes the JS files load via relative paths and function as intended.

Without any errors showing in my console or server logs I'm not sure I'm going to be able to get to the bottom of the AJAX issue, so for now a compromise seems to be to turn off aggregation for admin and content editing routes.

What would be the best way to do that? I know I can set $config['system.performance']['js']['preprocess'] = FALSE; and presumably a similar config key for AdvAgg's own setting (we have AdvAgg set to optimise/compress JS, so even with system.performance.js.preprocess turned off AdvAgg will still manage the files and use absolute paths to include them. Can config settings be altered on a per route/path basis?

So, the issue I describe in my question is this Drupal Core issue: Drupal.ajax does not guarantee that "add new JS file to page" commands have finished before calling said JS

So, my solution wasn't to disable the aggregation, but to apply the latest patch provided in the issue on Drupal.org


How Do I Disable CiviCRM locally if I don't need it? I'm working on a Drupal 7 site build and I have a local development environment.  The site has CiviCRM working with it, but I'm not doing any work related to CiviCRM so I'd like to just have it disabled in my local environment.

Can I somehow set my civicrm.settings.php or other file to just have CiviCRM disabled (or pointing to a dummy civi install) when working locally?

I could disable the module, obviously, but this throws a bunch of errors on various places, so I guess ideally I want to 'fake out' CiviCRM with fake database or other information in settings.php, making everything just fail silently.

In a clean Drupal and CiviCRM install, the CiviCRM module can be disabled without generating any errors.

Getting CiviCRM working in a local development environment that doesn't mirror the configuration of the actual site can be a pain and CiviCRM adds a lot of overhead to page loads and increases the memory required for many tasks, but the steps for resetting the paths and deleting temp files are well documented at http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location

CiviCRM includes handful of Drupal modules that give Drupal access to the CiviCRM data in modules like Views and Rules as well modules that do things like add or remove users from roles based on having paid their membership, but CiviCRM is much more than just those modules.  CiviCRM is a large PHP project (much larger than Drupal core) that runs within Drupal, WordPress, or Joomla's menu and authentication and includes APIs and hooks that allow custom development to tap into CiviCRM at many levels with any of those CMSes.

You could probably get away with a "dummy" CiviCRM install if the site hasn't done much customization to CiviCRM or written any custom code that leverages it, but if disabling CiviCRM "throws a bunch of errors on various places" my guess is you are working with an instance of CiviCRM that has already been customized and integrated.  You'd have to share the specific errors for anyone to confirm that.  As soon as anyone added a custom field to one of the CiviCRM data types (profiles, contributions, events, etc), that fields could be used in a View.  If a custom field is already used in a View, you have to get the client's copy of CiviCRM running or risk deleting a CiviCRM reference when updating a View.

While CiviCRM isn't Drupal, it isn't rocket science either.  If you aren't sure what customizations and integration have been done, it is much safer to get CiviCRM working than trying to disable it.


Migrating body text from 7 to 8, markup displays until edited and saved I'm migrating nodes and have run into a problem with the text formats when mapping our old site's input formats to the new site's input formats. (We're simplifying!)

Relevant yaml:

  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: static_map
        bypass: true
        source: body_format
        map:
          'plain_text': basic_html
          'basic_tags': basic_html
          'minimal_formatting': basic_html
          'filtered_html': basic_html
          'extended_tags': full_html
          'full_html': full_html

When I run this, all the content and formats are imported correctly, but the nodes all display the markup on the page until each node is edited and saved.

What could be causing this and how might I go about fixing it?

source: body_format

should have been

source: format

Turning off "bypass: true" let me see that it was just dumping them in with NO input set, opening and saving changed it to the default for that field.


breadcrumbs not displaying correctly for views I'm pretty new to the world of drupal so I'm hoping this will be a quick fix.

Anyhow here's the situation:
my breadcrumbs work correctly when hitting a node for example when i go to "contact" it prints out home > contact.  Now I have a view and when I go there things look ok. I go to events and it prints out home > events > view all. When I go to a subview like "tech events" however it spits out home > events > events > view all.

The code below is what is currently in place so I was wondering how to alter it to handle views or if anyone could point me to a good solution.

thank you

my code:

function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {

    $output = '

';
    $output .= implode('

', $breadcrumb);

    if( $currentTitle ){
      $output .= '

';
      $output .= $currentTitle;
    }
    $output .= '

';

    return $output;
  }
}

any help would be awesome guys. thank you.

Okay so it still needs some work to be a little more generic but this basically handles the case. It checks to make sure that the content-type is not a node we check to see if there's an additional argument and append that to the breadcrumbs. if it is a node we just print out hte breadcrumb trail checking to make sure that we don't repeat things. If you use a page jump, fragments, or redirects you might get a repeat, i.e. home > stories > stories.  So here it is.

function custom_breadcrumb($variables) {
  $currentTitle = "";
  $trail = menu_get_active_trail();
  $currentNode = array_pop($trail);
  if( $currentNode ){
    $currentTitle = $currentNode['title'];
  }

  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $lastCrumb = NULL;

    $output = '
' . t('You are here') . '
';

    $output .= '

';

  for ($i = 0; $i < count($breadcrumb); $i++) {
    $curCrumb = strip_tags($breadcrumb[$i]);
    if ($i == 0) {
      $output .= $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    } elseif (strpos($breadcrumb[$i], $lastCrumb) === false) {
      $output .= '

' . $breadcrumb[$i];
      $lastCrumb = strip_tags($breadcrumb[$i]);
    }
  }

  if (arg(0) != 'node' ) {
    $output .= '

';
    $output .= arg(1);
  } elseif( $currentTitle ){
    $output .= '

';
    $output .= $currentTitle;
  }
  $output .= '

';

  return $output;
  }
}


Drupal Webform Radio button slider? I have created a webform in Drupal. It has a pagebreak after every question.

What I want to achieve is the following: When someone clicks on a radio button, the next question should slide up without the user clicking the next page button.

I have tried with theming, but I am not very experienced with Drupal, PHP, or jQuery.

This is the link to my webform.

You can add to your page something like

<script>
(function ($, Drupal, window, document, undefined) {
  $(document).ready(function() {
    $('.form-radio').click(function() { $('#edit-next').click(); });
  });
})(jQuery, Drupal, this, this.document);
</script>

This is better done by adding a .js file via drupal_add_js(). Be aware that, since you are forcing your user to submit a form, you should provide a way to get back and resubmit a different choice.


Controlling block page display options programatically On block configuration page we can control the display of the block on three factors:
1. All pages except those listed
2. Only the listed pages
3. Pages on which this PHP code returns TRUE (experts only)

how can it be done programatically in my module file?

i solved it by giving configuration in hook_block_info function

function hook_block_info(){
    $blocks = array();
    $blocks['appendices_page_options'] = array(
        'info' => t('Appendices Page Options'),
        'status' => TRUE,
        'theme' => 'MY_THEME',
        'region' => 'MY_REGION',
        'weight' => 0,
        'visibility' => 1,
        'pages' => "aboutus/*",
        'custom' => FALSE
    );

    return $blocks;
}


How to show RSS icon for a views feed? I created a feed for one of my views. I was under the impression that Drupal would automatically display an RSS icon on a view that has a feed?
I see that page.tpl.php prints an icon:

However, I'm not seeing the icon. What am I missing?

You need to attach your Feed display to one of your Page displays (within the same view).

To do this, in Feed settings click on Attach to: None and tick one of previously created Page displays (or create one first if you haven't already done so). Only then the RSS icon will be displayed on the page your feed is attached to.

Here's a screen shot for anyone who (like me) can't see the wood for the trees.


Crumbs is not showing parent of taxonomy term I’m using Drupal 7.5.2 and am attempting to use the Crumbs module (version 7x-2.5) to show parent and child paths in the breadcrumbs trail and it’s not working.

My URL alias structure—which I am attempting to recreate in the breadcrumbs—is as follows:

My Great Node Pile: A view page that is neither taxonomy term or a node.
Category: A view page that is connected to the parent taxonomy term.
Category Child: A view page that is connected to the child taxonomy term.
Node: The node associated within that parent category and child category.

Only one category—child or parent category—can be associated to a node at any given time.

My “Entity Parent” settings for all node content types is as follows; note all content is based in the path of my-great-node-pile/ which is a stand-alone view that is simply the “home base” for this stuff; it is neither a taxonomy term parent item or a child item:

my-great-node-pile/[node:field_category:parent]/[node:field_category]

So if I have a node that resides in the aliased area of “My Great Node Pile” titled “Cool Stuff” that has this parent/child taxonomy term URL structure; using Pathauto for that so do not take this pseudeo-example 100% literally:

my-great-node-pile/field-category/field-category-child/cool-stuff

Then I would expect my breadcrumb trail to be this:

My Great Node » Category » Category Child » Cool Stuff

But with the default Crumbs settings, this is the bizarre breadcrumb trail I am getting:

My Great Node » Category Child » My Great Node » Cool Stuff

What? If the entity parent is [node:field_category:parent]/[node:field_category] then why is it apprarently rendering as [node:field_category]/My Great Node?

Example Note: The names of items here—including tokens—are neutralized to protect anonymity of the project, but I assure you all tokens and examples here are proven to have the values they should have via the output of the Devel (version 7.x-1.5) module.

After spending more time than I wanted to to dealing with this—exploring solutions and Googling seemingly forever—I came across this post on the official Drupal site titled “Crumbs not working” and specifically this answer from ‘donquixote’ which states:

  are these system paths or node aliases? If they are node aliases, do you have the "path" plugin enabled? (*)

Okay, so that seems like an idea. So I went into the Crumbs settings area under “Structure > Crumbs” and dragged the path setting—which describes itself as “Chop off the last fragment of the path alias, consider the result as the parent path.”—from “Disabled by default” to the second position of “Enabled” (see attached screenshot), hit “Save configuration” and… et voilà… It works! Parent and child taxonomy terms are being rendered in the breadcrumb path as expected.


How can I get the first character of the node title? In the node--my-content-type.html.twig, I want to add the French indefinite article to the title, which depends on the first letter of the word to which the article is added.

Banane => de Banane
Orange => d'Orange

So based on the Twig documentation, I'm trying to use one of the following code lines.

{% if label|first|lower == o %}

{% if label|slice(0, 1)|lower == o %}

{% if label[:1]|lower == o %}

None of them work.

How can I get the first character of the node title?

You could try this code:

/**
 * Implements hook_preprocess_HOOK().
 * @param $variables array
 */
function TEMPLATE_preprocess_node(&$variables)
{
  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['node'];
  $title = $node->getTitle();
  if(_isFirstCharIsVowel($title)){
    $variables['title_addition'] = "D'";
  }else {
    $variables['title_addition'] = "De ";
  }
}

/**
 * Check if the first character is a vowel
 * @param $string string
 * @return bool
 */
function _isFirstCharIsVowel($string){
  $vowels =
    'aàáâãāăȧäảåǎȁąạḁẚầấẫẩằắẵẳǡǟǻậặæǽǣ' .
    'AÀÁÂÃĀĂȦÄẢÅǍȀȂĄẠḀẦẤẪẨẰẮẴẲǠǞǺẬẶÆǼǢ' .
    'EÈÉÊẼĒĔĖËẺĚȄȆẸȨĘḘḚỀẾỄỂḔḖỆḜ' .
    'eèéêẽēĕėëẻěȅȇẹȩęḙḛềếễểḕḗệḝ' .
    'IÌÍÎĨĪĬİÏỈǏỊĮȈȊḬḮ' .
    'iìíîĩīĭıïỉǐịįȉȋḭḯ' .
    'OÒÓÔÕŌŎȮÖỎŐǑȌȎƠǪỌØỒỐỖỔȰȪȬṌṐṒỜỚỠỞỢǬỘǾŒ' .
    'oòóôõōŏȯöỏőǒȍȏơǫọøồốỗổȱȫȭṍṏṑṓờớỡởợǭộǿœ' .
    'UÙÚÛŨŪŬÜỦŮŰǓȔȖƯỤṲŲṶṴṸṺǛǗǕǙỪỨỮỬỰ' .
    'uùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự'
  ;
  // set necessary encodings
  mb_internal_encoding('UTF-8');
  mb_regex_encoding('UTF-8');
  $first = mb_substr($string, 0, 1);
  $vow = mb_ereg_replace('[^'.$vowels.']','',  $first);
  return !empty($vow);
}

This can be used in your .theme or .module file.
This of course will act on all nodes, so you need to add your type checking.
The _isFirstCharIsVowel function can be in a service, I placed it here for simplicity

UPDATE
Credits for vowwl detectioon goes to this https://stackoverflow.com/questions/14268970/how-to-detect-and-echo-the-last-vowel-in-a-word


What does "attach to content type" option in Feeds importer do? I am struggling to find a clear explanation of what the "attach to content type" field in the basic settings of a Feeds importer actually does. The closest explanation I can find is from here:

"Feeds importers" can be used attached to a content type or on
standalone forms. If attached to a content type, an import (or
aggregation) is created by creating a node. This is e. g. useful when
you would like your users to contribute feeds or when you need to
track many feeds of data of the same kind.Alternatively, a Feeds
importer can be used on a standalone form. This is useful for one-off
imports like importing nodes.

I don't understand what this explanation means. Would be grateful if someone could explain what setting this "attach to content type" option actually does.

Yeah - I found this confusing as well.

Personally, I always select "standalone" which means that when I'm ready to import nodes with an importer I've created, I go to the path /import (e.g., http://example.com/import)

On this screen, I can select my importer and then launch the actual import (the one I created under /structure/feeds).

If you decide to attach to a content type instead, it just means that you go to /content/add/[content type] to launch the import process rather than /import. This way just never made sense to me conceptually, but there are probably good reasons to use this approach. Probably depends on who (which roles) you want to be able to use feeds imports.

Anne


Unable to set #default_value for a date field I have a form with a date field.

$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
    '#default_value' => [
        'year' => 2015, 'month' => 05, 'day' => '09',
    ]
];

But when the form is displayed the date field doesn't contain the value "09.05.2015". The date field is empty.

Could you clarify me, how can I fill the date field with the value ?
I watched it as on my form as on the examle form from the Examples module.

Set it like this

$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
       '#default_value' => [
        '2015-05-09',
    ]
];


How can I make a node title input form in a block? Im on d7. I want to have a block on the landing page of my site that has a "enter your title here" input field. When a user enters something in it and clicks continue, they are directed to the node submission form and the title field should be populated with what they had just entered. How would I put something like his together?
Thanks?

Use the Prepopulate module, there is an example on the docs for pre-populating the title field. All you need is to have a simple form that appends your $data to this path:

/node/add/yourcontenttype?edit[title]='.'$data'


How to create a Search API search box that redirects you to the search page I am using Drupal 8 and the Search API. I have created a search page using the API and views (basically modified the view that came prebuilt when you install the search API). Everything works as expected when you are on the search page doing a search.

The problem I am having is that I would like to create a search block identical to the one the default Drupal Search creates with the same behaviour. Meaning that when you enter a search term, it redirects you to the search page displaying the search results. I can't figure how to do this (assuming it is possible to do so).

I have created a search block but it wants to display the results of the search in the block itself. I don't know how to make the search block redirect to the search page.

I know when using the default search block you can implement the following hook:

function mytheme_search_box_form_submit($form, &$form_state) {
   $form_state['#redirect'] = 'path of redirect';
}

Is there something similar for the Search API?

There was a similar question for Drupal 7 Expose a view's filters both in a block, and in the actual view. In Drupal 8 this should be much easier, you can do this in UI:

Place the block Exposed form: search_content-page_1 a second time, now in the region Content above the block Main page content and configure the visibility to show only on pages with the path /search/content.


How to implement a booking system using Drupal Commerce for checkout? I have been playing with Rooms, Availability Calendars, commerce availability, and many other modules to achieve my goal but I have had no luck in trying to achieve exactly what I want to do.

Does anyone know of the best solution to achieve the following:

A holiday home booking system where users can search node teasers via available dates and checkout via Drupal Commerce.
Views integration: Search nodes on available dates
Checkout: be able to choose a date range from available dates and checkout through Drupal Commerce.

You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).

Here are some more details about this distribution (quotes from its project page):

  ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.

  It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
  Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.

Note: for some other module suggestions that might possibly help, refer to my answer to the question "https://drupal.stackexchange.com/questions/173341/how-to-create-this-reservation-form-in-drupal/173467#173467".


How to add a slideshow inside a node with Slick? I created a Content Type with an Image Field that could take multiples images.
I would like to display a slideshow of these images.
So for each node of this Content Type, I would have a different slideshow, directly inside the node.
On Drupal 7, there is the Field Slideshow module that seems to do that, but I'm on Drupal 8.

So I installed Slick Carousel and Slick Extras so I can use the formatter called Slick Image for my multiple images field.
But there are many options and I can't find the correct ones to have the slideshow working.

Here are the options :

Can anyone give me the right options ?

The problem comes from an incompatibility from the theme I use, Zircon, with Slick carousel.
The full explanation and the solution can be found here : https://www.drupal.org/node/2875173#comment-12075392

In brief, the solution is to comment the following lines in zircon.libraries.yml with the # sign :

# assets/includes/slick/slick/slick.js: {}
assets/includes/bootstrap/js/bootstrap.js: {}
assets/includes/flexslider/jquery.flexslider.js: {}
assets/includes/flexslider/jquery.flexslider-min.js: {}
assets/js/slideshow.js: {}
# assets/js/carousel.js: {}

This file is in /themes/zircon/ folder


How can I insert a variable from a preprocess function in template.php to Block Body in admin Seems like a pretty easy thing to do, but I am having a hard time in using a variable from function theme_preprocess_block(&$variables, $hook) in template.php in a Block body in admin.

For example, in template.php, I have:-

function theme_preprocess_block(&$variables, $hook) {
  $variables['theme_url'] =  base_path().drupal_get_path('theme', variable_get('theme_default', NULL));

}

From here, I want to use theme_url variable in Block Body in admin as shown:-

It's not happening through the shown way. Any idea how I can achieve that?

Thanks.

You can't do that.

The block content doesn't ahve access to variables you add in the block preprocess function.
The block preprocess function code runs after the block content has been generated.

Since you have a PHP block just add that code from your preprocess function directly to it.

So put this at the top of your block content:

$theme_url = base_path() . drupal_get_path('theme', variable_get('theme_default', NULL));


Showing term description on terms page that are displayed using views I am currently using a view to override Drupal's core taxonomy pages. Unlike the core handling of taxonomy pages, views does not display the current term's description. Is there a good way to display a term's description through views or would I need to make a template file for the view?

1: Create a view much like this one (It is a term view using the term ID as a contextual filter then showing an unformatted list of the description field):

$view = new view;
$view->name = 'catalog_taxonomy_term_descriptio';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Catalog Taxonomy Term Description';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Catalog Taxonomy Term Description';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Taxonomy term: Term description */
$handler->display->display_options['fields']['description']['id'] = 'description';
$handler->display->display_options['fields']['description']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['description']['field'] = 'description';
$handler->display->display_options['fields']['description']['label'] = '';
$handler->display->display_options['fields']['description']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['description']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['description']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['description']['alter']['external'] = 0;
$handler->display->display_options['fields']['description']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['description']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['description']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['description']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['description']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['description']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['description']['alter']['trim'] = 0;
$handler->display->display_options['fields']['description']['alter']['html'] = 0;
$handler->display->display_options['fields']['description']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['description']['element_default_classes'] = 1;
$handler->display->display_options['fields']['description']['hide_empty'] = 1;
$handler->display->display_options['fields']['description']['empty_zero'] = 0;
$handler->display->display_options['fields']['description']['hide_alter_empty'] = 1;
/* Contextual filter: Taxonomy term: Term ID */
$handler->display->display_options['arguments']['tid']['id'] = 'tid';
$handler->display->display_options['arguments']['tid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['tid']['field'] = 'tid';
$handler->display->display_options['arguments']['tid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['tid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['tid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['tid']['not'] = 0;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'catalog' => 'catalog',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'catalog-taxonomy-term-description';

2: Go into your taxonomy term view (I'm assuming you have already edited/overridden this) and set the Header in the Page Settings section to Global: View area. In the settings for that you will be able to select your view description view. This will cause the term description to show up the top of the page while displaying the related nodes below it.


Redirect anonymous user to login in custom module In a custom module, I'd like to redirect anonymous users to the login page. After a successful login the user should get to the page he intended to see.

I tried the following code. This gives me the login form, but the user is never sent to the destination page. Instead the standard user page gets displayed.

if (!$user->uid) {
    $dest = drupal_get_destination();
    drupal_goto('user/login', $dest['destination']);
}

Any ideas how to fix that?

Have you tried drupal_goto('user/login', array("query" => array("destination" => $dest['destination'])))?


How to get rid of Re geocode and delete radio boxes on Location module? How can I remove the ReGeocode and Delete checkboxes from the Location module? I don't need these functions and there is no settings to delete them.

Where is the PHP or html file located so I can manually delete the lines of code? I searched for it but can't find it anywhere.

<label for="edit-locations-0-re-geocode-location">Re geocode </label>

<label for="edit-locations-0-delete-location">Delete </label>

I think these are the lines I need to delete?

There isn't a template to edit the location module's form elements. You'll need to alter its form element. You can drop the following functions into a custom module to alter the form element so that it doesn't display the Recode/Delete checkboxes.

function MYMODULE_element_info_alter(&$type) {
  if(isset($type['location_element'])) {
    $type['location_element']['#after_build'][] ='MYMODULE_location_element_post_render';
  }
}
function MYMODULE_location_element_post_render($element, &$form_state) {
  $element['delete_location']['#access'] = FALSE;
  $element['re_geocode_location']['#access'] = FALSE;
  return $element;
}


Changing the format of drupal pagers numbers Currently the dupal pager displays numbers normally as 0 1 2 3 4, how do i change this format to something like 01 02 03 04

There is a theme_pager function in drupal which help you to format pager. However i am not sure it can change the number from 1 to 01.

But, You can achieve this style with few lines of jquery. I am not proficient in jquery bu t a rough code is given below which may help you

(function($){
    function pad (str, max) {
        return str.length < max ? pad("0" + str, max) : str;
    }
    $( ".pager li" ).each(function( index ) {
         var number = $(this).text();
         if(number < 10){
           var new_number = pad(number, 2);
              if(($(this).attr('class')) == 'pager-item'){
                $(this).children().text(new_number);
              }else{
                $(this).text(new_number);
              }
          }

    });
})(jQuery);

The output


Managing Fields Tips My database is getting way out of hand with respect to field_data... and field_revision...

is there any tricks in managing fields, seems really odd design method to me, I have over 100 tables just for fields alone.

I have tried to reuse the same field multiple time, but you cant use the same field more than once in the one content type.

ideally i would just have a field for each different data type and not every single field.

How exactly is it going out of hand? Unless you have some kind of maximum number of tables you're allowed to have, 100 tables aren't really a problem. It's like this because this is the only way support multiple values per field.

The field storage system is pluggable, you can for example also use MongoDB to store your fields. The advantage of that is that it can store a complete content type in a single "document" and retrieve it with a single lookup/fetch. The downside is, you have to manage/maintain a second database server (and be able to so, which you aren't on shared webhosting for example).

See also The truth about field storage in Drupal 7. As linked from there, there is also a Per bundle storage project, but development stopped. Looks like nobody cares enough about this to maintain that module.


Is there a way to get all values for a particular node? I would like to create a customized view and search page by writing my own module because I believe that Views is unable to do what I want.  This requires me to write my own SQL queries, as well.  Is there an API call I can use to get all the data and values about a specific node?  For example, if I had a content type that asked for your first name and last name:

$values = get_node($nid)

and $values would end up looking something like:

$values['first_name'];
$values['last_name'];

Right now, it seems that all the fields and values are in their own tables, which makes it a nightmare in writing my SQL query to gather all data about the particular node.

You can use node_load() function.

eg:

 $node = node_load(nid); //you will get all fields values of particular node
 print_r($node);


How to add delete button to file field upload widget that actually deletes the file (not just association with content)? After uploading a file with the File widget for the File field, the file is on the server and remove only disassociates the file from the field (and the content that the field belongs to).

I would like to add a button to actually delete the file. I've considered a number of options:
- via hook_form_alter - but unsure as to what to insert into the $form or $form_state array for the content edit form, regarding new array elements and at what position
- by providing a theme .tpl file (based on what devel_themer suggests - tried a few possibilities by the themes did not 'fire' (execute)
- making use of the API in https://www.drupal.org/project/extended_file_field to write a hook or otherwise in a custom module

Which of the above would be the standard programmatical approach for extending the file widget to provide direct deletion of the file?

Update
I set my debugger to fire on the function file_managed_file_submit($form, &$form_state) that Geoff mentioned. On clicking the Remove button to the right of the file...

The function file_managed_file_submit($form, &$form_state) is called BUT the status is not zero, so the if fails and the delete does not happen - see debug screen below showing all of this:

This commenter has also seen the problem it seems: how to delete the files uploaded in the file field?

Update 2
I think I know what's going on: We have Workbench Moderation on the site. So, it would make sense to not delete the file but rather the remove just disassociates the file from the Current revision of the content. This makes sense if in previous revisions, they did actually need to refer to the file. So by keeping the file present means those previous revisions "integrity" is intact in that they still refer to the file and the link is not broken. So in summary this is 'as design' I think. Thoughts?

(There is a way to properly delete the file through admin/content/file)

The file should be deleted, if it isn't there is something going on. When a submit button fires, file_managed_file_submit($form, &$form_state) is triggered:

// No action is needed here for the upload button, because all file uploads on
  // the form are processed by file_managed_file_value() regardless of which
  // button was clicked. Action is needed here for the remove button, because we
  // only remove a file in response to its remove button being clicked.
  if ($button_key == 'remove_button') {
    // If it's a temporary file we can safely remove it immediately, otherwise
    // it's up to the implementing module to clean up files that are in use.
    if ($element ['#file'] && $element ['#file']->status == 0) {
      file_delete($element ['#file']);
    }
    // Update both $form_state['values'] and $form_state['input'] to reflect
    // that the file has been removed, so that the form is rebuilt correctly.
    // $form_state['values'] must be updated in case additional submit handlers
    // run, and for form building functions that run during the rebuild, such as
    // when the managed_file element is part of a field widget.
    // $form_state['input'] must be updated so that file_managed_file_value()
    // has correct information during the rebuild.
    $values_element = $element ['#extended'] ? $element ['fid'] : $element;
    form_set_value($values_element, NULL, $form_state);
    drupal_array_set_nested_value($form_state ['input'], $values_element ['#parents'], NULL);
  }


Linking to a homepage when Drupal is located in a Directory I have a problem with creating a proper link to the homepage of my website. I would like this code to redirect to my homepage:

Unfortunetaly it doesn't work, because it brings me to the homepage of my whole server and drupal is located in a subdirectory of the server. I tried to do this using php:

<a href="<?php print ('<front>');?>">

but it doesn't work too. When i click on the image it appears:

  Page not found The requested page
  "/drupal7/drupal-7.23/en/%3C?php%20print%20(%27%3Cfront%3E%27);?%3E"
  could not be found.

You should use url() function to generate a page URL. For the frontpage it is:

<a href="<?php print url('<front>'); ?>">YOUR LINK

If the generated links using the url() function are not correct, you can change the $base_url variable in the settings.php

$base_url = 'http://www.yourwebsite.com/drupal7/drupal-7.23';


Why I cannot export vocabulary terms via Features? Ok, I've installed features, uuid, uuid_features.

According to docs vocab terms shouls be exported too when creating taxonomy feature.

So I run a command:

  drush fe my_feature taxonomy:tags

but every time inside feature there is no such thing like terms. Only vocabulary is exported. What I am doing wrong?

From code review I see that only hook_taxonomy_default_vocabularies is implemented.

You need to use the module uuid_features.

It is both possible to export individual terms by listing the ones you want or you can export all terms with the vocabulary:

Enable uuid_features
Go to admin/config/content/uuid_features
Check the boxes of the Vocabularies under "Exportable Taxonomy term bundles"

If you want to export all terms then check the "Auto detect uuid terms" option, so future additions / changes will be added.

If you didn't select the "Auto detect uuid terms" option: Do a drush fc and you will see a new item "uuid_term", get the list of components and do a drush fe FEATURENAME uuid_term:THETERMSUUID1 uuid_term:THETERMSUUID2 (gets really long, hence the "Auto detect uuid terms" option)
If you selected the "Auto detect uuid terms" option: you just need to export the taxonomy so do a  drush fe FEATURENAME taxonomy:VOCABNAME

Sorry about the odd bulletted list, trying to represent two options in one list.


CCK field related to non-drupal table columns I need to define a CCK field that contains data from a non-Drupal table called Customers; i would like the field to show the list of Customers and saving the id_customer inside the node. Is there a way to do it without having to create Customers as node?

Well, one of the possible ways to do that is to create a cck field of type integer and use "select list" as a widget. And then in your implementation of hook_form_alter you need to extract data from Customers table and populate the select with this data.

You might find the following piece of code useful:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_CONTENT_TYPE_NAME_node_form') {
    $sql = 'SELECT id, name FROM Customers';
    $result = db_query($sql);
    $options = '';
    while($row = db_fetch_array($result)) {
      $options .= $row['id'] . "|" . $row['name'] . "\n";
    }
    $form['#field_info']['field_YOUR_FIELD_NAME']['allowed_values'] = $options;
  }
}


How to customize the  tag I have downloaded nexus free theme and I want to change the title
in all pages of my site.

Is there a way to do it editing the template.php?

thanks...

If you using D7 and not D8, take a look at page_title module. I just googled it for you.

  The word "title" is a bit overloaded. Every piece of content in Drupal
  has a title, and so does every page. The page title is the one found
  in the HTML head inside the  tag. It is also used on SERPs
  (Search Engine Result Pages) and can greatly enhance your websites SEO
  (Search Engine Optimization).

  This module gives you granular control over the page title. You can
  specify patterns for how the title should be structured and, on
  content creation pages, specify the page title separately to the
  content's title.


How to add an image field to a programmatically created form? Basically I want to create a block with my module which's edit page has a few content fields and two image upload fields. When visiting the node where this block is rendered, I want to render the images with a certain image style, while on the edit form it would be cool to show the images as a thumbnail preview.

I am adding a field like described here: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file but this makes me curious:

  New files are uploaded with a status of 0 and are treated as temporary
  files which are removed after 6 hours via cron. Your module is
  responsible for changing the $file objects status to
  FILE_STATUS_PERMANENT and saving the new status to the database.

Also, what is the difference of managed_file and file when I want to provide an image upload field?

Currently I have in hook_block_configure:

$form['left']['image'] = array(
        '#type' => 'managed_file',
        '#title' => 'test',
    );

Where do I define how this image shall be rendered (image style)? Do I have to set that permanent flag?

Thanks

You cannot use fields from the Field API in forms of the Form API directly, as Fields can be used directly in entities, and entities can be used directly with forms.

Instead, you can use the approach described here, as Clive kindly pointed out. Alternatively, you can use ctools_field_invoke_field() function of CTools module too.

The two fields 'file' and 'managed_file' of the Form API are similar, with the difference that the latter provides a progress upload widget. Also, managed_file will add the file entry to a table with the same name. Beyond that, there is some work involved in order to render the file on a page, and that is not the imagefield of the Field API.


What is the difference between _form_validate vs form_validate? I'm unsure which one you should use for a form_validation.

Seeing that _form_validate() starts with a _ makes it a private function following the Drupal coding standards if I'm not mistaken.

So my guess is that a form validation should be done with hook_validate().

But the question remains: what's the difference between the two and where should they be used?

EDIT:
I misunderstood the hook_validate() which is not the _validate "hook" used in the form API. I'll leave the question unchanged so other users can learn from my mistake.

You're totally correct, Drupal's coding standards denote anything with a _ prefix is seen as a pseudo-'private' function. As such the _form_validate() function was never meant to be called directly. Unless you really need to use it, and you're absolutely positive there's no other way to accomplish what you want, I wouldn't advise using it.

In fact only one function in the whole core system calls _form_validate(): drupal_validate_form(). It would stand to reason that you should be using this function instead (being that it's not marked as a private function).

These are the functions that Drupal uses internally to validate a managed form, so if you're using the Form API correctly you should never need to call them. Adding validate handlers to a form to validate individual elements is the correct way to do things.

Just to clear up a wee bit of terminology as well, hook_validate() has nothing to do with the form API as such; it's used by node-providing modules to validate nodes before saving. The validation handlers that you add to forms (with custom forms, or through hook_form_alter(), don't have a particular 'Drupal name' that I'm aware of.

Also, you don't actually even need to use the standard named _validate function if you don't want to...you can add a function with any name as a form validate handler:

$form['#validate'][] = 'my_strangely_named_function';

Drupal just looks for FORMNAME_validate() by default, and runs it if it exists.


How to view nodes that only you have published? I need to be able to incorporate into my system a method for which users can view nodes that only they have created.  How can this be done?

I've found the content_access module to be pretty helpful for this kind of thing.

Just enable this on the content type you want to control, and make sure that "view any content" is unchecked for authenticated users, and that "view own content" is checked for authenticated users.


View module diplaying wrong content type extra I am having a problem with the views module in Drupal. Everytime I add a new content type, views will display an other content type. I have tried different things, but I can't figure it out. Any help will be appreciated.

Here is the link:
http://carlosgandara.com

Here is my view settings...
Quotes is the only content type that I want to display.

Here is the quote block, but every time I add an other content type. For some reason, it replaces the content with the other content type.

You need to set up a filter - filter by content and choose the content type you want to show or use a contextual filter(advanced settings) to show only the content type you want to show. Right now youre not filtering so your view is set to show all content types.

In the example below I have a relationship of author. I have a contextual filter set up with this relationship so that it will only show content with this relationship and finally i have a filter that only shows content types of the kind flashcard and only the content where the logged in user is the author of the content.

There is a great set of tutorials about views here at nodeone


Drupal won't validate required field when disabled I have a content type with required field in it.
If the field is disabled then Drupal won't verify it. (it is being verified if not disabled).
How can I verify that the field has a value even if it's disabled?

More details:

For some of the users I set the value by Prepopulate and disable the field (by implementing the hook hook_form_alter).

I still want to prevent the user from messing with the URL.
For example: he can take the "new content" link I've created for him that looks like:

/node/add/my_type?edit[field_to_set]=12

and remove the URL query:

/node/add/my_type

I thought that if he would do it, he won't be able to save the form because of the required field (which is disabled) - but Drupal won't verify it.

According to the API docs of _form_builder_handle_input_element disabled fields are ignored, you can try using #access instead.

You can try adding your own handler after that of prepopulate and check if a (valid) value is entered, if not redirect the user or display a message

function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  $form['#after_build'][] = 'MY_MODULE_prepopulate_after_build';
}

function MY_MODULE_prepopulate_after_build($form, &$form_state) {
  // check #value
  if (empty($form['field_to_set'][0]['#value'])) {
    drupal_set_message ('You altered the URL', 'error');
    drupal_goto ();
  }
  // if #value is set, set #default_value as well
  if (empty($form['field_to_set']['und']['#default_value'])) {
    $form['field_to_set']['und']['#default_value'] = $form['field_to_set']['und']['#value']
  }
  return $form;
}


How to create multi login pages I have enabled the "User Login" block inside the Content Region and configured it to show on two specific Views which should be password protected.

I have also created two Views and two different access roles for each view.

After I access the password protected pages as anonymous user, I can see both Login screens  and authentication on one page works but refreshing the second page shows:

Access denied
You are not authorized to access this page.

Also if I authenticate on page A with login for page B, I get the same message but refreshing page B shows the content.

Could this be a cookie related issue, because I have to clear my browser cookie to logout. Does Drupal only allow one login cookie?

I tackle this with Panels.

Instead of having a view as a page, I make a new Panel page.  Then I add two variants.  For authenticated users, the content has the view, normally configured as a separate panel-pane display.  For anonymous users, the variant just has the login block and sometimes a custom content pane that has a brief message.


Update Entity Reference field programmatically I'm kind of new to Drupal development and I'm a little lost on something I'm trying to do:

My company has several locations and I am developing a method whereby each location can have their own page on my company's website.

I want location managers to be able to log in and post news articles about their respective locations and have those articles appear on the appropriate location page.

I have content types set up for 'Location' and 'Site Articles'.  'Site Articles' has a 'Location' field that is a reference type back to Location.

In an effort to restrict the ability of various site managers to select a location that is not theirs, I am using hook_form_alter() to adjust the 'Location' entity reference in the 'Site Article' content type that reads what Site a manager belongs to in their User Account Settings, and adjusts the form so that ONLY the managers site shows up.  That code looks like this:

function smg_site_articles_form_alter(&$form, &$form_state){
global $user;
$account = user_load($user->uid);
if(!empty($form['field_site_news_article_location'])){
     $entity_node = node_load($account->field_user_location['und'][0]['target_id']);
     $form['field_site_news_article_location'] = array(
      '#title' => 'location',
      '#type' => 'select',
      '#options' => array(
          0 => t($entity_node->title)
        ),
      '#default_value' => $entity_node->title);

The problem that I'm running into is when I save the Article, the "Location" entity reference does not get populated and I can't add Views filters to it the way that I want.

I'm assuming the problem lies with how I'm altering the 'Location' entity refernce field in hook_form_alter(), but I'm a little lost as to how I get the data updated correctly.

Can anyone help??

Fields in forms are fun, there's some info about those here

To summarise, the element you're looking to alter will be something like

$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id'];

Rather than replace the whole thing it would be wiser just to replace the existing options array, but that'll need a small change as well.

Select options are key => display, so if you use 0 as the key, it won't match up with anything on the backend (namely a node ID in this case), and the form won't save properly. Similarly the #default_value is expecting the key rather than the node title.

Something similar to the following should do the trick:

...
$options = array($entity_node->nid => $entity_node->title);
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
$form['field_site_news_article_location'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;


How do I rename a field name of a table? I need to rename one of my fields in a table via a .install file. How can I to do this ?

Let us consider I have a table called "register" and field name called "fname". Now I need to change the field name "fname" to "name". How can I do this using a .install file?

We can add a field for a table using the below syntax :

db_add_field($ret, 'table_name', 'field_name', array('type' => 'varchar',
             'length' => 255, 'not null' => TRUE,));

What is the syntax for doing a field rename?

Using db_change_field.

Under the parameter section:

  $field Name of the field to change.

  $field_new New name for the field (set to the same as $field if you
  don't want to change the name).


How to use wysiwyg text editor (text_format) in a system configuration form I couldn't find any documentation or examples about this. The implementation is very problematic. Do you a means to do this?

Problems

While trying to create a system settings form with text_format input, I get following errors while displaying the form. The form is being submitted normally and the values are being saved but when the page refreshes the text editor is not populated with the saved values and the errors are always there.

  User error: "value" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php).

  User error: "format" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php).

The code in buildForm() is as follows:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('commerce_distance_terms.distanceterms');
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#description' => $this->t('Title for the terms'),
      '#maxlength' => 64,
      '#size' => 64,
      '#default_value' => $config->get('title'),
    ];
    $form['distance_selling_terms'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Distance Selling Terms'),
      '#description' => $this->t('Enter Distance Selling terms'),
      '#default_value' => [
        'value' => $config->get('distance_selling_terms.value'),
        'format' => $config->get('distance_selling_terms.format'),
//         '#tree' => FALSE,
        '#printed' => TRUE,
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

Background information

This is the error as it links from the code.
The errors are thrown because of the #default_value part of the array. Adding a #value => array() reduces the errors. But nothing changes.
What I got from the stacktrace is that the form is being rendered, then the textarea is being rendered, and then the source of the error is being rendered (There are small elements inbetween). So I think the source of the error is the #default_value element of the textarea which is copied and pasted from the above array part while the compound text editor is being created.
In one of the rendering iterations, the Element::children() thinks that it should render the value and the format elements of the above array. Since they don't start with #.
There is a word here that system settings form doesn't support text_area input from Drupal 7. Also that and some linked issues tell that there are some automatic defaults for system_settings_form but I couldn't find the equal.
The text_format input is a compound element that includes a textarea (to hold and populate the actual value), a dropdown format element to select from, etc. The textarea element comes with the exact #default_value that I put above (as an array). I tried to preprocess this textarea and change that value to the related string to populate the field but whatever I do textarea comes always empty.
The #printed and #tree elements of the array don't change anything. I also put them inside the textarea array in the preprocess function but nothing changed.
The textarea's data-editor-value-original property comes with the above array flattened even tough I change the #default_value and #value in the preprocess.
The text editor not being able to be populated may not be related to above errors. I know nothing.

$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
];

And if you want to limit the wysiwyg editor to only the one format, add #allowed_formats as in:

$form['distance_selling_terms'] = [
  '#type' => 'text_format',
  '#title' => $this->t('Distance Selling Terms'),
  '#description' => $this->t('Enter Distance Selling terms'),
  '#default_value' => config->get('distance_selling_terms.value'),
  '#format' => $config->get('distance_selling_terms.format'),
  '#allowed_formats' => [
    $config->get('distance_selling_terms.format') => 'Description of format'
  ],
];


Views support for custom entity with base table in seperate database I have a custom content entity that has been setup with several properties declared. This was really nothing special, just a standard entity representation of data from a custom table in the Drupal database. Everything worked as expected (CRUD operations, views integration, etc.).

This was initially just a test however. The table behind this entity needs to live in a separate MySQL database. This database will be on the same sever as the Drupal database, but must be managed independently with write operations initiated from separate platforms. To attempt this I simply modified the relevant part of the entity annotation from:

base_table = "mytable",

To:

base_table = "mydb.mytable",
persistent_cache = FALSE,

The first line declares the base table inside the separate DB (also discussed here) and the second line bypasses local entity caching so fresh data is always displayed in Drupal (also discussed here). For the most part this also works great and seems fully compatible with Drupal's entity API (CRUD operations still work as expected). The issue is that views integration now fails. I can still create a new view based my content entity, but no properties are available (not even the base ID). If I attempt to alter a view created before changing the annotations all properties result in broken handlers and query errors, in the same manner as describe in this question (which is similar, though related to the prefixing of the base table, not fetching it from a separate database).

There are certainly projects in the contrb space that attempt to integrate views with external/remote data, and I always have the option to use search_api as an intermediary between my custom content entity and views, but I'd like to see if there is a native Drupal 8 core solution for this. Given that the main entity APIs appear to support entity data from another database just fine I was hopeful views support would be implied. Are there alterations required to my entity delcaration (perhaps something in the extended \Drupal\views\EntityViewsData object for my custom entity) to get this working?

Further research has led to the conclusion that this is a current limitation in views. Special characters are not escaped correctly in table names, specifically the "." separator notation in dbname.tablename. It could be framed as a bug depending on what sources views officially supports in core. I've opened an issue with more details:

https://www.drupal.org/node/2904787


Is there a module for creating a web directory like Dmoz? I need to be able to organize different sets of content using the taxonomy. The user can visually click through the different layers of the directory and find what there looking for. I want to have full control over the way the categories are arranged and styled.

You could use taxonomy_menu module. It is compatible with D7. You can arrange the taxonomy in whatever style you want and embed it in views/pages/blocks.


URL Redirect created over SSL only works over SSL I have added a redirect via:

  Configuration > Search and Metadata > URL Redirects

While accessing the site via SSL. When I add the link the from box auto fills the root of the redirect with https://myRootURL.com/ :

This redirect works for https://myRootURL.com/redirectedLink but does not work for non-ssl: http://myRootURL.com/redirectedLink. I would expect all of these redirects to be ssl/non-ssl agnostic - and the ones auto-generated by Drupal all seem to be.

Is this a configuration issue - or known problem? I have had no luck with Google or browsing the known issues, but I am not sure I am articulating the problem correctly.

EDIT: I am experiencing the same functionality with URL Aliases as well... what configuration options could impact this?

I am feeling a little sheepish here:

Caching was turned on for anonymous users. When accessing the site as https I was also logged into Drupal, unlike when I was accessing the site over http.

As such the anonymous users were not getting the redirect or alias applied until the cache was cleared. Should have been an obvious first step.


How can I make Search API search field collections? I have a content type called Basic Page with a few fields (title, description, page body), one of which (page body)is a field collection with a field called 'Section Body'. I created a view called Search Page that searches all my content (including other content types), then added my Field Collection Item datasource to my index and added the Section Body field (with type Fulltext) to the Fields section of my index.

After reindexing all of my content, I went to my view and added 'Field Collection Item >> Section Body' to the 'Search fields' section of my Fulltext search option in my view's Filter Options.

To test all this, I added in the unique term 'testterm123' to my content title, cleared the cache, and searched for the term. The test content returned successfully, so I know that the title is being searched for successfully. I repeated this process for description, and that worked as well. However, it did not work for my field collection field Section Body and nothing was returned.

So I'm confident that I indexed everything correctly, but the Field Collection field is not being searched. Has anyone run into this and if so, what did you do to fix it? Does anyone have any ideas on how to fix this or solutions to attempt?

You shouldn't use the field collection module in D8 to begin with, as the project page says

and it also says

Drupal 8
Use Paragraphs and Entity Reference Revisions instead of field collection for Drupal 8 projects.

If you don't make the change now you will have to, in the future, whenever you migrate to D9 as there won't be any D9 version.


How can I disable image resizing in CKEditor? Our site is responsive and when editors use the resizing handles after uploading an image into the editor, it puts in fixed width and height on the image. We don't want them resizing images at all, due to the responsive nature of the site. Is there a way to disable image resizing in the editor?

If I can write a simple Drupal custom module to get the job done, that would be preferable. I can't seem to find any clear instructions on modifying the CKEditor's configuration dynamically in Drupal, though.

According to How to disable the image resize handles ? this is supposedly solved with CKEDITOR.config.disableObjectResizing = true;.

But even when I change it directly (for testing purposes) in /core/assets/vendor/ckeditor/ckeditor.js

CKEDITOR.config.disableObjectResizing=!1 to

CKEDITOR.config.disableObjectResizing=!0
// OR
CKEDITOR.config.disableObjectResizing=1
// OR
CKEDITOR.config.disableObjectResizing=true

It doesn't make a difference, I can still resize.

So I guess you will have to solve this via CSS.

If you want them to still be responsive, you could do:

.some-div img { max-width: 100% !important; }

OR

.some-div img { max-width: 400px !important; }

Obviously, this would mean the size in the editor may not reflect the size on the page, but this will do at least in the meantime if you're not satisfied with this answer/approach.


Block view contextual filters What I want to achieve

I need to create a single view to display latest content of each content type. And I have content type: Article, Basic page.

What I do

I have create a View with a display Block called Latest content by Bundle. In this view, I add Contextual filters Content: Content type. I set When the filter value is not avaiable to Provide default value: Content ID from URL.

I try the view preview, type the value article and it display the articles content. I then go to Block layout, place the block view that I created to a region.

My problem

When I configure the Block view, there are option to select content type, but the dropdown item is empty.

I'm expecting list of content type displayed. Is this correct? Or there are something that I miss?

I don't think you can pass an argument into a block like that.

However, you can do it with page manager.

Make sure AJAX is enabled in your view
Install & enable page manager https://www.drupal.org/project/page_manager
You may need to apply this patch with composer for the following steps to work
Go to structure > pages
Add a new page manager page like this

Skip the next screen (click next)
Set up a context like this

Skip the next two screens (click next)
Add your view block like this

Now go to <your_url>/latest/article and the page should list your articles
You can add other pages/contexts for other content types


Display images of a specific content type in a lightbox when vocabulary is clicked Background
I am using Drupal 7 and I have a taxonomy "Kitchen Type" and content type "Kitchen Picture" having default field_image for images. There are three Kitchen Types Traditional, Contemporary and Transitional. I have more than 10 Kitchen Pictures assigned to each Kitchen Type.

Problem
I have a view at /kitchens (Page 1) that lists three kitchen types and when clicked, lists the Kitchen pictures (another dynamic view) (Page 2). When a picture is clicked a lightbox open up. But,  I would like to have a lightbox open up with kitchen Pictures (including next-back navigation) when any of the kitchen type (traditional etc) is clicked. So, I want to skip Page 2 actually. I have no idea how to go about it. Any help would be appreciated.

Edited
I am afraid I also have a link in the header "Kitchen Portfolio" that supposed to open a lightbox and allows visitor to navigate through all the kitchen pictures. I want to avoid loading all the images on all pages. I need a way out such as when link is clicked it loads the html and start lightbox navigation. I do not know how I can achieve it in Drupal.

I already have lightbox2 installed.

Thanks

If I were you I would create a "Kitchen Type" content type and then edit the image field to allow unlimited amount of images. Then add a taxonomy field to "Kitchen Type" assigning a taxonomy term to each.

Create a new view which pulls all "Kitchen Type" content types and add the Taxonomy Field and Image field to the display. Views allows you to style individual fields by its tpl naming convention. If you go to the "theme" option in that view you will see a set of file names to place in your theme to style individual fields. You will need to style the image field by looping through the image array and output html which conforms to the lightbox2 convention like this:

This should display each set of images for each kitchen type right under it. Once one image is clicked it should open up a lightbox with arrows to go to next image.

Hope this helps or at least points you in the right direction!


restrict user from certain role to change their email Is there any way I can restrict users from certain role to change their email address. Once they are registered I need them no to be able to change it in the edit settings page. I found how to restrict to change the username but not the email.

I am using Drupal 7. Thanks in advanced :)

Another way is programmically in your custom module

function mymodule_form_alter(&$form,$form_state,$form_id) {
   global $user;
    if ($form_id == "user_profile_form") {
       if(in_array('your role',$user->roles) && isset($form['account'])) {
           $form['account']['mail']['#disabled']=TRUE;
          }
      }
 }


Make form to show multiple field widgets with predefined values I have a node form with multivalue field (cardinality unlimited). I need to show user 3 widgets if this field with predefined value (like shown at screenshot).

At screenshots I show the current form, and its desired look.

How can I achieve this result?

You will probably need to build a custom module that calls hook_form_alter() or hook_form_FORM_ID_alter() and insert your required pre-filled values before the form is rendered.

Your function should look something like this:

<?php

/*
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id){
    // Install devel module and uncomment below to see the variables in the form printed on the screen
    // dpm($form_state);

    // Once you know where to put the variables you can add new values to the field array like this
    $form_state['values']['field_something_important'][] = 'First thing';
    $form_state['values']['field_something_important'][] = 'Second thing';
    $form_state['values']['field_something_important'][] = 'Third thing';
}

Note that the actual location to put the values will be different, and might be a few levels deeper into $form_state.

As always when making modules:

Replace the 'hook' part of a function name with the module name (case sensitive)
Make sure you have the right form id in the hook
Clear your cache so Drupal can find the hook


Override node.tpl.php for the Front Page I am trying to override the front page node, however after following the guide from the official site, it's not working.

Guide: https://www.drupal.org/node/1585528

I have taken node.tpl.php and renamed it to node--front.tpl.php and made changes to the layout, saved and cleared cache. The changes are not being displayed.

Now if I edit node.tpl.php directly it shows the changes, anyone know what I am doing wrong to override specific node templates?

EDIT:
I want to move the title below the image being displayed in the front page.

See below: Moving the title block under the content block, moves the title down as I want it to do, however how do I specify this for just the front page and not all nodes? (renaming node.tpl.php to node--front.tpl.php does not work as mentioned above)

In node.tpl.php: (title block)

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>

(content block)

<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
?>

You have to create page--front.tpl.php from page.tpl.php. You are changing  your front page, not the node.


Set class to an input with twig Hello i am working on theming for Drupal 8 using twig
My question is :
I want to assign css class to each input swicth the type of the input
exemple <input type='email' class='email_cls'>

<input type='submit' class='submit_cls'>

what code should i use ,knowing that i use the default template twig file input.html.twig  I did this

<input{{ attributes.addClass('submit_cls email_cls') }} />{{ children }}

The problem is on my form both of the inputs email & submit have the same display

You could use this in your theme:

function template_preprocess_input(&$variables) {
  $variables['attributes']['class'][] = 'your_class';
}

and maybe even check the type like:

function template_preprocess_input(&$variables) {
  if ($variables['attributes']['type'] == 'email') {
    $variables['attributes']['class'][] = 'your_class_email';
  }
}


How to send notification email to individual users I want to send notification email to some users when a node is created in my site. The author should select the individual users in the node creation form and then after save the node email will be sent to those users.
I use Entity Reference and Rules modules to do that but I don't know how set the right action.

I just implemented the same thing this morning. I hope my solution will help you, but it probably depends on if your content type field is set up like mine.

My user list is presented via an Entity Reference view that I created. Users check off who they want email sent to and save the content type.

My rule is as follows:

Event:
    After saving new content

Conditions:
    Content is of type
        Parameter: Content: [node], Content types: User message

Actions:
    Add a variable
        Parameter: Type: List of user items, Value: [node:field-people]
        Provides variables: List of members to email (members_to_email)

    Loop
        Parameter: List: [members-to-email]
        List item: Current member (member)

        Send mail
            (contents of email listed here)

You'll obviously have different names for your content type, node field, variable names, etc. but hopefully this will get you started in the right direction. If you want the export of the Rule instead of what I posted here, let me know. I thought that showing you what I did through the interface might be an easier start for you.


Aegir 3.0, need to copy and paste website ssl config to ssl.conf in centos I just upgraded to aegir 3.0. If I enable SSL on a site.com only, and if I hit https://example.com. I will be redirected to https://localhost.com (i.e. documentRoot /var/www/html, the default server host)

In order for https://example.com (with https) to work, I need to copy virtualhost config of site.com to /etc/httpd/conf.d/ssl.conf in Centos 6. That is not ideal, because the site virtualhost config is generated by aegir.

Is it a way to do it without copying virtualhost config to /etc/httpd/conf.d/ssl.conf?

Update

I did create a band new site (https://example.com) in Aegir. The virtual host configuraiton in /var/aegir/config/server_master/apache/vhost.d/example.com, contains a line like this <VirtualHost *:443>

If I change it to <VirtualHost 1.2.3.4:443> (i.e. the ip of the server), it works, but why?

If you don't have any apache config for the domain https://example.com then you land in the default vhost.

Add https://example.com as a site in Aegir and it will generate the config for you.


Looking for a hook called before any session is created I am using Drupal 7 and am looking for a hook which is called before any session is created.

According to the the API page, hook_boot() is called after DRUPAL_BOOTSTRAP_SESSION.  The link is for Drupal 6, I assume nothing changed in Drupal 7.

Is there a hook I can call which is called before any session is created?

If you wish to manage the session as mentioned in your comment, you can completely replace the default session handling by setting the variable session_inc to the path of an include file that defines the functions expected by Drupal.

In your settings.php file:

$conf['session_inc'] = 'sites/all/modules/my_session_handler/session.inc';

And in session.inc you will need to implement the following functions:

drupal_save_session
drupal_session_commit
drupal_session_destroy_uid
drupal_session_initialize
drupal_session_regenerate
drupal_session_start
drupal_session_started

You may want to start by copying Drupal's default session.inc and modifying it to suit your needs.  Keep in mind that any of the functions in the default session.inc starting with an underscore are considered private, and not necessary to implement in your custom session.inc.


Adding custom functions PHP to use in a views template I want to use a custom function in views-view-fields--field-name.tpl.php template file. Where do I have to put it? Is it possible to use it in template.php in some preprocess functions?

You can use a preprocess function in your template.php file. For example:

function YOURTHEME_preprocess_views_view_fields__field_name(&$vars) {
  // Do your changes for the field here
}


How to use Block Access with specific Block? I am using block access module to restrict block administration permission. I want to give permission to a role on specific block to edit that block. When I changed the permission firstly it permits only change title and description not body. Second it gives permission on every blocks I added manually.

I only want to allow one single block should be edited by site editors. How to do it?

Solved this using a patch and granting input filter permission. Patch is here https://drupal.org/node/1916028#comment-7302100.


Module/theme installation error I couldn't installed new modules/theme, when i try to install it asks for FTP request for server. Here I spell out what I did,

At first, Update manager module was not enabled. As I couldn't find "install new module" link in the module page, I enabled the update manager module. Now, I got "install new module". The problem starts here: In the module's page, it shows some warnings.

  fileowner()[function.fileowner]:stat failed for temporary

When I tried to install a new module (on click "install new module"), it shows warnings as follows.

I found Installing modules without FTP, but I couldn't resolve my issue.

I don't have the write permissions for the directory /admin/config/media/file-system. So, I got to change the write permissions to files directory that appears in /sites/default path
- change permissions from dwrx-rx-x to dwrx-wrx-wrx

If every thing goes well, you will no longer see the warning. Now, you are ready to install the new modules/themes.


Is it possible to expose custom table data to Views without custom code? I have a custom table that I'd like to expose to administrators so that they can perform simple searches on the table data. I know I can create a series of custom views handlers for each field, but is there is a way to expose and search through the custom table data without custom coding? I expect there is a contrib module out there that solves this problem, but my Googling has come up dry.

Apparently Views Custom Table does that:

View custom table module provide you functionality to integrate your
custom table data to views, and access all it's column in views. This
module use hook_view_data to add custom tables in views. this module
provides you following functionalities.

Auto integrate custom table data to views
Auto map mysql data types with drual data types
Extend relationship of custom table data to drupal entities


How can I remove all contextual links? When using the layout builder module, the contextual links module is a hard dependency. This works quite well in the context of the layout builder. But I don't want those links anywhere else, because elsewhere they are not helpful at best, and completly mess up my frontend theme at worst.

I've already written a custom theme negotiator to force my admin theme in layout building mode.

But I don't know how to remove all contextual links when I'm in frontend. My current ugly hack is

function wt_cms_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  /**
   * Suppress the contextual edit pen on frontend themes, we only want it
   * for layout builder in admin theme
   */
  if (isset($build['#contextual_links'])) {
    $routeName = \Drupal::routeMatch()->getRouteName();
    if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
      unset($build['#contextual_links']);
    }
  }
}

and an additional rule in my frontend CSS

.contextual-toolbar-tab, [data-contextual-id] {
  display: none !important;
}

This does at least hide the contextual edit pen in frontend, but it does not really remove the contextual link menu. (There still is an empty placeholder div).

I've also tried @Shreya Shetty's suggestion

function mymodule_contextual_links_alter(array &$links, $group, array $route_parameters) {
  $routeName = \Drupal::routeMatch()->getRouteName();  //incorrect, this always returns "contextual.render"
  if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
    $links = [];
  }
}

In contextual alter I've got other problems: The current $routeName is always contextual.render and not the route of the host page, so I've no "entry point" to specifically alter non-layout bulder-pages. It also has the same problem as the hook_entity_view_alter workaround: The menu items are suppressed, but the empty contextual placeholder divs are still rendered.

Can anyone tell me how to reliably and cleanly remove the contextual links? I don't want them anywhere, except in layout building mode.

It was a caching issue. This is my final code to cleanly hide all contextual links except in layout building mode:

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function mymodule_page_attachments(array &$page) {
  $routeName = \Drupal::routeMatch()->getRouteName();
  if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
    $page['#attached']['library'] = array_diff($page['#attached']['library'], ['contextual/drupal.contextual-links', 'contextual/drupal.contextual-toolbar']);
  }
}

function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $routeName = \Drupal::routeMatch()->getRouteName();
  if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
    unset($build['#contextual_links']);
  }
}

For the caching issue:
The changes above most likely will (after cache clearing) remove all contextual link entries, but leave an empty placeholder like

 in your rendered HTML. To get rid off those empty divs, go to your browsers Developer console > Application > Session storage and clear all keys starting with Drupal.contextual. After clearing them, the empty placeholder divs are gone too, no more CSS hacking needed.


Is there a common method to password protect registration pages? The site I am working on requires that affiliates register on the site. I've created a profile type for affiliates with corresponding permissions and a registration page. I'd like to give access to this and the site's main registration pages without having to deal with all the spam account registration attempts. Is there a standard way of allowing only users that you want to register to have access to registration pages?

Well, till they register/login, you can't actually say who they are.

I will suggest a CAPTCHA in the registration form. If you want to restrict it more, then you can search for email white listing modules. https://drupal.org/sandbox/amrit_b/1768342 This is something I wrote few months back. This is still in dev. In case you don't find anything else, you can try this one.


Is it possible to export/import content types from one site to another is there a way to import/export content types between diff Drupal websites?, assuming they are the same versions of Drupal

A few options:

Features

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Bundle Copy


How to show/hide login block on main page based on button in header? I would like to ask the following:

My sections are lets say header, main page and footer.

I want to have a button in the header, and when it is pressed, another section comes up between header and main page showing the login form. (username and password fields must be displayed in parallel). In this section also I would like to have another button and when it is pressed, the section becomes bigger, showing the signup form.

For the show/hide functionality I will do it with HTML5, so no worries on this one.

But my question is a basic drupal architecture question that I do not know and I would need your help :)

What is the best approach to build the above? The steps below are correct?

Create a custom module to alter the standard login block it display it horizontally? Or this can be done with theming?
Create another block which will contain the 2 buttons and the login / sign up elements? If yes, in which section do I put this block? If I put it on header how then can I display the inbetween section?

Is there a drupal module that may help with the above?

Thank you!

Your first approach you can consider as best as we won't be actually touching the core Drupal functionality and creating our custom module to tweak the core. You can also have a look at logintoboggan module it may help you to get the drop down effect for login form and login block on click of link once you do the configurations for the loggintoboggan. you may need to additional theming and some jquery code to tweak it more for signup.

Hope it helps.