Extending EntityFieldQuery's method finishQuery doesn't work as supposed Extending EntityFieldQuery's method finishQuery with the following code causes query return nothing:

class ClientEntityFieldQuery extends EntityFieldQuery {

  public function finishQuery($select_query, $id_key = 'entity_id') {
    $select_query->leftJoin('field_data_field_date', 'o', 'client_event.eid = o.entity_id');
    $or = db_or()
      ->condition('o.field_date_value', time(), '<')
      ->isNull('o.field_date_value');
    $select_query->condition($or);

    // Call parent method
    parent::finishQuery($select_query, $id_key);
  }
}

But when I copy the contents of finishQuery to the extended class (see below), the query works fine. So why does it not work when altering $select_query in the extended class and then calling parent::finishQuery($select_query, $id_key)?

This works:

class ClientEntityFieldQuery extends EntityFieldQuery {

  public function finishQuery($select_query, $id_key = 'entity_id') {
    $select_query->leftJoin('field_data_field_date', 'o', 'client_event.eid = o.entity_id');
      $or = db_or()
        ->condition('o.field_date_value', time(), '<')
        ->isNull('o.field_date_value');
    $select_query->condition($or);

    // This is copypaste from EntityFieldQuery's method finishQuery
    foreach ($this->tags as $tag) {
      $select_query->addTag($tag);
    }
    foreach ($this->metaData as $key => $object) {
      $select_query->addMetaData($key, $object);
    }
    $select_query->addMetaData('entity_field_query', $this);
    if ($this->range) {
      $select_query->range($this->range['start'], $this->range['length']);
    }
    if ($this->count) {
      return $select_query->countQuery()->execute()->fetchField();
    }
    $return = array();
    foreach ($select_query->execute() as $partial_entity) {
      $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
      $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
      $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
      $this->ordered_results[] = $partial_entity;
    }
    return $return;
  }

}

I think it's because you're not returning anything from the function.

The code for the base finishQuery() function returns at the very least an empty array; at the moment your function isn't doing that.

The fix might be as simple as changing the last line to:

return parent::finishQuery($select_query, $id_key);


get node title from url I have field_employee and i want to get his default value from nid in url

../node/add/qualifications?field_employee=3617&destination=node/3617

To display it Like:
field_employee == $node->title; //As a default value

function _get_emp_name(){
 global $base_url;
  $current_url = $base_url . request_uri();
  $url_sub = substr($current_url, 0, explode('&', $current_url));
  $to_array = explode('&', $current_url);
  $ar_name = explode("/", $to_array[1], 2);
  $node = node_load($ar_name[1]);
  $name = $node->title;
  return $name;

}

Then with form_alter I use:

$form['field_employee']['und'][0]['target_id']['#default_value'] = _get_emp_name();


Theming the node edit forms  to open them within Lightbox I'm trying to display all the node edit forms neatly within Lightbox, without any of the excess content I don't want: no sidebars, footer, header, nothing but just the content. So I created a page-node-edit.tpl.php file.

I have two problems daunting me, but for now I'll only mention the first since its more important.

From any page, clicking on the "edit" link for the node doesn't activate the Lightbox like it should; instead, it clicks through the link as normal.
With jQuery in the header I added a "del" attribute for the Lightbox to the links, but the box still doesn't activate. I tested the Lightbox on a link I hardcoded into the page, and it activated just fine. For elements generated by Drupal, like the node edit link/button the problem seems to be timing.

I think the "del" attribute needs to be built with the page, with the link, rather than appended onto it. The catch is, the link lacks an id and class, so I don't see how the hook_alter_link() function can help me.

I'm willing to try anything. Perhaps someone has opened a node/edit form within Lightbox before.

If installing one or 2 additional module is an option then you can check Popups API (Ajax Dialogs). When I last checked, the module had functionality of opening forms in popups, which you can theme. I also feel that, in the way Drupal form API works, there is more to done then just adding classes and JavaScript to make Drupal forms work in Lightbox.


How to log in to site after removing login form After I logout. I couldn't login. I didn't assign the block for the user login. I tried out ,

?q=user

$block['content'] = drupal_get_form('user_login_block');

$form = drupal_get_form('user_login');

It displays:

User account Error
The website encountered an unexpected error. Please try again later.

How to get the log in. Please help me

Best bet is to reset the default theme to Bartik or one of the other core themes to log in, then you can fix your mistake there.

Using Drush:

drush vset theme_default bartik

Not using Drush:

Look in your variables table and switch out whatever is currently in theme_default for bartik (ensure that the number following from s: matches the number of letters in the theme name, so Bartik would be 6, Garland would be 7)

UPDATE variable SET value='s:6:"bartik"' WHERE name = 'theme_default';
TRUNCATE cache;

(Modified from Unusable theme - How To reset your theme)


Drupal Twitter widget not showing tweets Hi i am working on drupal site And i have noticed Twitter profile widget is no more working and its showing an empty space in the tweets block. I checked developer pane i have found following notices.

TWITTER WIDGET: The Twitter API v1.0 is deprecated, and this widget has ceased functioning. widget.js:1

TWITTER WIDGET: You can replace it with a new, upgraded widget from https://twitter.com/settings/widgets/new/user?screen_name=people_10 widget.js:1

TWITTER WIDGET: For more information on alternative Twitter tools, see https://dev.twitter.com/docs/twitter-for-websites

Do you have any suggestions to overcome this issue ?

You did not provide enough information. Which module? Which version of Drupal? If you're on Drupal 7 and you're using the Twitter module, you must carefully follow the documented installation procedure, documented here.


How to open a link in ctools modal by clicking a views row in table format? I want to open a page in ctools modal. This works for me.

Click

But now I want to open the same page in ctools modal by clicking the views row. The views is in table format.

It opens the link but not in ctools modal. I am using bootstrap theme.

I noticed that after page load there is another class added to the anchor tag ctools-use-modal-processed which is not added to the table row.

And we can't use an anchor tag before or after the tr in html table. We can only use it inside a td.

How can I achieve this?

I used this code and it solved my problem.

// Bind table rows that will open ctools modals to the appropriate function.
      $('tr.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          element_settings.url = $this.attr('href');
          element_settings.event = 'click';
          element_settings.progress = { type: 'throbber' };
        }
        var base = $this.attr('href');
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
      });

and table row like this

<tr class="ctools-use-modal" href="/my-page/nojs">

Hope it will help someone.


Cannot access data passed to $vars in theme function I have got a problem in my template.php file, where I am trying to add data to $vars. I basically have a preprocess function for a view and in it I am trying to pass some extra info to $vars. However, the view is not getting those variables. This is what I have in my template.php file:

/**
  * Generic preprocess that is still working on D7
  */
function mytheme_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;
    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
* preprocess variables for the badge owners view
*/
//function mytheme_preprocess_views_view__badge_owners (&$vars) {
function mytheme_preprocess_views_view_fields__badge_owners__page_1(&$vars) {
  $bid = $vars['view']->args[0];

  //Get the badge info
  $badge = db_query("
    SELECT ubb.bid, ubb.weight, ubb.name, ubb.image, ubb.href,
    ubb.unhideable, ubb.fixedweight, ubb.doesnotcounttolimit, ubb.tid
    FROM {user_badges_badges} ubb
    WHERE ubb.bid = :bid", array(
      ':bid' => $bid
  ))->fetchObject();

  $vars['bid'] = $bid;
  $vars['name'] = $badge->name;
  $vars['badge'] = theme('user_badge', array('badge' => $badge));
  $vars['an_extra_variable'] = 'hope this shows up in $vars';

  drupal_set_title(t('Badge: @badge_name', array('@badge_name' => $badge->name)));
}

This is what I have in my views-view--badge-owners.tpl.php file:

<?php
/**
* Variables available:
* - $css_name: A css-safe version of the view name.
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
* - $admin_links: A rendered list of administrative links
* - $admin_links_raw: A list of administrative links suitable for theme('links')
*
* @ingroup views_templates
*/
?>
<div class="view view-<?php print $css_name; ?> view-id-<?php print $name; ?> view-display-id-<?php print $display_id; ?> view-dom-id-<?php print $dom_id; ?>">
  <?php if (isset($admin_links)): ?>

      <?php print $admin_links; ?>

  <?php endif; ?>

<?php print $badge;?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

 <?php /* class view */ ?>

Any help would be appreciated. Thanks.

OK, it looks as though you're using the $badge variables in a more general parent/container views template, when the $badge variables are added in a child template preprocess function. The tpl variables aren't available at that container point.

The solution is to implement

hook_preprocess_views_view

and add the badge data vars there instead.

e.g

THEMENAME_preprocess_views_view(&$vars){
  if (isset($vars['view']->name)) {
    switch($vars['view']->name){
      case 'badge_owners':
        if($vars['view']->current_display == 'page_1'){
          // Rename current function to this
          THEMENAME_preprocess_views_view_badge_owners_page_1($vars);
        }
      break;
    }
  }
}


Hide/remove js-view-dom-id in just one specific view I found, that the div with the id "js-view-dom-id" comes from views-view.html.twig. As I want to render one view output without any of Drupals HTML markup, I already hunted down the contextual links, which I can turn of for a specific view. Then I set the view format to an unused format, and removed all unwanted HTML markup from this views template as well.

Now I get plain {{ content.field_x.0 }}-output from this view. The only element left I need to get rid of is before mentioned "js-view-dom-id". I could remove this from views-view.html.twig, but then I would remove it from all views.

Is there any way to remove this markup for only one specific view? To be precise, I am using a custom content view mode, if that makes any difference.

Thank you very much in advance!

@edit:

Twig in views-view.html.twig looks like this:

{%
set classes = [
dom_id ? 'js-view-dom-id-' ~ dom_id,
]
%}
<div{{ attributes.addClass(classes) }}></div>

Is there any way to do something like:

{% if view mode is xy %}
// Do nothing
{%  else %}
<div{{ attributes.addClass(classes) }}>
{% endif %}

Yes, you can easily create an override for views-view.html.twig which will only apply to a single View.
Taking the example from Views template files:

View, named foobar. Style: unformatted. Row style: Fields. Display: Page.

views-view--foobar--page.html.twig
views-view--page.html.twig
views-view--foobar.html.twig
views-view.html.twig

So if your View is called "articles", you can use views-view--articles.html.twig to override the template for the whole View, views-view--articles--page.html.twig to target just a display named page for the same view, and so on.


How do I setup multi sites in Drupal 7 using xampp I face a problem in multisite with Drupal 7.34. I'm using windows 7 Os. The steps that I followed are:

1. Create a database for all sites : create db of all sites test_db, trial1_db and trial2_db.

2. Install Drupal : I installed the drupal 7.34 as usual and name it test.

3. Tell Windows and Apache about the multiple sites : Open Windows 'hosts' file in a text editor.  Which is typically in /system32/drivers/etc/hosts. And add following lines:

                   127.0.0.1 test
                   127.0.0.1 trial1
                   127.0.0.1 trial2

Now in httpd-vhosts.conf file, which is located in c:/xampp/apache/conf/extra. I append these lines at end of the file:

                   NameVirtualHost *:80
                   <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs"
                     ServerName localhost
                   </VirtualHost>

                   <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName test
                   </VirtualHost>

                  <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName trial2
                  </VirtualHost>

                  <VirtualHost *:80>
                     DocumentRoot "C:/xampp/htdocs/test"
                     ServerName trial3
                  </VirtualHost>

and make sured that these are not commented in httpd.conf.

                LoadModule rewrite_module modules/mod_rewrite.so
                Include conf/extra/httpd-vhosts.conf

4. Create directories for the sub-sites: Navigate to c:/xampp/htdocs/test/sites and create the directories 'trial1' and 'trial2'. And copy the default-settings.php file to each directory and rename it to settings.php. And also set the permission of these file. I mean these files are not readonly.

5. Install the sub-sites : In an open browser, navigate to http://trial1 or http://trial1/install.php

But here I got "Object Not Found!".

I followed the these links also.

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

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

http://www.dratek.com/node/77

How do I setup multiple sites with one database in Drupal 7

Thanks @Sumit Madan for your suggestion. My issue has been resolved now. I just append these lines in test/sites/default/settings.php:

  $sites['trial1.com'] = 'trial1.com';
  $sites['trial1.localhost'] = 'trial1.com';

  $sites['trial2.com'] = 'trial2.com';
  $sites['trial2.localhost'] = 'trial2.com';


Views exposed filter for several fields Have 3 content types. Apartment, hotel, motel.

Each has integer field "number of beds".

Lets say user wants to see apartments that have between 10 and 15 beds.
In views for apartment i made exposed search filter adding number of beds 2 times, 1st is "greater or equal to" and 2nd is "less or equal to".

This all works fine.

Now i want to apply this filter to all content types in one view so that user after entering from 10 to 15 beds applies this search request to all content types at same time.

Solution that should work is to create 1 bed field on apartment and use that existing field on hotel and motel, but i want to have it separated so that i have control of each field in each content type separately.

I have tried Global: Combine fields filter, but it does not support "greater or equal to", "less or equal to" etc.

Create your first view block for Apartment with the exposed filter. Create attachments for each of the other two that inherit the exposed filter. As the comments stated, as long as they used the same field this will work perfectly.


How do I show a Drupal 8 contact form on a page? I've created a new content type called "Form Page", with a required field being a reference to a contact form. So on the page you would have a body, and under that the contact form itself. I can't seem to figure out how to display the form on the page. I either get a link, or the system name of the contact form printed out. How would I go about this?

There needs to be a little more to the Contact Form entity for you to be able to display it.  The easiest way to get this is to install the Contact Storage module.  After doing this, your manage display options will include "Rendered entity" which will give you the contact form as you hoped and expected!


Similar/related tags block There are a lot of ways to build similar content block according to their tags. Is there any way to build similar tags block?

I try to build similar/related tags block.

I want to look at contents and common tags they have. How many times they added to contents together. Something like this:

For example: for first column green is similar for blue. For the third column yellow and blue similar for green.

Create one content views for block
Relationship > Taxonomy term: Content with term
aggregation setting yes
use count on aggregation setting for the field.

There are other options available over here.
https://www.youtube.com/watch?v=w22Utjm-chs


Creating an "unzip" module that can interface with Content created through the GUI and through node.create by was of Services module (Drupal 7) I am creating a website that will allow users to upload projects.  Project submissions will consist of a couple of text fields, a screenshot and a .zip file.  Once the user uploads their project, I need to unzip the .zip file and catalog its contents.  Also, it needs to be possible to upload these projects through the web interface "Add New Content" and through Node.create by way of the services module.

So my first question, is there a way to hook up a module that will be triggered after a content type is created?  I built my project content using the built in Drupal 7 CCK editors but I see no way to hook up some code to this that could unzip my file and then do whatever else needs to be done.

Now if the above is not possible using CCK does that mean I need to recreate this content type by making it into its own module?

Finally, where would be the best place to put this unzipping code?  I could see it might be cleaner to make a standalone module for unzipping but might it be easier to put this code directly in the content module (if I have to make one)?

I think the best place for your code is in a custom module, in hook_node_insert() and hook_node_update(); they're fired when a node is created and updated respectively. As the services module uses the standard node save/submission functionality these hooks will be fired even when using services.

It would make sense to keep your un-zip code in that same module.

This is a brief example just to show what I mean:

function MYMODULE_node_insert($node) {
  // Get the file ID from the node field
  $fid = $node->field_file[$node->language][0]['fid'];

  // Load the file
  $file = file_load($fid);

  // Pass the file path off to the unzip function
  $result = _my_unzip_function($file->uri);

  // Do the rest of your processing...
}


Having the NOT IN SQL query equivalent in a view I have a site in which user can choose three programmes between 9. I would like to have a view that gives me the 6 programmes a user didn't choose. I've created programmes using taxonomy so each of my users have a term reference on programmes that contain the 3 programmes.

Any idea would be appreciated, Thanks

Forget the Views Raw SQL module. Simple SQL is not going to give you the result you need. Queries look for what is there, not what isn't.

You will need to construct two lists. First, the list of programmes the user has selected.

$selected_programmes = array();

foreach ($user->field_taxonomy_programme['und'] as $selected_programme) {
  $selected_programmes[] = $selected_programme->name;

}

Second, the list of available programs.

$available_programmes = array();

$vocabulary = taxonomy_vocabulary_machine_name_load('programmes');

$programmes = taxonomy_get_tree($vocabulary->vid);

foreach($programmes as $programme) {

  $available_programmes[] = $programme->name;

}

Then you can use the two lists to produce a list of the unselected programmes, which can then be used to construct your query.

$unselected_programmes = array_diff( $available_programmes, $selected_programmes);

There is no way around it. The only way to construct a query for values which are not present is programmatically. I would suggest the use of a block with a php snippet to display this information.


Can I remove the "summary" from the "Text (formatted, long, with summary)" widget? When creating a new content type, by default it has the Body field, which has a Field type of Text (formatted, long, with summary).  For this content type, I don't want authenticated users to see the summary.

What's the proper way to hide the "edit summary" part for non-admin users?  Or, am I better off deleting the default Body field and creating a new custom field?

Well, that was easy.  On admin/structure/types/manage/page/fields/mycontenttype, you just have to uncheck the box for "Summary input."


db_add_field not working I want to add a new field to node  table using db_add_field when intalling a new module, but it seems there is something wrong or missing:
here is the code used:
/**
* Implements hook_schema_alter()
*/
function smart_delete_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['node']['fields']['show_in_inbox'] = array(
    'type' => 'int',
    'length' => '4',
    'default' => '1',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by Smart_delete module',
  );
}

/**
* Implements hook_install()
*/
function smart_delete_install(){
    if (!db_field_exists('node', 'show_in_inbox')) {
        $schema = drupal_get_schema('node');
        db_add_field('node', 'show_in_inbox', $schema['fields']['show_in_inbox']);
    }
}

ADD :
I made an db_query in hook_init() inside .module file :
$result = db_query("ALTER TABLE `node` ADD `show_in_inbox` TINYINT NOT NULL DEFAULT '1';");

this is working, but the same db_query in .install file is not working when disable/enable the module again!
(I cleared the cache, also add the file in .info file)

I don't think length is valid for integers. size is though:

$schema['node']['fields']['show_in_inbox'] = array(
  'type' => 'int',
  'size' => 'tiny',
  'default' => '1',
  'not null' => TRUE,
  'unsigned' => TRUE,
  'description' => 'Field added by Smart_delete module',
);

Data Types


Role can't see CKeditor options on Body field Probably a simple setting somewhere, but I can't find it.

On a Drupal 8 site, I have an editor role, to edit/create blog posts. They can see the body field, but it shows as raw html. The wysiwyg CKEditor doesn't appear for them.

The editor role is assigned to the same CKeditor configuration profile as the Administrator. They have ability to to edit the field and the content type. It's just specifically the CKEditor editing that is unavailable to them.

When I look under role permissions, the only option I see relating to any wysiwyg is "Administer Imce File Manager" and toggling this on/off doesn't make a difference.

I've double-checked that the role can edit simple html all the way up to full advanced html.

thoughts?

After some trial-and-error, changing role permissions, I was able to narrow things down.

I have a module called Simplify installed. When the permission "View hidden fields" is UN-checked, the role cannot see CKEditor. When I check that, everything works as intended.


X-Drupal-Cache header not always appearing on page I have a site which uses Drupal core anonymous caching.  However, I have noticed a very strange behavior. Sometimes I will load the home page and in the response headers will be the 'X-Drupal-Cache' header.  But if I reload the page again, the 'X-Drupal-Cache' header disappears.  I cannot understand how this could happen.

What might be the cause?

The response headers also containL Cache-Control:no-cache, must-revalidate, post-check=0, pre-check=0, which I understand will force the browser not to use a cached version of the page.

Strange thing is that if I access the same page using curl (e.g. curl -I http://example.com/), the X-Drupal-Cache header appears each and every time.

The behavior you're seeing is the result of having a browser cache. After the first request, your browser caches the document and keeps track of its  signature through the Etag/Last-Modified headers.

Upon subsequent requests, the browser makes a request to the server with the If-None-Match/ If-Modified-Since headers. If the document hasn't changed, the server returns a HTTP 304 Not Modified which tells the browser it's okay to serve its cached version of the page.

Because cURL doesn't have a caching mechanism, X-Drupal-Cache always appears; it needs to go directly to Drupal each time for the document.


How to create internal links during user navigation I would like to allow users to create links between pages within the website. This wouldn't even be a problem if I asked them to edit the page, but I would like to avoid the editing step in order to make their navigation more fluid.

What I have in mind more specifically is an empty field (like a search box) on each relevant page in which the user could just copy-paste an internal URL, which would then be processed by the system to create the link between the two pages.

I have no problem seeing how I could do that once the information is entered, but I have no idea of how I could do to integrate an empty field in my page and use it in the way I described.

Any hint? Thanks! :)

Igor

Relations module was built exactly for use cases like this. But be warned that it has a little steep learning curve.

Relations Add Module can significantly reduce your work and also has an auto-complete feature that is user friendly.

  This module provides a field that can be used to create/delete/update
  the relations from within the node/entity forms, with a generic
  autocomplete for each endpoint, and relation fields.


Add to cart link for product that sends user directly to checkout? I'm working on a Drupal 6 site with Ubercart 2.9. I need to create a link for a single product that adds that product to the cart and proceeds directly to the checkout page. The link would be in an email blast, and by clicking it the user would completely skip the product's node/page, would skip the Cart page, and would be deposited directly onto the Checkout page where they can enter their payment/shipping info and proceed.

Possible? If so, how?

The Ubercart Cart Links Builder turned out to provide the exact functionality I needed.


Creating line item of specific type programmatically Is there a way to create a line item of specific type (different from the default "Product" type) programmatically? The function commerce_product_line_item_new()creates a line item of type Product. I can't find a function that let's you specify an existing line item type other than the default Product one.

EDIT: Never mind. I just realized that the commerce_product_line_item_new() function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.


Countries Additional Data Tokens not working I'm using Pathauto and Countries to build path aliases that reflect the country and corresponding continent of a node. For example if a node's country field is set to Spain the url should be:
europe/spain/node-title.

My pattern is:
 [node:field-prgm-country:continent-name]/[node:field-prgm-country]/[node:title]
The country renders correctly but the continent shows nothing. I've tried any other additional data (see attached image) and none of it shows.

How do access this additional country data for use in my path aliases?

It apperas to be a known issue with some of the country metadata so the current solution is to use the following slightly different continent token:[node:field-prgm-country:continent]/[node:field-prgm-country]/[node:title]


how to Views call images of each node? I saw that is not in SQL of the view I have a View that shows the first image of each node (so, a common View). I saw the SQL of this view, and I saw that the image is not called inside this SQL, so, what's the way that Views call images of each node?

It sounds like your view is configured to show nodes instead of fields.

When a view is showing nodes (either as teaser or full), the view only uses SQL to get which nodes to show. Then it calls node_load() and node_view() before outputting. node_view() will output a node just like you were looking at it regularly and this is where the image is being pulled in, not in views itself (hence why there is no SQL to get the image).

When a view is showing fields, it grabs all the fields data using SQL instead of node_load() and displays that data using it's own templates instead of node_view().

Let me know if I can clarify further.


How do I remove container div from a specific view? I have tried for a few days now, to figure this one out on my own, but have had next to no luck getting a working solution.

The issue:
I have a view that displays a list of images, where all wrappers have been removed, so that it only contains the images themselves. I have also overwritten templates for this view, so that any additional wrappers from templates are also removed.

The issue is that views automatically adds <div class="views-element-container"> around the entire views. Normally this would be fine, but I have no need for it for this view, it's just cluttering the markup.

I know that it in some cases is used for additional functionality, such as the contextual links, but this has also been disabled for this view.

What I have tried:

I have tried to figure out if views also adds a template suggestion to container.html.twig, but sadly found no indication anywhere on what that might be (even if I used normal views template naming convention, it didn't override)
I have tried to access the views render array in a preprocess function, to unset #theme_wrappers, in hopes that this would prevent views from using the container. Sadly this also didn't do anything. Code example below.

function rodekors_preprocess_views_view__paragraph_gallery(&$variables) {
  unset($variables['view_array']['#theme_wrappers']);
}

I simply want to remove the wrapper div from my specific view, yet have found no information on how to do that.

Does anyone know how to achieve this? Preferably without having to install a module for what should be such a simply thing to do.

I was only able to solve this after much hair-pulling regarding Drupal not picking up my suggested template. Where I was hung up was that the template suggestion must start with container__ otherwise Drupal will ignore the file and use the next template in the suggestion list (likely the default container.twig.html).

Here is my code:

/**
* Implements hook_theme_suggestions_user_alter().
*/
function myTheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  // A list of view names in which to exclude the container markup.
  $exclude_views = [
    'someView',
  ];

  if (in_array($variables['element']['#name'], $exclude_views)) {
    $suggestions[] = 'container__no_wrapper';
  }
}

I then added container.html and container__no_wrapper to my theme at templates/container/.


.module file not being discovered I am developing a custom Drupal 8 module on my local VM. When I first created and enabled my module, it did not have a .module file (just a controller). Now I have added a .module file so I can add an implementation of hook_entity_insert() but Drupal is not discovering it. I have tried going to Configuration > Performance > 'Clear all caches' but no joy!

How can I get Drupal 8 to discover the .module file in my custom module?

Just clearing cache is not enough, you need to uninstall and then re-install your module in order for the .module file to be discovered.

In the Admin panel go to Extend and select the Uninstall tab. Select your custom module and click the Uninstall button. Now go back to the List tab and re-enable your module as before. Your implementation of hook_entity_insert() should now be recognised.


What causes my Rules error when trying to send an email if profile field contains some value? I'm using Rules and Profile2 in a D7 site.

I'm looking for help to check my logic for the following rule. I can't get it to work and don't know where I'm going wrong.

Event: After saving a new profile

Condition: Data Comparison--> Selected data: site:current-user:profile-main:field-become-a-distributor

Action: send e-mail

Condition is what breaks.  Here is what is in my error log:

  Unable to get the data value for the variable or parameter data. Error: Unable to get the data property field_become_a_distributor as the parent data structure is not set.

Use Data selector account:field-YourField


Change checkboxes in a node edit form alter I have a problem with an ajax function which doesn't work properly and I don't understand why. I done a similar thing long time ago in Drupal 7 and it seems I forget how it works.

I have a node type with terms references, a type and options. In the node edit, the selection for the type is a select list and for options it's a list of checkboxes. In function of this type, I want only show related options to my user.

Here my code:

function my_module_form_my_content_type_node_form_alter(&$form, &$form_state) {
  $form['field_options']['#prefix'] = '
';
  $form['field_options']['#suffix'] = '
';
  $form['field_types']['#ajax'] = [
    'callback' => 'ajax_options_choice',
    'wrapper' => 'options-choice',
    'method' => 'replace',
    'effect' => 'fade',
  ];
  if(isset($form_state['values']['field_types']) || isset($form['field_types'][LANGUAGE_NONE]['#default_value'][0])) {
    $type_tid = isset($form_state['values']['field_types'])? $form_state['values']['field_types']: $form['field_types'][LANGUAGE_NONE]['#default_value'][0];
    $type = taxonomy_term_load($type_tid);
    $type_option = $type->field_type_option[LANGUAGE_NONE][0]['value'];
    $bundle = "my_content_type";
    $results = db_query("SELECT nid, title FROM {node} as n inner join {field_data_field_is_$type_option} as fdf on n.nid = fdf.entity_id  WHERE n.type = :bundle AND n.status = '1' AND fdf.field_is_". $type_option . "_value = '1'", array(":bundle" => $bundle))->fetchAllKeyed(0, 1);
    $options = [];
    foreach ($results as $nid => $title) {
      $path_alias =  drupal_get_path_alias("node/$nid", "en");
      $value = ' ' . $title . ' ';
      $options[$nid] = $value;
    }
    $form['field_options'][LANGUAGE_NONE]['#options'] = $options;
  } else {
    $form['field_options'][LANGUAGE_NONE]['#options'] = [];
  }
}

function ajax_options_choice(&$form, &$form_state) {
  return $form['field_options'];
}

`

When I edit a content which have already a type, options are correctly limited. But when I change the value of the select list, the ajax doesn't seem work and options stay the same. I have no error in the firefox or chrome console so I suppose the ajax is simply not execute.

Additionnal questions:
Which ways can I test the ajax works or not? Is that possible to use dpm() in the callback?

But when I change the value of the select list, the ajax doesn't seem
  work and options stay the same.

Simply because there is no db_query logic inside the ajax_options_choice callback.

How is Drupal suppose to know that it needs to run again the results db_query and then assign it to #options?

So essentially, currently, AJAX is executing, but you're just returning the same value that was calculated on initial page load.

  Which ways can I test the ajax works or not?

function ajax_options_choice(&$form, &$form_state) {
  drupal_set_message('Yes AJAX was called');
  dpm('yay dpm works!');
  watchdog('my_module', 'ajax was fired', array(), WATCHDOG_NOTICE); // now check /admin/reports/dblog
  return $form['field_options'];
}


Problem with drupal $queue->DrupalQueue::get and $queue->createItem I am updating approx 10000 nodes using hook_cron_queue_info and hook_cron(), it execute only for 25 nodes.
Is there any problem?

function my_module_cron_queue_info() {
  $queues['my_module_batch'] = array(
    'worker callback' => '_my_module_process_queue',
    'skip on cron' => FALSE,
  );
  return $queues;
}

function my_module_cron() {
  $contents = lode_update_nodes(); // get node list for updation 10000 nodes.
  $queue = DrupalQueue::get('my_module_batch');
  foreach ($contents as $p_file) {
    $process_data = array(
    // set values for process
    );
    $queue->createItem($process_data);
  }
}

function _my_module_process_queue($arr) {
    // code for updation
    watchdog('update node', 'Custom msg');
}

You have to add the 'time' key in de function modulename_cron_queue_info() because the default call time for the queues are 15 seconds. In order to update 100000 nodes you need to asign more time, so you have to try adding time until all 100000 nodes are updated:

$queues['my_module_batch'] = array(
  'worker callback' => '_my_module_process_queue',
  'skip on cron' => FALSE,
  'time' => 60,
);


D7 - does drush rr ALSO clear cache? Someone just told me that in D7, drush rr and drush cc all do the same thing. I can’t find anything that explicitly states the difference, nor can I find anything that supports such a claim. Additionally, I’ve noticed there are some changes that seem to only show up with a drush cc all, particularly changes to code. Do drush rr and drush cc all actually implement the same functionality?

See https://drushcommands.com/drush-7x/registry-rebuild/registry-rebuild

drush rr has the option:
--no-cache-clear : Rebuild the registry only, do not clear caches.

drush rr rebuild the registry + clear the caches.
drush cc clear the caches only.


Dynamically size images for mobile first design (omega theme) I've built my first site using an omega subtheme and I'm really liking it. The mobile first design dynamically changes the width of the page to follow the width of the browser.

With my column arrangement with a wide browser, my content area is 780px wide. So, the header images I use on my blog posts are up to 780px wide. If the user's browser is more narrow, then the css will shrink the content area to the following sizes:

wide: 780px
normal: 620px
narrow: 460px
mobile: 720px and smaller (in this arrangement the sidebars are removed to give the content more room.

The smaller the browser gets, the smaller the content area gets. When it is below 720px, then it follows pixel for pixel, so if I make my browser only 480px wide, then that's how wide the content area will be.

PROBLEM:

The header image on my Article nodes is up to 780px wide so that it fills the content area in the widest browser size. However, when the content area shrinks to 620px, the image doesn't get smaller which means that it overlaps the side bar.

The image below shows how the layout would work in the "wide" arrangement.

The next one shows how the header image is overlapping the sidebar in the "normal" arrangement:

I tried to solve the problem by setting the css width of my header image to be 100% of its container element. That did successfully restrict the width of the image, but when drupal generates the html for that image it always includes explicit width and height tags. This causes the image to become distorted because the width is shrinking to match 100% of the parent container but the height isn't changing along with it, so it ends up looking like this:

Is there a way to prevent drupal from including the explicit height attributes? Or is there some other drupal solution?

I know that I could set up some javascript to strip those attributes off, but that seems really hackish.

Any suggestions or solutions?

More of a CSS than Drupal question, but the standard solution is

img {
  max-width: 100%;
  height: auto;
}

You might get some funny results with images inside table columns that don't have an explicit or minimum width set, but those just have to be handled on a case-by-case basis.


Managing display of articles promoted to front page How do we manage the way that blog items that are promoted to the front page are displayed?
Currently using Bootstrap theme, we promote some of our articles, these are displayed in a scroller, but just showing one article at a time.
How would I manage this so that the scroller showed 3 articles?

Go to yoursite/admin/config/system/site-information
Change the Number of posts on front page to 3 or whatever you want.

Please note your allow to display up to 30 post, however if you want to show more then 30 than i suggest to use View module, to create page of your article list


Trouble adding markup in a node with hook_node_view() I'm trying to add a piece of markup with a field in hook_node_view().  It's a little thumb icon for a music site, and I want to overlay this image over another field image (which I'll do with CSS).  However, it's not rendering, and I feel pretty confident that I'm going about it the right way. Here is my addition to the node array:

$node->content['like'] = array(
            '#theme' => 'image',
            '#path' => '/sites/default/files/likeimg.png',
            '#alt' => 'like',
            '#prefix' => '
',
            '#suffix' => '
',
            '#weight' => -1,
            '#attributes' => array(
                'class' => array('like-img')
            )
        );

What am I missing?  I am using Display Suite with fields in blocks, and Omega 3.

hook_node_view() is only called within modules that define node content types (ie. through hook_node_info().

What you want to use is hook_node_view_alter(), and render the content in your template file like Mike Vranckx suggested.


How do I get only one result using db_query() I am transitioning from 'old school' PHP MySQL methods of using mysql_fetch_array(), etc. and I am trying to be more Drupally by using the Database API in my modules.

I simply want to return and print out a value. For example:

$query = db_query("SELECT zip FROM {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city));

I know the value is there, I can access and print it by using traditional methods outside the database API.

print $query->zip is not working.

The API documentation is as clear as mud.

Can someone tell me the correct way to access these values?

Is there a good tutorial anyone could recommend as well?

If you wish to fetch only one result you could use fetchField with db_query to fetch the result, e.g.:

$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

You could also fetch the values retrieved from the query's returned result source using options like fetchObject() similar to methods of conventional PHP (mysql_fetch_object) coding like using and get results.


Uninstall core forum.module while keeping content type and taxonomy I'm upgrading a site from D5 to D7 and have a large amount of forum posts. However, I no longer want to use the core forum module, instead using views...

When I disable the module, I lose access to the "Forum Post" content type that the module creates. Also, Drupal doesn't have "ownership" of the "Forums" taxonomy.

On the plus side, the content remains. However, I can no longer add new "Forum Post" content and, since the forum module isn't enabled, I can't even create automatic aliases for the "Forum" taxonomy.

Is my only option to run through node_convert, and hope for the best? Or is there a few things I can manually edit in the DB that would give me full ownership of the content type and taxonomy (as if I had created them from scratch and never installed the module in the fist place)?

Thanks!

The problem is that there is no simple thing like "content type ownership". There is module column in {node_type} table, but simply changing it to "node" (as set for handmade content types) might not be enough. Forum module implements node-related hooks, and integrity of forum data might be endangered if you will simply turn them off and change module in database.

Safer option would be to export data you need to some neutral format, like XML, and then use Feeds or similar module to import it again, to the content type created with your new needs in mind.


How to have Drush make automatically find libraries download path? I don't know from what URL's I got my libraries files from. Is there a way for Drush Make to find those URL's, a command?

Additionally, what URL/Path can I use for my own custom modules?
Can I use a local path in a URL so the libraries are sourced locally?

As Molot states, there's no way for drush to know about any arbitrary library; you need to know the source URL to give it.

For any custom module project, you can use git or file download type to retrieve it from a git repo or an HTTP source.

projects[example][type] = "module"
projects[example][subdir] = "custom"
projects[example][download][type] = "git"
projects[example][download][url] = "git://github.com/jane_doe/example.git"
projects[example][branch] = "dev"

projects[example][type] = "module"
projects[example][download][type] = "file"
projects[example][download][url] = "http://example.com/example.tgz"
projects[example][subdir] = "custom"

The same for libraries

libraries[ckeditor][download][type]= "get"
libraries[ckeditor][download][url] = "http://download.cksource.com/CKEditor/CKEditor/CKEditor%203.4/ckeditor_3.4.zip"
libraries[ckeditor][directory_name] = "ckeditor"
libraries[ckeditor][destination] = "libraries"

Lastly, for local files you can use the file:// protocol in the url property to source the file from the local machine. See the Drush makefile docs for more information.


How can I add context (or distinguish between contexts) to translations with t()? I have made a custom address handler for the Addressfield module which uses the word "state" (for the geographic state/province).  However, I'm also using the Revisioning module, which uses the word "State" to describe the state of a piece of content.

Unfortunately, to translate this into Japanese, I need two different words for "State"; how can I get two different strings to appear on the translate interface screen?

(I know I could just re-write "State" in revisioning to something like "Revisioning state" but I'd like to know if there's a way to handle this without altering the strings.)

Yes, you can pass a context to t(), see the third parameter, $options. However, you can only do this in the source code, which means that it is often not helpful. Might be possible in your case, because it's your own code.


Adding additional dynamic to a canonical view Wasn't sure exactly what to search for in trying to find recommendations for this.

I have created a custom content entity type with some numerical fields. The canonical view for this entity uses "views_data" = "Drupal\views\EntityViewsData" as specified in the entity definition annotation. This entity type does not depend on node. Some modifications are made to the display of the field data using hook_entity_view_alter and hook_page_attachments. This is all working fine.

What I would like to do is two things:

1) add an additional HTML section to the canonical view, below the display of all the entity parameters, which displays the results of a database query. The query being executed will depend on the content of the entity being loaded. Currently I am just using "echo" to test, but that spits the results out at the top of the document.

2) add a form to the canonical view containing one text field, one dropdown, and one button. The contents of the dropdown will also depend on the entity field content. The button should perform some calculations on the numerical fields based on the form inputs, and adjust the build array contents accordingly after reloading the page.

I am not really sure what approach to take here or how to execute it, and would like to ask for recommendations and examples to look at. Should I be creating a custom class that extends Drupal\views\EntityViewsData to accomplish all of this? Should I be doing this with Twig instead (which I am not very familiar with and can't seem to find many examples similar to what I'm trying to do)? Would using jQuery instead be a better approach?

This would be the answer to the two questions:

1) add additional HTML to the canonical view

When using hook_ENTITY_TYPE_view() you have a render array and you can place new array keys with additional render elements. Don't use echo for testing, put it in the build array like this:

$build['text1'] = ['#markup' => '
Text 1
'];

2) add a form to the canonical view

Build a form class for this form. Then you can place the form also in hook_ENTITY_TYPE_view():

$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

You can pass additional parameters in getForm(), if you need information from the entity to build the form.

I don't understand what you are trying to do with Drupal\views\EntityViewsData. Other than mentioning this one class you are not writing anything else about views.


Display User Author Details in Block UserProfile I am looking to display my own block on user profile page. The block will to display the username of the user whom profile we are viewing.

I went ahead and created a view, show users, block.

Added contextual filter for UIID, Raw value from URL.
Path component 2

User profile and a user sub-pages have this structure:
domain.com/u/username (user main profile page)
domain.com/user/845/posts (user posts, where 845 is uid)

How can I add a contextual filter that will work on both cases? The username is changed a little by path auto. Dashes, commas, uppercases and such are removed so that may be why raw value from URL is not working.

Btw, I am open to creating a custom user profile by creating user/% view for user profile.

The alias doesn't matter, you get the argument for a contextual filter from the internal path, no matter if the URL in the browser was aliased (unless you enable the option "Use path alias"). For a user profile the internal path is /user/[uid].

For the user ID there is also a contextual filter "User ID from route context", this filter is able to get the user without specifying in which path position it is.


Users' list view based on current logged in user taxonomy field value I'm on drupal 7, with views 3.5.

I have added to the user profile, a taxonomy field.

I want to create a view, which will get the users which that taxonomy field has the same value with the current logged in user taxonomy field value.

Is it possible?

Suppose your taxonomy field is labelled User Tag and has a machine name field_user_tag.

Create a view that lists users
Add a contextual filter for User:
User tag (field_user_tag)
Under WHEN THE FILTER VALUE IS NOT IN
THE URL Select 'Provide a Default Value' and then Select 'PHP
Code'
Insert the following snippet:

global $user;
$term= user_load($user->uid)->field_user_tag;
return $term['und'][0]['tid'];

The PHP code grabs the current user. In this context the current user object doesn't have any additional fields loaded. So we need the user_load function to get those. The we need to extract the taxonomy id from the relevant array.

This approach works, but may not be the best or most efficient.


How to hide a field based on a specific condition? I have a website for ads, which are either of those:

Regular ads.
VIP ads.

The Regular ads have an additional field "field_adding_make_vip". If the user decides to change a Regular ad to a VIP ad, the user will use the description from that field and send a SMS to a specific number and that ad will become automatically a VIP ad.

The filter in Views to show the VIP content is a additional field "field_vip_date" that uses a date filter. That mechanism is created with a custom PHP file.

So only left to do is: when the Regular ad becomes a VIP ad, the field "field_adding_make_vip" will be automatically hidden and the VIP ad will have additional field "field_adding_vip_image" that will show a VIP image, so every user will know that the selected ad is a VIP ad.

How can I hide that field and show the VIP image when the ad becomes a VIP ad?

The Regular ad and VIP ad are the same content type (adding). I'm using the field "field_vip_date" as a filter in views by date. Let's say when the date field of a specific node is set to 25 October, that node will be displayed in a VIP block position in the website until 25 of October and the next day it will be automatically removed from that position. That's for a block view position.

In every page node the field "field_adding_make_vip" has a description with the node id how to send the SMS, to be used to make it a VIP ad. The whole idea is when the user sends an SMS with the number ID, the field "field_adding_make_vip" will disappear, because the regular node has become a VIP ad and that node will have an additional field "field_adding_vip_image" that will display an image with a text "VIP".

Somehow the field "field_vip_date" (which is a date field) will have to control the field "field_adding_make_vip". For an example if "node/120" has "field_vip_date" set to 25 October, the field "field_adding_make_vip" will be hidden until 26 October and the field "field_adding_vip_image" will be displayed until 26 October.

Note: I've tried the code from @harshal, but it has errors. The name of my custom module is "custom_alter" and here's the full code:

<?php
function custom_alter_form_alter (&$form, &$form_state, $form_id) {

 $node = node_load($nid);
 $date = date('d/m/Y');
 $todaysdate = strtotime($date);
 $field_date_vip = $node->field_date_vip['und'][0]['value'];
 $date = date('d/m/y',  $field_date_vip);
 $expirydate = strtotime($date);

If ( $todaysdate <  $expirydate )) {
  //Hide the field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_make_vip.css');
             }
else {
// hide field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_vip_image.css');

}

}

I'm not sure I completely understand what you need. But if I'm correct and you just need to show / hide specific fields in a node based on some other field in that node the hook_field_access should help you.

 /**
 * Implements hook_field_access().
 */
function YOUR_MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  switch ($field['field_name']) {
    case 'field_adding_make_vip':
      if ($node['isVIP'][value]) {  //Is the node VIP?
        return false;  //Show the field_adding_make_vip
      }
      else {
        return true; //Hide the field_adding_make_vip
      }
      break;
  }
    case 'field_adding_vip_image':
      if ($node['isVIP'][value]) {
        return true;
      }
      else {
        return false;
      }
      break;

}


find nodes by attribute and modify at once If I want to filter content by attributes (besides content type name), is there is some module around? if I am able to find these nodes, some way to update this attribute for all nodes at once?

Some options:

You can use Views in combination with Views Bulk Operations and Rules.
You can also have a look at Editable Fields in combination with Views


How to export path breadcrumbs I see written everywhere that Path breadcrumbs https://www.drupal.org/project/path_breadcrumbs can be exported via features. But I am unable to see any Path breadcrumb option when I'm creating a feature, nor I see any export thing in Path breadcrumbs settings.

Do you know where/how?

Features: Check if you have Path Breadcrumbs module checked in Features Settings (screenshot below). If it was checked and you still do not see it in the Features components list than something else is amiss.

Export: As for the direct export of Path Breadcrumbs, you can find "export" link while clicking on "edit" in path breadcrumbs actions list (screenshot below)

Hope this helps.


How to exclude contents from migration I'm using Migrate to import entities.

I want to exclude rows based on a custom plugin (my source has a "url" field and I've to check if this url contains a "www.mysite.com" string: if not, the rows must be ignored).

How can I do this?

This hook might be the solution it excludes different contents from migrating:

function hook_migrate_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  // Ignore content types from being migrated.
  if ($migration->id() == 'd6_node_type') {
    $ignore_content_types = array('content_type1', 'content_type2');
    if (in_array($row->getSource()['type'], $ignore_content_types)) {
      return FALSE;
    }
  }

  // Ignoring content of 4 content types.
  $ignore_content_types_content = array('d6_node__content_type1', 'd6_node__content_type2');
  if (in_array($migration->id(), $ignore_content_types_content)) {
    return FALSE;
  }
}


jquery get or post methods for drupal block module Is it possible to use jquery get or post methods to fetch data dynamic in a a drupal7.x block module. I am a newbie to drupal.

Here is my event_calendar.module file

      function event_calendar_help($path, $arg)
      {
          switch ($path)
          {
          case "admin/help#event_calendar":
          return '
'.  t("A block module that creates events and lists them in a event calendar") .'
';
      break;
          }
    }
     /**
    * Implements hook_block_info().
    */
    function event_calendar_block_info() {
      $blocks['event_calendar'] = array(
        'info' => t('Event calendar'),
        'cache' => DRUPAL_CACHE_PER_ROLE, //Default
      );
      return $blocks;
    }

    /**
    * Implements hook_block_view().
    *
    * Prepares the contents of the block.
    */
    function event_calendar_block_view($delta = '')
    {
      switch($delta)
      {
        case 'event_calendar':
          $block['subject'] = NULL;
          if(user_access('access content'))
           {
            $items = array();
            $basepath = drupal_get_path('module', 'event_calendar');
            $markup = '

                        Week :

                             -

Lane 1

Lane 2

Lane 3

Lane 4

';
      $block['content'] = array(
        '#markup'   => $markup,
        '#attached' => array
            (
            'css' => array($basepath . '/css/event_calendar.css',$basepath . '/css/smoothness/jquery-ui-1.8.16.custom.css'),
            'js'  => array($basepath . '/javascript/event_calendar.js',$basepath . '/javascript//jquery-ui-1.8.16.custom.min.js'),
            ),
        );

          }
return $block;
      }

    }

I want to know how to write functions inside above .module file to access some content dynamically through jquery get or post method?

Or should I use something like 'hook_menu' other than block?

For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'access callback' => TRUE, //you can set it with your permission
      );
   return $items;
   }

and in yourhalderjust need pass a block :

function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);
}

and in your clientside get it with something like this

$.ajax({
    type: "POST",
    url: 'youruniqepath',
    //data: {}, you can also pass block name and act more dynamicly
    success: function (data){
        $('#yourplace').html(data);
    }
});


Fatal error - Class 'context_condition_node' in date_context module I'm debugging a site that has completely broken - not finding too much out there and hoping for some help. The error I see is:

Fatal error: Class 'context_condition_node' not found /sites/all/modules/contrib/date/date_context/date_context.module on line 56

Anyone seen this before?

It means this module is missing or registry is broken.

Can you check if the date module does exist?

If not you may try to download a copy of date module and put it in the exactly the folder.

Use Drush drush cc all to clear the cache.

In Drupal 7 you can also go to admin performance page to clear the cache. Sometimes this is still available by admin/config/development/performance.

If it still does not work, you may want to have a go with registry_rebuild module to rebuild the registry totally.


$_FILES superglobal array key is not what file.inc expects I'm trying to do some custom stuff with a file upload field via the form API. I call to file_save_upload() but it thinks that the upload is empty because it's examining $_FILES['files'] but for some reason, my file is actually in $_FILES['CSV_file'] even when the file I uploaded is not a csv.

How might files superglobal end up with a CSV_file array key?

UPDATE

So apparently the form array

$form['my_menu_csv'] = array(
  '#name' => 'CSV files',
  '#type' => 'file',
  '#title' => t('Choose a CSV file'),
  '#title_display' => 'invisible',
  '#size' => 22,
  '#theme_wrappers' => array(),
  '#weight' => -10,
);

was causing the field to have the following HTML:

<input type="file" id="edit-my-menu-csv" name="CSV file" size="22" class="form-file">

and apparently the files array goes like $_FILES[$name], where $name = whatever the name attribute is in the HTML element. Makes sense! What doesn't make sense is why file_save_upload() expects to only ever encounter $_FILES['files'] but the form API uses a custom field name. Is this a bug in the form API?

I don't think it's a bug.

$_FILES['files'] is hard-coded into file_save_upload().

I believe you need to change how you construct your #name property.  The usage example in the Form API does it like this:

'#name' => 'files[' . implode('_', $element['#parents']) . ']',


What hook is most appropriate for code that should run as early as possible in bootstrapping but only on certain paths? I am writing a module that should run code as early as possible because it's a conditional redirect to another page, so the first page doesn't need to finish loading.

I only want to run it on /foo/*.

Is there a hook that can be bound to a particular path, like hook_form_alter() can be with form IDs? Or should I just use hook_init()?

Similar to the forms, there's hook_page_alter(), but that happens near the end, making it a bad place for redirects.

hook_init() should be fine, but is not invoked on cached pages.

hook_boot() sounds self-explaining; it's run so early that you can't call any module's function, not even drupal's.

however, since you need a conditional redirect and you already have your own module, just add it atop the page callback of 'foo/*'.

if that callback it's not defined in your module, use hook_menu_alter() to have that path pointing to a custom function that will execute your conditional redirect.


Administrator can add content for other users? I have some users in admin/people.
Administrator can have the permission to view/edit/delete contents created by these users.
Is there any possibility: Administrator can add content for a user from administrator back end?

Or is this out of scope?
Thanks

The author of content is driven by a field in the Authoring Information Tab on the content's edit screen. You can set this field to be any user, and that user will be considered the Owner of the content for permissions purposes. By default this field gets populated with the current user.


Prepopulating county/state field (ajax driven field) Before I describe my problem, just going to mention that I tried Commerce Addressbook and Commerce Extra (address populate) modules.

The first one is not suitable in general for my project (because it's based on billing address when the mother address used in this project is always user's one entered on registration) and
The latter is in alpha stage and has many issues (and still doesn't sort my problem)

The problem is that I cannot prepopulate County/State field on commerce checkout billing address form.

When using hook_form_alter, I can successfully prepopulate all fields, except county. The reason for this is that county drop down is loaded with ajax and dependent on Country value. It's getting created when the form is built so before the hook_alter_form is applied.

So for example let's say my billing address defaults to Ireland (one can setup a default value under customer profile -> billing information). A user registered using address in USA. When the user comes to billing form on checkout, gets all fields prepopulated with the address he/she registered with and country says United Stated, but county/state dropdown stays defaulted to Ireland (lists irish counties).

One needs to select other country than USA and then select USA again for ajax to load the proper county/states dropdown

I cannot seem to find a workaround for this. Any advice?

"So for example let's say my billing address defaults to Ireland (one can setup a default value under customer profile -> billing information)."

If I understand you correctly perhaps do not set a default value for the country in your addressfield options. I.e. do not select a country in the options illustrated below... this way the state options are generated after the user has selected their country...

Incidentally, if you could post whatever your hook_form_alter code is and where you put it... I'd find it really useful as I am also working to pre-populate addressfields with user-account details.
Thanks!


Git showing every changed file not folders Git is showing every change in every installed module folder. This makes it unusable because I can't see what I'm committing.

Previously git only showed the module folders. So if i installed Views, it would show me in
git status, untracked files "sites/all/modules/views"

I used git -rm to remove a file, but somehow it managed to completely mess this up and now it shows every single changed file. Here's the bottom part of my latest git status, it's so long most of it is untrackable.

What have I done, how can I change this back to what I had before, because I really need to roll back a commit.

EDIT:

Context for my problem, now having the solution.

Some modules in Drupal have a huge number of files. When you add them to the index, git lists all the files in the folder rather than each individual one.

In the case of some modules, in my case the commerce and jquery_update modules this will probably add more files than your command line shell can display, so you won't be able to see everything.

I got around this by removing the modules from my index with git reset HEAD *filepath*

and then adding them in separate commits.

The difference between showing the folder level for untracked files and the file level for tracked files is expected git behavior. This will always be the case. Once you add the folder (which adds all the files in it) each of the files is tracked by git and will be tracked individually. So, when you do a status, it SHOULD list each file separately. Yes, this is kind of annoying, but the general idea is that you'll add a folder and then commit that change. Once committed, you won't see each file unless is has been changed in some way.

As for fixing the situation, you probably haven't actually messed anything up; it's just tough to see that because there are so many new files in your index (a git term which you can research if you'd like more information).

If you'd like to undo it all, you can run the git reset command. In general, most things related to git can be demystified with a couple of Google searches. If you're new to git, I recommend the free Git Book.


Unable to delete a file with services I am making an AJAX call to /file/.json. Webserver log says DELETE /services/file/5710.json HTTP/1.1 200, console log says the file has been deleted; yet the file is still there when you go here. What am I missing? My code is as follows:

$.ajax({
  url: 'http://www.rejicast.com/services/file/' + oldFID + '.json',
  type: "delete",
  dataType: "json",
  beforeSend: function(r) {
    r.setRequestHeader("X-CSRF-Token", token.token)
  },
  success: function() {
    console.log('Deleted the file');
  },
  error: function(xhr, status, err) {
    console.error(xhr);
    console.log(status);
    console.log(err);
  }
})

(Note: oldFID is something I set at the beginning)

UPDATE: As per @Clive's answer, there is still a reference to the file in the database as seen below .

The file reference has been deleted, i.e. the record in the file_managed table; the file itself will be deleted later during the system_cron run.

See the 10 or so lines under this comment in that function:

// Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.


BeautyTips + Jquery Update not working Is it possible to get BeautyTips working with a new version of jquery 1.7 or 1.8.

Firebug returns the error.

`Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'curCSS'` - jquery.bt.min.js?v=0.9.5-rc1:97

Is there a new version of jquery.bt.min.js that will work?

According to the jQuery blog, the function curCSS was deprecated in jQuery 1.8:

  $.curCSS: This method was simply an alias for jQuery.css() from jQuery
  1.3 onward. Although it has never been part of the documented API, some external code has been known to use it, perhaps thinking it was
  “more efficient.” Now it’s “more gone.”

but since its simply an alias its possible to patch the beauty tips plugin to fix this. There is a patch here on Drupal.org that does just this and its been committed to the dev release. Its not ideal as you have to patch the library to get this to work but its really your only strategy since the beautytips plugin hasn't been upgraded for the newer versions of jQuery.


Clean URL in Exposed Filters in Drupal 7 How can i get a clean URL in my Exposed Filter and Contextual Filters. I want to create a archive were users can sort the nodes by its posted Date. I used contextual filter to achive this and its working fine when i pass the value in URL like.

"www.example.com/archive/10/09/2013".

But when i use a exposed filter and submit the value the URL became like this

"www.example.com/archive/archive?date_filter%5Bvalue%5D%5Byear%5D=2013&date_filter%5Bvalue%5D%5Bmonth%5D=9&date_filter%5Bvalue%5D%5Bday%5D=10"  and it returns a empty page.

How can i pass a clean value in Exposed Filter and make it work properly? Thanks in advance.

You will probably have to split this off into two different views displays, one for the clean URL with contextual filters and one using the exposed filters.

The only other way I can think of is making the contextual filters optional, but that may not be possible.


How to translate the author line "Submitted by ... on ..." I've created a custom content type in Drupal 8.9.1. Each content post automatically renders the line
Submitted by author_name on 08.07.2020 - 18:21

Even though my Drupal system language is set to German, I cannot find a way to show a translated version of this "submitted by" text.
When I check the translations page under /admin/config/regional/content-language I also see a correct translation for the segment ("Geschrieben von"). But there's no indicator how this is mapped to the actual English value.

I've also seen posts saying that you have to do that manually in the Node Template. But I have not found such template and guess the approach has changed after Drupal 7.

While the page /admin/config/regional/content-language holds the actual translated text, it's not the place where the "Submitted by" translation is derived from. To do so you need to

Navigate to Configuration > Regional & language > User interface translation
Search for "Submitted" in the String contains field. Note the uppercase S (thank you @Hudri).
Now enter the translation and save it. Also note the placeholders for author and date information.


How to create a simple form to redirect the user to entered URL? I want to create a simple form to redirect the visitors to a relative path they enter.

I created a search page with views and it has lots of exposed filters. I don't want to use this exposed filter as block.

On the main page I want to show only a simple search form and if the user enter a word then submit search button, it should redirect the user to example.com/advanced-search?full_text=word.

How can I do that?

Have a look at the Rules Forms Support module. Some more details about it (from its project page):

Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
For help getting started with Rules Forms Support, please see the module documentation.
Features

Activate events for form creation, validation, and submission on a form-by-form basis.
Target individual form elements or the entire form in conditions and actions.
Manipulate the attributes of a form element like title, description, weight, and more.
Validate the values of form elements during form validation.
Set form errors when rule-based validation fails.
Redirect users to a different page upon viewing or submitting a form.
Examine the attributes of elements in active forms with the element inspection tool.

Especially the "Redirect users to a different page upon viewing or submitting a form" should help to address your question.


Let users create content by using the default (non-admin) theme sorry to ask a more conceptual question but I am really stuck.

I have a Drupal 7 site where users will sign in and then create a certain kind of content. I have the content set up ready to go.

Do I just let them have access to the /node/add/[content-type] page? If so, how can I theme this page so it has the headers / menus / footers of the rest of the website (and not the standard Drupal 'admin' view)?

I am able to add a custom node-form.tpl.php file but when I output the form using echo drupal_render_children($form); it still looks like the Drupal admin backend, and not a form that is consistent with the style of the rest of the website. I want it to look more like, say, a webform. Perhaps there a way to insert a node/add form into a panels page for example?

I feel like there is a "Drupal way" of doing it, it must be a fairly common use case but it seems my Google fu is failing me. Any help or advice appreciated.

TLDR; I want a node/add form to look like a standard website webform and not part of the Drupal admin/backend.

PS: I am using a custom theme and I am comfortable with custom modules.

I might misunderstand you, or you did not yet try this. There is a permission View the administration theme, which normal users should not have.

This means that if you login as a less privileged user that has permission to [Content type]: Create new content, the add content page will look like any other front-end page already:


Form element replaced via Ajax callback doesn't seem to be submitting or the values are not appearing in buildForm I'm having a form with a select list and a textbox. On-change of select list will trigger an ajax callback. The callback function will replace the default value of textbox with an updated value.
But when I try to get the textbox value in buildForm() or if I try to submit the form, instead of the updated value the default value (old value which is set) is passed on submit handler. Below is the code -

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormStateInterface;

class MyAjaxForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_form';
  }

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

    $form['output'] = [
        '#type' => 'textfield',
        '#size' => '60',
        '#value' => 'oldvalue',
        '#default_value' => 'oldvalue',
        '#attributes' => [
            'id' => ['edit-output'],
        ],
    ];

    $form['input'] = array(
        '#title' => t('Crust Size'),
        '#type' => 'select',
        '#description' => 'Select the desired pizza crust size.',
        '#options' => [
          'medium' => 'Medium',
          'large' => 'large',
         ],
        '#ajax' => [
            'callback' => [$this, 'seyHello'],
            'event' => 'change',
            'wrapper' => 'edit-output',
            'progress' => [
                'type' => 'throbber',
                'message' => t('Verifying entry...'),
            ],
        ],
    );

    return parent::buildForm($form, $form_state);
    dpm($form['output']['#value']);
    //even after the ajax callback return and the textbox is filled with 'newvalue', dpm returns 'oldvalue' still.
  }

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

    dpm($form['output']['#value']);
    dpm($form_state->getValue('output'));
    //both returns 'oldvalue'

  }

  public function seyHello(array &$form, FormStateInterface &$form_state) : AjaxResponse {
    $elem = [
        '#type' => 'textfield',
        '#size' => '60',
        '#default_value' => 'newvalue',
        '#value' => 'newvalue',
        '#attributes' => [
            'id' => ['edit-output'],
        ],
    ];
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#edit-output',
    $renderer->render($elem)));
    $form_state->setRebuild(TRUE);
    return $response;
  }

}

I'm not sure why this is happening, it clearly seems to be the case of form values not getting updated after the ajax callback for me. Been debugging this for entire day. Any help/ suggestions would be lovely.
Thanks.

The ajax callback returns the part of $form which is inside of the ajax wrapper:

  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form['color_wrapper'];
  }

The wrapper has to be a div container.

Complete code example  https://cgit.drupalcode.org/examples/tree/form_api_example/src/Form/AjaxColorForm.php


Drupal is not saving any changes made through administrator, Drush works fine I just began working for a company and am using Drupal for first time.  I'm working locally on WAMP.  I started by installing and configuring a few modules before making my own and everything worked fine.  Then I needed to integrate it into the site.  I downloaded the repositories and all dependency modules/themes needed, as well as exported from the server and imported into my machine the database Drupal was running on. That got the correct look/feel/content of the site.  However, since then I have been unable to make any changes through the administrative menu/pages.  I can't enable/disable modules, make configuration changes, etc.  Here's where my troubleshooting starts:

I can enable/disable modules through Drush.
I've verified my Drupal settings.php file has the correct database settings for the imported database.
I've verified I can log into our dev server and edit things there.
I've verified the user priviledges and roles databases transfered correctly.
I've used Drush to add the "Superuser" role to myself.
I've used Drush to log on as the root user.
Since I can't change configuration of a module, I can't enable debugging through Devel.

I've spent hours trying things and searching online, and I'm out of ideas.  The closest I've seen someone else post about is this:

Can't save settings after copying site to new server

However, the symptoms aren't a 100% match, as I can log out/in.  Any recommendations would be appreciated.

Problem is fixed.  Late last night I tried investigating why my attempts to enable Mod Rewrite were not working properly, and when I figured out how to enable it natively in WAMP instead of manually in .htaccess, it fixed the issue.  Apparently I was having the exact same problem as the linked post, just with slightly different symptoms, and I must have been attempting to enable it wrong so I didn't feel it was the same issue.

For other users in the same situation, you can't enable Mod Rewrite in .htaccess to fix it, you have to enable it through the WAMP server interface.  It's under Apache > Apache modules > Rewrite_modules.


Understanding the 'node' string in a Views SQL Query I'm trying to understand this Views SQL Query:

    SELECT node.nid AS nid, node.title AS node_title, 'node' AS
field_data_field_icon_node_entity_type, 'node' AS
field_data_field_price_node_entity_type, 'node' AS
field_data_body_node_entity_type
    FROM
    {node} node
    INNER JOIN {field_data_field_type} field_data_field_type ON node.nid =
field_data_field_type.entity_id AND (field_data_field_type.entity_type =
'node' AND field_data_field_type.deleted = '0')
    WHERE (( (node.status = '1') AND (node.type IN  ('resource')) AND
(field_data_field_type.field_type_value = '4') ))
    ORDER BY node_title ASC
    LIMIT 10 OFFSET 0

Specifically, I need to know what the line in the SELECT statement that says 'node' AS field_data_field_icon_node_entity_type means.

I see in the database I have a field called 'field_data_field_icon' but not with the rest of the jargon attached to it. So I'm not sure how it's getting that data.

Anyone know?

The 'node' string is a placeholder of sorts.

Internally, it indicates to Views that we are not going to attempt to fetch the requested field value in this SQL query itself. Instead, during the Views render process, the full node object is going to be loaded, and the output for that Views field is going to come from partially rendering the node object.

This allows Views to take full advantage of Drupal's field formatting system, which would be impossible on raw SQL values.


Using debug with services 3 I'm desperately trying to debug some problems I'm having with creating an manipulation of nodes in drupal 7 Services 3.

I've tried to insert a few debug statements to figure out where things are going wrong. When I create a node using poster (from the browser) it worked great, it prints the info I want.

When I do it from my app (iphone app), the same function is called, but the debug does not seem to print out to the page, even if I refresh it. I wonder what I am doing wrong.

Thanks

Standard debugging functions like dpm() and dvm() use the drupal_set_message() function, which is tied to a user's session. When you try using the node form, you see the message because it is saved to your session. However, when you use the service via your iphone app, the messages get saved to a session that is probably not the one you're logged in under.

Fortunately, for situations like this, you can use the dd() function, which will print the debugging information out to a file in the /tmp directory, typically called drupal_debug.txt.

[edit] I notice you're using the debug() function, which triggers error handling, note that this also uses drupal_set_message(), so the above is still relevant. (The dpm() and dvm() functions are from the Devel module.)


"Unknown engine type outputformat" I did a Drupal 7 update using drush up and received the following message, repeated numerous times:

  Unknown engine type outputformat

Since that update, Drush does not work, but rather returns the same message.

How can I fix this problem?

I have Drupal 7.52 and Drush 5.9.

You can install drush to latest version or specified version.
I prefer drush 7, you can make this, first uninstall the current version of drush of your server.

i use debian, then i install with

sudo apt-get install drush

and you need remove

sudo apt-get remove drush

and later install again with composer

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo ln -s /usr/local/bin/composer /usr/bin/composer

sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
sudo git checkout 7.0.0  #or whatever version you want.
sudo ln -s /usr/local/src/drush/drush /usr/bin/drush
sudo composer install
drush --version

and ready to use drush version 7


For an event node type, should I use Datetime or Datestamp? I'm about to create a node type event and have to choose between three different date formats, Date, Datestamp and Datetime. I've read how they are stored differently in the database, but that doesn't explain to me which is best for an event node type. Well, not exactly, from what I understand the Date format doesn't store time so that can't be used. I'll be using views to sort events if the make a difference. Which format would you use and why?

Especially in Drupal 7, you should use the Date field. Datestamp is almost useless, and there is no real need for Datetime.


Error: Maximum function nesting level of '512' reached when injecting custom service to webform (6.x) handler I'm trying to use my custom service in the handler like this (in webform 6.0-beta1):
class TriggerAutomationWebformHandler extends WebformHandlerBase {

  /**
   * Ecomail.
   *
   * @var \Drupal\ecomail_automation\EcomailInterface
   */
  protected $ecomail;

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->ecomail = $container->get('ecomail_automation.ecomail');
  }
?>

mymodule.services.yml file looks like this:
services:
  ecomail_automation.ecomail:
    class: Drupal\ecomail_automation\Ecomail
    arguments: [ '@config.factory', '@logger.factory' ]

My Drupal\ecomail_automation\Ecomail class in constructed like this (\Ecomail class is different class in a global namespace - see https://packagist.org/packages/ecomailcz/ecomail):
  public function __construct(ConfigFactoryInterface $config, LoggerChannelFactoryInterface $logger_factory) {
    $this->config = $config->get('ecomail_webform.settings');
    $this->logger = $logger_factory;
    $this->ecomail = new \Ecomail($this->config->get('api_key'));
  }
?>

This leads to error (shortened to important parts):
Error: Maximum function nesting level of '512' reached, aborting! in Drupal\Component\Plugin\PluginBase->__construct() (line 53 of core/lib/Drupal/Component/Plugin/PluginBase.php).

Drupal\Component\Plugin\PluginBase->__construct(Array, 'trigger_automation', Array) (Line: 141)
Drupal\webform\Plugin\WebformHandlerBase::create(Object, Array, 'trigger_automation', Array) (Line: 43)
Drupal\ecomail_automation\Plugin\WebformHandler\TriggerAutomationWebformHandler::create(Object, Array, 'trigger_automation', Array) (Line: 21)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('trigger_automation', Array) (Line: 76)
Drupal\Component\Plugin\PluginManagerBase->createInstance('trigger_automation', Array) (Line: 81)
Drupal\Core\Plugin\DefaultLazyPluginCollection->initializePlugin('trigger_automation') (Line: 35)
Drupal\webform\Plugin\WebformHandlerPluginCollection->initializePlugin('trigger_automation') (Line: 80)
Drupal\Component\Plugin\LazyPluginCollection->get('trigger_automation') (Line: 40)
Drupal\webform\Plugin\WebformHandlerPluginCollection->initializePlugin('trigger_automation') (Line: 80)
Drupal\Component\Plugin\LazyPluginCollection->get('trigger_automation') (Line: 40)
Drupal\webform\Plugin\WebformHandlerPluginCollection->initializePlugin('trigger_automation') (Line: 80)
Drupal\Component\Plugin\LazyPluginCollection->get('trigger_automation') (Line: 40)
...

What am I doing wrong?

The problem is that you're instanciating the Ecomail object into your Ecomail constructor $this->ecomail = new \Ecomail($this->config->get('api_key')); which is kind of a fork bomb.
Your Ecomail is creating an Ecomail itself creating another Ecomail, etc.
That's an infinite loop


how to upload multile user profile pics at a time? I have used user reg with picture module for uploading user profile picture on registration page but there is option for uploading only one picture at a time .

I am developing social network website there is requirement of uploading multiple user profile pics.

but how its possible?

You can use something like profile2 module and create image upload filed that allows multiple files.


How to force cron to use config saved during a SimpleTest? I write a test using Drupal\simpletest\WebTestBase for a custom module, which implements hook_cron(). The test saves a configuration object, which should be used by the cron, and then runs the cron:

function testCron()
{
    $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
    $config
      ->set('some_setting', 'some value')
      ->set('another_setting', 'another value');
    \Drupal::service('cron')->run();
}

The settings are saved and can be used during the test. But when I want to use them in the cron (in mymodule.module):

/**
 * Implements hook_cron().
 */
function mymodule_cron()
{
    $config = \Drupal::config('mymodule.settings');
    ...
}

then instead of the saved values, the default settings from config/import/mymodule.settings.yml are used.

How can I force the cron to use the settings saved in the test?

As commented, you were missing the save call in the test.

That means that the change is only in the runtime object returned by getEditable() and since get() and getEditable() do not share the static cache, you didn't see the change.


is there a way to overwrite the views Sort criteria? i have overwritten a field's output, and want to use it as the Sort criteria. so i must overwrite the Sort criteria?  is there a way to overwrite the views module Sort criteria?

the sort criteria is:

table votingapi_vote, the field content_id,which is $node->nid, the vaule=1. i want to to sort it by the number counts of the vaule. desc. HOW TO do it?

if i want to alter the  sort criteria in the template.php, is there a way to get it?

Sure, just use hook_views_query_alter().
You can intercept the view's query object and make any changes you need to it, including (but not limited to) adding/removing sort criteria.

Better WHERE's for your Drupal forums with hook_views_query_alter and Using hook_views_query_alter to change your views sort order give some examples of how to alter a view query.


Assign unique IDs to HTML elements via twig file I have a "block--system-menu-block.html.twig" file, which prints the menu content into the menu.
{# Menu. #}
{% block content %}
  {{ content }}
{% endblock %}

However, I would like each menu item (the resulting
 elements) to get a unique ID.
For example:

abc

abc

...
The idea is that I can use that in my css to have different colors or hover colors for my menu items.
I have already achieved this with JavaScript on the front end, but I would rather have it done in the backend, in the twig files.
Is that possible?
If so, any ideas?

Copy /core/themes/bartik/templates/classy/navigation/menu.html.twig
and modify a bit:
{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see https://twig.symfony.com/doc/1.x/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% set count = 1 %} {# <------------------ Added #}
    {% for item in items %}
      {%
        set classes = [
          'menu-item-' ~ count, {# <------------------ Modified #}
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
      {% set count = count + 1 %} {# <------------------ Added #}
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Result

Then you can do, Ex: #menu-block-id .menu-item-1 { border: solid green; }


Creating a site tour I created a site that allows people to create user accounts, login and communicate with other users, or view certain content. The site is completely finished accept for one thing. I am worried that users are going to get confused, or not know about all of the features that are on the site, so what I wanted to do, was to create a walk through tutorial of the site. I noticed there is a module for Drupal 6 that looks like it does almost exactly what I am trying to do, but I can't seem to find anything similar for Drupal 7, and I was wondering if anyone else has had any better luck. Also, I am I don't want the tutorial there permanently. I want it only there for the first few times that the user logs in, and then after that, to simply have a link saying "take site tour" on the bottom. Does anyone know of a module that can do that?

This module can do the same: Guidance

For controlling first time, you can use Rules module.


How can I show anonymous users their own content? I've tried to reach this with views and https://www.drupal.org/project/session_node_access and https://www.drupal.org/project/views_extras with no luck.

Any suggestions?

An anonymous user is a user with uid=0. So all (repeat all) anonymous users have the same uid value, and therefor there is no way to do what you are asking for out of the box.

There are various techniques you could programmatically do, but of course they all have their limitations.

Starting an anonymous session. Here when the node is created you add the Node ID in a $_SESSION variable and you can use this to retrieve the Node ID and pass that to the views arguments. Obviously, the limitation is that as soon as you close the browser, the session ends and you can no longer tell if it's the same user. So you have to start the cycle again, create a new node, etc...

Using cookies same as above but with cookies. Once cookie expires or it's cleared it's over.

Using IP You would save the IP as a field in the Node and you can query the DB to retrieve the Node that belongs to that IP. Obviously, the limitation here is if the user's IP changes it ends here.

Combination of all 3 Lastly, you could do all 3, have the other 2 as possible backups.


Theming forms in Profile 2 I was recently introduced into the Profile2 module for adding fields to the registration process and I think it just solves my problem. Can anyone show me how to theme the fields? All I need are the .tpl files but I don't think there are any since it's form so it uses the Form API. I may be wrong though.

By default the form will be rendered using the form rendering system, which doesn't include template files, instead functions like theme_textfield is used instead. You can choose to let the entire form or certain form elements be rendering by your custom theme function using the #theme key.

For certain type of fields, this can be dangerous as they require certain markup.


Approving Pending Userpoints I'm developing a site that allows users to earn points based on site actions.  I have the site working for users and their points earned are going into a "pending" category.  The next step is that the points need to be administratively approved.

I was trying to find a way to have this action work through a page content or onclick button without having to go through config -> points -> moderation.

If anyone has any ideas or thoughts that have worked for them I'd love the help, I've been stuck on this for a few days now.

Thank you!

you can try rules module to achieve this.
Create a event like "when a node is saved" and provide some condition if required and then action like grant/deduct user points. User points is integrated with rule.