Node count published, unpublished and total I have been on this for a while, considering my low php knowledge. Anyway I would like a view that lists users with total number of articles created, total number of those articles that are published and total number of those articles that are not published per user. I have looked around for an answer to this and the closest I get is node view count which does not do what I need.

In my opinion this is not as simple as it sounds although it should be considering the capabilities of Drupal.

I'll provide you with my solution (Drupal 7) which i implemented once in a site:

Create a users view in which you should do the following (in that order):

Remove any default Sort Criteria and don't add anything in that section
Add a field of "User: name"
Add a "User: Content authored" relationship
Add a filter "Content: Type" = Article
Add filter "Content: Published" = Yes
Add a contextual filter of "User: uid"
Activate aggregation
Set aggregation settings of user name field to "Count"

Now when you type the uid of a user in the "Preview with contextual filter" field of the view you will get the number of published articles that particular user has created.

Clone that view and (in the cloned view) change the Content:Published filter to No from yes. Now you have a 2nd view that gives you the number of unpublished articles for every user.

Last install and enable Views Field View module and create the following users view (in that order):

Add a field of "User: Uid" and exclude it from display
Add a field of "User: name"
Add a global view field. In the window that pops up choose the 1st view you created and the display you want from the "Views Settings" section (master display can be chosen if you like) and finally (and most importantly) in the "Contextual Filters field" use the [!uid] token (replacement patterns: [!uid] == User: Uid (raw)).
In the exact same way add a another global view field to "pull" the 2nd cloned view in this current view.
Recommendation: style the view as a table for trial reasons then theme as you like.
Also be careful to always have both global view fields after the user uid field in the Fields listing.

So this final view will present all the users of the site and next to each user the respective number of published and unpublished articles they have created. If you need the total number of articles then create an extra view without any Content: published filters and use it accordingly.


Default value to 'datetime' field in form loaded from the database I want to display the datetime field on my Drupal 8 form with some date loaded from the database, but the front end always shows empty fields as if no data has been provided. I tried several combinations to default_value field, but none of them are showing any thing.

The code I am using is the following.

$form['dateopening'] = array(
  '#type' => 'datetime',
  '#title' => t('Opening Date'),
  '#default_value'=> date('Y-m-d H:i:s', strtotime($dateFromDB)),
);

Why doesn't it set the default value as expected?

The response is in this thread : on stackoverflow

$form['valid_dt'] = array(
    '#type' => 'datetime',
    '#default_value' => DrupalDateTime::createFromTimestamp($data->valid_dt),
    '#title' => $this->t('Valid'),
);


Display youtube video using Media Oembed in the node I have embedded youtube video in an article using media+media_oembed+media_internet modules.Media(my field) is a field collection item with two fields - media and caption field.I have custom themed(necessary for my custom bootstrap template) media using theme functions according to file type whether it is an image or video.For image i have used picture module and displayed it as below.This is written in the theme_preprocess_field function.:

$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name,$display = array('label' => 'hidden','type' => 'picture','settings' => array('picture_group' => 'main_story_image','fallback_image_style' => 'w555xh372', 'image_link' => '')), $langcode = NULL

When i try to display embedded youtube video using the code below i get an icon and a filename with a link.

$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name, $display = array('type' => 'media_oembed'), $langcode = NULL);

How do you find out the correct formatter for the media_oembed module? I got the media_oembed from media_oembed/themes/media_oembed.theme.inc.

First of all i got all the default displays in my drupal site using the function : field_info_formatter_types().Since media is a file entity, the formatter should be file rendered.Then i had to give the file view mode in the settings array to show the way i wanted it.I created a custom view mode called article_page(machine name) and added oembed formatter.Here is the final code.

$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name,
            $display = array('type' => 'file_rendered','settings'=>array('file_view_mode' => 'article_page')), $langcode = NULL);


How to un-cache a specific node field (also for anonymous) My goal is to replace (by a custom markup) the render array of field_product when some conditions are met. (in a ecommerce site)

Ex: If this is the weekend or if it is after 12pm the field_product must not be rendered (but a markup like "the webshop is closed")

In mymodule_preprocess_node(&$vars) I have tried without success:

$vars['content']['field_product']['#cache']['max-age']=0;

or

$vars['content']['field_product']['#cache']['contexts'][] = 'session';

Unfortunately, it is not working for anonymous users

The only solution I found is:

$vars['#cache']['max-age']=0;

But as you can see, all the node is un-cached... not the field_product

What is wrong with my code?

Again: this should be uncached for anonymous users

You have to make sure you add #cache data inside of a render array only to render elements (containing #type, #theme or #markup). In other places of a render array it doesn't work.

Where you add cache max-age or contexts inside of an entity doesn't make a difference though, because there is no field level, only entity level caching.

Another problem is page caching for anonymous users. See How do I disable Twig and block cache for a specific module?


Can I use the Twig template engine? I do a lot of Django development and I like their templating language.
Twig, the new templating engine in Drupal 8, looks very much like it.

How can I use Twig in Drupal 7 or even Drupal 6?

Yes, you can, here is an article about my own experience with it, working with Bootstrap http://makina-corpus.com/blog/metier/2015/develop-with-twig-in-drupal-7

So http://www.drupal.org/project/tfd7 is the way to go if you want to write template files with Twig syntax, it must be moved to theme/engines.
Note that development is now happening at https://github.com/TFD7/TFD7 and documentation is at http://tfd7.rocks.

Don't be confused with the project https://drupal.org/project/twig, unfortunately, it is only an input filter because modules cannot provide theme engines in Drupal 7 (due to license reasons it seems).


How do I retrieve media from a reference field? Inside a node type, I have a reference field to target a media.
With a db select, I need to load all related medias of the nodes.
For this I use this code:

$database = \Drupal::database();
$result = $database->select('media_field_data', 'm')
->fields('m', ['mid'])
->condition('m.bundle', 'gallery')
->leftjoin('node__field_related_gallery', 'n', 'media_field_data.mid = node__field_related_gallery.field_related_gallery_target_id')
->leftjoin('field_related_gallery_media_field_data', 'd', 'node__field_related_gallery.entity_id = field_related_gallery_media_field_data.nid')
->range(0, 5)
->execute()
->fetchAllKeyed(0, 0);
dpm($result);

But with this code I get an error and don't get the related mids. If I remove the line with the leftjoin I get the mids.

How can I proceed to verify if a media is related to a node and get only the media with a related node?

With views I can get easily the results with this query:

SELECT media_field_data.mid AS mid,
field_related_gallery_media_field_data.nid AS
field_related_gallery_media_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {node__field_related_gallery} node__field_related_gallery ON
 media_field_data.mid =
 node__field_related_gallery.field_related_gallery_target_id AND
 node__field_related_gallery.deleted = '0'
 LEFT JOIN {node_field_data} field_related_gallery_media_field_data ON
 node__field_related_gallery.entity_id =
 field_related_gallery_media_field_data.nid
 WHERE (media_field_data.status = '1') AND (media_field_data.bundle IN
 ('gallery')) AND (field_related_gallery_media_field_data.nid IS NOT NULL)
 LIMIT 26 OFFSET 0

Thanks.

Do you have to do it with a DB call? Why not use Drupal's existing functions?

  // Load a node by node ID.
  $nid = '213';
  $node = \Drupal\node\Entity\Node::load($nid);

  // OR load current node.
  $node = \Drupal::routeMatch()->getParameter('node');

  if (!empty($node)) {
    // Assumes you have a media field called "Related gallery"
    $medias = $node->get('field_related_gallery')->referencedEntities();

    foreach ($medias as $media) {
      // Do stuff with the media.
    }
  }


How to place a users role after username in Forums On my site, i have the Forums module enabled.

Please is it possible to put a users role in parenthesis next to the users username in the Forums?

For example "Brian (Student)" and David (Teacher)".

Thank you.

If you can find the display in views.

You can add a  "User: Roles" Field. Mark it as excluded.

Then

Under "user: name" field. select "Rewrite the output of this field" and include the [rid-role] token in the username.

Be sure to add the "role field" before "user field" otherwise the token will not be available.

Example


How to use a field other than node id or term id as contextual filter? I have a content type "Person" which has a field called "state". On the node page of any "person", I want to display other nodes of "Person" which has the same value for the "state" field.
For e.g. If a we are on a person node who is from New York, the view block placed on this node should display other persons from New York.

I know how this could be done if it were node id, or term id : using contextual filters and getting content id from URL, etc. However, I'm not sure how do I get this from other text field like "state".

Any pointers would be appreciated.

I think you need use the field type "list" or the field type "Taxonomy term".


Upload as Teaser Background I have created a views page which displays teasers of specific content type.

When creating content I am also uploading an image which we want to display on the background of the relevant teaser.

So every teaser has its image on the background.

Looking forward for professional guidance in this regard.

Try to use Background Images Formatter module, hopefully it will fulfill your requirement.

  Background Images Formatter module provides an image formatter who allows you to set an image
  in background of a div. The images are from a field of an entity and
  not from a configuration page or sth else, so it's very easy to setup
  and manage.

Change selector value to whatever you want in manage display section (explained in attached screen shot)


Uploading changed Drupal content from production to server I haven't yet setup version control (GIT) for my development and production environments as a result I am facing trouble syncing everything. My site is powered by Drupal 7.

For example, for a Content type that I created, what exactly is the folder on my development site that I should be uploading. And as far as the content type I created, what folder should I be uploading to the live server?

Another case is where I make changes to 'Text formats' found in admin -> configuration and a couple of other places in admin -> configuration, well, Not sure what folder I should be uploading either.

GIT will not be helpfull in this case. To transfer a contenet type from one Drupal installation to an other one you can either export and import it or use the features module (with features GIT could be handy).

For the other configuration changes you might be succesfull with the strongarm module. But for small configuration changes it's often more convenient to take some notes and just redo them on production.


Drupal 8 \Drupal calls should be avoided in classes, use | | dependency injection instead I used Drupal 8 and written a module.
in my form page I called.

\Drupal::service('library.discovery')->clearCachedDefinitions();
$cache = \Drupal::cache('discovery');
      $cache->delete('block_plugins');

It's worked, but I always see the warning.

  \Drupal calls should be avoided in classes, use | | dependency
  injection instead

I have the similar with File::load(), too.
I used:

use Drupal\file\Entity\file;
class BXBlock extends BlockBase {
public function build() {
...
$file = File::load($value);
...
}
}

Anybody can help me, please?
Thanks so much.

You can check how the dependency injection works in general in this documentation.
https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form

The parts that you need are:

Use statement -

 use Symfony\Component\DependencyInjection\ContainerInterface;

Class property - here we are going to store the whole \Drupal::service('current_user') object.

 protected $account;

The __construct magic method. This is called upon instantiating the class.
The dependency injection bit here is providing all the data required in a later stage as input.

function __construct(AccountInterface $account) {

Built in method that  has a dependency injection
create(ContainerInterface $container)

return new static(
  // Load the service required to construct this class.
  $container->get('current_user')
);

Eventually we are using the whole construction like that:

$uid = $this->account->id();

where $this->account is the same like \Drupal::service('current_user');


Drush is updated but not usable in Drupal 8 in Windows Is this a bug? I've the version that does support Drupal 8, so what is actually the problem here?

Update

I followed kiamlaluno and seem to have updated Drush but I still get the same error. I haven't touched the settings.php file. It's a totally brand new site so I would still get an error :\

You need drush 8 for drupal 8. You have drush 7 installed.


Add "- Please Select -" to a required CCK field In Drupal 6, by default, a required CCK field will display the first allowed value.
I want it displays "- Please Select -": Is there an easy way to do this?

I do not want to save "- Please Select -" in the database.

Use the key|label format for allowed values:

|-Please Select -
1|option1
2|option2
3|option3

By making the key for "-Please Select -" an empty string, the form can't be submitted with this value.


How to properly works in Chrome as a Drupal administrator? Not sure if is there I can do from the Drupal side, then I'll close this question if not suitable here...

I use Chrome to admin my drupal sites and I noticed that after some hours (let's say 3 or 4 hours) the site start to take more time to load admin pages. I resolve this by clearing the Chrome cache. This is ok but then I loss all stored data in Chrome.

Is there I should do within the drupal configuration to avoid this?

When you clearing the chrome cache it will ask for some options(shows a dialogue box with checkboxes), there you only need to check the Empty the cache checkbox and uncheck all other checkboxes and then click on Clear browsing data. Then it will only clear your browser cache not all chrome data.


how access $content array inside a block php? I have created a block and the format of it's content is PHP CODE.

this block is available only full page of node type article.

now in my block , I want to access $content or $page array.

I used global operation such as

global $content;
dpm ($content);

or

global $page;
dpm($page);

But both of these blocks return no result.

Please guide me.

Thanks a lot.

If you need to extract the comment of a node and put it in a block you can achieve this with a view.

Create a new view who show 'Comments' and create a block.
Now you can add a contexual filter:

Comment: Nid
The node ID to which the comment is a reply to.

After that select 'Provide default value'
and 'Content ID from URL'

Now you can add a 'Validation criteria'
and select 'Content' and check only the content type you want with this block.
now set 'Action to take if filter value does not validate' to 'Hide view'

Now you can add this block to a region in the block page and you have the node's comment displayed in a block.

Let me know if this will work for you ^^


How to show fields of referenced entity when referencing entity is being loaded? I have 2 content types, the first one has an Entity reference fields that references nodes of the second type.

I want to build a view (block) that shows some fields of the second (referenced) node when the visitor loads the node id of the first (referencing) entity.

For some reason I think this may be done really straight forward, but I'm not getting it to work.

A similar question was self-responded for the user who made it, but I dont seem to understand the screenshot he posted. How to use Entity Reference and Views

Another question seems to be answered but It looks to me like it lacks some information, as following that 3 points I cant get my block-view to work. Puilling Information From Referenced Entities to Display/Use In A Custom Content Type?

Any ideas?

Depending on where you want to create the block/ show the information the way to retrieve the data from the referencing node may vary. Here's a simple example for rendering from within a node.tpl.php:

$referenced_node=node_load($node->reference_field['und'][0]['target_id']);
print drupal_render(field_view_field('node', $referenced_node, 'field_something', 'displayname'));

This solution makes use of standard Drupal rendering methods/ display suite rendering for your referenced node. Change displayname to the proper display you want to use for rendering, you might want to add a custom one with different settings.


Include content of subdomain inside a block or view? I have created a subdomain - example sub.homepage.com. The subdomain is pointing to a server. But I need the template to be the same as my website.

My question:
Can I somehow include the content of that subdomain inside a block or view, or something else?

thanks

I think I got the answer on this.

I've created a new block, added this:

<?php print file_get_contents("http://sub.homepage.com/"); ?>

Remember textformat should be PHP.

And it worked. It now shows my subdomain inside my template.


Flags: get Action after a user flagged a specific number of nodes? I would like the users of my site to choose a specific number of nodes. After this they should see, to which taxonomy term these nodes belong to.

I have already found the flag module as well as flag limiter module. I have put the limit to 12 (This is the amount of nodes the user should be able to choose).

Now I would like that the user is redirected to a new page (where he can see the belongig taxonomy terms to his flagged nodes - this I can manage to create with views), after he flagged the 12th node.

Could anyone help me, how to achieve this?

Thanks,
Tabea

You can able to detect limit has reached using hook_flag_flag hook exposed by flag module..

Flag Limiter module uses the same logic to detect the limit as you can see the below code

function flag_limiter_flag_flag($flag, $entity_id, $account, $flagging) {
  // Get the flag limits.
  $flag_limit = variable_get('flag_limiter_' . $flag->name . '_value', 0);
  $peritem_limit = variable_get('flag_limiter_' . $flag->name . '_peritem_value', 0);

  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) > $flag_limit) {
      $unflag = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag) {
        drupal_set_message(t("You've already signed up @num times", array('@num' => $flag_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }

  if ($peritem_limit) {
    $flagging_data = flag_get_counts($flag->entity_type, $entity_id, TRUE);
    if ($flagging_data[$flagging->flag_name] > $peritem_limit) {
      $unflag_item = flag('unflag', $flag->name, $entity_id, $account, TRUE);
      if ($unflag_item) {
        drupal_set_message(t("The event already signed up @num times", array('@num' => $peritem_limit)), 'error');
      } else {
        drupal_set_message(t('Fail limiter operation'), 'status', FALSE);
      }
    }
  }
}

You can implement same hook in your custom module to redirect user to the page you want.. You can use drupal_goto function to redirect user..

function YOURMODULENAME_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}

writing custom module instructions ..

Create a folder called "custom" inside sites/all/modules
Create a folder called "myflaglimit" inside sites/all/modules/custom/
Create a file called "myflaglimit.info" inside "myflaglimit" folder create above.
Put in below code and save file

Below code goes into myflaglimit.info file..

name = My Flag Limit
description = Provides a redirect on reaching limit.
core = 7.x
package = Custom
dependencies[] = flag_limiter

Your logic goes into .module file

Create a file called myflaglimit.module file inside myflaglimit folder you have create with below code
You extend drupal function using hooks which are nothing but functions which starts with modulename_hook

use below code inside module file

<?php
function myflaglimit_flag_flag($flag, $entity_id, $account, $flagging) {
  if ($flag_limit) {
    $user_flags = flag_limiter_get_user_flags($account->uid, $flag->fid);
    if (count($user_flags) >= $flag_limit) {
      drupal_goto('path');
    }
  }
}


How to show a user login form on a completely separate page? I am developing a application where I want to restrict everything from anonymous users. If anyone tries to access any page from url directly they will be redirected to login page. How to do this?

Also I want show the login page in a completely separate page where there should be no menu or any other links, just the login form (like for example: google login page). What is the best way to do this.

Easiest way would be to remove all permissions from the anonymous user at /admin/people/permissions and then set the 403 page on /admin/config/system/site-information to /user.


Add more fields to content type dynamically I am looking for the ability to let the user who is creating the page add more fields to the node rather than the entire content type.

For example if I had a content type called Book and each content type I wanted the user to select how many authors the book had. Some books might have 5-50 authors. It does not make sense to be to create 50 fields in the content type, id rather let the user select how many author fields they will need with an "add more" button.

In my case I am using videos and the Brightcove video module that adds a custom field to my content types. I figured the process would be the same. What is the best way to create this add more experience?

This is in core for the field types supported by the fields module.  When you add the field to the node type, just pick Unlimited  as the maximum number of values the user can enter for this field.  Every time the user adds a field, a new one ready to be filled in will appear.


is there anything like $view_mode in user-profile.tpl.php in node.tpl.php you have variable $view_mode, is there anythings like that in user-profile.tpl.php?
user is bundle like node, and you can define different view modes for it.

I don't believe there is. There should be, and if I had to guess I'd say there will be in D8. Large parts of the entity api simply didn't get implemented in D7, and nodes were probably just considered a higher priority.

I believe the Profile2 modules work by extending the user entity, it may provide you with what you want.
Otherwise my suggestion is Panels, which can control the user view via something called "Selection rules", instead of view modes.


Custom widget not saving I've created a custom widget for a textarea (to display the contents in a table as well). So the textarea should appear and work just like a normal textarea widget, but with an additional HTML table of its contents.

I can make it appear correctly, but when I save the form the values do not get saved.

In fact, my "data_source_field_is_empty()" function is never called (the dpm() text never appears).

function data_source_field_widget_form(&$form,
                                         &$form_state,
                                         $field,
                                         $instance,
                                         $langcode,
                                         $items,
                                         $delta,
                                         $element) {
  switch ($instance['widget']['type']) {
    case 'data_source_data_widget':
      $thisItem = isset($items[$delta]) ? $items[$delta]['value'] : '';

      $widget['#type'] = 'textarea';
      $widget['#default_value'] = $thisItem;

      // Only do this if there is already content in the field
      if (isset($items[$delta])) {
        $rows = _data_source_parse_csv($thisItem);

        $widget['#prefix'] = '<button type="button" id="show-hide-raw-table-data">Show raw data</button>';
        $widget['#suffix'] = _data_source_dataTable($rows, 0);

        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/js/data_source.js',
          'type' => 'file',
        );
        $form['#attached']['css'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/css/data_source.css',
          'type' => 'file',
        );
      }

      $element[$field['field_name']] = $widget;
      break;

  }

  return ($element);
}

function data_source_field_is_empty($item, $field) {
  dpm("Got here");
  return empty($item[$field['field_name']]);
}

Any ideas? I'm looking at the $element[$field['field_name']] = $widget; part, but none of the variations I've tried have worked.

After studying the code in modules/field/text/text.module, I found the missing item: I had to assign my new widget to $element['value'], so:

$element['value'] = $widget;
return ($element);


module to test if e-mail is working In D7 I'm trying to determine the best way to periodically check if e-mail is working. I'm looking for a way to create a workflow that, say, on cron would check the day of the month, if it's the day that has been configured in the module as the test day, send an e-mail. Check the return value on the e-mail function. If the e-mail failed, write the error to the logs and/or send it to another service, like Slack, to alert the team.

Is there a module that comes close to doing this, or can something be cobbled together with actions and rules, etc? Thanks!

What I did instead: Since all I really want to know is when e-mail fails, I went the watchdog rules route instead. Combining watchdog rules with the Slack API allowed me to create a rule that sends a slack message whenever one of our sites has an smtp error.


HTML tags removed during Views Rewriting Hello I created a sitemap with the modules "Views and data export". The sitemap of my page works fine, but I would add images to my page.

The sitemap should look at first capture, I do a test with figure and they are well placed. When I "rewrite the results" the tag is ignored.
How to implement these label ? it's been weeks since I'm on it.

Thank you

If I replace the HTML tags with text data it works:

However when I add HTML it gets removed:

I found answers to How add markup and prefix / suffix for computed field. Can you tell me how to put that in place?

HTML tags, ugh, finally I understand your Q.

You can re-write your field using template files.

Go to /sites/all/themes/YourTheme/templates folder and

create views-view-fields--[view-name]--[machine-name].tpl.php

  For Example:

  If you view is called "Hello World" and the machine name is
  block_1

  then it would be views-view-fields--hello-world--block-1.tpl.php

Inside your template file you put:

<?php

$fields["path"]->content = '<loc>' . $fields["path"]->content . '</loc>';

$fields["field_image"]->content = '<image:loc>' . $fields["field_image"]->content . '</image:loc>' . '<image:title>' . $fields["field_image-atl"]->content . '</image:title>';

echo $fields["path"]->content;
echo $fields["field_image"]->content;

When you are working with template files, remember to clear/flush the cache to see the changes.

Now your HTML tags should not get removed.


How to clear form element values after validation error I have a rather complex form validation depending on multiple fields. If validation fails, I would like to set the form values (of all or some explicit fields) to an empty value. This is what I tried, but none of the three approaches works:

public function validateForm(array &$form, FormStateInterface $form_state) {
  ...
  if (!$authorized) {

    $this->messenger->addError($this->t('An error occured.'));

    $form['name']['#value']=''; // approach 1

    $form_state->setValue('name',''); // approach 2

    $form_state->setValueForElement($form['name'], ''); // approach 3

    $form_state->setRebuild();
   }
 }

Have you looked at unsetValue()?

Example usage:

public function validateForm(array &$form, FormStateInterface $form_state) {
  ...
  if (!$authorized) {

    $this->messenger->addError($this->t('An error occurred.'));

    $form_state->unsetValue('name');

   }
 }

From the doc:

  Removes a specific key from the submitted form values.

  @param string|array $key
  Values are stored as a multi-dimensional associative array. If $key is a string, it will use unset($values[$key]). If $key is an array, each element of the array will be used as a nested key. If $key = array('foo', 'bar') it will use unset($values['foo']['bar']).


how rewrite pagination URL views for SEO? i am trying to rewrite the views url pagination :

  /mypath/cat?page=1

to

  /mypath/cat/1 or > /mypath/cat/page/1 or /mypath/cat-1

cat is a taxonomy term.

I have tried to rewrite url with Drupal\seo\PathProcessor but without really success...

  Code for rewrite /mypath/cat?page=1 to /mypath/cat-1 :

    public function processInbound($path, Request $request) {

        $page = \Drupal::request()->query->get('page');

        if($path == '/mypath/cat' && $page>0) {
            \Drupal::request()->query->set('page', $page);
            return $path.'-'.$page;
        }

        return $path;
    }

    public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
        return $path;
    }

This ll redirect to /mypath/cat-1?page=1.

That broke the views filter too, it's normal.

i can alter the views filter for remove the "-" but how remove the ?page=1 from the uri ?

This is the right way for alter the url views pagination ?

In Drupal 7 you can use Query Parameters To URL but the D8 port needs more work. Maybe you can help with that in the course of the work for your current project?

It's similar with Clean Pagination that cleans up the pagination specifically, D8 needs more work.

In the meantime maybe you can replace some of the exposed Views filters with contextual ones, they take arguments separated with /.

With a Contextual filter you can display a Summary of taxonomy term names at the top of your views (or any region for that matter) instead of an exposed filter with the term names. That way you would see a list of terms as links at the top of your Views, and the links paths would look like mypath/cat.

Pagination would still add ?page=1 so you'd have mypath/cat?page=1 unless you get the Clean Pagination running.


Cascading taxonomy term selection widget To be honest, I'm not sure if cascading is the right term, and if it's not then this can just be edited in the future for clarity.

I need a taxonomy term widget that is a drop-down list, and all that is initially populated are the top-level taxonomy terms in the particular vocabulary associated with the widget.  After selecting a top-level term, another drop-down list is added next to the previous (the one you just selected from) with all of the children of the selected term.  The parent drop-down list is then disabled.

You should be able to click a link to go "up a level", basically removing the right-most drop-down list at the time and re-enabling the right-most list after that.

For example, say I have the following structure:

A

AA
AB
AC

B

BA
BB
BC

C

The initial drop-down list would just contain: A, B, and C.  You now select 'A'.  The list with A, B, and C would then become disabled, and another list would be added directly to the right of it with the terms: AA, AB, and AC.

The term submitted along with the form would be the term represented by the right-most disabled list's selection at the time.

Is there anything that exists with this functionality (or similar)?  If so, I haven't seen it (and I'm looking hard).  Otherwise I guess I'll just have to code it up myself, but I'm hoping I don't have to invent a new wheel.

You can use the Hierarchical Select module:

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.


How can I update the values of an exposed view filter when another filter changes value? I know there are several examples of this around, on a view with two exposed select list filters, I need to update the value of the second based on the value selected on the first. I can't even seem to get any debugging info on my callback, but the request is throwing a Drupal\Core\Form\Exception\BrokenPostRequestException. Here's the simple form alter I'm trying.

use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == "views_exposed_form"){
    $form['field_article_value1_value']['#options']  = _MODULENAME_get_update_value1_values();
    $form['field_article_value2_value']['#options']  = _MODULENAME_get_value2_values();

    $form['field_article_value1_value']['#ajax'] = [
     'callback' => ['_MODULENAME_get_value2_values_ajax_callback'],
     'event' => 'change',
     'wrapper' => 'edit-field-article-value-wrapper',
     'progress' => [
     'type' => 'throbber',
     'message' => NULL,
     ],
  ];
}

function _MODULENAME_get_value2_values_ajax_callback(array &$form, FormStateInterface $form_state) : array {
  $markup = '
Testing!
';
  return ['#markup' => $markup];
}

This module might help: Views Dependent Filters

If you really want a custom solution take a peek at the code there and see if it helps, or help the D8 version get released :)


List all users using Drupal Views I am new to Drupal and Views. I need to list all the authors(users) in my drupal 7 page? Do I need to add relationships for this ?

No.

When you add a new View, in the first screen there is a GUI with menus that let you create a view to;

Show users sorted by newest first

And that is all there is to it!

You can obviously refine the View to enhance the presentation, change the sorting, add a pager, etc. - but just to list the users, the above is what is required.


form_set_error Not displaying error after invalid form submission I've created a form using my custom module. At the validation handler, I'm calling form_set_error() but no error messages are being displayed.

Also, I've marked several fields as '#required' => true; do I need to validate them manually? I thought Drupal will be validating them automatically and displaying error messages. But I see no error message for them, when I submit invalid data (i.e. not providing any value for the default fields).

This is the code in the implementation of hook_menu() that defines the callback for the page containing the form.

function myModule_menu() {
  $menu['user/signup'] = array(
    'title' => 'Signup',
    'description' => 'Sign Up',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myModule_signup'),
    'access callback' => TRUE,
  );

    /// Others
}

The rest of the code is the following one.

function myModule_signup($form, &$form_state) {
  $form['user_email'] = array(
    '#type' => 'textfield',
    '#size' => 15,
    '#required' => true
  );

  $form['user_name'] = array(
    '#type' => 'textfield',
    '#size' => 15,
    '#required' => true
  );

  $form['user_passwd1'] = array(
    '#type' => 'password',
    '#size' => 15,
    '#required' => true
  );

  $form['user_passwd2'] = array
        (
    '#type' => 'password',
    '#size' => 15,
    '#required' => true
  );

  $form['user_gender'] = array(
    '#type' => 'select',
    '#options' => array('male', 'female')
    // '#size' => 15,
    // '#required' => true
  );

  $form['user_age'] = array
        (
    '#type' => 'select',
    '#options' => range(18, 26),
    // '#size' => 15,
    // '#required' => true
  );

  $form['user_country'] = array(
    '#type' => 'select',
    '#options' => array('Bangladesh', 'USA'),
  );

  $form['user_state'] = array(
    '#type' => 'select',
    '#options' => array('Dhaka', 'Chittagong', 'Mymensing'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sign Up')
  );

  return $form;
}

function myModule_signup_validate($form, &$form_state) {
  $formValues = $form_state['values'];
  if (empty($formValues['user_email'])) {
    form_set_error('user_email', t('Email can not be empty'));
    dsm('I can see this message...');
  }
}

And I'm also calling <?php print $messages; ?> in my custom theme's page.tpl.php file.

I  made a  quick test module using your code, and I was also not getting any error messages.  The error message problem was solved when I added '#title' fields to each of the elements in your form array.  Drupal is using those to figure out what messages to display.

The reason form_set_error message isn't getting set is because drupal displays at most one error message per field, and it is already detecting that the user_email field is required and setting its own error message because of that.  If you want additional validation, you'll have to check for more than just the existence of the field, and also pass in some malformed data.


Webform twig template causes "the form has become outdated" error We want to customize the theme of our webforms. We will want the ability to add markup around individual webform elements (like my_element_01 and my_element_02 in the example below)

Below is a very basic twig template that seems like the right path (based a little on How to access webform elements in webform.html.twig ). However, when I submit this form I get "The form has become outdated. Copy any unsaved work in the form below and then reload this page.".

I have read that the form_id and form_build_id has to be rendered in the template but I am doing that. I am not sure what is wrong or if there is a better approach.

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_01 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

{{ title_suffix }}

</form>

The issue was I was not rendering out the {{ element.form_token }} element. I added that element and it works:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.form_token }}
  {{ element.actions }}

{{ title_suffix }}

</form>

This works which is why I submitted it as an answer. I do think it could be better written. This would require effectively using the twig 'without' filter which I can't get to work. I am creating a separate post about that as I feel they are different topics. The basic idea is I shouldn't have to fish or remember to render all the items that make up a drupal form such as form_build_id, form_id, form_token, or actions. I should render the entire element array and hide the fields I want to wrap in markup. Then I can explicitly render those fields. Something like:

{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element|without('elements) }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

{{ title_suffix }}

</form>

But that currently renders my_element_01 and my_element_02 twice.


How can I cache the operations on the admin content overview per user? The admin/content view page gets cached, but the operations column is different for the various users. When a user visits the page after the cache is cleared, their operations are correct. Another user, with the same role, may have different access to other nodes, but the result of the first user is shown => this leads to unwanted, in access denied resulting edit buttons.
I installed Views Custom Cache Tags and set the cache tag to user:[user:id], but it didnt work (looking at the module I'd guess it supports tokens).
How can I set that the output of admin/content is cached per user? I dont want to completely disable the cache for that view.

This is not a cache tag issue. You need a cache context.

You can use a contextual filter for the user, then Views would add the cache context automatically.

Another option is to add the context to the render array of the View:

function mymodule_views_pre_render($view) {
  if ($view->id() == 'content') {
    $view->element['#cache']['contexts'][] = 'user';
  }
}

The cache context user.permissions is used by default in drupal caching. If this doesn't give you the variations you need in cache use the more general user context. Then for each user a new version of the View is cached, which will obviously use more database space.


When I double-click on the publish content tab on a node, I end up on /user instead This is on a pretty complex site so I have no idea where to start looking for the cause of this behavior.

I have installed the Publish Content module, which creates a little "publish" or "unpublish" tab along with "view" and "edit" on each node, for users that have permission to publish or unpublish content.

When I click on "publish" or "unpublish" once, the expected behavior follows. But if I double-click on that tab (and only that tab – others don't do this), then instead of reloading the node, it takes me to my user page.

I tried disabling the devel module but that didn't help. It happens on multiple content types, and as multiple different users with different roles, including user 1.

I have a couple of rule-based redirects in place, but they're only for specific roles and they're only triggered on particular actions (such as login). And none of them redirect to the user's own page.

I have no idea where to start debugging this.

It's because when you double click, most probable case is the second click will try to use an already used token.

Or it could also be due to the fact that the second click might be translated as trying to publish an already published node.


How do I revert the changes made by a specific user? I want to revert the changes made by a specific admin user in Drupal 6.37. In all the pages that I want to revert, the create new revision box was not selected. Hence, I have no way of finding out the changes.

If you don't have revisions you can't rollback the changes unless you have a database backups that you can use to restore and old copy of your site.

If you don't have any strategy to save your database you can consider use the Backup and Migrate module, for Drupal 6 the last release is the 6.x-2.8

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.


I can't upload images in CKEditor With Drupal 8 I'm having issues uploading images in a node.

I select an image in the upload dialog box and add it, yet when I go to view the page the image is not there? Directory permissions for image uploads are set to read/write.

When I inspect the source, I don't even see an image path.

My upload dialog box looks pretty crappy too.

What am I doing wrong?


How do I update from 8.4.5 to 8.5.0? I am trying to update Drupal core using Composer, but I am not able of doing it. I have followed a few blog posts, but nothing worked for me. This is the output of composer update drupal/core --with-dependencies.

There is some dependency changes with the new drupal version and drush but this should fix it.

composer update --with-dependencies drupal/core:~8.5 symfony/class-loader:~3.2.13 drush/drush:~9.@dev


Login form inaccessable? When I go to mysite.com/user I see the login form. But it is not accessable. I cannot click in either of the text boxes and the button does not click.

This is true in Firefox, Chrome, and recent IE. It does work in IE8 for some reason.

Anyone have a clue why this should be? I tried moving it to other regions. I looked at the HTML and it appears to be fine. Maybe I'm missing some crucial Javascript?

Any ideas would be appreciated.

It sounds like there is some invisible HTML over the top of your form.

Inspect one of the form elements with Firebug and see what it actually selects, then fix the HTML / CSS.


How to edit the sidebar form content? I recently inherited this website from a colleague of mine: http://cityrentacar.gr

It runs under Drupal 7 with the Nexus theme.

I am trying to edit the fields/select-options on the sidebar request form but as soon as i login i only see a configure button over the form?

Is there a way to manually edit the field?

Any help would be appreciated.

Thanks.

It looks like your predecessor used jotform to set this up, see this screenshot:

If I am right, then you should be able to edit these values via the related jotform account.
Hope this does it for you, it seems you need the get those jotform credentials for the linked jotform account!


dynamically populate a select field based on the selection in another field works only the first time I am trying to dynamically populate a select field (chamiponship) based on the selection in another field (country).
It works fine when I load the page but just the first time, the second time I select another country it does not work.
Did anyone have this issue and how did you solve?
Here is my code

<?php

function testform_menu(){

    $items['data'] = array(
        'title' => 'data access',
        'description' => 'get acess to the data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('testform_form'),
        'access callback' => TRUE,
    );
    return $items;
}

function testform_form($form, &$form_state) {

        $form['country']=array(
            '#type'=>'select',
            '#title'=>t('Select your country'),
            '#options'=>array('FR' =>'France', 'UK' =>'England','DE' =>'Germany'),
            '#ajax' => array('event'=>'change','callback' =>'LoadDiv','wrapper' => 'DivSelect',),
        );

        $optionsDiv = array('Ligue 1','Ligue 2');
        if (isset($form_state['values']['country'])) {
            $optionsDiv = loadDivision($form_state['values']['country']);
        }

        $form['champion']=array(
            '#type'=>'select',
            '#title'=>t('Select your championship'),
            '#options'=>$optionsDiv,
            '#prefix' => '
',
            '#suffix' => '
',
        );

        $form['submit'] = array(
            '#type' => 'submit',
            // #value is the text to display inside the button
            '#value' => t('Submit'),
        );

        return $form;
}

function LoadDiv($form, &$form_state) {
  return $form['champion'];
}

function loadDivision($country_id) {
  $data_count=array('FR' => array('Ligue1', 'Ligue2'), 'UK' => array('Premier','Championship'), 'DE' => array('Bundesliga1','Bundesliga2'));
  $championship = $data_count[$country_id];
  return $championship;
}

It is hard to say without seeing your JavaScript, but what you describe fits perfectly with the following scenario:

When your page loads initially loads, the LoadDiv JavaScript event is bound to #DivSelect, but when that #DivSelect element is overwritten by the Drupal AJAX api, the event is no longer bound.

The solution is to use Drupal.behaviors - there is a good, short explanation at http://www.amazeelabs.com/en/blog/drupal-behaviors-quick-how.

Wrap your LoadDiv javascript in the drupal behaviors code, and it will be added for every request, including AJAX requests:

Drupal.behaviors.myModuleDoSomethingCool = {
  attach: function (context, settings) {
    $('#DivSelect').change(function() {
      // Loaddiv etc etc
    });
  }
};

I agree with comments suggesting that this is a good use case for hierarchical select - but the above is the likely explanation for why your AJAX works the first time and not the second time.


Getting QueryString from with a module I've trying to get the querystring from within a module.

I've tried the following.  However the following always returns A

exporter/directory?l=o

$l = "A";
if ( !empty($_SERVER['l']) ) {
    $l = $_SERVER['l'];
}

/* edit */

    $l = "A";
if ( !empty($_GET ['l']) ) {
  $l = $_GET ['l'];

}

Oswald is correct. Alternatively, in Drupal 7, you can use drupal_get_query_parameters():

$query_parameters = drupal_get_query_parameters();
if (!empty($query_parameters['l'])) {
  $l = $query_parameters['l']
}


Drupal 8 hide meta tag fields in node form I am just wandering is there a way to hide some of the input fields in MetaData while creating/editing a node.

For example, I want to hide,

Geographical place name and Geographical position,

that is in MetaData->Advanced, in node form, so that user doesnt have access to it while creating a node.

Anything like hook form alter?

I'll make the assumption you're using the Metatag module (https://www.drupal.org/project/metatag).

Unfortunately, this module doesn't allow fine-grain control of fields through its UI, so the only way I've found to hide these fields is through a form alter.

In this case, I'm modifying all node forms (use whatever hook fits your scenario here). Example, hiding the "advanced" fieldset entirely by disabling access to it, so it's not rendered:

function MY_MODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['field_metadata']['widget']['0']['advanced']['#access'] = FALSE;
}

I'm sure this can be modified to target more specific nested groups/fields, but should give you a start at least!


Filter view based on displayed part of an Open Layers map I have a page that shows an OpenLayers map which is fed with data coming from an Open Layers data overlay view (user locations; the location is provided via a location cck field in the user account settings). Right underneath the map the overlay data is listed using a clone of the Open Layers data overlay.

Is there a way to filter the displayed entitites in the list based on what part of the map is currently looked at? That is, is there a way to hide entities from the list when I zoom into a different part of the map?

Example: Zoomed to full extend, showing the whole world -> display all entities. Zoomed to the US, showing only California -> display all entities with a Californian location.

We had the same requirement in a recent project. It was solved with javascript, there is no out of the box way to do this.

Please see https://www.transpower.co.nz/projects

Here is some code to get you started:

(function ($, Drupal, window, document, undefined) {

  // ...

  $(function(){

    if($(".not-front .openlayers-map").length && !$('.node-type-project').length) { // only run when there is actually a map on the page, but not on the home page

      if ($('body').hasClass('page-community-initiatives')) {
        is_ci = true;
      }

      mapData = $(".openlayers-map").data('openlayers').openlayers;
      pointLayers = mapData.getLayersByClass("OpenLayers.Layer.Vector");

      // cycle through all layers and points on those layers, adding the points to an array
      for (var i in pointLayers) {
        for (var j in pointLayers[i].features) {
          pointData.push(pointLayers[i].features[j]);
        }
      }

      // if we've pulled out some points, go make a list
      if (pointData.length) {
        makeList(pointData, ".pane-openlayers-map");
      } else {
        $('.pane-openlayers-map').append('

Your search returned no results, please try again.

')
      }

      // add event listener to the map to be fired whenever the user interacts with it.
      // calls refreshList function above
      mapData.events.on({
        "moveend": refreshList
      });

      Drupal.openlayers.popup.popupSelect.events.on({
        "featurehighlighted": popupOpen,
        "featureunhighlighted": popupClose
      });

    }

  });

})(jQuery, Drupal, this, this.document);

The entire JS file can be download (unminified) from the theme. Please alter to suit your needs.


Rules: fire at adding term only when one of this term anscestors is other specific term I'm trying to add menu items programatically by using rules - the item should be added after user will create a term, but I need a specific condition that I cannot accomplish - fire rule only if ONE OF THE ANCESTORS of created term is specific term. So for example if I have hierarchy:

Term 1
Term 2
 - Term 2.1
 - Term 2.2
   -Term 2.2.1

I would like the rule to fire when the added term is 2.x.x.x... How can I accomplish this? I was trying for few hours different approaches without luck.

Write your own condition for rules

function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_needs_veryfication' => array(
      'label' => t('ONE OF THE ANCESTORS of created term is specific term'),
      'group' => t('mymodule'),
      'arguments' => array(
        'aplication_node' => array(
            'type' => 'node',
            'label' => t('A fancy condition'),
        ),
      ),
      'module' => 'mymodule',
    ),
  );
}
function mymodule_condition_needs_veryfication($node)
  if(condition($node))
    return true;
  return false;
}


How to relate a field to another field in content type like a foregn key? Can anyone guide my to the best method or module to connect 2 fields together?
I want to create a field called (Author) in a content type book, which will refer to a field called (name) in a content type author.

So a book author, will refer to field name of an actual existing author.

It's like creating a foreign key from the a book field to the author author field.

But the modules that I found (like node relation, relation and entity reference) only do a node reference, which is not what I want.

Not sure if I did use the modules correctly. But am I missing something here?

I am kind of new to Drupal as well as the web development era.

Any help?

Instead of using relationships use field collection module. In this module you may create a collection of fields that they all point to an entity.

As an example you can create author collection and in this collection insert first name field,last name field,gender field or any other information you need.

You can add this collection as a field to the book content type.


Print the query which is built using db_select() I want to print the query which is built using db_select() in a programmatical way. Is there any API function provided by Drupal Abstraction Layer?
It is similar to query output in Views, but I want to print it from my custom module for debugging purpose.

SelectQuery implements SelectQuery::__toString(), which is called in the contexts where a string is required.

Consider the following code.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

print $query;

Its output is the following one.

SELECT block.*
FROM
{block} block
WHERE  (theme = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1)

To get the array of arguments used for the query, you can call SelectQuery::arguments().

The following code prints the query and its arguments using the functions made available from the Devel module.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

dpm((string) $query);
dpm($query->arguments());

The Devel module is not necessary, though, and you could drupal_set_message() to show the output. For example, you could use the following function to get a  string with the placeholders replaced by their actual values.

function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

The previous example code I shown would become the following one.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

drupal_set_message(format_string('Query: %query', array('%query' => _get_query_string($query))));

function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

Notice that SelectQuery::arguments() returns the array of query arguments only when it is called after SelectQuery::__toString(), SelectQuery::compile(), or SelectQuery::execute(); otherwise, SelectQuery::arguments() returns NULL.

You could use a function similar to the following one to get the string query, with the placeholders replaced with the arguments.


How to pass different parameters to the same form function based on different urls I have a custom model containing two paths. Each path goes to the same function. I wanna to send to each page arguments specific parameter and reception on the function then pass the hidden value to submit function.

  $items['parkingcalculator_normal'] = array(
    'title' => t('Parking calculator'),
    'description' => 'Parking Calculator Page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('parkingcalulator_form',0),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['parkingcalculator_valet'] = array(
    'title' => t('Parking calculator'),
    'description' => 'Parking Calculator Page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('parkingcalulator_form',0 ),
    'access callback' => TRUE,
  );
function parkingcalulator_form($form, &$form_state , $type){...}

but the function does not take the parameter and does not pass the value in the hidden form type to

function parkingcalulator_form_submit($form, &$form_state ,$type)

Remove $form from the submit function and just keep the $form_state.

The function would look like

function parkingcalulator_form_submit(&$form_state ,$type)


Strip overlay context from File field I have a basic File field set up to allow my users to attach files to nodes.

However, the File field widget in the node edit form displays files as a link to the file, and the URL contains #overlay-context=. Thus when users right click to copy the URL to the file, the URL includes the overlay context, and the link doesn't work (or images don't display).

How do I stop the Overlay module from adding that on to the File URLs on the node edit form?

I have the Insert module, IMCE, and IMCE WYSIWYG bridge enabled to provide users with other options, but some users (including myself) still prefer to right click the file name and copy the URL.

The only thing I can think of offhand is to play with hook_url_outbound_alter() and make a regex to alter only the file paths url in question (not just any and all urls on the site) and strip out the context.

There might be a better way to do this ... maybe like theme_link or theme_links overridden for the given region ?


Filter a Drupal View by a Taxonomy Term Reference I have a view that generates a block on all taxonomy term pages under a specific vocabulary (lets call this vocabulary 'pages' for now). That specific vocabulary has a field added that is a term reference to a a vocabulary we can call 'pagetype' (you can only select one value). I want my view to display all 'pages' that have the same 'pagetype' as the one that I am currently on. The problem is I cannot figure out how to use the current term's 'pagetype' for the contextual filter instead of the current term ID. Any help with this would be awesome.

Create view (block)
Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
“Arguments” is from now on called “Contextual filters”, so go there.
Add the filters: “Content: Has taxonomy term ID (with depth)” and “Content: Has taxonomy term ID depth modifier”
Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid
Set the ‘when argument is not present’ to ‘Provide default argument’
Set the ‘Default argument type’ to ‘Content ID from URL’
Go to “MORE” , and check the “Exclude” box.
Move the filter “Content: Nid” to the top position.
Add a block to your view and embed the block on your node pages
Save your view


Get profile ID after using commerce_customer_profile_save() Anyone has any idea how to get the profile_id after I created a new profile using commerce_customer_profile_save() ?

Apparently this function does not return the new profile object and I don't think it's very safe just to select last inserted profile from the database :(

Stupid me, it's in the $profile object itself.

commerce_customer_profile_save($profile);
$profile->profile_id;


Allow authorization via cookies We are migrating from Drupal 7 to Drupal 8 and are currently at the last hurdle - relying on Drupal's session to authenticate for custom scripts.
Previously we used to rely on drupal_bootstrap but now I have implemented a similar Drupal 8 aware version for bootstrapping and checking the user is authenticated (and which roles they have etc) - this is broadly based on core/authorize.php.
However - this only works in the drupal root directory or the core/ directory - in every other directory this fails to authenticate the user.
I believe this is down to the routing, and authentication only working for pre-defined routes.
Specifically I want to be able to authenticate users in any script in a folder (recursively). EG

external_scripts/script1.php
external_scripts/script1.php
external_scripts/other_scripts/script3.php

How do I add a route to allow this? Or can I just bypass this route checking when using the cookie? Can I spoof the route?
<?php

/**
 * @file
 * Locates the Drupal root directory and bootstraps the kernel.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\Routing\Route;

function _find_autoloader($dir) {
  $autoloadFile = $dir . '/vendor/autoload.php';
  if (file_exists($autoloadFile)) {
    return include_once($autoloadFile);
  }
  elseif (empty($dir) || $dir === DIRECTORY_SEPARATOR) {
    return FALSE;
  }
  return _find_autoloader(dirname($dir));
}

// Immediately return if classes are discoverable (already booted).
if (class_exists('\Drupal\Core\DrupalKernel') && class_exists('\Drupal')) {
  return \Drupal::service('kernel');
}

$autoloader = _find_autoloader(empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD']); // defined in start.inc
if (!$autoloader || !class_exists('\Drupal\Core\DrupalKernel')) {
  print "This script must be invoked inside a Drupal 8 environment. Unable to continue.\n";
  exit();
}

const MAINTENANCE_MODE = 'update';

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();
  $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  $kernel->preHandle($request);
  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');

$content = [];
$show_messages = TRUE;

$account = \Drupal::service('authentication')->authenticate($request);

if ($account) {
  \Drupal::currentUser()->setAccount($account);
}

var_dump(\Drupal::currentUser());

I tried many different ways of loading the user, using the session as the starting point. In every singe scenario it fell down.
So in the end I used as much of the Drupal scaffold as I could, and copied the relevant bits from the relevant classes and functions in order to control the loading of a user record in an ajax handler that exists outside of Drupal's page space.
It uses the cookie to load the session, retrieve the user id, details and roles and create an account object before setting the bootstrapped Drupal kernel current user to the account object.
We deal with access control at a higher level (relying on \Drupal::currentUser() and leveraging $user->isAuthenticated() for example) so this script gets up to a consistent point in both contexts (inside Drupal, and non-drupal pages inside the domain) for user management etc.
<?php

/**
 * @file
 * Bootstraps the Drupal kernel and loads the user for the incoming request via cookie
 */

use Drupal\Core\DrupalKernel;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;
use Symfony\Component\HttpFoundation\Request;

function _find_autoloader($dir) {
  $autoloadFile = $dir . '/vendor/autoload.php';
  if (file_exists($autoloadFile)) {
    return include_once($autoloadFile);
  }
  elseif (empty($dir) || $dir === DIRECTORY_SEPARATOR) {
    return FALSE;
  }
  return _find_autoloader(dirname($dir));
}

// Immediately return if classes are discoverable (already booted).
if (class_exists('\Drupal\Core\DrupalKernel') && class_exists('\Drupal')) {
  return \Drupal::service('kernel');
}

// Load autoload
$autoloader = _find_autoloader(empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD']); // defined in start.inc
if (!$autoloader || !class_exists('\Drupal\Core\DrupalKernel')) {
  print "This script must be invoked inside a Drupal 8 environment. Unable to continue.\n";
  exit();
}

const MAINTENANCE_MODE = 'update'; // Don't bother theming

if (PHP_SAPI == 'cli') { // CLI won't have a cookie, stop now
  return;
}

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$connection = $kernel->getContainer()->get('database');

// Get session id from session cookie
$sid = reset($_COOKIE);

// Get uid from sessions, get user from uid
$query = $connection->queryRange('SELECT uid FROM {sessions} WHERE sid = :sid', 0, 1, [':sid' => Crypt::hashBase64($sid)]);
$uid = (string)$query->fetchField();
$values = $connection->query('SELECT * FROM {users_field_data} u WHERE u.uid = :uid AND u.default_langcode = 1', [':uid' => $uid])->fetchAssoc();

// Get roles from uid, and set account
if (!empty($values) && $values['status'] == 1) {
  $rids = $connection->query('SELECT roles_target_id FROM {user__roles} WHERE entity_id = :uid', [':uid' => $values['uid']])->fetchCol();
  $values['roles'] = array_merge([AccountInterface::AUTHENTICATED_ROLE], $rids);
  $account = new UserSession($values);
  \Drupal::currentUser()->setAccount($account);
}


Display multiple values in entity reference view I have created an entity reference view to display the values of a multi value field in Drupal 8.

The field is a date field.

In the view I have set the "Multiple Field Settings" so the date field values will be shown in separate rows.

When I preview the view, I can all of the date values shown is separate rows as expected.

I then create an entity reference field and select the view as its reference type /view.

The problem is, when I then view this field, I am only shown a single value instead of all the dates as seperate rows.

How do I setup a multi value field so I can select from all of its values in an entity reference field?

Thanks in advance.

Try to use Entity Reference Views Select module. For me it worked when I had the same issue.


How to save custom label as parameter for a custom entity_reference field widget? I am creating a custom field widget for an entity_reference field. This has a custom select field and an Ajax Submit button. Once the user selects an option (entity) from the select_field and submits it, I am adding the entity in a dragTable below.

I could achieve that until now, but my need is to add a custom label for the entity selected. I provided a textfield to capture the custom values and I am able to fetch the values. But, I am unable to save this custom text_field data. I am extending the core WidgetBase class for my custom field Widget.
For an entity_reference field, is it possible to save custom label parameters along with the entities?

Updated:
After enabling fieldType, duplicate results are appearing while creating field. Any help on this? .

You need to create a custom field type that can hold the value along with the entity reference.

A field widget can not store any data that the field type has not provided space for.

You must create a new field type would look similar to this:

<?php

namespace Drupal\MY_MODULE\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;

/**
 * @FieldType(
 *   id = "entity_reference_with_value",
 *   label = @Translation("Entity reference with value"),
 *   category = @Translation("Reference"),
 *   default_widget = "my_custom_field_widget",
 *   default_formatter = "some_formatter",
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class EntityReferenceWithValue extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
    $schema['columns']['value'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Value'))
      ->setRequired(TRUE);

    return $properties;
  }

}

Now you can get the value with $entity->field_name->value.

It would also be better to extend EntityReferenceAutocompleteWidget in your field widget, instead of WidgetBase. Then you can just do like this in the formElement method:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $widget = parent::formElement($items, $delta, $element, $form, $form_state);

  $widget['value'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Value'),
    '#default_value' => $items[$delta]->value,
    '#weight' => 999,
  ];

  return $widget;
}


Ajaxly set Text Field Value with Drupal Forms API I have a text field and a ajaxified link in my form:

$form['id_number'] = array(
    '#title' => t('ID Number'),
    '#type' => 'textfield',  //textfield
    '#suffix' => '
l(t('101-03043'), 'myid_choose_result/101-03043/1, array('attributes' => array('class' => 'use-ajax')))
',  //ajaxified link
    '#attributes' => array('id' => 'myid_search_id_number'),
);

The link above calls a function myid_choose_result define in my hook menu:

function myid_menu(){
    $items = array();

    $items['myid_choose_result'] = array(
        'page callback' => 'myid_choose_result',
        'access callback' => 'myid_user_access',
        'file' => 'myid.pages.inc',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

What I want to achieve is every time the user clicks the link, the text field value will be the link's text. After doing so, I want to call a another function:

function myid_choose_result($id,$template){
      //Change the textfield's value into $id
      myid_some_function(); //Call another function
}

How will I do that?

I suggest you instead of creating link and try to call ajax with old method( call form your custom js file ) try  drupal ajax method

My suggestion is :

function yourmodule_form_alter(&$form,$form_state,$form_id){
if($form_id=='your specified form name '){
$form['id_number'] = array(
    '#title' => t('ID Number'),
    '#type' => 'textfield',  //textfield
     '#prefix' => '
',
    '#suffix' => '
'
    '#attributes' => array('id' => 'myid_search_id_number'),
 );
$form['myajax'] = array(
        '#type' =>'button',
        '#value' => t('fill me'),
        '#ajax' => array(
            'callback' => '_myfuction_fill_number_ajax',
            'wrapper' => 'vm-container',
            'method' => 'replace',
            'effect' => 'fade',
            'prevent'=> 'sumbmit',
        ),
    );
 }
}
function _myfuction_fill_number_ajax(&$form,$form_state){
     $form['id_number'] ['#default_value'] = myid_some_function();
    // if not work try it with  $form['id_number'] ['#value'] = myid_some_function();
      return $form;
    }

also if you can want do ajax with jquery, add js file to your form, in that js file  set click handler for your link (  tag) and in click  call $.ajax with you menu rout.


Programmatically assign new users to OG My site is sub-divided into organic groups.

Group administrators are allowed to create new users, but I need a way to auto-assign the new user to the same organic group the creating group administrator belongs to.

Can anyone tell me how I can accomplish this auto-assignment either programmatically or with a module?

You should write a custom module that implements hook_form_alter().

Get the $form_id of the 'create new user' form that you want to alter.

( drupal_set_message($form_id); is an easy way to do this. )
Add a custom submit handler to the 'create user' form that uses the respective details and the og_group() function to add the new user to the group.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {

    if (isset($form_id) && $form_id == 'YOUROG_USERCREATION_FORMID') {
        $form['#submit'][] = 'MODULENAME_submit_handler';
    }

}

function MODULENAME_submit_handler($form, &$form_state) {

    $gid = $form_state['values']['groupID'];
    $uid = $form_state['values']['userID'];

    $account = user_load($uid);
    $values = array(
        'entity_type' => 'user',
        'entity' => $account,
        'state' => OG_STATE_ACTIVE,
       );

    og_group('node', $gid, $values);

    return $form;
}

Just as a point of information, this code sample is geared towards OG 7.2.x.

If you're using OG 7.1.x, you drop the first argument in og_group, so it would be og_group($gid, $values);

Also, the possible $values you can use, and defaults, are as follows:

# taken directly from og.module

$values += array(
     'entity type' => 'user',
     'entity' => FALSE,
     'state' => OG_STATE_ACTIVE,
     'save' => TRUE,
     'force reload' => TRUE,
     'membership type' => OG_MEMBERSHIP_TYPE_DEFAULT,
     'membership fields' => array(),
     'created' => time(),
    );


Reset/Delete the value of a field with node_save() I have a content type with a field_FOO of type text. I have a procedure that check which nodes have this field_FOO without value ($node->field_FOO == array() ), extract 1 at random, make some operations, set a value for this field (field_FOO[LANGUAGE_NONE][0]['value'] = 'bar') and save the node.

Now for 10.000+ nodes I need to delete this value but I don't want to do a node_load, empty field_FOO, node_save because for every node_save Drupal change the changed date associated with that nodes.

So, how can I "delete" the value of a field without use node_save()? If I delete the entry from field_data_field_FOO table I risk a site down ?

In the field_data_field_FOO table there is a "deleted" column. If I set it to 1, at the next hook_cron() that fields are deleted without a site down ?

Thanks.

If you want to do by changing the database entry then you need to check key constraints for the field table and also you need to remove its dependency from the parent table.


Which html div classes are relevant when styling Views in Drupal 7 (for CSS)? Generally, I wish to be able to style Views output on my site, but I am unsure which div classes and classes from other html elements to select in CSS to style.

There are many nested divs with classes and some to me seem like housekeeping/ancillary ones that should not be effected, e.g.:

General advice requested please: in the form of: technique, experiences, guide, tools, books and examples.

I've also considered Semantic Views for this aim, but this appears to be not yet in beta for Drupal 7 (i.e. unstable). Also View Element in Chrome browser or firebug - but not sure how much benefit these would have.

Also considered a mix of answers from:

How to design a page created using Views
Complicated views layout
How to create a list of FULL Nodes without titles (Views)
Customising the first item in a view

But would prefer a more general approach and one which doesn't require adjusting theme php code.

I can only speak to my personal experience. I use these classes to style my views primarily:

.view-myview .view-content the main content of the view, encapsulates all rows
.view-myview .views-row this is the row in your view, add a border, some margins, etc.
.view-myview .views-field-myfield a singular field in a view

You also get views-row-even, views-row-odd and views-row-first, views-row-last, etc.

The classes can handle all tags, it doesn't matter if they're divs, spans, etc. I did a presentation at DrupalCon SF 2009 which explains a lot of different ways to customize views if you're interested it is here: http://sf2010.drupal.org/conference/sessions/jquery-views-and-view-themeing.html


Performing an HTML substitution from AjaxResponse rather than using a wrapper I have an autocomplete textfield whose autocomplete_route_parameters is updated on the onChange event of a textfield, which is filled by a jQuery UI datepicker. Everything works, but after the update of the list the datepicker, which was closed after the selection of the date, shows up again. So I thought, well, I'll just use jquery to close it again.

This means that the ajax callback cannot simply return a renderable array, but rather an AjaxResponse; the problem is that I don't understand how to use a form element inside a ReplaceCommand. If before the change I had

function seduta_senato_form_datetime_changed(array &$form, FormStateInterface $form_state) {
  return $form['struttura-input'] ;
}

now I should say something along the lines of

function seduta_senato_form_datetime_changed(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse() ;
  $response
  ->addCommand(new ReplaceCommand('#ajax-wrapper', "
" . $form['struttura-input']->??? . '
'))
  return $response ;
}

but the form element has to be rendered somehow, otherwise it will simply appear in the HTML as Array.

I thought this would be simple, since for sure the functionality that renders the changed element is already there, but the research I made gave me only rather intricate solutions. Any help or hint would be greatly appreciated!

So, I used the source, and I found out that Drupal\Core\Ajax\ReplaceCommand calls getRenderedContent(), I found an implementation in CommandWithAttachedAssetsTrait where I saw that it expects an array, as I should have well known. So I ended up with the following calls:

$response
  ->addCommand(new RemoveCommand('label[for^="edit-struttura-input"]'))
  ->addCommand(new ReplaceCommand('input[id^="edit-struttura-input"]', array( $form['struttura-input'] )))
  ->addCommand(new InvokeCommand('#edit-field-next-field-to-edit', 'focus')  )

Note that I removed the wrapper, as suggested by @4k4, but then I had to select on a match on the start of the ID of the element, and to remove the label, since it is added by each new rendering. As a command to get rid of the datepicker I simply moved the focus to the next element to edit, which is very convenient to the user.


Wrap a field in a link conditionally in views I'm quite new to Drupal but I've been a developer for a few years. I'm struggling with what should be a very simple task. I have created a field 'field_client_link' that authors can use to enter a url to a portfolio content type about a client. If an author has entered a link I want to wrap a client logo in it, otherwise just display the image. I'm sure this is not as hard as I'm making it out to be. In WordPress I would just write something like this and be done with it:

<?php

    if (get_field('link')) {
        echo '' . get_field('image') . '';
    } else {
        echo get_field('image');
    }

?>

Here are my settings. I've set the link to be hidden because I don't want it outputting until I call it later. Hoping you can help me:

There's a lightweight module that lets you attach a custom link to any image using the image formatter setting: Image Link Formatter

It will automatically detect any link field and make it an option to set that link for the image.

I usually just go this route instead of dealing with tokens or template modifications every time I want to link an image.


Huge amounts of locale queries clogging up drupal to 40 MB per request I got an email today from my hosting company stating that they had to kill some processes of my site because it was using too much memory. Looking at the process table they provided, there were 10 processes of 40 MB, while my limit is 256 MB.

This poses me with two problems to solve.

1: Each page request drupal creates a process which uses 40MB of memory (which is of course killed again after the page is loaded). I've installed Devel and saw that each page makes around 900!! queries to the DB, most of which are from locale. All of them like this one:

   0.28270 locale P A E

   SELECT s.lid, t.translation, s.version
       FROM locales_source s
       LEFT JOIN locales_target t ON s.lid = t.lid AND t.language = :language
       WHERE s.source = :source AND s.context = :context AND s.textgroup = 'default'
   default

How can I reduce this?

2: Apparently some1 put in 10 page requests at the exact same time (elapsed time of each process was equal). Is there something I can do about this?

If you need any more information please ask. Thanks in advance.

Does your site use a caching system like Boost? Try installing the Drupal boost module and see if it helps. It is a static page caching system and needs to access the database only once.


Anyway to clear cache on Drupal 7 without any extra modules or even going to the performance page? I'm looking for a way to clear cache easily without installing any fancy modules or going to the performance page. Is there a URL I can just visit to clear the cache? Basically try to find the shortest and fastest way to clear cache without much effort.

drush cc all is the safest bet.

Visiting www.example.com/update.php will also clear the caches, but you need to be logged in.  Otherwise, this is a DOS vector.


How do you customize the title of an RSS feed created by Views RSS? I have an RSS feed for each user provided by the Views RSS module. The view uses

  users/$uid/feed

as the display path. The feed is titled "All articles by 34 on example.com". The "34" is the userid being viewed. I want the title to be "All articles by username on example.com". I can't set this to use a variable/data in the views title field, which does change the RSS title.

I can't use hook_preprocess_html() or _page(), as these  are not called for feeds
I don't see a hook in the Views RSS module, but I may have missed something
I don't want to do this in the theme templates for display, as this feels like the wrong place to put the logic

How do I change this? Is there another preprocess function I can use?

Not sure how much this will help as its not exactly what you're asking (i think):

I was using views_rss to show comment threads to a question_answer module question. But I wanted the question to show up as the 1st time in the RSS feed (as RSS feeds) may only show 1 piece of data by their nature (eg, comments or new posts or blog posts) ...

I didn't muck with the title of the Feed because I saw issues with Firefox Sage vs. Google Reader as what the "title" of the RSS feed is -- so I stuffed the "FAQ question" to the comment thread at the top of the RSS feed ....

/**
 * Implementation of hook_views_pre_render().
 *
 * For the comment rss feed we want the description to contain something such
 * as "topic #N: topic text". These values are excluded in the view already.
 * The RSS feed supports a description field but cannot have PHP code in it,
 * it's just static text.
 *
 * This is a means to theme the RSS description field for valid RSS feeds. The
 * view enforces that the parent node is published, and that comments are
 * published as well.
 *
 * http://stackoverflow.com/questions/4011505/how-can-i-add-a-summary-row-to-a-drupal-view
 */
function MYMODULE_discussion_views_pre_render(&$view) {

  if ($view->name == 'MYVIEW_discussion_comment_rss' &&
        $view->current_display == 'feed_1') {
    # Insert the question as a leading comment for this feed.
    $question = node_load(array('nid' => ARG(3)));
    $qrow = new stdClass();
    $qrow->comments_subject = htmlentities('Question Was:');
    $qrow->comments_comment = htmlentities($question->field_topic_text[0]['value']);
    array_unshift($view->result, $qrow);
  }
}

EDIT: My answer was coded for a D6 site, but the exact same principal applies to D7 (and I think the code as well).


Save own fields in database i've altered a form by adding my own fields. they're not part of the node.
i'm wondering which hook to use, to save these fields in the db.

i guess hook_nodeapi is the right one, but the form variable only gets transfered in the 'validate' $op, and it doesn't seem right to save data in the validate operation.

So how would i go about that?

When you alter a node editing form, the fields you add are part of the node and can be accessed using the $node argument of hook_nodeapi. Save your data when $op == 'insert' and $op == 'update'.

If you do not want your fields to become part of the node, write a form submit handler and add its name to the $form['#submit'] array. The submit handler should remove all your fields from $form_state['values'] (in addition to whatever was intended when adding the field to the form).


Interface Translation: Separate Drupal interface strings from theme strings? I want to translate all the t() strings in my theme but there's no way to filter those strings by your theme only. Instead they are bundled with Drupal interface strings which creates an excessively large export to deal with and potentially unwarranted translation requests from core strings such as:

!local-task-title!active

which is located in function theme_menu_local_task of includes/menu.inc

Is there a solution on how to filter your strings by ones in your theme only?

Looks like you are looking for contexts. In t documentation:

  Parameters

  $string: A string containing the English string to translate.
  $args: An associative array of replacements to make after translation. Based on the first character of the key, the value is escaped and/or themed. See format_string() for details.
  $options: An associative array of additional options, with the following elements:

  'langcode' (defaults to the current language): The language code to translate to a language other than what is used to display the page.
  'context' (defaults to the empty context): The context the source string belongs to.

You can have separate translations for separate contexts if you need.


Pre-populate webform default values with hook_form_alter I have a webform (version 4.11 on Drupal 7) that is failing QA test because the javascript validation is not correctly attaching to an empty required form element-- the 'Please fill out this value' tag is going to the top of the screen instead of near the element that failed validation.

So as a work-around, I decided to add a hook_form_alter and a new validation callback, to manually perform the validation. I am setting the error messages with drupal_set_message.

It turns out that the $form and $form_state arrays for webforms are apparently different from the typical form. Instead of $form_state['values']['field_key'], I found them here: $form_state['input']['submitted']['field_key'].

However, I can not figure out where each field's #default_value key resides in the $form array. I would expect it to be $form['field_key'], but it's not there.

How can I pre-populate the default value of form elements in a webform with hook_form_alter?

I found the values here

$form['#node']->webform['components']

So for the first component, I would change the value like so

$form['#node']->webform['components'][1]['value'] = 'test';


hook_node_access($node, $op, $account) not working I'm using drupal 7.41 module: Devel

I created module_template module.

function module_template_node_access($node, $op, $account) {
kpr($op);
    kpr($account);
}

But when I view or edit node not display krumo ??? Can someone help me in this matter?

You would need to check the access as the Admin role would have Bypass content access always.

hook_node_access

Also, try to check with the Reference.


Code highlighting in CKEditor How can I highlight the code section and reserved words for common languages like c/c++/Php etc ? I have tried the GeSHi Filter, but it does not work with the CKEditor. Am I doing something wrong ? Can anyone suggest some workable solution for the CKEditor?

If you're having trouble with the Geshi Filter, you could try the alternative http://drupal.org/project/syntaxhighlighter module.


Drush command terminated abnormally I'm using https://github.com/drupal-composer/drupal-project and get an error when starting drush:

[~/public_html/drupal]# alias drush="~/.composer/vendor/bin/drush"
[~/public_html/drupal]# drush
[error]  Drush command terminated abnormally due to an unrecoverable error.
 Error: Cannot declare class Drush\Commands\DrushCommands, because the name is already in use in /home/myuser/.composer/vendor/drush/drush/src/Commands/DrushCommands.php, line 12

What am I missing oder messing up?

I had to use another drush location. With the one in [~/public_html/drupal/vendor/drush/drush] everything seems to work.


How do I find which file contains a function? How do I find where a Drupal function is defined? For example, in which Drupal file is db_query() defined?

You can find it at includes/database/database.inc, line 2342.

Your editor may be providing a similar feature like the one implemented in Zend studio: When you press control while you click on the function name, it will take you to the file containing the implementation of that function.


How do I add a COALESCE to a db_select? I want to achieve the following query using db_select():

SELECT
  Column1,
  Column2,
  COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES

How do I add the coalesced column to the query?

Thank you

You can add an expression:

$query = db_select('TEST_ATTRIBUTES', 't')
  ->fields('t', array('Column1', 'Column2'));

$query->addExpression('COALESCE(Column1, Column2)', 'Column3');

The above yields:

SELECT
  t.Column1 AS Column1,
  t.Column2 AS Column2,
  COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES t


index.php file for custom module i have custom software and wanna write an api for drupal (custom software -> drupal). The thing is the custom software will call api calls to index.php (you cant change that). So how can i write something like an index.php for my module, like (http://drupal.install/myhookmenulink/index.php) so the software can reach that link and send infos to my module. anyone know ?

greetings

Drupal allows calls to .php files out of the box. Take a look at the .htaccess file and you will see that .php files will be handled just like any php application.

So... just create your .php file and make sure you are including it at the appropriate path.

That all said, in D8 (or in D7 + elbow grease) you get some pretty powerful autoloader capabilities out of the box so ideally you could take advantage of that in your module.


list of parent nodes with a list of child referring nodes I would like to make a list of all parent nodes and under each parent display a list of child nodes that are referencing parent node. Something like drupal.org modules page, except in my case this is not with taxonomy. Using drupal 6 views 2

example

parent1
-child1
-child2
-child3
more parent1

parent2
-child1a
-child2a
-child3a
more parent2

I am not able to display it using one view. Can anybody help me with some ideas? Thank you

probably you're using Node reference, right? If this is your case the solution is quite simple.

1) Create a view with a contextual argument for displaying all the children of a specified parent.

2) Use Display Suite module to attach this view on a custom display mode of parent nodes. With display suite you can pass the current nid to the view argument. You can also use Views Attach module ( https://drupal.org/project/views_attach )

3) create a view with the list of every parent and set to show the customized display created before.

I hope this will help you.