Filter menu parent dropdown by language for multilingual site? I am working on a multilingual site that has about 60+ pages per language. When an admin user wants to add a page to the navigation menu its becoming quite the task because literally every single link (from all languages) is listed in Main Menu. Its even more confusing because the site has some cases where French and German are in the menu twice because the site has Canada-French and France-French as a language.

Is there any way to manage the navigation menu better? Like if I select German for the language could the menu dropdown automatically filter itself to just show the German nav items? Right now we have a list of about 300+ items in the dropdown :(

This seems to be the issue page for this problem: https://www.drupal.org/node/1242288. There are patches but as Jose Reyero points out, it would be only a partial solution.

There is a https://www.drupal.org/project/content_menu which enables you to first deal with the menu and then with the content instead of vice versa. Haven't tried but seems nice. This combined with Fixed language menus (provided by Menu Translation at admin/structure/menu/manage/menu-mymenu/edit, Multilingual options - Translation mode) could clean up the menu interface nicely.

Personally, I usually just don't bother dealing with the Parent item, I just head to the menu interface after creating a node, and drag my item, which will be at the bottom, to its place.

Enable the Multilingual Select module. The very same thing had happened to me years ago.


Is it possible to get render a field for a paragraphs field in the parent twig template My use case requires that I get a fields values in the parent paragraph template file.

So to be more clear I have a paragraph type (wrapper) which itself has a field referencing to another paragraph type (nested).

I am trying to get the values of a field (like title) from the child paragraph (nested one) in the parent twig template.

Hope for some help with this.

in your node.html.twig file you can traverse up the element array like this

{{node.field_parent.entity.field_paragraph.entity.field_text.value}}

where

field_parent.entity is the parent paragraph
field_paragraph.entity is the child paragraph attached to parent
field_text is a text field attached to child paragraph

OR inside your paragraph.html.twig

{{paragraph.field_paragraph.entity.field_text.value}}

NOTE: its actually better to put this code in a paragraph--parent.html.twig file otherwise this template is going to be used also for the child text paragraph which does not have field_paragraph and its going to lead to error.

I have eventually gotten this to work, this is how I accessed the field from the parent paragraph template

field_product is the paragraph field on my parent paragraph type.
field_title is the field I was trying to get the value of which belonged to the child paragraph type

{{ content.field_product.0['#paragraph'].field_title.0.value }}


How can I get more than 10 search results on one page in Drupal 7? By default search page shows only 10 results. How can I change it to display unlimited number of results?

I recommend using views for this. Views comes with a search view included (disabled by default). Use an exposed search term filter to provide the search functionality, and customize other aspects of the view as needed.

You can use search limit module too or use following code in template.php

if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}


What version is the CKEditor in the CKEditor module? I have installed the CKEditor module for Drupal 7 version 1.14. This version of the module comes with CKEditor already integrated with the module, so I am not sure how to find out exactly which version of the CKEditor this module comes with by default. I need to know this because when adding plugins from the CKEditor website only certain versions of the plugin are compatible with certain versions of the CKEditor. So how can I find this out? I have looked through the different module and JS files but I cannot find this information anywhere.

The library files are linked to directly via CKEditor's own CDN, so the answer can change depending on what their CDN is currently serving.

You can use ckeditor_get_version() to check which version is currently being used:

$current_version = ckeditor_get_version();
// e.g. 4.3.2

You can go to Ckeditor module in your contrib module list and open the readme.txt file. At the section "Requirement" you can see the compatible version of ckeditor library that you can download. the section look like this :

Requirements
------------
  - Drupal 7.x,
  - PHP 5.2 or greater,
  - CKEditor 3.4 or greater.
    You will need to download CKEditor from the official download site: http://ckeditor.com/download.
    It is recommended to always use the latest CKEditor version available.


Custom template for custom block I'm tying to show all the taxonomy terms from a specific vocabulary linked to the current node being viewed. I'm doing this with a new block defined in my module.

In my hook_block_view i need to give a $block['content'] a value, i'm putting a 'foobar' in it because i won't use it, and i add a new key 'tags' which is a array with my tags to render. Then in my block.tpl.php i check the block name and change the rendering if my custom block is rendered.

I guess there must be a better way of doing this...

I would love to add a custom template file, that will be used on my specific block. Is this possible?

Thanks,
Jonathan

This is a good article on what trying to do...

http://www.pixelclever.com/how-theme-specific-blocks-drupal


Add custom URL to Image on a node I'm using Drupal 7, and my nodes have an image and a weblink in seperate fields, The weblink is using the link module so not sure if that will complicate things here. (if so I could downgrade the link field to a text field)

anyway I'd like to create an <A> tag around my image whilst its being themed and I want the href or that <a> tag to point to the weblink url. Sounds like an easy thing to do hey... well I can't figure it out at all! so any help would be awesome :)

If I understand well your question, an alternative can be edit your image field ("Configure field" options) and select Rewrite results > Rewrite the output of this field. Here you can make lots of things with your image, for example add a link from other previous view field, over your image.

here one example to string included in the rewrite field:

[field_image_test]

in this example [field_test_link] is a text field with the respective web address, and [field_image_test] is the field that comes with the image.

this image comes from Drupal 7, but this steps also are possible in Drupal 6

LinkImageField is a CCK module that allows you to specify the hyperlink for images with a custom URL. The CCK ImageField allows links from the image to the node or to the image itself, but not to a user supplied link :  http://drupal.org/project/image_link_formatter


Where does Drupal store its content? I have been currently learning Drupal while trying to duplicate a Drupal application into CakePHP.

I have been looking at the  database tables to know where data is being stored so I can safely migrate any data or study how it is working.

I have researched and have come across questions like:

Where does Drupal store the content of a node's body?
Where does Drupal store NODE data?

So far, I have only seen the title in my Drupal (7) installation.

What I have seen in my node revisions table for a recipe content type, which includes fields like, field_ingredients, field_instructions, field_description, field_preptime, field_cookingtime, just the title of the recipe. This is a sample record on my node_revision table.

nid   |  vid  |  title         |  log   | timestamp  | status | comment | promote  | sticky
-------------------------------------------------------------------------------------------
1     |  1    |  Awesome Sauce |        | 1369998600 | 1      | 2       | 1        | 0

As you can see I can only see the title. Where are the other field contents?

Drupal 6 stored it's content in one table per content type. CCK will adhere to that unless you share a field among several nodes, in which case the fields will be broken out to a separate table.

Drupal 7 creates a new table for every field, so you'll see a lot of tables named field_data_[name_of_field], and field_revision_[name_of_field], the former for the active data, and the latter for tracking any other revisions of the same data. You might be interested in this discussion How to disable the revision feature completely? if you don't need the revision functionality.

Use the entity_cache module to alleviate some of the performance hit from all the joins this causes on complex content types.

If you need an entity that is complex enough to make the D7 approach unusable, consider creating a custom entity where you make properties of your fields. That costs a bit of flexibility, but will make Drupal store the content like the title, which is a property, in the types table.

It is stored in node_revisions table. fields are stored in a new table for each field. so field_description would have a table called field_data_field_description


How to delete all nodes of a given content type? I have several thousand nodes of a particular content type. Using the web interface (example.com/admin/content), I can only delete about 50 at a time. How can I quickly delete them?

There is a module for that (TM).

See Bulk Delete.

That will use the Batch API to delete the nodes to avoid timeout or memory issues when deleting thousands of nodes with a single call to node_delete_multiple().

Bulk Delete is an abandoned module.  See for alternatives:

Views Bulk Operations
Delete All

I ended up using db_delete, no modules required:

<?php
  db_delete('node')
    ->condition('type', 'MY_CONTENT_TYPE')
    ->execute();
?>

Edit/Warning: See Berdir's comment below. This method does not clean up all data related to the nodes.


How to filter a View by Date Range (start, end)? In Drupal 7 with Views an Date module enabled, it was pretty easy to filter a view by Date: The UI just gave you the option to do so.

In Drupal 8, however, the date field and views are part of core, but if you choose a date range field as filter in views it does not offer you date specific options anymore, but shows you only filtering options for text fields:

The date specific options, however, are available for internal date values like ´Content: Changed´

As I would like to show only specific nodes, with a date before or after the actual date, where the date is specified by a custom date range field, this does not suit my needs.

How can I filter a view in Drupal 8 by a date field with date specific operations?

Surprisingly this is not possible with Drupal 8 yet. But there is a long history of trying to make it work: https://www.drupal.org/node/2786577
The last patch, you find in this post, seems to work. You can download and apply it, using the following commands:

wget https://www.drupal.org/files/issues/improve_the_views-2786577-76-core.patch
git apply improve_the_views-2786577-76-core.patch

If git isn't available on your server, try:

patch -p1 < improve_the_views-2786577-76-core.patch

TO apply the patches you have to navigate to the core folder first. And be aware that you have to reapply this patch, after committing a core update. (This sucks!) So let us hope, the Drupal Gods will get this into core soon!

Date popup This module serve the purpose.


Summary or trimmed body field formatter does not display anything when the trim length is anything below 888 I am creating a view for blog items to be displayed on the home page.

Obviously I would not want the whole blog to show on the home page and I want a summary of this to be displayed.

Whenever I set the summary to anything less than 888 it seems to delete the markup completely from the page.

Does anyone perhaps have a solution for me? Thank you in advance.

Well I still don't know exactly what the solution to the issue with Drupal's own summary or trim option. I did however get the trim right using the Smart Trim Module. Thank you to the developers of the Smart Trim module.


How to disable i18n language dropdown in node form? I'ld like to prevent editors from changing the language of a node. Role check works. But I how to disable the language field? Why doesn't it work like any other form field? How is this field placed there? Where can I alter it? This doesn't work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
        $form['language']['#access'] = FALSE;
    }
}

So, the i18n dropdown is attached to the node form afterwards. For now I simply unset($form['#after_build'][0]) where _i18n_node_form_node_form_alter is called. Unsetting it hides all other available languages from the dropdown making it impossible to change it. To me that seems fine. If there's a more appropriate way to do this, please let me know.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE && $editor) {
        unset($form['#after_build'][0]);
    }
}

Finally I did it like @J.Reynolds suggested with hook_module_implements_alter to ensure that my module runs after Locale module

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
    }
}

function MYMODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'form_alter') {
        $module = 'MYMODULE';
        // store
        $group = array($module => $implementations[$module]);
        // unset
        unset($implementations[$module]);
        // add to the end
        $implementations = $implementations + $group;
    }
}

You can do this easily by disabling multi language from your content type.

For example admin/structure/types/manage/YOURCONTENTTYPE

Go to publising option
and disable the multilanguage

Save the content type
That's it.


How to generate a resume after an applicant submitted an online resume? I'm currently building a recruitment system using Drupal 7. In my system, an applicant who wants to apply for a job, needs to complete an online resume (one time only).

Question: Are there any modules that can generate a simple resume after the applicant finishes (saves) the online resume, similar to this Online resume example?

I would create a profile type using Profile2 module and call it something like 'Resume'. So that every user can create a Resume profile for themselves.

Then I would install Print module and enable Print PDF and set it to show up on Resume profile pages.

You must play with the permissions so that only the owner of the profile can access the profile page and the PDF version. You may have to write some custom code to make PDF version accessible only once. You may achieve this writing an access callback function for the PDF path.

You can try with Recruiter Module

  Recruiter is a Drupal distribution for building Drupal based e-recruitment platforms. Users can register either as recruiter and post job classifieds or they can register as applicants and fill out their resume. A faceted search helps users to find jobs and possible job candidates.


drupal 7.21 views exposed form The question is - what may be the reason for exposed form to not be working/showing in a block? Thanks so much - hope someone has an idea about that.

Assuming that you have chosen 'block' as the display rather than 'page', you have to set 'Use Ajax' to 'Yes' in the Advanced options (See this issue on Drupal.org: http://drupal.org/node/1115782#comment-4384348):


Categorize the contents of content type without creating a different template file for each I want to apply similar style to the nodes of same content type (style may vary or may be same between content types,  but will definitely be same for the nodes of same content types) without creating a template file for each of the content type.

I know one way is to create a template file as node-TYPE.tpl.php but I am looking if there is some other way.

You can use

Panels Module

It gives you UI to override node templates,providing appropriate selection criteria you can have different layout as per content types.

Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

If am not wrong than you want to add different class for each content type nodes (this is what the drupal already provides), but if you want to add class to body in your own way or may be adding same class to two different content types than you can try the following.

You can use hook_template_preprocess_node() for adding class to the contents following:

function MyTheme_preprocess_node(&$variables) {
  // If you want to same class to two different content types.
  if (('YOUR_CONTENT_TYPE' == $variables['type']) || ('ANOTHER_CONTENT_TYPE' == $variables['type'])) {
    $variables['classes_array'][] = 'CLASS-NAME';
  }
}


Big pipe and behaviors context I have problem with drupal behaviors and context in combination with big pipe. It seems like context variable sometimes contains same part of page. I have tried:

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      console.log(context);
    }
  };
})(jQuery, Drupal);

When I load page and watch browser console contexts there is div with main menu block but there is also whole #document element which contain menu block also (see screen).

This behaviour is for me real problem because I use zurb foundation and I have to initialize all components and I do it:

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(context).foundation();
    }
  };
})(jQuery, Drupal);

I think this is correct way how to initialize foundation for all elements and it should be compatible with big pipe. But if I get same html part in context twice (some sub elements in context are same) I initialize some zurb foundation plugin twice (see next image).

This breaks zurb foundation plugins. I'm not sure what to do. I read lot of Drupal documentation about js, behaviours and big pipe and according to documentation there should not be problem.

When I disable big pipe everything works as expected but that's not solution.

Do anybody knows what am I doing wrong?

Alternately, using once:

(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      $(body, context).once('foundation-init').each(function() {
        $(document).foundation();
      });
    }
  };
})(jQuery, Drupal);

Try this

(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      if (document === context) {
        $(document, context).foundation();
      }
    }
  };
})(jQuery, Drupal);


jQuery.ajax() results in a 403 error I created a custom block and I was trying to use the ajax method of jQuery, but it seems that whenever I access the method of the controller, it returns a 403 error.

This is my contoller (custom_blocks/src/Controller/CustomBlocksController.php)

namespace Drupal\custom_blocks\Controller;
use Drupal\Core\Controller\ControllerBase;

class CustomBlocksController extends ControllerBase
{
  // $variable is the wildcard from the route
  public function ajaxCallback($variable)
  {
    return ucwords($variable);
  }
}

This is my routing file (custom_blocks/custom_blocks.routing.yml).

my.route:
  path: '/sample-page/{variable}'
  _defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
    _permission: 'access content'
    _access: 'TRUE'

This is my custom JavaScript code (custom_blocks/js/command.js).

(function($, Drupal) {
     $('#custom-button').click(function(){
        var name = 'john doe';
        $.ajax({
             type : "POST",
             url: '/sample-page/' + name,
             success : function(response){
                  console.log(response);
             },
        }, 'html');
     });
})(jQuery, Drupal);

Hope someone can help me.

That's because by default Drupal only allows GET request on default controllers. In your case you should create a custom resource.

Using resources has multiple advantages:

No custom paths per request method
Access control
CSRF protection
Using the API that the REST module in Drupal 8 provides

It basically comes down to creating a class with an annotation:

             /**
              * @RestResource(
              *   id = "my_resource",
              *   label = @Translation("Resource label"),
              *   uri_paths = {
              *     "canonical" = "/sample-page"
              *   }
              * )
              */
             class CustomResource extends ResourceBase {
                public function post($data) {
                  // Do stuff with the posted data.
                }
             }

Some more elaborate examples:

Example one

Example two

You will have to alter your jQuery POST request to something like:

 $.ajax({
         type : "POST",
         url: '/sample-page/',
         data: {'uid':2},
         success : function(response){
              console.log(response);
         },
    });

The data you post in your jQuery request will be available in $data of your resource class.

The controller must return right answer. I recommend to use json response.
Add use Symfony\Component\HttpFoundation\JsonResponse; to your controller.

 public function ajaxCallback($variable)
      {
        return new JsonResponse(['variable' => ucwords($variable)]);
      }

And in your JS file console.log(response.variable);.

And indicate method in your route!!

Also i recommend to pass variables not in url.

In route file:

my.route:
  path: '/sample-page/'
  defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
  requirements:
    _access: 'TRUE'
    _method: 'POST'

in js:

 (function($) {
     $('#custom-button').click(function(){
        var name = 'john doe';
      var sentdata = new Object();
      sentdata.name=name;
        $.ajax({
             type : "POST",
              data:sentdata,
             url: '/sample-page/',
             success : function(response){
                  console.log(response.name);
             },
        });
     });
})(jQuery);

in controller:

//...
use Symfony\Component\HttpFoundation\JsonResponse;
//...
public function ajaxCallback()
      {
      $name = \Drupal::request()->get('name');
        return new JsonResponse(['name' => ucwords($name)]);
      }

PS. Instead of drupal service wrapper (\Drupal::request()) a right way is to  use dependency injection


How do I schedule a PHP function every 2 month? I need, every 2 months, to execute some rule component programmatically, but I don't know how to do this.

If I use hook_cron(), I don't know how to check 2 months are passed from the last time it was executed.

I can check 'the 10th day of the month' + 'month number is even'.

If cron tasks run twice a day, I cannot send 2 identical emails to users.

How can I achieve this?

You can easly do this without having access to crontab/shell, by using following code in your cron_hook:

// check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

For more info on the modulo-operator (the % ) check:
http://www.php.net/manual/en/internals2.opcodes.mod.php

The best way is use crontab ,create a php file as example mycorn.php trigger your rule in it and  create a crontab to run your php file every 2 month.
Just one note, please set permission  only owner can execute it.

Below  links help you , how to set cron.

http://www.adminschoice.com/crontab-quick-reference/
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/


How can i use main-menu items as a fields in selectbox in drupal 7 Helllo,
I have a content type called "Lookbook" in that i want to put one field like "Lookbook For" and this field content select box and main-menu items. I have main-menu list but I want only display submenu items of lookbook menu in select box.
Is it possible that menu links display as fields??
Thanxs..

First, create a view that references the nodes you want - e.g. that have a parent item with node id x (or whatever the criteria is for those nodes). Get that view right, and the rest is easy.

Upload and enable either the references, or the entity reference module http://drupal.org/project/entityreference or http://drupal.org/project/references

In your content type, choose a node reference item and select widget. You can base the option list on your view.


Display the username in a custom block I'm using D7 and I have a custom content type (Client) and I have a custom select list field for the User entity displayed in a custom block.

I have a custom display layout for the Client content type, wherein all fields are displayed in different blocks using Display Suite. The user's name is displayed only when the user field is enabled in the node main content, else it remains blank.

How do I display the username in the block without the need to keep the field enabled in another part of the node view?

try with arguments or use views module and configure your block view CONTEXTUAL FILTERS


Put class error when I use validate I am working with the Metatags module, and I have these fields.

I need that looks like as in the following screenshot, when the fields meta description and meta keywords are validated.

This is my code, I don't know how can include the class error and put the * symbol.  My question is related with styles.  I want the field keywords and description looks as fields required for the user.

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    $form['#validate'][] = 'mymodule_test_validation';
  }
}

function mymodule_test_validation($form, &$form_state) {
   if (($form_state['values']['metatags']['description']['value'] == '')) {
        form_set_error('Description', t('field is required'));
      }
      if (($form_state['values']['metatags']['keywords']['value'] == '')) {
        form_set_error('Keywords', t('field is required'));
      }
}

If the only validation you are looking for is to make sure the fields are required, then you don't need to call to a validation function. The solution in that case will be to set the "required" attribute to TRUE for the fields description and keywords in the "form_alter" function. This solution will give you the style you are looking for in the required fields.

Something like this (this is a proof of concept):

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {
    // Make META DESCRIPTION required
    $form['metatags']['description'] = array('#require' => TRUE,);

    // Make META KEYWORDS required
    $form['metatags']['keywords'] = array('#require' => TRUE,);
  }
}

To get the right field names do the following:

mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form_id = $form['form_id']['#value'];
  if ($form_id == "article_node_form") {

   print_r($form);

  }
}


Error installing CiviCRM Following the amazing work @david-snopek posted:

Blog post - CiviCRM & D8,
David's StackExchange Post.

I spent the better part of last evening trying to get CiviCRM up and running on a Drupal 8.4 BLT project.

After trying a few different approaches, unfortunately I'm now seeing the following error when trying to enable the CiviCRM Core Module

  CiviCRM must be downloaded into the libraries folder.

No matter what I try, I can't seem to get the module to recognize that civicrm is installed.

Other things I've tried:

manually copying the [project_root]/vendor/civicrm-core into [project_root]/docroot/libraries/civicrm-core
Renaming libraries/civicrm-coreto libraries/civicrm
Modifying composer.json to try and install CiviCRM into the libraries folder:
Creating symbolic links to the folder (my least favorite attempt)

Here is the composer.json update for number 3 above:

    "require": {
    "acquia/blt": "^8.3",
    "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    "civicrm/civicrm-core": "4.7.25"
},

...

"repositories": {
    "phpword": {
        "type": "vcs",
        "url": "https://github.com/dsnopek/PHPWord.git"
    },
    "zetacomponents-mail": {
        "type": "vcs",
        "url": "https://github.com/civicrm/zetacomponents-mail.git"
    },
    "civicrm": {
        "type": "package",
        "package": {
            "name": "civicrm/civicrm-core",
            "version": "4.7.25",
            "type": "drupal-library",
            "source": {
                "url": "https://github.com/civicrm/civicrm-core.git",
                "type": "git",
                "reference": "origin/master"
           }
        }
    }
}

source: https://gist.github.com/mortenson/a5390d99013b5b8c0254081e89bb4d47

I think this has to do with an autoloader issue perhaps seeing that BLT does not use the Drupal composer.json file and the instructions @david-snopek posted were for the traditional Drupal installation method.

I was able to trace the error to modules/custom/civicrm-drupal/civicrm.install:125.

/**
 * Returns the path to where CiviCRM is installed.
 *
 * @return string|void
 *
 * Recommended location for civicrm is in /libraries/civicrm [citation needed].
 * We also allow /modules/civicrm, which seems to work fine.
 */
function _civicrm_find_civicrm() {
  if ($path = drupal_get_path('module', 'civicrm')) {
    if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
      return \Drupal::service('file_system')->realpath($path);
    }
  }

  $path = 'vendor/civicrm/civicrm-core';
  if (file_exists($path . '/CRM/Core/ClassLoader.php')) {
    return \Drupal::service('file_system')->realpath($path);
  }

  return NULL;
}

Notes on my process:

I ran into a couple snags with the Gist David posted.

When running $ composer require 'phpoffice/PHPWord:dev-zend-version as 0.13.0', I noticed that Composer was trying to add the dependency as:

"require": {
    "phpoffice/PHPWord": "dev-zend-version",
    "as 0.13.0"
},

This failed but I was able to get past the issue by manually adding the dependency to the composer.json file as:

    "require": {
        "acquia/blt": "^8.3",
        "phpoffice/PHPWord": "dev-zend-version as 0.13.0",
    },

Unfortunately, I then got stuck on the next step requiring civicrm-core until I read the comment a bit closer. I believe this step is now incorrect as civicrm-core 4.7.25 has been released.

#Require civicrm-core at the requested version.
#TODO: Need to keep using my fork until 4.7.25 is released!
#composer require civicrm/civicrm-core:$CIVICRM_VERSION
composer require "civicrm/civicrm-core:dev-roundearth-$CIVICRM_VERSION as $CIVICRM_VERSION"

I was able to get past that issue by updating the additional repository via:
composer config repositories.civicrm-core vcs https://github.com/civicrm/civicrm-core.git

Reference:
https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm

Following literally the instructions for manual installation as given by David Snopek (https://www.mydropwizard.com/blog/how-install-civicrm-drupal-8-and-why-choose-it-over-pure-drupal-crm) I succeeded in installing civicrm 4.7.27 under Drupal 8.4.2.

One caveat: I installed Drupal with composer (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies), using option B on that page "drupal/drupal" as using this option put vendor under the document root, something that is necessary according to David's blog post. In the Drupal documentation it is indicated that with option B one must manually add some lines to the composer.json file but, at least with 8.4.2, it is all there. But the error code about the libraries folder may indicate that these lines are not available in your composer.json file.

I cannot provide additional help but at least, the instructions from David seem to work still with the latest versions of both Drupal and Civicrm.

Yes @kdvgent, I can confirm that the instructions from David Snopek works with the latest versions of Drupal and Civicrm. This is great.

I used "The full, manual process" with :

Drupal 8.6.4
CiviCRM 5.8.2

That was not easy. You need composer, bower, git and wget. Note that you cannot run the composer command as a root. This is a good habit.
The script of David Snopek gather several installations process needed to use CiviCRM. It handles the multilanguage support.
There is still several issues like the use of cron jobs and some extensions issues when using civi in multisite.


How I can unit-test APIs? How I can unit-test APIs? Is there any method for asserting API response in drupal 7?

You can find an example in the Examples for Developers module. Here are two excellent guides:

Simpletest Testing tutorial
Unit Testing with SimpleTest


Drupal: on node save, redirect user to homepage? How can I redirect the user to the home page (or another drupal page) on node save instead of them seeing the saved content?

The Rules module will help you.

If you found a problem with using this module and you want to know how to do this technically, just tell me and I will explain in detail.

Have a look to the code reported in this comment, which is for Drupal 6; similar code can be used for Drupal 7, but it needs to be adjusted to it (e.g. hook_nodeapi() is not used with Drupal 7).

function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;
  switch ($op) {
    case 'insert':
      if ($node->type == 'h_energy_feedback' && $user->uid == 0) {
        drupal_set_message(t('Your feedback has been saved. Thanks for taking the time!'));
        drupal_goto();
      } else {
        drupal_set_message(t('The feedback was saved.'));
        drupal_goto('forms/henergy-feedback');
      }
      break;
  }
}


How to force migrations to not copy files I have a migration with an image field and the files already exist on the server where I want them.

There is a file, some_file.jpg that already exists at sites/default/files/some_file.jpg but when I run the migration, it tries to copy the file from sites/default/files/some_file.jpg to sites/default/files/node_type/some_file.jpg and then also creates another file entity for it.  I just want it to re-use the file and file entity that already exist for it.  The destination field type is an image field.

I have this on the field mapping for the file field:

$this->addFieldMapping('field_upload_image', 'field_res_upload_photo');
$this->addFieldMapping('field_upload_image:preserve_files')
     ->defaultValue(TRUE);
$this->addFieldMapping('field_upload_image:file_replace')
     ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

Well if thats not working do a scan for the file on the destination location to set or unset the field value (so it's not updated on save). You can do this in the prepare function of your migration class. See the commonly implemented migration methods page for example implementations.

Also have you tried setting the preserved_files key:

    $this->addFieldMapping('field_images:preserve_files')
  ->defaultValue(TRUE);

I haven't done any file migrations myself lately, but I stumbled across that in this thread: https://www.drupal.org/node/1886404  it looks like you got the field ordering correct (well from the issue the source field primary and sub-field ordering now no longer matters).

I normally use file_copy function to update this manually.
Set target folder to be same as copy from folder.

Use drupal_realpath function to transfer directory path to image into drupal file path.
e.g  /sites/default/node_type/some_file.jpg  into public://node_type/some_file.jpg
set file object
use file_copy($file, 'public://node_type',FILE_EXISTS_REPLACE); this will not copy file if file is exists.
set this file into your node. and update it. something like this

$node->field_category_image = array(LANGUAGE_NONE => array( (array) $file));
node_save($node);

whole code

$filepath = drupal_realpath('/sites/default/node_type/some_file.jpg');
      $file = (object) array(
        'uid' => 1,
        'uri' => $filepath,
        'filemime' => file_get_mimetype($filepath),
        'status' => 1,
      );

$file = file_copy($file, 'public://node_type',FILE_EXISTS_REPLACE);
$node->field_image = array(LANGUAGE_NONE => array( (array) $file));
node_save($node);


How can I protect development sites with Basic Auth module enabled? During development phase a dev site should be protected from being browsable by unauthorized visitors. Usually I use Basic Auth configured in the web server. This way the only information an unauthorized visitor gets is the domain name.

Drupal 8 uses Basic Auth or OAuth for REST (no Cookie method).

If you want to protect dev sites and use REST with Basic Auth you have a problem. Usually, you setup the webserver to use Basic Auth, as said above. But with Basic Auth module enabled Drupal triggers a 403 Access Denied because Drupal tries also to process the Basic Auth header.

Problems:

The header goes also to Drupal, that tries to use it, giving you a 403 because webserver Basic Auth doesn't match with Drupal users.
If you use two Basic Auth headers (one for the webserver or external layer, another for Drupal when consuming the REST services) you have you tweak your REST service consumers to send those two headers. Also, your webserver or external layer should remove the right header and pass header that Drupal should use.

Obvious solutions

(Use always OAuth for REST services) It seems that OAuth uses Authorization header too so not a solution.
Use other method to protect the dev site than Basic Auth.

Any other way to accomplish this?

NOTE: Clients have no static IP and can't use a VPN to connect (this is mainly because customers must be able to check the dev site).

The steps are as follows:

Modify .htaccess to read DirectoryIndex index.html index.php
Construct your index.html file to show whatever you need.
Modify your robots.txt to disallow any search engine robots to index your site.

Clients can check http://www.example.com/index.php whenever they like, and you can revert your .htaccess and robots.txt when you are done.

Use other method to protect the dev site than Basic Auth.

Trying to keep thins as simple as possible, you may take advantage of the Drupal user permission setting. In your case, create roles you need (maybe developer, tester, themer, etc ) and give them access to content as per your needs. Once done, give no access to anonymous users. This can be done by  a few lines of custom code or contrib modules (example https://www.drupal.org/project/content_access )

Thanks for your feedback


Copying a CiviCRM/Drupal install from one server to another (got error) I've tried copying a a CiviCRM/Drupal install from 1 server to another. I copied all the files within the drupal root, and the database, and changed the database details in both Drupal's settings.php file and CiviCRM's civicrm.settings.php file. Drupal now works fine - copying this over appears to have worked, and I've done so succesfully with the same method many times. However, CiviCRM is not fully working. When I visit the main CiviCRM admin page (ie. http://cea-crm.philosofiles.com/civicrm/ on my server) I see CiviCRM's sidebar boxes (indicating it's working to some extent) but, to the right of them, see:

Page not found
The requested page "/civicrm/" could not be found.

When I click on any sidebar box link, such as 'My Contact Dashboard', I likewise see:

Page not found
The requested page "/civicrm/user?reset=1" could not be found.

Presumably I've missed some change I needed to make to reflect my new server setup? I can't see anything in civicrm.settings.php I still need to change, e.g. I've added lines like define( 'CIVICRM_UF_BASEURL'      , 'http://cea-crm.philosofiles.com/' ); and $civicrm_root = '/home/myusername/public_html/d7/sites/cea-crm.philosofiles.com/modules/civicrm';

If you have Drush installed, you can also use the following command to update some of those settings:

drush civicrm-update-cfg

It will try to update the URL and directory settings, which is pretty equivalent to the URL: "http:///index.php?q=civicrm/admin/setting/updateConfigBackend&reset=1".

After that, you can use the API to flush various CiviCRM caches which may be using that data:

drush civicrm-api system.flush

This page on the CivicRM wiki: http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location
is very helpful on moving an installation to a different server.

Also you can override lots of the settings by putting override staements into civicrm.settings.php as described on this wiki page: http://wiki.civicrm.org/confluence/display/CRMDOC/Override+CiviCRM+Settings


How do you rename the machine name of a content type? I have this content-type that i created titled: "Engineering".
1500 hundred nodes later management wants me to rename it : "Staff". I can easily rename the label but how do i rename the machine name? Does anyone have any success renaming a content-type machine name that is loaded with content/revision and relationships?
It is sometimes impossible to predict these kind of changes. How do we rename the machine name a a content-type.
i have tried the instructions from this article below : https://medium.com/@philw_/how-to-change-a-content-type-s-machine-name-in-drupal-8-33fc3c0520dc with no success.

Error: bundle name cannot be changed.

I will be trying the following:
export the database out.
find and replace the old content-type machine name with the new name
I will also rename any tables named after the content type in the process
re-import the db
I will see how that works out.

I disagree with most of the comments above simply stating: don't change the bundle machine name. These don't answer the poster's question.
This was a simple task in Drupal 7; but due to the added complexities in Drupal 8 it was decided to attempt to remove this ability. See this issue for history:
#2172843 Remove ability to update entity bundle machine names.
That being said, if you do a database search/replace on the machine name this should do what you are looking for - BUT beware, some of those machine names are embedded in serialized data (e.g. key_value table) and you will need to modify the json string size if the machine name you are replacing is a different length than the new name.

Leave the machine_name intact
Create path alias wherever outdated machine_name is exposed to the end user via the URL.
Define custom const in a custom module - name it after "new" machine_name and set the value to the old machine_name. Use new const in the code as a replacement for old, incorrect machine_name.


How to add a dynamic cart link to the user menu? Commerce already defines two menu items in the Navigation menu:

Shopping cart - 'cart' - enabled by default, static
Shopping cart - 'cart/my' - disabled by default, dynamic

'cart/my' uses a custom title callback, 'commerce_cart_menu_item_title' that builds a dynamic menu link in the form: Shopping cart (2 items)

If I want to add a new menu item for the shopping cart to the User Menu, what's the proper way to do this? Do I first need to duplicate a menu item, then override the duplicate?

Ideally, I would be able to set my own title callback so that I can optionally build a dynamic menu in any format I choose.

You can create a new menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module.

For example

function mymodule_menu() {
     $items['cart/new_menu_item'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'mymodule_new_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'mymodule_new_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}


Drupal 8 : Render a field collection item in a Twig template In Drupal 8, I have a content type which use Field Collection Module like that :

field_body (FieldCollection, repeatable)

field_image_alignment(Boolean)
field_picture (Image)
field_free_text (Long Text)

I want to theme this fields.
I overrided the field template with a file named field--node--field-body--news.html (news is the content type that contains theses fields.).

Default template is this :

{% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
{% endfor %}

And my template overrided is like that :

{% for item in items %}
  {% if item.content['#field_collection_item'].field_image_alignment.value == 1 %}
    {{ dump(item.content['#field_collection_item'].field_picture) }}
    {% endif %}
{% endfor %}

How can I render "child" fields field_pictures, field_free_text ?
I used item.content['#field_collection_item'].field_image_alignment.valueto access to the plain value but I would like to have the rendered view.

Thanks a lot.

I've just started learning Drupal and encountered the same issue.
I solved it by creating custom field formatter:

public function viewElements(FieldItemListInterface $items, $langcode)
{
  $elements = array();
  foreach ($items as $delta => $item)
    if ($item->value !== NULL)
    {
      $builder    = \Drupal::entityTypeManager()->getViewBuilder('field_collection_item');
      $elements[] = $builder->build($builder->view($item->getFieldCollectionItem()));
    }
  return $elements;
}

Use this module for Nice Table format Look
Link: https://www.drupal.org/project/reference_table_formatter


Query URL containing term name instead of term ID on Views Exposed Filters I've got a View with an Exposed Filter that shows Taxonomy Terms that are used to filter the content that's going to be displayed as the result.

It's a View that shows recipes based on the filters chosen by the user (Type of Recipe, Type of Meat).

When I submit the form, I get the following URL:

/recipes-view?type-of-recipe=all&type-of-meat=22

The last parameter shows the number 22, which is the Term ID for the value chosen. The URL has to contain the Term Name instead of the Term ID.

Can I change it via hook_views_query_alter() or is it needed to create a custom handler for that?

Thanks in advance.

There's no need to do this in code. You basically need to:

Add relationship to taxonomy term via entity reference field (it would probably also work with term reference)
Add exposed filter using this relationship (search for field Taxonomy Term: Term)

It works fine and you get URL, such as:

recipes-view?tid=vejuu

If you want to have an URL key type-of-meat, you can set it in More drop-down in you exposed filter configuration. The field name is Filter Identifier

I experienced problems with using features trying to prevent duplicates created by joining taxonomy terms.


Hiding admin (user/1) account How can I hide the main administration account from authenticated users? I have created a new role and created a new admin account.

You can implement hook_menu_alter() in a module to alter the access callback used for the "user/%user" path.

The code I would use is the following one, which is generic enough not to take assumptions about the access callback already set, and the arguments passed to that access callback. This means the code will work even if there is another module that alters the access callback for the same path.
The same code would work for Drupal 6, once you replace any occurrence of user/%user with user/%user_uid_optional.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user'])) {
    array_unshift($items['user/%user']['access arguments'], $items['user/%user']['access callback']);
    array_unshift($items['user/%user']['access arguments'], 1);
    $items['user/%user']['access callback'] = 'mymodule_user_view_access';
  }
}

function mymodule_user_view_access($account, $callback) {
  $args = func_get_args();
  // Remove $account and $callback from the arguments.
  unset($args[0], $args[1]);

  $uid = is_object($account) ? $account->uid : (int) $account;

  // 1
  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return ($GLOBALS['user']->uid == 1);
  }
  // 1

  // Let the previously set access callback decide who has access to the user account.
  return call_user_func_array($callback, $args);
}

The code would not allow any user to access the super user account, except to the super user. If you want to allow the users with the permission to administer users to see that user account, you can replace the control statement commented with // 1 with the following one.

  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return user_access('administer users');
  }

The easiest way to do that is to create a hook_FORM_ID_alter

function legal_form_user_admin_account_alter(&$form, &$form_state, $form_id){
global $user;

  if($user->uid != 1){
    unset($form['accounts']['#options']['1']);
  }

}


Server Error 500 on every Ajax Call we have a problem that we get a internal server error on about every ajax call. The example below happens when editing a view clicking "add filter" and directly click on abort. It also happens when making changes to a view. At first glance the change seemed to be ignored but after refreshing the pages the changes will be visible.

When accessing the URL which throws the error we get a valid json string (checked with jsonlint.com).

Our server logs sadly show nothing interesting. I would appreciate any kind of hint where to look for a solution.

Edit:
The nojs version seems to work fine but that's no solution in the long term :/

Look at your PHP error log. It should give you the file and line number it's having an issue with.

If you can, copy and paste the last few lines of the error log on here for us to look at.

When I have something like this it has always to do with the .htaccess file.
Or maybe you just haven't enabled clean url's or something like that.

EDIT
Is there somthing like this in your htaccess file

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

Make sure it's uncommented


Overriding the function of a module in another module Module1 has a function named 'function1'. 'function1' is not a type of hook, but it is a menu callback, or called inside a hook.

Module2 wants to override 'function1' using all variables which are available to function1 inside Module1.

I can call function1 using module_load_include(), but I need to override the called function.

How can I achieve this?

If you want to use a different menu callback, you can implement hook_menu_alter() to change the menu callback. Suppose you want to override the menu callback Drupal defines for search, you could use the following code.

function mymodule_menu_alter(&$items) {
  if (isset($items['search'])) {
    $items['search']['page callback'] = 'mymodule_search_view';
  }
}

From mymodule_search_view() you can call search_view() without first including the file containing it, as that is done from Drupal before calling the menu callback.

Similar code could be done if the menu callback is returning a form, with the exception that, instead of changing the page callback (which probably is drupal_get_form()), you would change the page arguments to use as first argument the callback name of the function returning the form array. Rather than doing this, you should implement hook_form_alter(), and to hide the not necessary form elements with $form['element']['#access'] = FALSE', and not withunset($form['element'])`.

As for replacing a function that is called from a hook, what can be done is removing the hook implementation that calls that function, and replacing it with a different implementation. It is possible only with Drupal 7, and it must be done carefully. (I will explain why right.)
Suppose you want to change the function called in menu_node_update() (the implementation of hook_node_update()) from menu_node_save() to mymodule_node_save(). You could use the following code.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    unset($implementations['menu']);

    $implementations = array('mymodule' => group) + $implementations;
  }
}

function mymodule_node_update($node) {
  mymodule_node_save();
}

In this way, menu_node_update() would not be invoked anymore, but mymodule_node_update() would.

Normally, modules that depend from a hook implemented by another module don't check if that hook is executed; they check the module is enabled (and assume the hook is invoked), or they add that module as their dependency. Avoiding a hook is executed could cause problems to other modules which could be difficult to track. If it is really necessary to avoid a hook implemented by another module is executed, you should first check on a test site that all is working as expecting. Bear in mind that future Drupal version could break your code, and the code you are writing should be tested on future Drupal version too (when they are available).

Try overriding this function's output by another function where they both meet in any other hook(as you have mentioned the function is being called inside a hook).


Seamless Responsive Photo Grid with Omega I'm trying to create a responsive full screen gallery based on quite a simple idea, but without success. Idea is to have full screen view of many pictures that are adapting to screen resolution responsively.

The idea you can see here: http://css-tricks.com/seamless-responsive-photo-grid/

I'm working on D7.20, Omega 3.x

And what I want to do is to have content type, let's say, "picture" and create a view, which is displayed in a fluid full screen layout and is shown in such a way like in a given example.

But no success, it looks like it should be simple, but I cannot manage to understand how should I change the CSS to make it work...

It is probably possible to make similar effect using jQuery Masonry module, but I would like to do this with only CSS.

I have a kind of similar issue. I was actually trying to display different packages where the packages div's had variation in heights. I tried to align them using css without any luck.

so I then tried Isotopes and that worked perfectly.

You should also try https://drupal.org/project/isotope it comes with Example Context Reaction for Isotope.

there is also https://drupal.org/project/views_isotope module

You can also use

https://drupal.org/project/views_fluidgrid
https://drupal.org/project/masonry
https://drupal.org/project/masonry_views

If you use a view, you can make a template for the view, and for each record of the view, and then use both html and css to style it as you want.


Upload images in custom modules I work on D7, and create form from custom modules. Create a field upload images by
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['image'] = array(

'#type' => 'file',

'#title' => t('Upload picture'),

'#description' => t('Select a picture of at least @dimensionspx and maximum @filesize.', array(

  '@dimensions' => '1000x1000',

  '@filesize' => format_size(file_upload_max_size()),

)),

);

Show form correct.

and submit form by hook_form_submit();
print $form_state, upload images not find.
How to get values of upload image.

Write Also

$file = file_save_upload('image', array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array('500x500', '100x100'),
  ), 'public://uploaded_images/', FILE_EXISTS_RENAME);

Not find of upload image.

Drupal makes a distinction between regular files and managed files. The first are only stored on the filesystem, the second are stored in the database (managed) as well.

If you use a manged file (type = 'managed_file') the $form_state will contain a file id (fid) of the newly stored image.

Also note that file_save_upload takes the file path as the first parameter, so 'image' means nothing there. And that you still have to store your image as a permanent file after file_save_upload():

$file = file_load($logo);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'your_module', 'using_entity_type', $entity_id);

The values are in $_FILES.

You shouldn't need to set the enctype of the form, Drupal will handle that for you automatically.


Omega 4: Export settings to .info I'm sure its a simple question but i cannot find any resource to the solution.

In Omega 4, i keep getting this message "The settings for this theme are currently served from a variable. You might want to export them to your .info file".

So how do i do that?

drush omega-export
drush omega-revert

or

omega-export --revert

See: http://friendlymachine.net/posts/getting-started-omega-4

you have to run  'drush omega-guard' and the error will desapear


How to add reset button to forms? I've been researching this matter for a while with no clear answer yet.
So, here are a few questions ...

I'm assuming (correct me if I'm wrong) that Drupal 7 doesn't support reset buttons. It appears, according to the form API (as discussed in Pro Drupal 7 Development), that all the buttons (input type="submit", button, and image_button) are by default submit buttons. There doesn't appear to be a way to override the defaults either.
So, if I wanted to add functionality to my forms for my users to clear forms (if they choose), would I have to create a module?

Would I be able to pull this off by using the general button type with executes_submit_callback set to false and by adding some type of Ajax function to the mousedown event?

** EDIT: I added the following to my hook_form_alter() **
$form['reset'] = array(
'#input' => TRUE,
'#name' => 'reset',
'#button_type' => 'reset',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => TRUE,
'#process' => '',
'#theme_wrappers' => array('button'),
);

I got the following error message & warning:

Notice: Undefined index: #type in _form_builder_handle_input_element() (line 1949 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).
Warning: Invalid argument supplied for foreach() in form_builder() (line 1763 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).

Is there a way to add the "reset" button type to the types of buttons without crashing the entire form.inc?

My preferred way to do this is.

Add the button to your form like so:

$form['options']['reset'] = array(
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('MY_MODULE_FORM_ID_reset'),
);

Then create the reset function like so:

function MY_MODULE_FORM_ID_reset($form, &$form_state) {
  $form_state['rebuild'] = FALSE;
}

No Javascript, no markup.

This is my way to add Reset button, hope you like it :D

$form['reset'] = array(
'#markup'   => '<input type="reset" class="form-submit" />',
'#title'    => 'Reset',
);


How to pass variables between theme functions I often use functions that contain variables in the following files:

Template.php
Custom Panels Style Plugins
node.tpl.php files
field.tpl.php files
views.tpl.php files

I often needed to pass variables between these functions.

At the moment, I do this by declaring my variable as a global Using PHP's global command. However, I have read that is not best practice. Is there a better way?

I know that Drupal has variable_set() and  variable_get(). However, apparently these have similar problems to using Globals for lots of little variables.

I am newish to Drupal, but will give this a shot (I'm sure someone will tell me if I am wrong).

You can set variables that exist in different contexts by using the template.php file of your theme by adding stuff to the $variables array with preprocessor functions. So you could maybe add your variables to the YOURTHEME_preprocess_html() function, which should make them available everywhere.

function YOURTHEME_preprocess_html(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}

You probably need some settings, so using variable_set is a normal practice I think.


Show block for specific content type programmatically How can I show a block on a specific content type programmatically? I want in my image the 'basic page' selected.

I used the xxx_block_info() function, should it set in here?

If you look at the node_module file it controls the node type visibility using the hook_block_list_alter.

So basically it might looks something like this.
NOTE: This is a non tested version.

function hook_block_list_alter(&$blocks) {
  $node = menu_get_object();
  // list of all block deltas u want to apply this
  $block_delta = array('deltas');
  foreach ($blocks as $key => $block) {
     if (!empty($node) && $node->type == 'page' && in_array($key, $block_delta)) {
       unset($blocks[$key]);
       continue;
     }
  }
}

You can do like this:

function xxx_block_info() {
    $blocks['xxx'] = array(
    'info' => t('Xxx'),
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => '<?php global $node; if ($node->type == 'yyy') return TRUE; else return FALSE; ?>'
  );
}

Verify that the PHP filter module is enabled if you want to use BLOCK_VISIBILITY_PHP!


How to send mail with multiple images from node using Rules module? $language = field_language('node', $node, 'YOUR _FIELD_NAME');
foreach($node->YOUR_FIELD_NAME[$language] as $file) {
  echo drupal_realpath(file_load($file['fid'])->uri);
}

I used this code to send mail in attachments but image file does not work

<?php
foreach($node->field_name['und'] as $file) {
  echo  drupal_realpath(file_load($file['fid'])->uri);
echo ("\n");}
?>

This code worked for me!!!


How do I exclude a bunch of nodes from being indexed by Solr? I want to remove unused nodes from indexing in solr and also I need to make sure that they are not indexed again. I will fetch the list of the unused node IDs using a query.

If any of the nodes is getting updated, then I need to index that node again.

How can I achieve this?

For d7 you are looking for the hook: hook_apachesolr_exclude

Example from the apachesolr.api.php

/**
 * This is the place to look for the replacement to hook_apachesolr_node_exclude
 * You should define a replacement for the status callback and return
 * FALSE for entities which you do not want to appear in the index and TRUE for
 * those that you want to include
 */

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  return FALSE;
}

See here: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.api.php/7

UPDATE

For deleting certain nodes (entities) you can use apachesolr_remove_entity.

In Solr configuration at "admin/settings/apachesolr/content-bias" you can set the content types to exclude from the search index.


How know if user is visitor or logged member? How can I determine programatically whether the current user is anonymous or authenticated?

For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g.

if (\Drupal::currentUser()->isAnonymous()) {
  // Anonymous user...
}

U can use this code::

global $user;
if ($user->uid == 0) {
  //user is not logged in
}else{
  //user is logged in
}


Fetching text field from the node I am working on flex slider module and I want to add one button in caption so for that I have added one field in content type with Machine name: field_image_url and Field Type: text.

Now I am changing in core file of the module to fetch that URL into the front end.For that code is below:

    <?php
    /**
     * @file
     * Default output for a Flex Slider node.
    */
    ?>

      <div class="flexslider-content flexslider clearfix" id="flexslider-<?php print $id; ?>">

        <?php foreach($items as $item) : ?>

<?php print render($item); ?>
            <?php if(!empty($item['#item']['title']) || !empty($item['#item']['alt'])) : ?>

<?php print $item['#item']['alt'];?>

<?php print $item['#item']['title']; ?>

             <?php if(isset($node->field_image_url)): ?>
                <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More
             <?php endif; ?>

            <?php endif; ?>

        <?php endforeach; ?>

I know I am making some mistake as I am very new to drupal development.

     <?php if(isset($node->field_image_url)): ?>
        <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More
     <?php endif; ?>

Above code is for fetching URL.It is not giving me any error, but it is also not showing me the button.I have already entered URL for one slide.

Where am I lacking ?

Edited :

I want to also mention that Slider is on front page and there is an article content just below to the slider.

I have given node path to the front page from the Configuration to show it on front page.

So now, If I do

     <?php
        if (arg(0) == 'node' && is_numeric(arg(1))) {
          // Get the nid
          $nid = arg(1);
          // Load the node if you need to
          $node = node_load($nid); print_r($node);
        }
     ?>

It is giving me the node ID of the article.I want the node ID of the slider Image so that I can pull out the image URL field that I have added to the Slider Image Content type.

EDITED:

    <?php
        //this code will load all nodes from your content type and then print them
        $node_type = "slider_image";
        $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
        $nodes = array();
        while ($obj = db_fetch_object ($result)) {
          $node = node_load($obj->nid);
          echo $node->field_image_url['und'][0]['value'];
          echo '
';
          $nodes[] = node_load($obj->nid);
        }
    ?>

I have tried above code but it is giving me an error :
Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, string given, called in path to modules\modules\flexslider\theme\flexslider-container.tpl.php on line 19 and defined in db_query() (line 2345 of path to site\includes\database\database.inc).

So to resolve above error, I tried following code with help of this:

$result = db_query("SELECT nid FROM node WHERE type = ':type' ", array(':type' => $node_type));

But above code also gives me error : Fatal error: Call to undefined function db_fetch_object() in path to module\modules\flexslider\theme\flexslider-container.tpl.php on line 21

In general to get the value of field if the entity type is a node

$node = node_load($nid);
echo $node->field_image_url['und'][0]['value'];

or try to print the $node to figure out how to get it

echo '<pre>'; var_dump($node); var_dump($node->field_image_url); die;

in your situation try the next to figure out what is happen there

<?php
$node_type = "slider_image";
$sql = db_query("SELECT nid FROM node WHERE type = $node_type");
$results = db_query($sql);
foreach($results as $row){
   $node = node_load($row->nid);
   echo $node->field_image_url['und'][0]['value'];
   echo '<br>';
}
?>

You can use KPR function that comes with devel module. Once you enable the module you could add kpr($fields) function and it show you the structure of data returned by drupal. In general it should be something like $fields->field_image_url['und'][0]['value'];


Force Language Path Prefix For Default Language I have a multilingual site configured to use path prefix for URL language detection.

When no prefix is used in the URL, the default language is assumed. How can I change this behavior?

I want the site to return content only when a language prefix is set in the URL, otherwise return a "page not found" error.

Reasoning behind this functionality:

Preventing duplicate content in search engines
Keeping everything well organized (under language prefixes)
Avoiding users to be able to view content without a language prefix and thus potentially link to it (loosing link juice)

Edit: added reasoning.

You can configure it from (admin/config/regional/language/edit/en) if English language is the default and change (Path prefix language code) field from empty to en for example

@ovi: Next to the language list tab, there is another tab - "Detection and selection".
URL: admin/config/regional/language/configure
Go to this page and enable detection method - URL.
Save settings. It should work now. It worked for me without having additional modules.


How to display article from category and show it in block I have created a content type which has some fields, and I want these fields to be displayed as a block.

I need to display some article like 5 articles from category called sport news only.

how can i do that in drupal 7

Not sure of your exact need, between articles, your content type... Try something like that :

Go to admin/structure/views/add.
Fill in the form : Show Content of type article (or Your content type). If  sport news is a taxonomy category, tagged with sport news.

Uncheck create page, check create a block, display format table of fields, five items, then continue and edit.

Now in the left side of the form, click on add fields, choose the fields you'd like to display and settings for each field. Give a admin name to your block in Block settings, at the top of the middle column. You now have a block view with 5 items of content type article and the fields you selected.

Go to admin/structure/block, look for the block you've just created, and set the region where you'd like to display it, or click on configure to be more specific, displaying it on specific pages, for specific roles or whatever.

You must install the views plugin. After installing the plugin, you can go to structure-view-add a view to make a list of posts with condition that the content type is of specific criteria and set the display type to be a block. After that go to the block setting and set region the block belongs to.


How to check if a View was cached? Is there a simple way to check (example: see from UI or browser developer tools) if a rendered View was retrieved from cache or just generated on the page load?

This would need to work for every view display, like a View Content pane embedded in a Panels page.

Would this need custom code or is there a module or any-other-simple-way for this?

Thanks

Caching only works for anonymous users (people who are not logged in).

So, a simple test would be to add new content to your view or make a change to your view. Ex: change your view title.

On another browser have your page open, but as anonymous. If your view doesn't change, it means the cache worked.

The View will NOT change to anonymous users until you clear the cache.


How do I apply cufon.js only for Internet Explorer, in template.php? I have some font problems in Internet Explorer, so I am trying to apply font-family through JavaScript. It works, but the JavaScript code runs for every browser.

How do I run JavaScript code only on Internet Explorer?

This my code.

drupal_add_js('sites/all/themes/blogbuzz/js/cufon-yui.js');
drupal_add_js('sites/all/themes/blogbuzz/js/Helvetica_CE_35_Thin_100.font.js');
drupal_add_js('(function ($) {
  $(document).ready(function() {
    Cufon.replace("#content-header");
    Cufon.replace("#client_tle");
    Cufon.replace("#block-block-16");
  });
})(jQuery)', "inline");

You can't apply JS only to one browser using Drupal functions. What you can do is:

CSS workaround:

apply CSS only to IE
assign some style that will not be visible, but also will not be present in non-IE, like white 1px border on white background
use css() jQuery method to test if element has property you expect it to have in IE, and if true, execute your code.

JavaScript way:
Use jQuery Browser Plugin or similar solution to identify browser inside your js file. Execute your code if it's the browser you need it executed in.

Something like this is what you are looking for:

function yourtheme_preprocess_html(&$variables) {
  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie8style.css', array(
    'group' => CSS_THEME,
    'browsers' => array(
      'IE' => 'lte IE 8',
      '!IE' => FALSE,
     ),
    'every_page' => TRUE,
    'weight' => 10,
   )
  );
}


How to change MENU_LOCAL_TASK title for the View and Edit tabs according to content type? I am trying to change the title ( tab text ) of the standard Drupal menu local task tabs 'View' and 'Edit'.  I want them to reflect the content type of the current node.  So on the page node/1234 ( which is a blog node, say ) I want the View tab to say 'View blog' etc.

I can change the text using :

$items['node/%node/view']['title'] = 'View blog';

in a hook_menu_alter() function, but I can't seem to get hold of the node itself to test what content type it is to vary the text.  The arg() function doesn't return anything within the hook_menu_alter() function for some reason ?

How do I do this ?

Thanks

hook_menu() implementations are cached so aren't executed for every page (can you imagine how bad that would be for performance?)

You can use the title callback property from hook_menu() to evaluate a title on each page load, e.g.

$items['node/%node/view']['title callback'] = 'MYMODULE_title_callback';
$items['node/%node/view']['title arguments'] = array(1);

...

function MYMODULE_title_callback($node) {
  if ($node->type == 'foo') {
    return 'bar';
  }
  else {
    return 'baz';
  }
}

You can try Tabname Tweaker module.

This module allows admins to override the name of the 'View' tab on node pages. Useful for Organic Groups, where the normal 'View' tab serves as an overview or landing page rather than a specific piece of content.

This module allow to change and override the View and Edit tabs


How to grep Rules to search for a deprecated function? I'm removing an obsolete custom module, but I want to make sure it isn't referenced in any rules.

Is there a way for me to search / grep for a function name within all the rules on my site?

Consider a rule, actually a rules component, as in this (random) sample (in Rules export format):

{ "rules_grant_access_to_a_node" : {
    "LABEL" : "Grant access to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_containing_classified_ad" : { "label" : "Node containing classified ad", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-containing-classified-ad" ],
          "type" : { "value" : { "article" : "article" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "node",
            "id" : [ "node-containing-classified-ad:field-free-format-nr" ]
          },
          "PROVIDE" : { "entity_fetched" : { "fetched_classified_complete" : "Fetched classified complete" } }
        }
      },
      { "drupal_message" : { "message" : "Trying to grant access to node with Id = [fetched-classified-complete:field_free_format_nr]" } },
      { "content_access_action_user_grant" : [] },
      { "redirect" : { "url" : [ "fetched-classified-complete:url" ] } }
    ]
  }
}

The above rule (Rules Component) has a Rules Action content_access_action_user_grant (= machine name) which is available if (a) you have the Content Access module enabled and (b) the ACL module is enabled also. So ACL is a weak module dependency of the Content Access module.

However, that content_access_action_user_grant Rules Action is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that refers to that Rules Action content_access_action_user_grant will show a "... fails the integrity check").

With the above example (and Rules Action) in mind, execute an SQL query on the Drupal database which looks like so:

SELECT id,plugin,name,label
FROM `rules_config`
WHERE `data` LIKE '%content_access_action_user_grant%'

The results I get by using this query looks like so:

id  plugin   name                             label

216 rule     rules_grant_access_to_a_node     Grant access to a node

Obviously, this result with id=216 matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin.

Replace the machine name of the Rules Action in my example by whatever fits with your "function name" (as in your question), and a similar SQL query should list all "rules in your site" (as in your question) that reference your custom module.

Note: another approach (if you can afford to do so), is to simply disable your custom module, and then use the Rules UI to find out which Rules / Rules Components show a similar message containing such "... fails the integrity check".

The standards documentation recommends that modules use the @deprecated tag when deprecating a function/method.

Assuming the author of any given module has followed the guidelines properly, searching for @deprecated should get you the correct results.


How to add multiple value using autocomplete widget We create a input field using user interface for add multiple languages .How i can add multiple language using comma separate so after comma they will populate other language.

You need to explode the string inside the autocomplete function.

function autocomplete_callback($string) {
  $explode_str = explode(',', $string);
  $last_str = drupal_strtolower(array_pop($explode_str));
  // use $last_str in the query
  $explode_str[] = $result;
  return implode($explode_str);
}


How to set the default value of a CCK field I got a CCK field to select a currency; this field is not required, and the dropdown displays '-None-'. I want to change that.

There's the option to let PHP-Code return the value. It says:

return array(
    0 => array('value' => 'value for value'),
    // You'll usually want to stop here. Provide more values
    // if you want your 'default value' to be multi-valued:
    1 => array('value' => 'value for value'),
    2 => ...
);

So I tried with:

return array(
  0 => array('value' => 'my_text'),
);

Drupal now tells me:

The PHP code for 'default value' returned Array ( [0] => Array ( [value] => my_text ) ) , which is invalid.

I got a list of 4 currencies to choose from, which are the allowed values in my dropdown. What do I have to do to replace '-None-' with my own default?

In order for you to use PHP you must return a simpler array:

return array(
  'value' => 'my_text'
);

Also, if all you want is to set a default value, you don't need to use the PHP option.

First, define the allowed values (manually or via PHP, doesn't matter)
Then click save
Now click edit to go back to the form. Close to the top there will be a "Default Value" fieldset populated with the allowed values. Just select one!

The tip from Alex about doing this without using the PHP option is great. However, remember to set the permissions on the new cck field. Until you have done this, you will not be able to see the "Default Value" box.

.. remembering to do this will save much frustration :-$


500 internal server error on a single node This just happend randomly today. I tried to access a page, but it keeps giving me a 500 internal server error http://www.austravel.com/holiday-destinations/australia

All the other pages are working fine. Any ideas why this may be?

Display PHP errors for that page or examine your Apache log file with errors enabled. Nobody can tell you what's misconfigured, or whatever typo you've made in your PHP ... log files can tell you though.

EDIT:

For further explanation on "errors" and specifically 500 error from Apache see:
https://stackoverflow.com/questions/8564259/php-5-3-troubleshooting-500-errors-debugging-parse-errors

  PHP will respond with a "500" when it encounters a Fatal error, such
  as E_PARSE, E_ERROR and uncaught exceptions. 500 is the HTTP response
  code for "Internal Server Error" - something unrecoverable happened
  while processing the request.

  In your php.ini, on a development machine, you should set your
  error_reporting level to (at least) E_NOTICE - preferably E_ALL - and
  make sure display_errors is on. This will show you the error message
  in the browser, including for "500" errors.

  You can also check your Apache error logs, the errors will be listed
  there, as long as log_errors is enabled in php.ini. By default, this
  will be at \logs\error.log.

  You can also control all this at run time with ini_set() and
  error_reporting()

Sorry for not posting this sooner.

Just to answer @AgA yes there is a error_log file, I checked it and found the problem.

For anyone wondering, it was just a large image file that was breaking the page. I deleted it from the page and it worked fine.


How to customize Commerce order admin view I would like to customize the Commerce order admin layout, the tables shown when admin clicks View or Edit in the Orders table.

These pages are typically shown on the following URLs:
yoursite/admin/commerce/orders/order_id/view and
yoursite/admin/commerce/orders/order_id/edit
where order_id is a number.

I want to add a custom column (a field from my product content type) to these tables. I have searched all the views which were created automatically when I installed Commerce but wasn't able to find the one which is rendering these pages.

In Drupal 7, Commerce 1 (7.x-1.x)

For the actual individual order page, you'll want to edit the view entitled "Line items (Commerce Line Item)"
Bear in mind however, the column you add may cause errors if the field only exists for some product types and not others. You might need to add an additional relationship to the view to get the field of data.

For the actual order summary page found at /admin/commerce/orders, you'll want to edit the "Orders" view.  You'll probably need to add a relationship for Commerce Order Line Items.


How do I get the current node ID? In Drupal 7, if I wanted to get the node id of the currently displayed node (e.g. node/145) I could get it with the arg() function. In this case, arg(1) would return 145.

How can I achieve the same in Drupal 8?

The parameter will have been upcasted from nid to full node object by the time you get access to it, so:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See the change record for more information.

Note on the node preview page, the following doesn't work:

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->id();

For the node preview page, you have to load the node this way:

$node = \Drupal::routeMatch()->getParameter('node_preview');
$nid = $node->id();

How to load node object in node preview page?


Regex Jquery in Drupal 7 not working (I have posted this on Stack Exchange as well)

I have a Drupal 7 page on which I need to remove text bracketed by "Keywords:" and "Description:", there are a number of text blocks all with the class .feedDesc

Page is here: http://www.cafe.gen.nz/node/236/feed-items

I have this working on a plain html page with this Jquery below but can not for the life of me make it work in the Drupal setup:

  $('p.feedDesc').html( function (index,text) {
    var regex = /Keywords(.*)Description/;
    return text.replace(regex,"");
  });

On the site the below does work indicating the whole stack is good.

  $('p.feedDesc').html( function (index,text) {
    return text.replace("Keywords","Foobar");
  });

Help !

Any ideas?

Update:

This works to do the find/replace:

    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      return text;
    });

However I also need to trim whitespace and $.trim does not work:

    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      text = $.trim(text);
      return text;
    });

If that's the exact code, then

var regex = /Keywords(.*)Description/;

should be

var regex = '/Keywords(.*)Description/';


Create renderable nested tree array like Menu Tree or Taxonomy Tree I am getting a nested array with children property from the WebSerice. I want to create the render able array so that I can use "drupal_render" function to render final HTML. I looked at the 'menu_tree_output' and 'taxonomy tree" that Drupal generates, but there is not proper documentation that mention how to structure the array to make it render able nested list.

Lets make it short: How do I restructure the final array that I get from Webservice so that I can make it renderable using drupal_render api. Final output is nested list(Folder tree).

What you are trying to solve is a recursive problem.... See below code which solves problem..

function listArrayRecursive($array_name, $ident = 0){
  if (is_array($array_name)){
    foreach ($array_name as $k => $v){
      if (is_array($v)){
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . "
";
        listArrayRecursive($v, $ident + 1);
      }else{
        for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; }
        echo $k . " : " . $v . "
";
      }
    }
  }else{
    echo "Variable = " . $array_name;
  }
}

$ages = array(
        "ahmed" => "25",
        "mohamed" => "35",
        "group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20")));

listArrayRecursive($ages);

Output will be


Adding tool tips to menu items and views I need to add tool tips to some of the primary links in my menus, and also to a link in a view, I tried to use the Tool Tips module, but it doesn't seem to be designed for this kind of use... is there another module I can use, or is there another way I can integrate tips to my dynamic content?

Take a look at the qTip module or the Tipsy module as alternatives to get "good looking" tooltips or simply add a description to the menu items for basic browser created tooltips

Beautytips would do the trick, I think:

  The Beautytips module provides ballon-help style tooltips for any page
  element by integrating the BeautyTips jQuery Tooltip plugin by Jeff
  Robbins with Drupal. It provides an API for adding custom beautytips
  as well as some built-in features. Admins can enable rollover
  balloon-help style tooltips for text fields within forms. It also
  supplies hover tips for Drupal help links and advanced help links.

The module page has a very nice video to achieve what you need


Twig conditional render if specific field in array of referenced entities contains text In a Twig template, I'm conditionally rendering a sidebar based on whether custom field content.field_body (Paragraphs entity reference revisions field type) contains any items.
{% if content.field_body['#items'] %}

In this article:

      {% for item in content.field_body['#items'] %}
        {% if item.entity.field_subhead %}

            {{ item.entity.field_subhead.value | raw }}

        {% endif %}
      {% endfor %}

{% endif %}

This worked fine until the requirements changed. :)
Now I need to render this entire sidebar
 if and only if one of the item.entity.field_subhead fields in the ['#items'] array contains a value.
{{ dump(content.field_body['#items']|keys) }} returns the following:
^ array:2 [▼
  0 => 0
  1 => 1
]

So the ['#items'] are a regular numerically-indexed array.
Rephrasing the question, is it possible in Twig to write a conditional that returns true if any key of a multi-value field contains a specific field?
This is further complicated by the fact that there may be different Paragraph types referenced here, and only one of these (the "Section" paragraphs type) will contain entity.field_subhead, but there might be any number of Sections.
Bonus points if whitespace returns false.
EDIT: Thanks @Hudri!
For future reference, the code that worked in my case looked like this:
{# Test every Section for non-empty Subhead #}
{% set render_sidebar = false %}
{% for field_item in node.field_body %}
  {% if field_item.entity.field_subhead %}
    {% if not field_item.entity.field_subhead.isEmpty %}
      {% set render_sidebar = true %}
    {% endif %}
  {% endif %}
{% endfor %}
{# If any Section contains non-empty Subhead, render block #}
{% if render_sidebar %}

    {# a bunch of markup #}

{% endif %}

I'd always do data checks on the entity object (in this case node), and not on the render array content. The second part is the magic .entity to get the linked referenced entity from the host's entity reference field:
{% set render_something = false %}
{% for field_item in node.field_entity_reference %}
  {% if not field_item.entity.field_to_check.isEmpty %}
    {% set render_something = true %}
  {% endif %}
{% endfor %}

{% if render_something %}
  <div class="my_wrapper">
    ...content...
  </div>
{% endif %}

Be warned though data behind .entity is usually not cache-safe (but it is cache-safe in this special case with Paragraphs, because their revisioning is directly tied to their host entity)

So I had this similar issue and decided it was much easier to do this in a preprocess function rather than trying to handle it in twig, and then pass has_sidebar as a variable to the template.  Much easier to handle this in something like preprocess_node or something like that.  Our case was a little more complex because it had to be pre content type, but that premise was the same.  This is the case where preprocess is really the best option.


How do I invoke a service after submitting a form? I am very new to Drupal and I am asked to create form with a submit button and a service that makes a get request to an API with the values from the form. The API is a simple API that the user can enter a country and it will return a response with the correct greeting from that country.
This is my routing file.
hello_world.salutation:
  path: '/hello'
  defaults:
    _controller: Drupal\hello_world\Controller\HelloWorldSalutation::salutation
    _form: Drupal\hello_world\Form\GreetingForm
    _title: 'Get a greeting from a different language'
  requirements:
    _permission: 'administer site configuration'

First problem is that I do not know how to make the form and the controller in the same routing,
and second is that I do not know how to invoke that service when the user has entered submit.
This is the services file.
services:
  hello_world.salutation:
    class: Drupal\hello_world\HelloWorldSalutation
    arguments: [ '@config.factory' ,'@tempstore.private']
  cache.nameofbin:
    class: Drupal\Core\Cache\CacheBackendInterface
    tags:
      - { name: cache.bin }
    factory: [ '@cache_factory', 'get' ]
    arguments: [ nameofbin ]

I will skip some lines from the GreetingFrom class to keep it simple, but I can add them if it is required.
Here is the submitForm function from the GreetingForm class. The idea is to put the input in a global tempstore so I cal access the values from the controller I guess.
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $search_str = $form_state->getValue('greeting');
    // check the input
    $params['items'] = $form_state->getValue('greeting');
    // 2. Create a PrivateTempStore object with the collection 'greetingForm_values'.
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    // 3. Store the $params array with the key 'params'.
    try {
      $tempstore->set('params', $params);
    } catch (\Exception $error) {
      // dump the error for now, read error, --fix this!
      dpm($error);
    }
  }

And the salutation function from the controller looks like this.
  public function salutation()
  {
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    $params = $tempstore->get('params'); // this value should come from the search form
    return [
      '#markup' => $this->salutation->getGreeting($params),
    ];
  }

You're trying to do four things at once (form, service, integration with API, caching), so you can't see where the problem is. Instead, break this down into distinct steps.
First, code and debug your form. In the submit function, just use the messenger service in your form ($this->messenger()->addMessage('this is a test message');) to display a static value for your greeting. You should reach a point where visiting /hello and submitting the form will display the message. You can customize that message later. Get this working first.
Second, code and debug your service class. I find it useful to use drush php-script here to execute a standalone PHP script that accesses your service. That way you can ensure your service is doing exactly what you want, and figure out how to communicate with the external API, before you try to use your service in a form. You don't need the "_controller" in your routing file. The way to access your service is using \Drupal::service('hello_world.salutation')->salutation(). Instead of passing variables through a tempstore, pass them as parameters to your salutation() method. So your standalone PHP script for drush would look something like this:
<?php

  $greetings = \Drupal::service('hello_world.salutation')->salutation('some string entered on your form');
  echo $greetings;

Save this as test.php then execute this with drush php-script test.php.
Third, once your service is working as you want, integrate your service with your form. You should be able to take the PHP script you wrote in step two and insert it almost unchanged into your form submit function. (As a future enhancement, learn how to inject your service into the Form rather than use the static \Drupal::service() call, but that can wait until after you have this working).
Fourth (do this only after you have the above working), examine your need to cache data, and then implement some sort of caching in your service if needed. You haven't shown all your code or completely explained what you're doing, but I don't see anything that justifies using cache.nameofbin or a tempstore.

I would suggest taking a look at hook_form_alter
Forms can have multiple submit functions and its best not to wipe out the original functionality (unless that's what you really want to do)
Your code might look something like this
function yourmodule_YourFormID_form_alter(&$form, &$form_state) {
     // conditions you execute custom code

      $form['#submit'][] = 'yourmodule_submit_function';
}


Form Submission Problem I've a form...

function modulename_myform($form, &$form_state)
{
        $form['my_ta'] = array(
            '#type' => 'textarea',
            '#resizable' => FALSE,
        );
        $form['my_submit'] = array(
            '#type' => 'submit',
            '#input' => TRUE,
            '#value' => 'Submit',
            '#name' => 'sub_1',
            '#button_type' => 'submit',
        );
        return $form;
}

My form couldn't submit any data... So I tried doing two variants...

/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message('Submitted Value @name',array('@name'=>$form_state['values']['my_ta']));
}

Output : Doesn't print anything and says value is null at that location...

/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message(t('Submitting values: @values', array('@values' => var_export($form_state['values']['my_ta'], TRUE))));
}

Output : Prints the Dump with proper values...

Why is that? It should be giving me the text entered in my_ta right? Please help me...

the first attempt doesn't contain t() function in set message function... hence it's failing...

The 1st would not work as it is neither default and nor explicitly defined against #submit.
For first to work:

$form['#submit'] = array('modulename_myform_submit')

The 2nd should work.

If still it is not getting submitted then make sure the form is properly rendered and processes by drupal_get_form()


enable jquery ui effects in theme .info file Now I should add something like <?php drupal_add_library('system', 'effects.bounce'); ?> to my page.tpl.php to enable jquery ui effects to use in views_slideshow_cycle module.

is there anyway to do this inside theme .info file?

No, it's not possible to add a Drupal library through a module or theme's .info file. You can add single CSS/JS files, but not a defined library.

That means it's physically possible to download separate copies of system libraries and include them statically in your theme, but you should not do this. It's not the 'Drupal' way, and it makes things very difficult to maintain.

You're right in thinking the logic shouldn't be in your page.tpl.php file, it should rather be inside your theme's hook_preprocess_page function in the template.php file.

That way the library will be added in time to be included in the page, you maintain a nice level of separation between logic and display, and your theme will be protected in the case that core updates need to be applied to the libraries you're using.

Sure, download jquery ui from http://jqueryui.com/ and put the javascript file you need in your theme then add a line

scripts[] = relative/path/to/file.js

Just make sure that jquery UI is binding to the jQuery variable and not $ and you should be good to go.