Gmap click marker should zoom the map and display other markers I have two content types: City and Place.
Both of them use a location field which has lat long fields enabled.

The Place content type has a node reference field to City content type.

I want to display a google map, which will display the City nodes markers. Clicking on any marker will zoom the map and will display the place nodes markers in that city.

And then clicking the place marker which will open its detail page.

Is it possible with gmap and views or any other module? Or a custom script will be used?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it.


How to add Variables in Drupal (and how to visualize them)? I'm new to Drupal Answers, but I've been programming for a few years now.

I'm looking to create something simple (at least I think) within the Drupal CMS to use throughout the site. I want to create a variable, let's call it $phonenumber and store the value of this variable, like (789) 456-7894 (not a real number). That way I may use the value of this variable on my site without hardcoding the number.

I have installed the Variable module, which has little to no documentation, and poor usability all around.

I build in PHP, I know this is basic, Drupal is built on PHP. But for some reason I cannot get a printr or echo of the variable on any page to work.

Are you aware of the devel module? It is typically used in dev versions of a site only, and is not recommended for production status sites.

After you enable that module, you'll get many features, such as dprint_r(), dpm() (I like the last one for debugging). For more details, refer to https://www.drupal.org/node/174575 ...


Entity Filtering mechanism I've come to face this issue time and again and I haven't yet found a solution without having to compromise something.

This scenario applies both to admin and front end.

There seems to be a lack of an efficient way to filter Entities according to some of their properties and/or fields.

In my example I'll use Users as my entity.

In multiple occasions I've had to filter users. Either to reference them to a node (entity reference), or to perform a bulk operation (front end - invite them to something or send them an email, doesn't really matter). The requirement would be pretty much the same: A view-like presentation with exposed filters that would allow for an operation to be performed to the selected Entities.

I am aware of Views Bulk Operations but even that lacks flexibility in this aspect, as it "resets" the form in each trigger of the exposed form.

If, I wanted to send an email to all the "Johns" and "Marys" on my user base, I'd
have to filter against "John", select the users that are presented to me, and then filter against "Mary", select all the users that are presented to me, again, and then, either press the submit button or reset the filter to preview my selection.

Thing is that after the (ajax or not) exposed filter submission, the "John" checkmarks are lost, and if I Clear the exposed form, so are the "Mary" checkmarks.

The exposed form submission simply fetches a "fresh" view-form with it's rows filtered accordingly.

On the backend (entity reference) there seems to be some work by the entityrefence_view_widget module but it's still in the makings.

My question would be: How do you tackle such an issue when you face it in your projects? Is there a way I am not aware of?

Customized as it may be, it worked:

Using VBO and performing a hook_form_alter onto the exposed filter form I was able to add a hidden field.

Using javascript, I store the values of the selected entities (derived from the checkboxes attributes) into the hidden field. If the user triggers the exposed form submission, the values remain and on the new page load I use the same values to recheck the checkboxes thus providing the illusion that the values got preserved.

Downside is the unavoidable use of javascript and the possible huge URL.

If anyone has anything better to propose or make the exposed form NOT place it's parameters as $_GET parameters in the url I'd be glad :)


How to check if custom variation field is null in twig? I would like to know how to check if a custom variation field has content in a twig template (commerce-product.html.twig with variations injected). I have tried with some filters and conditions but without success. I need to hide some html markup if the field is empty. For example:

{% if product.variation_field_mycustomfield is not empty %}

My custom field: {{ product.variation_field_mycustomfield }}

{% endif %}

My products have some variations that users can select from a list. When this select changes, the product information must change, and some variations of the same product could have this field empty or not.

This question isn't related to only image fields. It's for any kind of field.

just vardump() the product.variation_field_mycustomfield that have an empty field then :
then if it is an array  :

{% if product.variation_field_mycustomfield|length == 0 %}

My custom field: {{ product.variation_field_mycustomfield }}

{% endif %}

otherwise, if it is not an array and it is no empty but it has
default value that is considered as empty:

{% if product.variation_field_mycustomfield == 'the vardump output you get at step1' %}

My custom field: {{ product.variation_field_mycustomfield }}

{% endif %}


Automatically backing up uploaded files? One of the news sites I'm developing is heavily reliant on its image database, which has been migrated from the old site and is ~15-20gb at this point.

It's dawned on me that it would be really bad if there was some sort of server malfunction and all of the images in that directory were lost -- they're generally created on-the-fly by one person every week from much higher-resolution versions that have been pushed so far back into a totally-disorganized archive that it would take ages to resize and upload them all again (Which isn't even going into the awful process that would be re-adding them to the site's ~15,000 article nodes).

To this end, I'm looking for a way of backing up the uploaded images folder in sites/default/files. One thought I've had is to use Subversion's WebDAV Autoversioning capability, though I'm not overly sure how I'd get the Drupal 7 filefields to use this.

I could also just write a script to rsync files between two servers once a night -- the newspaper's office has a few servers for that sort of thing.

Any thoughts what a good backup solution would be for this particular situation?

Thanks!

I have not been in the situation before, if I were in your shoes I would take a look at the CDN module.

In File Conveyor mode (ie, a push model), it will automagically copy files up to your CDN of choice.  A side effect of this is the fact that the files will now live in two places.  You can go with one of the commercial CDNs, or you can set up your own with another server.


I have images missing between pages I have edited the page.tpl.php file to include an image in the header and another in the footer of the page.

When I am in the home page of the site ie. '/product_range' the images are there. If I navigate to another part of the site ie. '/node/1' they are missing. Coincidently this is actually the same page just referenced differently in the url.

In the page.tpl.php template I have referenced the image like this:

<img src="<?php global $base_path; print path_to_theme(); ?>/images/brand_icons.gif" alt="" />

This is the actual path to the images:
'\sites\all\themes\MySubTheme\images'

This is most frustrating... Thank you in advance for your assistance.

The return path from path_to_theme() doesn't have a slash at the front of it and so becomes relative to the path you're currently at. That would probably explain why it works for pages in the root of your site, but not those that are at least one directory down.

You should be able to fix it easily by adding a forward slash to the start of the image path:

<img src="/<?php print path_to_theme(); ?>/images/brand_icons.gif" alt="" />

On another note, make sure you fill the alt in...people with screenreaders will thank you for it :)


User error: "1" is an invalid render array key in Drupal\Core\Render\Element::children() I want to print "your_variable" (array) in my twig template, but i have errors.

I have .theme in my theme  :

function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $some_data = $tempstore->get('nid');
   $vars['your_variable'][] = array(3,4,5,6);
}

My "views-view-field" twig :

{% for  value in your_variable %}
    {{ value }}
{% endfor %}

The code work but i have errors :

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

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

Someone have idea to resolve this problem ?

I use Drupal 8

Remove the brackets after the ['your_variable'] part as your variable holds only 1 array:

function MYTHEME_preprocess_views_view_fields(&$vars) {
   $tempstore = \Drupal::service('user.private_tempstore')->get('evenementrimouski');
   $some_data = $tempstore->get('nid');
   $vars['your_variable'] = [3,4,5,6];
}

Also use the short array syntax. It's part of the new coding standards: https://www.drupal.org/node/2135291


Displaying products per store in a marketplace Don't know if I am skipping an obvious available feature but I am not seeing it.
I am building a marketplace, I have been struggling to display products of particular stores, visiting stores doesn't show the products of the store so I have been trying to make a view of the products belonging to a store. I want on the store page, products belonging to the store will be listed under the store profile. I am using commerce_marketplace. I have not been able to get the right contextual filters to display the products of a store on the store profile. What I am building is a showcase of stores, you click a store and find products of the store.
For store owners and admins, commerce_marketplace does a great job: on store profiles, there is a 'Product's tab. But for anonymous users and customers, no 'Products per Store' displays.
Is it me missing an obvious way to do this?

After 3 days of trying all kinds of Views setting, I finally found a solution to this issue, https://www.drupal.org/project/commerce/issues/3153177


block_html_id for view comes with uuid drupal I am not sure but to my understanding the block_html_id for the views should be with the patter of block-views-NAME-OF-VIEW-MACHINE-NAME, however it is coming up as block-views-UUID...i am guessing it is uuid some kind bunch of letters and numbers. Is this a bug? or this can be configured. The problem with the block-views-UUID pattern is that i am unable to use it in the preprocessor functions such as THEME-preprocess-block()

Any help is much appreciated. Thank you

Env: Drupal 7.26, views 7.x-3.7

The answer is in the following:
Views Block's machine name is being "hashed" (?)

It hashes block view name if the view name is larger than 32 chars


"exceeded the maximum file size" error even when uploading small files This error in my Drupal 7 site happens when I try to upload an image through image_field field. This is the error:

  An unrecoverable error occurred. The uploaded file likely exceeded
  the maximum file size (64 MB) that this server supports.

Although I am trying to upload a small 5KB photo, this problem exists. I know this is kind of common problem, but can't understand why this happens for as small images as 5KB!

How I can fix this? At first I thought this issue may have been temporary and does appear to have resolved itself this morning but again it happens.

I found a workaround, as this is a tricky one to nail down.

Don't hit the "Upload" button at all.  Just hit the "Next" button directly.  If that works, you ran into the same problem I did.


CKEditor - Apply Script I got a script that will change headlines etc in the CKEdtior. I'm sure a lot of you have done this before. Talking about the ckeditor.styles.js

Now, where do I apply this script into CKEditor? I can't find it anywhere. Can somone walk me through of how do add it into CKEditor

Thanks!

You need to FTP into your site and go to sites/all/modules/ckeditor/ckeditor.styles.js. There is not an admin option to do this, which it sounds like you expected.


How to import Product Kit via CSV file? I am trying to import product kit from CSV file but I am not getting how to import it as I need to link with products in product kit.

I am using Ubercart, Feeds and Ubercart product mapper to import.

Any suggestions?

Ubercart Feeds Mapper module:

Refer to the answer to the question about "How to import products to UberCart 3 using CSV data?". It contains a link to Drupal 7 Port of uc_feeds, which seems to include everything that's needed to make this to work by using the Ubercart Feeds Mapper module.

Note: from your recent question "Ubercart Product import containing HTML formatting in product description", I'm assuming that you are referring to the Ubercart Feeds Mapper module (instead of "Ubercart 'product' mapper" ...

From Ubercart.org:

Importing from CSV files also details the steps required for such import. The process consists of 3 steps. Here is a summary of these steps:

Prepare product data.
Activate the Node Import module.
Import process.

Attention, the 'Node Import' module does not have a D7 version, only a D6 version.


How to share Redis cache across Drupal servers? I have configured 2 Drupal servers to share the same Redis cache. One of the Drupal servers is being used for editors within the local network, the second server is used to serve up guest traffic. However, I noticed that Redis is storing cached based on the host key, so each of the two servers is storing separate keys in Redis.

What Redis configuration would be used to have it share the same keys and either override hostname to a single host or have it not use host as the key?

If you use the Redis module for Drupal, you can set the database and prefix used by your sites. The default Redis database is 0 (so multiple sites use the same database) but the default prefix is the HTTP_HOST variable (so multiple sites use different prefix). You can however, set a shared prefix on both site in their settings.php:

$conf['cache_prefix']['default'] = 'mysite_';

You can also set prefix per cache bin, to only share a subset of the cache between them. See Redis module's README.txt for more details.

Of course, this should only be done if your are sure the cache can actually be shared. In your case, I guess the sites share the database and are used to balance the load.


Should I use t() in a hook_menu's description? I have always used t() for hook_menus title and description like this:

$items['some-path'] = array(
    'title' => t('My Page Title'),
    'description' => t('This is a description about what my page is for'),
    'page callback' => 'profile_user_page',
);

This makes sense to me so users can translate the title and description into different languages if required.

However this comment on a module review on DO says:

No, that's wrong, don't do that - descriptions in hook_menu() should never use t().

What is the reasoning for this and is this actually best practice?

Also if this is true then should we not use t() for the title as well?

See Strings at well-known places: built-in menus, permissions, log messages and .info files community documentation:

  The Drupal 6 and 7 menu system stores menu item titles and descriptions in English. This allows the system to cache the data, but display to users using various languages on demand. For this to work, you should not use t() on the title or description of menu items in your hook_menu() implementation. Additionally, you should attempt to use a literal string (rather than a dynamic string) for these two keys, so the translation template extractor can find the string you used.

Emphasis mine.


Create email everytime a webform is sent off (in custom module) I'm trying to write some code that sends off an email every time a webform is submitted/edited.

I tried using hook_webform_component_presave() figuring I could just stick some mail code in this function and it would work... it didn't.

This is what I have

mymodule_webform_component_presave(&$component){
  mail('test@mail.com', 'subject', 'message');
}

I am aware that this can be done through a webforms setting, but that's not what I need.

I've solved this issue in Drupal 6 by adding a secondary submit function to the webform.  In that submit function, I use webform's email handler to send my email.

In hook_form_alter:

function custom_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
        case 'a_form': // the value we stole from the rendered form
        case 'another_form_form': //Fall through, instead of trying to do case A OR B:
        case 'the form I want to send emails from':
            $form['#submit'][] = 'my_submit';
            break;
    }
}

Then the secondary submit function:

function my_submit($form, &$form_state) {
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    module_load_include('inc', 'webform', 'includes/webform.components');
    global $user;

    $node = $form['#node'];
    $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);

    //Build the custom email array for the webform email handler
    $email = array(
     array(
      'nid' => $node->webform['nid']
      ,'eid' => count($node->webform['emails']) + 1
      ,'email' => $form_state['values']['submitted'][3]
      ,'subject' => 'Your Custom Subject Line!'
      ,'from_name' => 'default'
      ,'from_address' => 'default'
      ,'template' => '

Hello '.$form_state['values']['submitted'][1].',

More HTML goes here

'
      ,'html' => 1
      )
     );
     webform_submission_send_mail($node, $submission, $email);
 }

You could also probably just use the drupal_mail function to send the email in your custom submit function.  I just haven't tested that option.

For further info, take a look at  webform_client_form_submit and webform_submission_send_mail


Translate to specified language I know I can translate to current website language with t() function, but I need translate to specified (not current) language, my site has three languages and I want get English of some of the worlds in some template files when current language is French. How can I get translate of string according to specified language instead of current language?

According to  t() documentation you can pass specified language it t() function.

As Example below code return French translate of language string without consider current site language.

  $fr_value = t('language', array(), array('langcode' => 'fr'));


when the hook_block_info is get called? when

hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

are get called? is it possible to call these hooks manually in a module?

From the comments, I think you're confusing things a bit. There are two types of block:

Custom

the ones you create through the UI. The content for these is stored in the block_custom table.

Programatically defined

the ones that Drupal auto-discovers for modules that implement hook_block_info(). The content for these is defined in hook_block_view(), and is built on-the-fly, so to speak. The content can be cached, but when that cache is invalidated the implementation of hook_block_view() will be responsible for re-building it. Drupal doesn't store this content anywhere on your behalf.

You can use either type for your needs. If you want to use custom blocks there's a good approach here.

If you want to use the hooks, the approach should be like this (this assumes you have a data table called my_table that you've populated with the necessary content for the block):

function MYMODULE_block_info() {
  // Get identifiers for all your custom blocks.
  $deltas = db_query('SELECT delta FROM {my_table}')->fetchCol();
  $blocks = array();

  foreach ($deltas as $delta) {
    $blocks[$delta] = array( /* Block definition */ );
  }

  return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  if (!empty($delta)) {
    // Get your custom data for this delta
    $data = db_query('SELECT * FROM {my_table} WHERE delta = :delta', array(':delta' => $delta))->fetchObject();

    // And populate the block with it.
    $block['subject'] = $data->title;
    $block['content'] = $data->content;
  }

  return $block;
}

Obviously that's a trivial example and you'll want to add error checking and the like, but it should get you started. Note that you won't be able to have a temporary table as such with this method, your data will need to persist so it can be re-queried when the time comes.


How to send an email on every 10 contents that are waiting for admin approval? I want to notify admin only if there are 10 nodes in a queue. If 10 such nodes do exist, a single email should be triggered to admin.

How can I do this, any idea?

I have get all the users (uid) of particular role from the users_role table.

i.e :

$query = 'SELECT DISTINCT(ur.uid) FROM {users_roles} AS ur WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(3,8)));

Next step, I have count nids from workbench_moderation_node_history table.

i.e  I have made one function like get_train_users() in which i have returned the above $result array.

$trainusers = get_train_users();
foreach ($trainusers as $key => $value) {
   $tresult [] = db_query ('SELECT COUNT(nid) AS con,uid FROM  {workbench_moderation_node_history} WHERE uid = :uid AND state = :state' ,array(':uid' => $value, ':state' => $state))->fetchAll();
}

Now, In last step, I am counting the count of con, Like if it is greater then 10, then i am sending the mail when cron runs.

That's it.


How to go to external website from within a module? I have created a custom module in which when a user enters a valid id, it should them take them to an external website. The problem I am having is redirecting to the external website. The code I am using in my module is to do the redirection is:

  // clear out the output buffer
  ob_start();
  while (ob_get_status()) {
    ob_end_clean();
  }
  return header("Location: $external_url");

This doesn't work. What should I be using to accomplish this?

Thanks.

You should use drupal_goto to redirect to a URL.

drupal_goto($external_url, array('referral' => $referral_url));


How do I get a field label by the field name? How do I get a field label by the field name in Drupal 7?

The label is set per instance (not per field) so you would use the field_info_instance() function with some appropriate arguments:

$entity_type = 'node';
$bundle_name = 'article';
$field_name = 'field_some_field';

$info = field_info_instance($entity_type, $field_name, $bundle_name);

$label = $info['label'];

There's a bunch of other useful functions in the Field Info API documentation that might be helpful in case you haven't seen it already.


What is wrong with my custom token to embed entities via token? Edit: I guess it has something to do with the info part:

function mymodule_token_info() {
  $info = array();
  $info['types']['embed'] = array(
    'name' => t('Embed'),
    'description' => t('Embed entities via token.'),
  );
  $info['tokens']['embed'] = array(
    'name' => t('Embed entities using embed:node:nid:viewmode'),
    'description' => t('Embed entities'),
    'dynamic' => TRUE,
  );

  return $info;
}

I wrote a small module to allow embedding entities, such as nodes, via token:

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'embed') {

    // return $replacements;

    foreach ($tokens as $name => $original) {
      $args = explode(':', $name);

      if (count($args) > 1) {
        $entityType = $args[0];
        $entityId = $args[1];
        $viewMode = isset($args[2]) ? $args[2] : 'full';

        $entity = \Drupal::entityTypeManager()->getStorage($entityType)->load($entityId);
        $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);
        $renderable = $viewBuilder->view($entity, $viewMode);

        $replacements[$original] = \Drupal::service('renderer')->render($renderable);
      }

      // @todo: use cache bubbleable_metadata better
    }
  }

  return $replacements;
}

The token [embed:node:1] actually works fine.

For some reason though, I get the error:

  Fatal error: Cannot use object of type
  Drupal\Core\StringTranslation\TranslatableMarkup as array in
  /modules/token/src/Token.php on line 89

when saving any node, sometimes even regular admin pages/ forms. Uninstalling my module fixes the issue.

Is something wrong with how I return the replacements?

Token.php:

/**
 * Extracts data from the token data for use in array_multisort().
 *
 * @param array $token_info
 *   List of tokens or token types, each element must have a name key.
 *
 * @return string[]
 *   List of the names keyed by the token key.
 */
protected function prepareMultisort($token_info) {
  $by_name = [];
  foreach ($token_info as $key => $token_info_element) {
    $by_name[$key] = $token_info_element['name'];
  }
  return $by_name;
}

See the example : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21token.api.php/function/hook_token_info/8.3.x

Inside tokens there must be 3  levels, tokens][token_type][token].

Also tokens don't usually work like that and it will not be possible to validate that token, it is always a token type and that has tokens, which can have a type which then again has tokens. So you'd need to define types for your nested structure.

Not quite sure why you aren't using the entity_embed project to inject tokens, I assume this is supposed to be used inside a formatted text. https://www.drupal.org/project/entity_embed


Twig template not rendering new field variable I created a new field for a custom block type and have already exported necessary yml files and updated the yml for different view modes.
However, when I make a reference to the new field using the correct field_machine_name, it doesn't recognize it.
This new field is a checkbox, that when enabled, hides the h1 header of the page, but is still visible for screen readers.
sample code:
{% set hide_header_title = content.field_hide_header_title|render|striptags|trim %}

 {% if hide_header_title == 1 %}
    {% set hide_header_title = "show-for-sr" %}
  {% else %}
    {% set hide_header_title = "block" %}
  {% endif %}

With the code above, I'm only getting to the else statement.

@4k4, thanks for sharing the link. I was able to retrieve the value
this way: content.field_hide_header_title[0]

content.field_myfield[0] still gets the rendered output, now of the first field item. It's not a good idea to use it for programming, because the output can be formatted in different ways and is translatable. You don't want to adjust the code anytime this is changing.
For programming if/else code better use the block content object.
content['#block_content'].field_myfield.value
This is a similar question for a node field: Boolean field inside node twig renders ok but does not work in if statement


Best way to achieve the following layout I am pretty new to Drupal, I have a Content Type with a "Field Collection" say like below..

Title
Banner Image
Details - Field Collection Type (Short Title, Description, Links)

I would like to achieve the following style of output, basically upon "User Selection" in the LHS the RHS side should refresh and show the selected Field Collection item's Description. What is the best possible way to achieve this in Drupal 7 (Views with Contextual Filters?, Cycle? or Rotator components etc). Please advice.

Edit: It's only the Content area shown in the picture, there will be a Menu/navigation system wrapping this. Hence this actually becomes 2nd level navigation for that page/node.

thanks,
Vasanth.

Try Single Page Website module. Its a good option for this kind of website. Just create menu and give proper link.

  This module provide the ability to display the content of all menu items of the menu that you indicate in settings on the Single Page Website module.
  On the page 'single_page' the links in the menu will be replaced to the links to the correspondent anchors.
  You can set URL 'single_page' as front page of your site, and your visitors will see the Single Page Website. But it will be the site managed by Drupal 7.


Drupal recommended-project missing Drush I am looking to transform from drupal-project to recommended-project and seeing  some difference in the folder structure.

drupal-project contains a drush folder outside'web' folder and  'composer.json' contains line "drush/drush": "^9.0.0".

However, recommended-project does not have this setup although I could still install drush using composer require drush/drush. Still drush isn't installed outside 'web' folder.

Can I please know why the setup has changed and a way to have drush folder outside 'web'?

It is important to understand the distinction between the Drupal core project templates and the drupal-composer project template.

The Recommended and Legacy project templates are maintained by Drupal core. As a result, it only includes those components validated by the core maintainers to be very stable and needed by most Drupal users. The bar for this is very high, and the complexity of the component plays into the decision. For example, Drush is very stable and used by most Drupal users, but it is a fairly large and complex project, and therefore has not been added to a core project template. Use the Recommended project if you'd like your web root inside a "web" directory, or the Legacy project if you would like your web root at the project root.
The drupal-composer/drupal-project template is maintained by the community. It contains more components that are likely to be useful to a wide range of users. If a bug or configuration problem is found with this project, then it must be reported and fixed through the community repository on GitHub.

The latest version of drupal-composer/drupal-project uses the same core scaffold components as the drupal/recommended-project Composer template provided by Drupal core. It is safe to start with the drupal-composer/drupal/project template for your site.

If you add Drush to your site, either by starting with drupal-composer/drupal-project, or by adding it manually to the drupal/recommended-project, then the Drush binary will always be installed inside the vendor directory. This will be inside the web root for the Legacy project, or outside the webroot for the Recommended project, and for drupal-composer/drupal-project.

If you decide to start with the Recommended project and add Drush, you should also look at the composer.json for drupal-composer/drupal-project and see if there is any configuration in the "extra" section that you might want to copy over for your site.


How do I modify the "group" label? I would like to use Organic Groups in a way that would make each group a company. Is there an expeditious way to do a mass modification of the label "group" wherever it appears on the UI? I'd like the references to "group" to be changed to "company".

I think the String overrides module would be the quickest way. The module:

  Provides a quick and easy way to replace any text on the site.


Facebook for drupal throws errors on install. I have Drupal 7.9 installed with Facebook for Drupal module version 7.x-3.x dev.
Here are the errors given after turning on FB API & FBCONNECT:

Warning: include(/src/facebook.php) [function.include]: failed to open stream: No such file or directory in fb_requirements() (line 66 of C:\xampp\htdocs\drupal\phswap\sites\all\modules\fb\fb.install).
Warning: include() [function.include]: Failed opening '/src/facebook.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in fb_requirements() (line 66 of C:\xampp\htdocs\drupal\phswap\sites\all\modules\fb\fb.install).

reverting to a 6.x install for functionality is not an option.  I hope someone can help.

Have you read the powerful README.txt file inside the module. It says you have to install the facebook-php-sdk. The instructions in the readme are pretty clear. The error is thrown because it can't find the file.


how to show contents tagged under a parent taxonomy term I have contents that can be tagged per taxonomy terms (with hierarchies in content type), say,
Events > weddings
Events > birthdays
Events > public > national day celebration

The events (which is a vocab) actually turns into a menu (using taxonomy menus) and I want it so that when users click 'Events' menu all contents tagged weddings, tagged birthdays, tagged national day celebrations will show up on the page.

This content type (Events) has a field called 'Type' which is a hierarchical taxonomy list from the vocab 'events'. I had it set so that the term lineage will be save in the hierarchical select settings, I was under the impression that for any content tagged 'weddings' for example, this same content will also be tagged as 'events' by the system due to 'save term lineage' settings...

When I go to http://mysite/events (which i already configured using pathauto, and used views to display taxonomy terms related to nodes) none show up, as if none is being tagged 'events' at all. But when going http://mysite/weddings i get all contents tagged under weddings only (which is right).

Thanks!

EDIT: This content type (Events) has field called 'Type' which is NOT a hierarchical taxonomy list but a select list. Sorry for that.

I believe you may need to have the content tagged in both terms,  "Events" and "Type" for this to work without custom coding.

You can get this through a view or custom module quite easily, though. If no answers posted later on, I will post you an update when I get home as I am writing this from mobile.

Good-luck


How to display a field before the title when the title was printed before the node template? This answer works when the title is printed in the node template.

However, the base node template contains this code:

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

<?php endif; ?>

So how do I print a field before the title when the title was already printed in the page template?

page.tpl.php has a $node variable on all node/%nid pages. So you have two options:

You can use it directly in page.tpl.php (with the help of the field_get_items() and field_view_field() functions).
You can do your messing around with $variables['node'] in a THEME_preprocess_page() function in your theme's template.php, then add your complete data to $variables[] to print the final value in page.tpl.php.

This may also help: Setting up variables in preprocess functions


Display root terms based on child in a view I've a city vocabulary (see example below) which I import from 3-th party service. Each city may be spelled differently (either with wrong spelling or with special characters). In my example let's assume that TEST is a different variation of Oslo city.

These cities are already used in Content Type 'Person'. I built a view that display Persons with a category City. Everything works well and my view looks like this:

Now I need to substitute/replace TEST with Oslo (as it is different spelling of Oslo city).
On a view I expect to not see TEST and Oslo must get +1 as a counter.

  Oslo (34)

UPDATE
Here are my settings for the view.

What should I do in order to achieve that? Thanks.

Try this:

You can use relationship, and add "Taxonomy term: Parent term" field relation in it. Now make relationship with city field. It will give root term name based on child term name.

I have recently done this, it works.

Hope it will works for you.


Node reference URL in Drupal 7 How can I make a node reference URL visible only to the person who created the page/article?

You can do it by setting the appropriate permissions. For Drupal 6, content_permissions is part of CCK, and lets you set permission for every CCK field of your content type. For Drupal 7 you can use the Field Permission module.


How to show contact profile and membership details in one Civicrm report? I had a new profile called "Registration details" for contacts, and the profile fields can be edited in account page.

In my contribution page, membership form is enabled as a sign up form for my members, and the new profile  "Registration details" is included in the form.

I would like to have a report to show a summary of contact details, including  "Registration details" profile, and filter by membership status.

If I'm using Constituent Summary Report, I can get all the contact details summary, but I can't filter the report to show those with active membership only.

If I'm using Membership Details Report, I can filter the membership status accurately, but can't show the new profile fields of "Registration details".

Is there anyway I can configure it so that I can show both contact details and filter by membership status? Or should I make any changes to the profile?

PS: I'm using drupal 7, with CiviCRM 4.4.6.

Since you are using Drupal it can often be easier in my non-coding experience, to build a View to provide you with these kind of Reports - happy to provide more pointers if that is the direction you end up going


Overlay and jQuery don't work, what should I do? I have installed Drupal 7 on a local computer on stack called Denwer (similar to WAMP) and Windows 7; I see that all pages load without Overlay module (it is on, on modules page).
I guess that  jQuery does not work at all: Views slideshow doesn't work, when I add node all parameters load in a list instead of paging-listing mode.

I cleared all caches, reinstalled Drupal 7 using the development snapshot, clean-installed Denwer: all this doesn't work.

I remember I didn't have such problems on Windows XP.

Have you seen Overlay and jQuery dont work on Win 7, but work on XP?

The last comment reported in that report is the following one:

  Problem resolved. I still don't know why this problem arise, but after Windows 7 latest updates installed (on 18 apr 2011) overlay and jquery now working.


Cannot add new release for new contrib project I've recently promoted my project from sandbox
My project's "default branch" is set as 8.x-1.x
I've got a tag on my latest commit -- 8.x-1.0-alpha1 -- which is listed on my project's "git tags" area
As far as I can tell, I've followed the release naming conventions outlined on https://www.drupal.org/node/1015226

However, when I try to follow https://www.drupal.org/node/1068944, I do not see an "add new release" option at the bottom of my project page (or anywhere else). Any suggestions for what I may be doing wrong?

I see that dev releases appear to be generated every 12 hours, but the above has all been set up for longer than 24 hours.

It happens because on Media Entity Remote Image (the project you linked):

You aren't the project owner

The project owner didn't give you the permission to administer releases

As you see in the second screenshot, the checkbox for the Administer releases for the mrweiner account isn't selected.

If it were, you would see an Add new release link right after the Downlaods table, which is empty, for the given project.

If you want to be able to create new releases, you need to get the permission to administer releases too. Otherwise, the project owner needs to create the new release.

[Disclaimer: On Drupal.org I have more permissions than a normal user; that is why I see what project owners would see for their own projects.]


Return themed node via AJAX / AHAH Is there a way to get a fully themed node given the node id or path alias so that I can render it via AJAX / AHAH?

Create a menu hook with the path "[themed_node/%node]".

Within the function returning the the output for the menu hook use

return theme_node($node);

And then make an ajax call to "themed_node/nodeid" whenever you need the themed node.

Hope that should work.


How to edit the template of a node teaser that is sent in a newsletter email? I have a content type for my newsletter, it has an entity reference field that displays the latest articles of my site in a teaser format.

I tried to edit the teaser display in my node.tpl.php like this:

<?php if ($teaser): ?>
    <!-- teaser template HTML here -->
  <?php else: ?>
    <!-- regular node view template HTML here -->
  <?php endif; ?>

in the website all is correct, what i put inside the if, is working but just in the website, but when i send the newsletter, the email arrives with something very different (something like a standard format), could you please tell me were can i edit the way my newsletter send the emails?

I think it would be easiest to change the teaser in the Manage Display tab under the appropriate content type. That will apply everywhere.

However if you have custom theme stuff you want to accomplish you'll have to make sure you're affecting the correct theme. It sounds like the e-mail generator may be using a different theme to send the e-mail?

A simple way to test for this is putting
HELLO
 in a template that you think it's using.


Dynamic file directory for file fields I just learned about the creating fields and content types and had a quick question about the file field.  When you create a file field you can specify a relative path that the uploaded resource will be stored by entering a path in the "File Directory" text field, but what I am going to need is to have the value be different depending on the circumstances.  For example I might want to clump all of the files uploaded by a certain user so I might want the relative path to depend on the user's name.  Is there a way to specify this type of dynamic path?  Is the something people normally do?   Or would they just organize files based on type?

It's very easy if you have the Token module installed. On the file field edit page you'll see something like this:

The big table is a list of tokens that you can use in the path for the file. By default there are tokens available for current user, current page, current date and a couple of others.

For example you could have a path such as users/[current-user:name], in which the token would be substituted for the current user's name. You just need to click in the text box you want to add the token to and then click the links in the table, it will auto-fill for you.

Hope that helps


Checkbox so user can decide whether image should be displayed or not I would like to add a checkbox yes / no whether the image field should be displayed or not in a node.

Mh, there are several ways.

One of this is to add a boolean field to the content type.
Then you can create a template for the node, or the field, and display it only if the value of the boolean field is "on".

What do you think?


How to get parent node from a attachment in drupal8 search api results I have apachesolr index search with Search API attachments. In the results I get a link to the file but I would like to get a link to the parent node. I tried in the view but there is no such field with relationship to file usage.
I wrote the following in a module to override the field fid in the view but it returns an error

function hook_preprocess_views_view_field(&$variables) {
$view = $variables['view'];
$field = $variables['field'];
    if ($view->storage->id() == 'saa' &&
    $view->current_display == 'page_1' &&
    $field->field == 'fid') {
        $fid =  $variables['output'];
        $file = \Drupal\file\Entity\File::load($fid);
        $file_usage = \Drupal::service('file.usage')->listUsage($file);
        $variables['results'] = $file_usage;
    }
}

It returns

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to Drupal\file\FileUsage\DatabaseFileUsageBackend::listUsage() must implement interface Drupal\file\FileInterface, null given, called in /home/rebecca/public_html/new5/modules/pdf_app/pdf_app.module on line 262 in Drupal\file\FileUsage\DatabaseFileUsageBackend->listUsage() (line 123 of core/modules/file/src/FileUsage/DatabaseFileUsageBackend.php).

$file should be instance of Drupal\file\FileInterface but in this case $file is null so you should check first on $file something

function hook_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->storage->id() == 'saa' &&
    $view->current_display == 'page_1' &&
    $field->field == 'fid') {
    $fid = $variables['output']->__toString();
    $file = \Drupal\file\Entity\File::load($fid);
    if ($file && $file instanceof Drupal\file\FileInterface) {
      $file_usage = \Drupal::service('file.usage')->listUsage($file);
      $variables['output'] = $file_usage;
    }
  }
}


How to output $variables without loading everything? I'm trying to debug a drupal 7 site and print_r() the $variables variable, but its HUGE and crashes certain pages when there is alot of data in it. Is there a way to only output the first level of the array without outputting everything inside of it?

Devel is a great tool for debugging. It comes with krumo() function which works similar to print_r() but doesn't output everything, only up to certain depth (I think 3 or 4 levels).


What good is the create() method? Most classes are instantiated using create($container) and __construct(...$services) in conjunction, it seems that the more efficient workflow would be to simply pass the container to the constructor __construct($container) and not have the create method at all. Is this inherited from Symfony? What purpose does it serve?

The create() __construct() pattern does make testing easier, but not by much. A new container can be very easily generated and populated with the required services for unit testing.


Changing Global: Text Area based on an exposed filter in views? A client wants to display different text in a page depending on the value of the View's Exposed Filter.

I could throw this logic into the template.php or use javascript (showing and hiding a span depending on the value), but this feels like a very poor way to do this when considering maintainability?

Does there exist a Views plugin to perhaps show different text blocks in the header based on the value of an exposed filter?

Currently on Drupal 7.31 using Better Exposed Filters. I'm open to using something other than Global: Text area if there is a better mechanism.

You could use

hook_views_pre_render(&$view){
    $view->attachment_before = $view['exposed_input']['your_desired_field'];
}

Hope it works


Error after migrating site I get this error after I have migrated my site from local to live.

  Notice: unserialize() [function.unserialize]: Error at offset 718 of
  1340 bytes in views_db_object->load_row() (line 2251 of
  /storage/content/16/184116/.com/public_html/sites/all/modules/views/includes/view.inc)

And this results in my site not showing my views. I suspect that this could have something to do with me changing "mylocalsitedirectory" to "mylivesite" in DB before importing DB to live site and ending up having a different serialization in Views than what it expects. But how do I solve this?

You don't have to delete everything.  Using database viewing/querying software (phpMyAdmin, dbForge Express, etc.), you can identify exactly which view is causing problems allowing you to remove only one view or attempt to fix it.

It is detailed in this answer: https://drupal.stackexchange.com/a/105393/8506


Is drupal bootstrap phases will be called for each page request or its only once on site load? All drupal bootstrap phases will be called on each page load or only one time  when site will load.

Since Drupal is a PHP application, there isn't a persistent process running on the server for it (unlike some other language frameworks).  This means that Drupal will bootstrap for each request it handles.  This can be a page load, a request to make an image derivative, an AJAX handler, a 404 page, and other things that aren't thought of as normal pages.  It also means that concurrent requests will result in concurrent PHP execution.

However, with the way it is designed, there are various levels of bootstrap, and different requests don't require the full bootstrap.  For example, a page request from a cold cache will require the full bootstrap.  When the page cache is enabled, and there is a hit, it will stop at DRUPAL_BOOTSTRAP_PAGE_CACHE.


Can I add my own if statement to node.tpl to test if field groups are null? I have a content type with 4 different field-groups utilizing the Field Group module. I want to test to see if those groups are empty and render them and some additional HTML if they are NOT empty, and not render them, and additional HTML, if all the fields in the group are empty.

I'm not sure of the syntax to test if field groups contents are NULL, any pointers there?

So far this still isn't working for me. I have a field group that I know is empty group_factory_images

When trying to use the code from the answer:

<?php if(!isset($node->group_factory_images))
print 'Yep, Empty';
?>

It just prints the "Yep, Empty" string.

For example:

I created content type
In display settings for Full content display created group group_mygroup

If group elements are empty then group wil not be displaying. In this case you should check it:

//if node's group_mygroup does not exist
//in our case it means that all elements in group are empty
if(!isset($node->group_mygroup))
        print 'Group elements are empty';
print render($content);

As you can read in node template help part - block of comments:

 * Other variables:
 * - $node: Full node object. Contains data that may not be safe.

Now, what you can do to understand solution more clearly:

Install Devel module

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).

Somwhere in your template's code use
dpm($node);
Create content of your type and see how it is displaying. You should see same picture

Click on header of appeared block and you can see structure of node object

If you want to check if some field doesnt exist - use same construction:

if(!isset($node->field_name))
print 'Field is empty';


OpenLayers default zoom level I have a map setup with Openlayers and mapbox. I need to set the default zoom level to be in-between 1 and 2. So something like 1.5, as 2 is too zoomed in and 1 is too zoomed out.

I have entered different values under 'zoom level' within 'center & bounds', but only whole numbers seems to have an effect on the map.

Does anyone know of a way to set a default zoom level that is not a whole number? So something like 1.5 ?

I am using Drupal 7.

Thanks you help is much appreciated.

I'm not sure you can do that, I think the Zoom level has to be an INT.
Basically there is as many tiles'size as the number of zoom available.
That means there is no tiles available for a float value, otherwise it will require too many tiles to have a map not fuzzy.


How to block third party cookies? I have EU Cookie Compliance installed on my website.
In the settings I have selected Opt-in option.
On the site front end, I only agreed to the functional cookies but there are cookies set by third party websites which are still saved.
I checked the module's issue queue and found this.
https://www.drupal.org/project/eu_cookie_compliance/issues/3109974#comment-13459494
https://www.drupal.org/project/eu_cookie_compliance/issues/3059471
It seems that this module will not block the third party cookies.
Is there any other way to do this?

There's no way for the module out-of-the-box to block cookies created by 3rd party components. That's a simple fact of life. For example, if you by some means inject the code to embed a YouTube video on your site, it'll serve YouTube cookies to visitors to that page and EU Cookie Compliance won't be able to block them. When a YouTube video is served there is a direct communication between YouTube and the browser which other components cannot interfere with.
(In the case of YouTube you can use their cookie-free domain but let's ignore that for the sake of this illustration.)
In order to allow EU Cookie Compliance to prevent YouTube videos appearing to users who haven't accepted cookies, you'll need to implement some Javascript that calls the function Drupal.eu_cookie_compliance.hasAgreed() provided by the module for this purpose and blocks YouTube by some means when they have not. Typically you'll have to alter the embedding code to include your own JavaScript checks and display a suitable placeholder message when a video is blocked.
An example of how to do this for Google Analytics can be found at https://www.drupal.org/node/1648286#comment-6145800
For YouTube, the EU has their own component that does a similar job, that can be seen at https://ec.europa.eu/trustfund-syria-region/content/home_en
You'll need to perform a full audit of all cookies if you want to properly comply with the regulations. That's a larger topic than I can cover here but there are plenty of online guides and tools to get you started.


What is the best choice to create a node through code? The scenario goes this way, I have a node type which has lot of Taxonomy term fields in it. It does also have other fields like text, date etc but 90% of it is a taxonomy field. I am aware that a node can be created programatically in two ways,

node_save() -  Creating a node object and saving it

$node =  new stdClass();

$node->type = 'article';

$node->field_term[LANGUAGE_NONE][0]['tid'] = 3128 // term id of the term

node_save($node);

Form submit - creating a form array and submitting using drupal_form_submit

$node[field_first]['und'] => chennai;

$node[field_second]['und'] => "iphone5";

$node['type'] = 'article';

$form_state['values'] = $node;

$form_state['values']['op'] = t('Save');

drupal_form_submit($node_type . '_node_form', $form_state, (object)$node);

with $node having the POST values.

Advantage of using form submit method is Drupal will take care of creating new terms in vocabulary (I am supposed to get more new terms). Form submit can follow form validations which is needed for creating a node.

Is there any method to create nodes faster in to Drupal system which supposed to get more terms in it?

If there is no other method than the above mentioned, what is the best one?

The safest method is to use drupal_form_submit(). If you take at look at the services module it does the same thing. Form validation should be important if you are creating nodes programmatically. Are you importing or creating multiple nodes at once? If this is the case and you are concerned about performance you can use Drupal's batch api or queue. Batch is great if you need user feedback but if you are creating nodes on cron and don't require a ui with feedback then queue is the way to go. In both cases they take care of memory management for you.

I wouldn't be to concerned about how long it takes to create one node as that is how long it would take with the ui. Unless the reason you are doing it through codes is to increase creation times.


How to attach a database of data to a content / entity type I have an sqlite database representing a collection of Foo which is immutable. I would like to be able to take this collection of Foo in the GUI of Drupal, and append a few fields onto each Foo instance, these new fields are to be editable.

I see no point to inserting the data as nodes / entities directly as the data is only going to reflect what's already in the database and inserting data using node_save is incredibly slow for duplicating the data.

How would I accomplish this so that a content-type / entity type uses data from another database, but manages a few additional editable fields?

Would it be a custom content type with a module to manage the pulling of the data from another database, or would it be a custom entity?

I would use a custom content type that stores the primary key (pk) of an instance of Foo as text, integer or whatever you need, just that one field.  Let's call the content type Bar.

Then for display create a node template for Bar that:

Queries your database by sending Bar->pk and returns the Foo row/object
Iterates through the fields in the row and displays them where and how you choose

In case you haven't already come across it, if you're intending to use an external database, it is best to define it in your settings file and call it when you need it as described here.


How i could save a block that i had called it before with block_load? I call a block via a block_load function and i do some changes. What i want to save this block with my changes..

After reading the code in the block.module file I can suggest the following:

Leave your code in hook_block_info_alter unchanged.
From your hook_enable hook call the following function to force calling and saving your hook_block_info_alter code:

_block_rehash();

Quoting from the function's documentation:

  Updates the 'block' DB table with the blocks currently exported by
  modules.

Hope this does it for you!


List of links in an article I want to add a field on my type of content which allows authors to select a link in a list. If author doesn't find the good link, he can directly add it and name it.

The list has to be composed with the name (title) of all links saved by all the authors of my site. All authors have to be able to add directly a new link in this list.

Any idea ?

I would create a content type for the link and then there are two options I can think of:

Linkit, but I'm not sure it has a create option
Nodereference with a module like Node Reference Create or References Dialog


Separating User Picture from Submitted by date in Node on my node pages (drupal 7) the user picture is displayed along with the submitted by date. I'd like to separate them somehow so I can style them separately.

Anyone know a great way to do this?

Use the Display Suite Module

  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!

Watch the screencasts to see it all in action!


Advertisement block changing I have a Drupal 7 site, where there is a normal static block at the top of my content region. This is basically an advertisement with some full html content. Now I want to have a second similar block, and I'd like to keep them switching periodically somehow.

Before jumping on to coding something with javascript, I'd like to ask around to see if there is any easy solution for this, maybe a module for rotating ads?

(I know there are some themes that come with this feature out-of-the box, but I like my theme, so would not switch that for this minor thing)

Thanks!

Ok, looks like the right approach is not looking for something that changes blocks. I needed to define a content type, then create a view that lists my ads, and apply one of the numerous view-based carousels, like https://www.drupal.org/project/views_slideshow


Why is my form_state being reset after submission? I have a menu item with page callback:

function my_menu() {
  $items = array();
  $items['my/action/%ctools_js'] = array(
    'title' => 'do something',
    'page callback' => 'my_action',
    'page arguments' => array(2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

function my_action($js = NULL, $nid = NULL) {
  $form_state = array('nid' => $nid);
  if(!$js) {
    drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state['ajax'] = $js;
  $form_state['title'] = t('Form Title');
  $output = drupal_build_form('my_action_form', $form_state);
  $commands = array();
  if (!empty($form_state['finished'])) {
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect('challenges');
  } else {
    ctools_modal_form_render($form_state, $output);
  }
  print ajax_render($commands);
  exit;
}

function my_action_form($form, &$form_state) {
  // form fields defined here
}

function my_action_form_validate($form, &$form_state) {
  // $form_state['finished'] = true;
}

function my_action_form_submit($form, &$form_state) {
  $form_state['finished'] = true;
}

If I uncomment out the line in my_action_form_validate The modal form dismisses and the redirect works. But with that line commented out when I try to set the $form_state var in submit, the modal doesn't dismiss and doesn't redirect. The form submit code executes (calls to drupal_set_message work fine), but by the time it gets back to the conditional (line 11) in my_action, $form_state has been set to default and a blank form reappears in the modal popup. How can I dismiss the modal window after submission?

The issue was in the callback frunction my_action(). I was using the ctools_modal_form_render() function wrong. In the end I replaced the call to ctools_modal_form_render() with ctools_modal_form_wrapper():

function my_action($js = NULL, $nid = NULL) {
  if(!$js) {
    $form_state = array( 'nid' => $nid );
    return drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('My Action Form'),
    'ajax' => TRUE,
    'nid' => $nid
  );
  $output = ctools_modal_form_wrapper('my_action_form', $form_state);
  if ( !empty($form_state['executed']) ) {
    $output = array();
    $output[] = ctools_modal_command_dismiss();
  }
  print ajax_render($output);
  exit;
}


How to show children terms of parent terms in taxonomy? Ok this thing is driving me completely haywire! I think this question has been asked before in some ways but I seem to be too dumb to tweak those to my requirement.

I've created a taxonomy vocabulary named "Brands" of products like so

Level 1: Brand names like Logitech, Gigabyte etc.

Level 2: Product categories like mice, keyboards, headphones etc inside each brand.

Level 3: The actual products inside each categories.

These levels can go deeper if necessary. Like in mice there can be wireless and standard ones. I hope I'm being clear. I've also created a menu from this taxonomy by using "Taxonomy Menu" and "Superfish" modules.

Now what I want is that when I click a menu entry (could be of any level) the page loaded should list it's children inside it. Like clicking Gigabyte should list only the names of categories of products inside the page not the actual products. I've gone through many insane combinations of options in views but to no use. So far I've only managed to show product teasers on every level but that's not what I want.

I want to do things the way it's done on the following site:
http://www.shophive.com/

I'm using Drupal 7 by the way.

Please please please help me with this as I'm on a deadline! :(

Here's one way to do this.

Use Panels to override term_view.

Edit the overridden term_view panel.  Add a new variant with the default settings.  In the Content section, add content.  You want a List of related terms, which can be found under Taxonomy term.  You can set this to be the Child terms of the Term being viewed.


Force IE Compatitbility Mode I need to force IE to show my site in compatibility mode, and I know I can just add a META header. The problem is how... can anyone point me in the right direction please? I'm running a custom theme.

Thanks

IE has a header for controlling this, X-UA-Compatible.  Normally, people set this to 'IE=edge,chrome=1' which disables compatibility mode and tries to force Google Chrome Frame.  If you want to emulate IE7, you can use 'EmulateIE7'.

In Drupal 7, it is best to use a hook_html_head_alter for this

function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['MYTHEME_ie_compatability'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'name' => 'X-UA-Compatible',
    'content' => 'EmulateIE7',
    ),
  );

  $head_elements['MYTHEME_ie_compatability']['#attached']['drupal_add_http_header'][] =
    array('X-UA-Compatible', $head_elements['MYTHEME_ie_compatability']['#attributes']['content']);
}

This sets the <meta> in the <head> and also sets an HTTP header in the response.

In Drupal 6, you could use

function MYTHEME_preprocess_page(&$variables) {
  drupal_set_header('X-UA-Compatible: EmulateIE7');
}

You can also do this via Apache (eg, in .htaccess) with

<IfModule mod_headers.c>
  Header set X-UA-Compatible EmulateIE7
</IfModule>


Highcharts not working I am using the Charts module for displaying charts in my Drupal project.
When I took the chart API example module page, it's not displaying any. It throws me this error (in the console):

  Uncaught TypeError: $(...).highcharts is not a function

Any idea on how to resolve this issue? Or is there anything additional to do after installing the module?

I enabled all the sub-modules of the Chart module:

And I selected Highcharts as the Charting library option:

Notes:

I added the chart js file inside charts/modules/charts_api_example and referenced the charts_highcharts.js file in the charts_api_example.libraries.yml file.
I think the issue may be because jQuery must be loaded before Highcharts when checked the view source on the API examples page the jQuery is loaded at last after the Highcharts library. Not sure though that's the issue.

I was thoroughly mistaken about the installation of the charts. After installation, I was editing the repositories section in composer.json  and running the composer command to install the specific library (eg: composer require --prefer-dist highcharts/highcharts:6.0.4) from the particular sub-module. But it has to be done from the Drupal project root directory. Appreciate your valuable time and expecting this will help others.


Node access, Cron, and DANGEROUS_ACCESS_CHECK_OPT_OUT' Observations:

Anonymous users can view nodes of a certain type
Cron runs as an anonymous user
Cron cannot access nodes of this type when
using EntityFieldQuery
Cron can access nodes of this type when the tag 'DANGEROUS_ACCESS_CHECK_OPT_OUT' is added to the query.

It seems to me that DANGEROUS_ACCESS_CHECK_OPT_OUT is a misnomer and should actually be DANGEROUS_ACCESS_CHECK_OPT_IN. If access was checked, Cron would know that anonymous users have access to this type of node, or am I missing something?

Based on the initial comments I think my question is not clear, so I am going to rephrase it. What I am seeing is that I allow the anonymous user to see this type of node, but Cron cannot query it. The references to this issue are ambiguous about the reason. If Cron runs as an anonymous user, then Cron should not get different access than an anonymous site user. Or Cron does not run with any user profile at all. That would actually make sense, but that is not how people explain this. So what is really going on? Is the flag a misnomer, or do people not make a clear distinction between "anonymous user" and "no user"?

I read it more as "Dangerous, Access Check Opt Out"


Image styles thumbnail, medium, large to default dimenssions My drupal create thumbnail of my uploaded image (thumbnail, medium and large).
I don't want to have redimensioned images, I want original size.

PS: drupal create 3 images per uploaded image, so, for me are lots of nodes.

How can I stop drupal from creating these?

Go to Configuration -> Media -> Image Styles (or analogous path in non-7 versions). By default you have 3 styles there, the ones you mentioned. You can edit them to suit your needs, but deleting them is not supported - to many modules uses them.

On the other hand, styled image files are supposed to be created on first access. You shouldn't have them on your file system until something really needs them, so to get rid of those files simply turn off everything that uses them, and purge /sites/*/files/styles directory.


Content appearing under specific tabs My site will be divided into multiple areas, or tabs, for example, Music, Politics, News, etc. Under each tab I'd like to display a different sidebar (my sidebar will contain menus representing categories, for example, in the Music tab, the sidebar should show Rock, Classical, Jazz, but in the News tab it should show National, International, Sport, etc). I'm hoping that all my content could be of the same content type, but that they exist under one tab or another.

How should I set this up?
So far I have tried similar content types, one for each tab, and a theme for that type which shows the appropriate sidebar. But it'd be nicer to use just the one content type overall, with a field indicating which tab it belongs to. Is that possible?

A multi-level taxonomy could accomplish this for you. Something like:

Music

Rock
Classical
Jazz

Politics
News

National
International
Sport

Create this, and then add a field for it on your single content type. Then use the Taxonomy Menu module to create a menu from your taxonomy, and the Menu Block module to place both a top level navigation, and the sidebar navigation. You can adjust what level the menu starts at for this.

Your taxonomy menu will link to each taxonomy term listing page, which is a default view. Further, if you setup URL aliases for your taxonomy, and then rebuild links, each page will have a meaningful URL (home/news/international). You can take it a step further by adding URL aliases for your content type as well, and use the taxonomy term path in that so you end up with (home/news/international/title-of-article).


Remove index.php from imported urls I made some migration of pretty old website to d8. And urls ported fine from latest WP version:

/user1/article-name1
/user2/2009/article-about-something
/user3/2017/11/06/article-something

But from what I see in google many articles would be linked with index.php at the end i.e.:

/user1/article-name1/index.php
/user2/2009/article-about-something/index.php
/user3/2017/11/06/article-something/index.php

etc etc. Somehow WP could handle it (no traces of overrides in htaccess), but Drupal would not.

Puzzled how to fix it with htaccess, preferably with 301 redirect.

Thanks for your ideas!

Solved thanks to https://stackoverflow.com/questions/27907044/htaccess-rule-to-remove-index-php-from-the-end-of-my-urls

Modified part of Drupal's .htaccess. Important to add new rule before standard index rewrite:

# Remove trailing /index.php that comes from external links.
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]

# Pass all requests not referring directly to files in the filesystem to
# index.php.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]


Hooking into page not found event My question is similar to How to redirect user for specific pages not found and some what useful discussion here: https://drupal.org/node/344960
and redirect missing pages to another site

I've a job site and I want to redirect using 301 all expired jobs to one common page. All expired jobs are deleted. To make it easy the job urls have unix timestamp suffixed in some pattern so that I can recognize a url as expired job.

Whenever a page request comes, I want to let it go normally but if page is not found then only I want to check the url with specific pattern and then redirect 301 to common page if it is url of expired job.

Is there any way to do it?

Go to Home » Administration » Configuration » System and set Error pages to some not used yet value, like http://localhost/403 and http://localhost/404, or http://localhost/forbidden and http://localhost/not-found. Then create a custom module. Implement hook_menu() to provide these pages. Use all logic you need in page callback function.


CSS sprites and pop up windows I have just implemented a css sprite for a list of items. The purpose of this was that when a user hovers over an item, the image changes... What I have been asked to do now is  to add a pop up for each of those list items. How would I go about doing this?

Is there any way by using aFancybox module to achieve this?

The pop up would consist of a page title, image and a close button.

At the moment the list items are hard coded in the page.tpl.php template.

I use drupal 7

This is the sort of thing I am trying to achieve. So a set of images which change on hover, and when clicked on a little pop up appears.

I wouldn't approach it this way. Hardcoding list items, with content, in a tpl.php is generally frowned upon and will ultimately require more work than this should entail.

Instead use Views and the Colorbox module. Create a view with the list of nodes you want to display, pop it in a block on the page in the region you'd like it to display, and use the Colorbox plugin to Views show the popover on click. Use CSS to style the colorbox however you please. This can be handled strictly with configuration and a touch of CSS. This way, when the theme changes someday, the functionality is maintained.

See http://drupal.org/project/views and http://drupal.org/project/colorbox for more details.


How to enable Google analytics while site is in maintenance mode? I want to know how many users visit my site that is currently in maintenance mode. I have installed the google analytics module, but it doesn't add google tracking codes to the maintenance page, so google analytics says "Tracking not installed".

How do I enable it while site is in maintenance mode?

You'll have to do it manually unfortunately, the normal page building handler isn't called for the maintenance page so the analytics module never actually builds up the necessary javascript.

You can follow the instructions here to set up a custom maintenance page template, from there you'll just need to add the tracking code manually to the bottom of the site. It should start working instantly.


Drupal View rewriting output of the field I created a taxonomy vocabulary with several terms and it is assigned to a content type. So a node can have multiple terms from that vocabulary. After assigning it I have created a view to format the content type nodes into a json data.

Now in the JSON data the taxonomy field is showing multiple values. I want to separate those individual items by comma. Please help me out how to do it. I've tried adding this expression to the tpl file.

]+>/i', ', ', $output); ?>

Without seeing your view, it is difficult to solve. But if you edit the taxonomy field in your view, make sure that in the MULTIPLE FIELD SETTINGS section the checkbox "Display all values in the same row" is checked. That should display the taxonomy terms as term 1, term 2, term n.


How to make Drupal 8 forget an old deleted field? After deploying a Drupal 8 site to a new server, we have the problem of an old deleted field being remembered by some subsystem or other, leading to this error being thrown on whenever cron runs:

Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[42S02]: Base table or view not found:
1146 Table 'drupal8_neu_default.field_deleted_data_1c89727af8' doesn't exist:
SELECT DISTINCT t.entity_id AS entity_id
FROM {field_deleted_data_1c89727af8} t
WHERE  (bundle = :db_condition_placeholder_0)
LIMIT 50 OFFSET 0; Array
(
    [:db_condition_placeholder_0] => video
)
in
Drupal\Core\Entity\Sql\SqlContentEntityStorage->readFieldItemsToPurge()
(line 1546 of /srv/www/neu.default.ch/builds/v1.0.0-alpha.7/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

I've spelunked all over the database, and I can't figure out where to expunge the reference to this long-dead table. It's not mentioned in config and the field_config table we knew from Drupal 7 is long gone. It's also not in the exported configuration.

Does anyone know how to fix this?

Execute this to remove deleted field(s), pending deletion:

drush php-eval 'field_purge_batch(1000);'


How to display field collection fields in tabs on add another item button? I have a content type which has a multivalued field collection field.
In this field I have a set of field collection items.
In field collection I have put the fields in horizontal tabs.

But the problem is when I click on add another item button it adds those set fields in a new row not in another horizontal tab.

Is there any module which should add fields in new horizontal tab? Or any custom code hint?

I have found the solution.

I used multiple value widget module. It does exactly the same.


Webform2PDF doesn't display arabic characters I'm using webform2pdf with TCPDF library to generate pdf of submissions, I have some arabic words in the submissions, the generetaed pdf doesn't display them.
Is there any config to do to solve this issue?

It solved, I just changed the font to 'DejaVu Sans' in Generate-PDF settings.


8 - Form Validate Entity Reference I would like to add a form validation to an entity edit form. The entity has an entity_reference field on which I would like to perform a manual validation. I have successfully implemented a hook function to access the data entered into the widget, perform the required checks, and raise an error if necessary. The problem is that I do not want to make my function dependent on the widget that is used to alter the entity_reference field.

An entity_reference field with cardinality bigger than 1 (i.e. the ability to store a list of entries) can be edited using, e.g., an Autocomplete, an Autocomplete (Tag Style) or a Select List. The problem is that the data accessible in the validation function will differ depending on what widget is used.

The function $form_state->getValue('field_name') returns either

Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) )

or

Array ( [target_id] => Array ( [0] => Array ( [target_id] => 2 ) [1] => Array ( [target_id] => 3 ) ) )

For a select_list or an autocomplete_tag, respectively.

I could obviously check what the structure of the array is to determine how to handle it, but I'm sure there must be a better way to obtain the data from this array.

My custom validation involves a check to be performed on a relation between the referenced entities and the user, so I do not need to perform any checks on the entered raw data. Basically, I just want to obtain a list of target_id's that I can interact with.

The solution was to implement entity-level constraints. This allows Drupal to manage the data that gets typed into the widgets, and no additional (widget-dependent) validation is necessary.

Apparently, the idea in Drupal 8 is that most entity-related validations are not done via the form validations. Instead, so-called constraints can be added, either on the field level to affect only one field, or on the entity level to affect multiple fields.

This GitHub repo contains example files for creating entity-level constraints, which were very helpful. You will need to create files for the Constraint and for its Validator. Furthermore, you will need to attach the Constraint to the Entity, which can be done either using hooks (as demonstrated in the .module file, see link above) or by adding this to the annotations of your entity:

 *   constraints = {
 *     "ExampleConstraint" = {}
 *   }


Display No Results Text for Individual Field Groups in View I have a drupal view set up to show links to certain documents.  These documents are grouped by department in a Grid layout and then sorted by date.  What I want to do is if there are no results available for a particular group in the grid layout, display a no results text line for that.  I am willing to just put php generated text in the header or footer if that is an option.  I do not want to generate a page of non-sense content titled "No Results" to inject it in the grid (that's what we're doing now)...I'm trying to get it to handle itself. Hopefully this layout will demonstrate it better if it's hard to understand:

  Department Documents

  Department 1

  04/25/2015 <--(These dates are rewritten to link to documents)

  04/26/2016

  Department 2

  No results

  ...

Edit

I would rather not make this behavior global for all Grid views, if possible.  I have other grid views where I do not want to display this, it is only on this one view.

The best to do this is using theme layer. In your case,views-view-grid.tpl.php is used to display the results.

There are different ways to alter that.

Solution A: Using template preprocessors

Add this function to template.php in your theme folder.

<?php
/**
 * Implements hook_preprocess_views_view_grid().
 *
 * Check if there is no result for this group and provide an appropraite message.
 *
 */
function phptemplate_preprocess_views_view_grid(&$variables) {
    $view = $variables['view'];
    if ($view->name == 'YOUR_VIEW_NAME') { // Only do this for a specific view
        if (empty($variables['rows'])) {
            $variables['caption'] = t('No results.');
        }
    }
}

Solution B: Overriding the template file

Copy views-view-grid.tpl.php to your theme folder and then modify it.
You may also want to rename the template file so it would only apply to a specific view. (Learn how to find the appropriate template file name for Views).

<?php

/**
 * @file
 * Default simple view template to display a rows in a grid.
 *
 * - $rows contains a nested array of rows. Each row contains an array of
 *   columns.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>

<?php // We check if there is no result we print a meesage ?>
<?php if (empty($rows)) : ?>
  <?php print t('No results.'); ?>
<?php endif; ?>

<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>

<?php print $caption; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>


how to refer to data of referenced node In drupal 6, I have an event node type and an event_attend node type.

The event_attend node type has a nodereference to event. In hook_form_alter for the event_attend node type, i added a validation routine.

In the validation routine, i would like to have access to the parent event node. I would like to compare event_attend's date of participation to the date when the event is taking place.

Is there a way of doing this without doing a node_load($nid_of_parent_event)?

I was kind of hoping that somewhere in the $form variable lies data for the parent event's date but I think such is not the case. That is why I am posting the question here.

I am using openatrium 6x by the way. Anyway, I'll just make a query directly to the database to get the parent event's date using the event nid.

Thanks to everyone.

In drupal 6, the standard way of doing this is by using the following function:

node_load($nid = NULL, $vid = NULL, $reset = FALSE)

However if you want to implement it in Drupal 7, it becomes a lot easier using the Views and the References module. All you need to do is :

Create two different content types say a and b and add fields to them. You MUST add a node reference field(say to b)
A pop up would ask you to choose which node you would like to reference(choose a here)
After that if you wish to look for some advanced settings, you can add Relationships depending on your requirement.


Need your advice. MultiSite I want to create a project like http://www.chinatexnet.com/, but before begin writing code I want to ask for advice from the experts.

So, project that I am planning to develope contains just one main website and multiple sub-sites (about 500 subsites). If you look at http://www.chinatexnet.com/, there is one main site and too many subsites with same(simple) structure. The main site has noting its own it just gathers information from subsites. Subsites have defferent look, defferent information but same simple structure.

So what I am thinking is to create two sites, one for main site, the second is just template for subsites. Than create instalation profile by the second site (of course with the data which users inserted) and automate procces with drush. Finally get multisite system.

Is this right way or I need to use contrib modules like Domain Access or Subsites? I've read a lot about multisite system, and I know there can be problems like updating or gathering data to main site. But I can't see another way, so, if anyone has experience with such kind of projects, please, advise me.

P.S.: Sorry for my english :)

Given your description, the domain access module is the better way to go. Drupal multisites won't give you the capacity to have one main site and many smaller sub sites but that is the key feature of domain access:

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites ...


How do i display format_interval? In Drupal 8 I am using

$date_service = \Drupal::service('date');
$options = drupal_map_assoc(array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200,
  64800, 86400, 172800, 259200, 604800, 1209600, 2419200), array($date_service, 'formatInterval'));

But this gives me error

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  You have requested a non-existent service "date". Did you mean one of
  these: "theme.negotiator.system.db_update",
  "entity.definition_update_manager", "date.formatter",
  "update.post_update_registry", "update.post_update_registry_factory",
  "access_check.db_update", "access_check.update.manager_access",
  "update.manager", "update.processor", "update.fetcher", "update.root"?
  in Drupal\Component\DependencyInjection\Container->get() (line 161 of
  /Applications/MAMP/htdocs/drupal-8.0.x-dev/core/lib/Drupal/Component/DependencyInjection/Container.php).

What wrong am i doing? Am i missing use class something like this use Drupal.... or something wrong in line $date_service = \Drupal::service('date');

My piece of working code:

$time_intervals = array(30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000);

$options = $this->build_options($time_intervals);

Also i have defined following function in the same class:

function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}


How can I show a block in a view page, excluding its paginated pages? I want to place put a block in a view page. Let's say the news page, whose path is http://www.example.com/news.

The view uses pager to list the content.

I want a block to show up only in the very first page of the news page (http://www.example.com/news), excluding from paginated pages, such as news?page=1, news?page=2.

I set the visibility to only list in news, but the block still shows up in news?page=1, news?page=2.

How can I show a block in a view page, excluding its paginated pages?

You can also achieve the same in using following snippet, in the blocks visibility settings by turning PHP code on,

<?php
  $url = request_uri();
  $pos = strpos($url, "page");
  if ($pos === false && arg(0) =='news') {
    return TRUE;
   }
 ?>


Making one term in a vocabulary priority and print it separately I have several terms in a vocabulary and my content type can be tagged with more than one of them.

When I print the term names tagged with the currently viewed node it seems that the term names are printed always in the same order (in the order of term id?)

However I somehow need to make one priority term per node and then print its term name first or separately from the rest.

Is there anyway to do this?

Easiest non coding way make a separate vocab and disable tags and multiple select for the new vocab then theme as required.


Content restrictions for logged in user with specific role We use a D7 site to market and sell products B2B. We have a special client that only wants to see a small selection of products when logged in. I can of course give them a special role and allow them permission to view content that others cannot see. But when it comes to hiding ALL the other products on the site, I'm not sure how to think... it means giving them more restrictions when logged in with a special user role.

Normally you get more access when logged in and given a special role, compared to not being logged in at all. But in this case I need to do the opposite.

Any ideas?

This looks like a perfect use-case for hook_node_access with $op='view'. You check if the user is 'special' and apply your logic to approve/deny the view.
You could have a new role for this, or a new field on the product nodes, or some other idea. It very much depends on what your logic is there.


MAMP database upload problem I completely removed Acquia Dev Desktop & XAMPP and installed MAMP.

Plain vanilla Drupal 8 that I downloaded which is works. Now I want to import the database dump created by ADD, but keep getting an error message saying the file is too big. I believe the problem centers around php.ini. I can find no php.ini in the WAMP folder. I found php.ini-development & php.ini-production. I increased the parameters in both files relating to maximum file size upload, but they had no effect. I then copied php.ini-development & renamed it php.ini. I restarted the server, but it had no effect. Got any ideas as to how to fix this problem? i want to uploaded my new drupal website to this url https://www.kvtech.ae please help me to fix this problem.

Parameters changed -
max_execution_time = 30 to 1200

Changed post_max_size=8M to 128M
max_execution_time = 60 to 90000
upload_max_filesize=2M to 128M

Versions -

MAMP 3.2.0

Apache 2.2.27
Nginx 1.7.5
MySQL 5.5.41
PHP 5.3.23 & 5.4.1 & PHP 5.4.40 & 5.4.45 & 5.5.0 & 5.5.24 & 5.5.29 & 5.6.0 & 5.6.8 & 5.6.13 & 7.0.0
OpenSSL 1.0.2e
APC 3.1.13
APCu 4.0.4 & 4.0.7
eAccelerator 1.0
XCache 3.0.4 & 3.1.0
OPCache 7.0.4
Python 2.7.6
mod_wsgi 3.4.0
Perl 5.16.1
mod_perl 2.0.8
phpMyAdmin 4.2.7
SQLiteManager 1.2.4
phpLiteAdmin 1.9.4.1
Freetype 2.4.10
curl 7.36.0
libpng 1.5.18
ImageMagick 6.8.9-1
Imagick 3.1.2
gd 2.1.0
zlib 1.2.7
libxml2 2.9.1
gettext 0.18.1.1
iconv 1.14
mcrypt 2.5.8

I assume you are trying to import this via phpMyAdmin and that the file is an standard DB dump.

I would recommend either doing this via drush or the mysql command line.  E.g.:

drush @mysite sql-cli < \backup\my-dump.sql

Note:  drush @mysite status should show db schema and user name.

or

mysql -u user -p d8-database-schema-name < \backup\my-dump.sql

Another alternative would be to use the MySQL Workbench Tool.  Excellent GUI tool that runs on any OS and can even access databases via SSH.  Set up a connection to your DB, then load the dump as a script.  Make sure your target database schema is selected as default.


How do I display a message to users, with the selections they has made from the contextual filter? I have a view with more than one contextual filters.
For example, filter on Age, and Gender. if the filter is on Age, and/or gender
I would like to display a message to the user regarding the selections he/she has made. i.e, Message to user: "you are filtering on age"...
How can i achieve this? I thought about writing my own module to do it, but i figured there might be an exiting module, or solution that does this already.

Thank!!

You can add a Header to the view, some of the tokens you can add include the Contextual filter values


Video embed field doesn't honor the autoplay settings So I have an embedded video field inside of a paragraph and want it to autoplay.  I have set the settings for the field to have it autoplay, but when the iframe is rendered the url has autoplay=0.  Are there other settings I need to enable to get this to work?

Use the following code to change autoplay to 1 in your template or Javascript file. It works for me.

jQuery('.video-embed-field-launch-modal').attr('data-video-embed-field-modal', function(i, oldSrc) {
  var isAutoPlay = oldSrc.match(/autoplay=([^&]*)/);
  if (isAutoPlay && isAutoPlay[1] == 0) {
    return oldSrc.replace('autoplay=0', 'autoplay=1');
  }
});


7 - Add classes to individual fields of paragraph bundle Hi in paragraphs module for drupal 7, how can we assign classes/html tags to individual field items of paragraph bundle?

There is Classy Paragraph module that lets us to add classes to the paragraph wrapper/section. How to achieve the same for individual fields of paragraphs?

Most people add another field, such as a select list with predefined options, and turn that into a class using a preprocess, or merge in the paragraph twig template.  If don't have a predefined list, and you allow user input, you will need to sanitize the input.

How I do it in the twig template is like this:

{# Renders Width field. #}
{# Sets class name from values in database. #}
{% if content.bp_width|render %}
  {% set layout_width = content.bp_width['#items'].getString() %}
  {% set layout_width_classes = [
'paragraph--width--tiny' == layout_width ? 'paragraph--width--tiny',
'paragraph--width--narrow' == layout_width ? 'paragraph--width--narrow',
'paragraph--width--medium' == layout_width ? 'paragraph--width--medium',
'paragraph--width--wide' == layout_width ? 'paragraph--width--wide',
'paragraph--width--full' == layout_width ? 'paragraph--width--full',
  ]
  %}
{% endif %}

{# The template default set classes. #}
{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}

{# Merges Width field with classes. #}
{% set width_field = content.bp_width|render %}
{% if width_field %}
  {% set classes = classes|merge(layout_width_classes) %}
{% endif %}

{# Prints div with classes, and content without Width field. #}
<div{{ attributes.addClass(classes) }}>
  <div class="paragraph__column">
    {{ content|without('bp_width') }}
  </div>
</div>

How do the Bootstrap styles get added?  Here is an excerpt from the LESS file:

.paragraph {
  .make-row();
  margin-left: 0;
  margin-right: 0;
}

.paragraph > .paragraph__column {
  .make-sm-column(12);
  .make-md-column(12);
  .make-lg-column(12);
  padding-bottom: @jumbotron-padding;
}

Which compiles into the following CSS:

.paragraph {
  margin-left: -15px;
  margin-right: -15px;
  margin-left: 0;
  margin-right: 0;
}
.paragraph > .paragraph__column {
  position: relative;
  min-height: 1px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 30px;
}

You can overwrite that in your theme if needed.


Does hook_node_submit() fire on feed import? If I implement hook_node_submit(), will it be invoked when I import nodes from a feed?

I believe hook_node_submit() only gets fired when submitting a node form. So the answer to your question is no.

I think you might be better off using hook_node_presave(). This hook is invoked from node_save() before the node is saved to the database.