Views rewrite results texfield to uppercase I need to display text field to Uppercase, using Rewrite Results in Views.
For example from the text value "paper Title" to "PAPER TITLE".

How to transform the text to uppercase in Rewrite Results?

One solution is to rewrite with inline CSS styling. For example:

[my_field]

Depending on your design needs you might want use CSS classes instead.


Rewrite link field in views I'm trying to rewrite the output of a link field in a view in Drupal 8, to include a font-awesome icon, I have tried overriding my view field template in twig, but all i'm getting in the twig template is {{ output }}, which contains a rendered link already.

Desired output

Current output

http://www.facebook.com/profile

Have you tried doing this through the Views UI? You can use the Rewrite results as per the image below. In the rewrite output you should be able to add your font-awesome div.
You might need to use the output this field as a link option to make it clickable (you can use the replacement token of your link field) but that dependends on the field, so I am not sure if it is required.

Source: https://www.drupal.org/node/1578524


Show all tags for a views query? I am trying to write a views_query_alter hook and I want to identify the query I'm interested in. I have found the methods hasTag(), hasAllTags(), and hasAnyTag(), but I don't already know which tags I'm looking for. How can I get Drupal to tell me what tags already exist on queries? I didn't see any getTags() method.

I believe you mean hook_query_alter() here by mentioning hasTag(), hasAllTags(), and hasAnyTag() not hook_views_query_alter().

You can understand more about these methods from this documentation.

By help of these methods you can specify the targeted query, when you apply this in your module. A example code has been given in answer at Stackoverflow question, which helped me long ago to modify a query of views.

function MY_MODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasAllTags('views', '[MY VIEW NAME]')) {
    $query->addJoin('INNER', 'taxonomy_index', 'ti', 'node.nid = ti.nid');
    $query->condition('ti.tid', '2,3', 'IN');
  }
}

If you are looking for the tags which you can use, just try to print $query inside the hook & see the result on the page where you are working. You will get what query you can target & the tags which you can use.

I hope it helps :)


how to use intersection in a db_query? i want to select elements that exist on table_A and not in table_b, in other words, how to make the sql "intersect" in a drupal select query please ?

I've got it, just using :

$check = db_query("SELECT DISTINCT A.something FROM {table_A} as A
    where something not in (
    SELECT  B.something FROM {table_B} as B)
    ")->fetchField();


Dynamically prepend or append a path element to content urls? Is there a way I can easily prepend a dynamic element to the beginning of content urls?

For example, I have a /photos-galleries Panel/Page which includes a View showing a bunch of photo galleries. I also have /videos which similarly shows Videos. Both of these items exist in my main nav menu.

If I let the user browse to /cats/photo-galleries then my View uses a contextual filter so it will only show photo galleries tagged with cats. That's fine and I have that working.

Let's say one of those photo galleries has the content url /photo-gallery/kittens-1

If the user clicks on that link and goes to /photo-gallery/kittens-1... then my problem is that the main menu with the /videos link no longer has the cats "filter" on it. I want that filter type to follow the user along.

So, I'd like to rewrite the links to the content generated by the View so that I can change /photo-gallery/kittens-1 to /cats/photo-gallery/kittens-1 that way when the user clicks on that piece of content, I'll still be able to know that I'm filtering my site content according to cats.

Does that make sense? Any suggestions on how I can rewrite those urls, based on the current page url, being generated by the view?

Or if it is easier, I can append the cats filter tag to the end of the urls and make it /photo-gallery/kittens-1/cats. That would be fine also.

I'm not asking about how to filter the content in the view, I'm asking about rewriting the url of content items generated by that view so that it maintains the same /cats filter.

The hooks that can actually change the links used from Drupal are hook_url_inbound_alter() and hook_url_outbound_alter().
I have never used them to alter a link basing on the URL of the currently viewed page, but in the case of hook_url_outbound_alter() that should not be difficult, as it would require to use arg(); in hook_url_inbound_alter(), it would be more difficult, since you would need to be able to understand in which cases you happened a string to the URL. If the added part comes from a vocabulary of taxonomy terms, that would be probably easier, hoping that the taxonomy terms don't cause any conflict with enabled modules.

Appending the term at the end of the URL would avoid conflicts. It would also be easier to understand when a URL has been modified from your module.


Display site UUID from module Is it possible to display the site UUID on a Drupal 8 module?

"display" is pretty ambiguous, but you can get the site UUID like so:

$uuid = \Drupal::config('system.site')->get('uuid');

(depending on context, injecting the config.factory service would be preferable)

It's a string so rendering it will be easy.


How to display a variable in callback hook_menu? I'm creating a page with Hook_menu and I would like to display the user agent that page. This is my code to generate my page.

/**
 * Implements hook_menu().
*/
function custom_module_menu() {
    $items = array();
    $items['custom_module'] = array(
        'title' => 'My Custom Module',
        'description' => t('Best Custom Module'),
        'page callback' => 'custom_module_back',
        'access arguments' => array('administer site configuration'),
    );
    return $items;
}

function custom_module_back(){
        $output =  array(
            'first_para' => array(
                '#type' => 'markup',
                '#markup' => '
Test
 '
            ),
        );
        return $output;
    }

I try to set a variable like this $user_agent = $_SERVER['HTTP_USER_AGENT']; and then call it after the p tag.

Like this

function custom_module_back(){
            $output =  array(
                'first_para' => array(
                    '#type' => 'markup',
                    '#markup' => '
Test
 ' $user_agent,
                ),
            );
            return $output;
        }

And this did not work.

How can I display a variable into a callback ?

Based on your code, it should be written as

$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' . $user_agent,
  ),
);

rather than

$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' $user_agent,
  ),
);

You need the period to concatenate the your string and variable.

Edited - Full working module

/**
 * Implements hook_menu().
 */
function testing_menu() {
  $items = array();
  $items['custom_module'] = array(
    'title' => 'My Custom Module',
    'description' => t('Best Custom Module'),
    'page callback' => 'testing_back',
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

function testing_back(){
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $output =  array(
    'first_para' => array(
      '#type' => 'markup',
      '#markup' => '
Test
 ' . $user_agent,
    ),
  );
  return $output;
}


How to access a website database? Firstly I'm extreamly new to drupal and right now I was given a task to edit a currently online published website. The old designer didn't left me with any idea but from what I was told, the website uses Drupal to operate. I'm more to the classical way of building a website, for example: I create the scripts and upload it to a server and the server published it online. So how do I acess the website's database to make all the necessary changes to the scripts?

Thanks in advance.

The short answer: you don't generally access the database in Drupal.  Drupal serves as an intermediary between you and the database, and if you access the database directly more than likely you are going to cause yourself many problems in the long run, especially in the beginning when you're not very familiar with Drupal.

For more, see Understanding Drupal and the Structure Guide on Drupal.org.


How to get a node by its url alias? I know I can load a node by its title with the node_load() function. Is it possible to load a node by its URL alias?

You want to investigate menu_get_object and drupal_lookup_path.

Something like this would do what you want:

$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);


Add a custom submission handler to a form How can I add a custom form submission handler?

I tried adding $form['#submit'][] = 'mymodule_form_submit'; or $form['actions']['submit']['#submit'][] = 'mymodule_form_submit'; to hook_form_alter().

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
      }
    }
  }
}

function mymodule_form_submit(array $form, FormStateInterface $form_state){
    //die("why won't this execute? :(");
    drupal_set_message("Why won't this message show?");
}

It seems drupal_set_message() is not called. I also tried rebuilding the cache, but the function is still not called.

I am using Drupal 8.2.3.

If you use hook_form_node_form_alter() maybe use example code:
function MYMODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'mymodule_form_submit';
    }
  }
}

and for the submit function use:
function MYMODULE_form_submit(array $form, \Drupal\Core\Form\FormStateInterface $form_state){
  //die("I'm not getting run, why :(");
  \Drupal::service('messenger')->addMessage("Why won't this message show?");
}


Entity Reference | View - Display content based on a entity reference field's value that is randomized? We are using Entity Reference.

We have a content type "Dog", and a content type "Breed".
In the Dog content type, there is an entity reference field to Breed

We want to have a View that displays pictures and names dogs of a random Breed. If the page is refreshed, it should select a new random breed by which to filter the Dogs displayed.
We are displaying Dogs by Breed no problem, but getting it to load (and refresh) with a Random breed (and populating the Dogs accordingly) is the challenge we cannot yet solve.

I have a feeling we need to use a PHP Contextual Filter to handle this, but not sure what the approach is to make it work properly. Does anyone have any insight here??

you just have to configure a view that:

shows 1 breed, sorted random.
has another display that shows dogs based on a contextual filter on the breed nid
Install views field view
use the block from step 2 as a field in your first display and give the nid of the breed as a contextual filter to your views field.

So this views will show one random breed and has a view field to show the dogs that are of that breed. Hope this helps you out.


How can I execute Drush commands programmatically? I'm working on a Drupal 8 site, and part of the requirement is giving the client a page where they can click a button to do a particular task. I am able to do this using a Drush command from the command line, but I want to do it from a module.

I had seen code using either php_exec() or drush_invoke_process(). How can I use this function?

Just start it from the other side. Imagine that every Drush command executes some PHP code. Then check the code of the Drush command you want to run. And then refactor it into the submit function of your button.

Doing it like suggested in your question doesn't seem to be very sustainable, taking into account that not every host has Drush installed. So you better make that functionality work independently from its environment.

Found one possible way: How to run Drupal console command from code? using Symfony's Process and flagged question as possible duplicate. And regarding drush_invoke_process(), as how I understand it so far, it seems to be callable only from within other Drush commands.

Next thing that came to my attention: In the comments to your question you are saying that you are trying to execute /vendor/bin/drush/drush status which would mean you have the vendor folder at the root of your machine. Which very probably is wrong and you just need to fix that path.


Can I call two callback function in one ajax call? I just want to know how we can achieve two ajax callback on one form submit.Is it possible?and how?

You can't do that directly. Instead, use a function that calls the two other functions.

'#ajax' => array(

  'callback' => 'my_callbacks_wrapper',
)
...

Then:

my_callbacks_wrapper($form, $form_state) {

  $first_callback_processed_form = first_callback($form, $form_state);

  $second_callback_processed_form = second_callback($first_callback_processed_form, $form_state);

  return $second_callback_processed_form;

}

Make sure your callbacks don't interfere.


What is the accepted way to display certain content on different pages I have a couple different pages.  Each page has a main content area and a sidebar.  Each sidebar contains a paragraph unique to that page.  It is necessary that the paragraph in the sidebar and the main content are different content types.

I handled this by using references module.  I created a content type "category page" and a content type "page spotlight".  The page spotlight has a "node reference" field that references a category page.  I then created a view that enforces that relationship.  This allows me to map the spotlight to the pages.

I am wondering is using taxononmy a better approach?  I come from a very structured programming background where there are "right" ways of doing things, and I am just looking for the "drupal way" of approaching this problem.

That is definitely one way to do it.  I don't think there is a "Drupal way" to accomplish this per se, but you can also accomplish this through taxonomy and panels.  It really just depends on if having an extra Content Type bothers you or not.

I think the way you currently have it is the most efficient way.  To me you should only use taxonomy if it fits the mold of Drupal's definition of taxonomy.

    Taxonomy, a powerful core module, gives your sites use of the organizational keywords known in other systems as categories, tags, or metadata. In Drupal, these terms are gathered within "vocabularies." The Taxonomy module allows you to create, manage and apply those vocabularies.


Grouping by day + events spanning several days This is a question that has already been asked on Drupal.org. It's exactly what I need on my view, but it hasn't been answered yet.

Posted by Amanda-333 on April 12, 2011 at 5:58am
I wanted to ask how I can group events by day in a view.

It works fine if I only have events that have their start- and endtime on the same day.
2011-04-12
2011-04-12 10:00 – 2011-04-12 18:00 Event 1
2011-04-12 12:00 – 2011-04-12 14:00 Event 2

2011-04-13
2011-04-13 10:00 – 2011-04-13 18:00 Event 5
2011-04-13 12:00 – 2011-04-13 14:00 Event 8

The problem: I have some events that take several days or weeks.
Example: I create one event with the start date of 2011-04-12 10:00 and the end date of 2011-04-15 19:00 for example.

This event now shows up in the grouped view as
2011-04-12 - 2011-04-18
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

I would like to have that event sorted into the regular day groups (split that event into day parts):
2011-04-12
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-13
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-14
2011-04-12 10:00 - 2011-04-15 19:00 Event 11

2011-04-15
2011-04-12 10:00 - 2011-04-15 19:05 Event 11

Similar to how it is done in the calendar – day view. But with a simple text list format.
I can not find a way to do this? Perhaps someone can give me a little help?

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

Make 2 or 3 computed view fields (which will require some php):

1field for day of event
1 or 2 fields for start time and end time dates.

You can group the View output by the first field. Then create the event time range by inlining the 2 other fields.

With these 3 pieces of info the calendar should be able to see the start and end datetimes and make a line representing the event duration.


Add "Sale" or "Discount" text to a product display using drupal commerce? I have been searching for an answer a long time with no success at all.

I am buildind a drupal commerce website and i would like to show on a specific products the word "Sale" or "Discount" as showing in the picture below (like the green Sale Tag).

I can do it using photoshop but is really a pain to go over hundred of product just to photoshop a "Sale" text on every product picture in question.

Can someone point me to a specific module that can do such job ?!
Note that i know basic CSS so if this could be done using some CSS code, a starting push from any body will be appreciated !

Thank you,

With Views Conditional you can make it that if Label Discount Name is equal to Sale then

 Otherwise output nothing.

Then do the same for Discount.

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

  Views conditional allows you to output text based on the result of the
  condition.


Lists the organic groups current user is not a member I want to create a view that lists the groups user is not a member of.
Tried to add the filter criteria -:(author)user:current(no),but it displays the groups user is a member & only filters the  groups manage(created) by user.
Views-:7.x-3.7
og-:7.x-2.3

You can create a view that lists all groups the current user is not a member of, but you need to develop your own custom Drupal module for it (if anybody knows of a simpler way, please share your knowledge).

The general idea is as follows: Create a view that lists all groups. In your custom module, implement the hook hook_views_query_alter. There, add a condition to the view's query that checks whether the current user is or isn't a member of a group.

You can create the view that lists all groups via the website, or implement it in your custom module as well. For the latter, you can get a rough idea from tutorials like this.

In the database, the memberships are stored in the table og_membership. The field gid refers to the group's node id in the node table. The user who is member of the group is referred as an "Entity". So for each membership, the field entity_type is "user", and etid is the user id. So, a user is a member of a group if there exists a record in og_membership with the user's id in etid, "user" as entity_type and the group's id as gid. The other way around, if a user is not member in a group, such a membership record doesn't exist. In plain SQL, you could say something like (for user id 123)

SELECT n.nid, n.title
FROM node AS n
WHERE NOT EXISTS (
  SELECT *
  FROM og_membership AS m
  WHERE n.id=m.gid AND m.entity_type = "user" AND m.etid = 123
);

In your custom module, you need to add this NOT EXISTS-Condition to the view's query. To do that, you implement the hook hook_views_query_alter. The following is a rough idea of what the implementation should look like:

// the parameters are a reference to the view and the query, respectively
function MY_CUSTOM_MODULE_views_query_alter(&$view, &$query) {

  // get the current user's info from the global scope
  global $user;

  // alter only the query for the correct view, not for every view on the site
  if($view->name == "MY_VIEWS_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // the subquery to check for memberships
    $member_query = "SELECT * FROM {og_membership} AS m WHERE m.entity_type = 'user' AND m.etid = :uid AND m.gid = node.id";
    // add a new expression to the WHERE part of your view's query
    $query->add_where_expression("AND", "NOT EXISTS (" . $member_query . ")", array(":uid" => $user->uid));
  }
}


How to change front page title? The front page title in the menu is Home or Startseite in german. I would like to give it another name. How can I do this?

The question is asked multiple times over the internet (fore example here) but no clear answer... Thank you

Just deactivate the predefined menu link and add a new one - use

<front>

as path.

In Drupal 7 and 8 go to

Home > Administration > Structure > Menus > Main menu > Add link

Your German version will say something like

Startseite > Verwaltung > Struktur > Menüs > Hauptmenü > Hinzufügen

Drupal 7

See tooltip for details (using Rubik Theme)

Drupal 8 (German version)


What is causing Drupal to return a 404 HTTP header, but correctly return the page? I have a Drupal 6 site that is correctly returning site content (like the home page), but if you look at the response headers every page has a 404 header, instead of a 200.

Things I've tried:

Rebuilt the node access table (/admin/content/node-settings/rebuild)
Cleared the cache
Run update.php

Do you have any idea on what might be causing this?

Are you using clean urls?

It is possible that Drupal is called through the 404 error handler which results in the 404 header.

Make sure your .htaccess configuration is correct and that mod_rewrite is enabled and you're allowed to override the relevant settings.


Removing input formatting options and description from comment form How do I remove the input formatting options and descriptions from the comment form?

I'm not interested in a CSS and/or jquery based solution, nor am I interested in using the Better Formats module, as I am using Drupal 7 and it specifically states it is not ready for production sites (besides the fact installing a module to do this seems like overkill).  I want the html sent over the wire to not have the "input format" related text at all.

Drupal drives me nuts sometimes, because some stuff that should be simple is ridiculously complex.

I've searched but no one seems to know how to do this. Here's some things I've found:

form_alter hide Text format option
Hiding the comment form's input format selector: A zombifying experience
Drupal 7 notes - Hiding unwanted form elements in comment forms

Ok found this drupal issue discussing the matter: Node and Comment Input Format fieldset is not working (I found it by searching for "edit-comment-body-und-0-format" which html id of the fieldset that contains all the input format mumbo jumbo).

At the end of this issue is a link to the following site which gives a solution:
How To Remove Format Options / Guideliness From Comments Textarea in Drupal 7.

Here's the code I'm using on my site, in template.php of my theme (I'm using a zen subtheme):

function mytheme_form_comment_form_alter(&$form, &$form_state) {

  $form['comment_body']['#after_build'][] = 'mytheme_customize_comment_form';

}

function mytheme_customize_comment_form(&$form) {
  $form[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $form;
}

I just tried it and it does seem to be working. Woohoo!


CCK text field does not appear in views fields nor filters I have a CCK text field in my TOC. However, it is not displayed for selection under the views fields nor the views filters.

I tried clearing cache and refreshing the module list with no luck.

Any hint of what could be happening?

The problem was that I had in Views -> Tools the option "Disable views data caching" unchecked. Fixed now, thanks for your help!


E-mail validation form api What is the best way to handle server side e-mail validation in the form API?
Can it be implemented somewhere inside part of the form described below or are there other options?

 $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
 );

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

 return $form;
}

Create a validation function for your form.  Here is an example using your form. For instance, say your form code is in a function called my_email:

<?php
function my_email() {
  $form = array();

  $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
  );

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

  return $form;
}

function my_email_validate($form, &$form_state) {
  // YOUR CUSTOM VALIDATION CODE GOES HERE
 if (!valid_email_address($mail)) {
   form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
   }
}

function my_email_submit($form, &$form_state) {
  // YOUR CUSTOM SUBMIT CODE GOES HERE
}
?>

This function will allow you to write custom code to determine if the values entered in your fields are valid or not.  You can also add a custom submit function for your form to execute custom code while the form is being submitted.

Read more about validating forms at Validating Forms, submitting forms at Submitting Forms or read the whole article for a better understanding of the Forms API: Form API Quickstart Guide


Redirect user from a custom access callback In my module routing I have a custom access callback for a payment page.

_custom_access: 'Drupal\mymodule\Form\PaymentForm::access'

It checks if the user:

is allowed to make the payment (it's their own)
actually needs to (has it already been paid)

It works fine, but in the latter case, whilst I can give them an explanatory warning:

\Drupal::messenger()->addWarning('Fee already paid or no fee to pay.');
return AccessResult::forbidden();

it'd be nicer to redirect them to a page that's friendlier than:

  Access Denied - you are not authorised to access the page.

Drupal / Symfony insists on returning something that implements AccessResult - so I can't return a RedirectResponse.  Any suggestions? Moving the checks to buildForm() seems a bad idea.

For the second condition an access denied doesn't seem to be the right answer because permissions are not the reason. It is to control the business logic and for this I think it is a good idea to use buildForm(), which acts in a form route as a controller from which you can return a redirect response:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if (...) {
      $this->messenger()->addMessage('Fee already paid or no fee to pay.');
      return $this->redirect('<front>');
    }

    // build form if fee is not paid already

  }


Alternative to the need for dozens of roles to access special materials My organization wants to create access to specific resources and materials based on a role, but the issue is that there is the potential for dozens of such roles, each granting access to specific materials.

Is there a better way to manage this without having to have dozens of roles and permissions in the system, such as to use taxonomy or something else that is set up to accommodate such a volume?

Scenario:

A user can access our site and pay for and subscribe for special access to sections A, B, and C, each separately. Then we would need a way to track who has paid for access to which sections. I believe the section would include text, downloads, and possibly a forum and training videos.

Note: CiviCRM takes and tracks payments and memberships.

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types.

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Rules integration

Since you seem to be using CiviCRM also, you should definitely also consider using the CiviCRM Entity module, especially because of its integration with the Rules module ... combined with automagically creating (or deleting) so called "Group memberships" (which you can do via Rules). For an example of how to use Rules to create or remove such group memberships, refer to my answer to "How to add and delete a user to another group using the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Note

About your concern (as in your additional comment), which includes:

  ... having a list of permissions associated with each role multiplied so many times, editing and saving them taking extra processing power and stability issues. As well as the amount of work to the system each time the organization wants to add content. It just seems messy.

You're right, using standard Drupal permissions (with a zillion of roles) it would indeed become messy. But after you realize/discover how the Group module's roles/permissions work, your concern should be addressed ...


How to add a profile cover with a user field image in a view? I am trying to add a cover image to user profiles in a block view, the image comes from a user profile field.

The problem is that I need the path to that image because my neede code is like this:

<div class="profile-background"  style="background-image: url('/sites/all/themes/pingu/img/Circles.jpg');">

You need to install the Image URL Formatter module

Then in your view, click on your image field and select url as the formatter, so it prints the url rather than the image.

Views doesn't allow to use the style attribute in re-write results.

Therefore, you will need to use a template file. views-view-fields--[view-name]--[machine-name].tpl.php). This file needs to be in /sites/all/themes/THEMENAME/templates folder.

put this inside it:

<div class="profile-background"  style="background-image: url('<?php print $fields["field_image"]->content; ?>');">

<?php print $fields["field_other"]->content; ?>

...

Clear/Flush all caches to see changes.


Is there a way to import Paragraphs with Feeds module (no code)? Given a Content Type (a Node), which has a Paragraph field, which in turn has some fields on it, is there a way to import the Paragraph fields into the Content Type using Feeds (or some other method, but not involving coding)?

Example:
The Content type Photograph includes a Paragraph field called 'Inscription' that has these fields:

field_inscription (text)
field_inscription_type (term reference)
field_inscription_location (term reference)

How do I import these three fields into the Paragraph field of a Photograph Content Type?

Note: There will be multiple instances of the Inscription field on some photographs.

I'm currently in Drupal 7, but would consider working in Drupal 8, if there's a solution that works in Drupal 8.

The Drupal 8 version of Paragraphs does support some basic Feeds integration with a "Target" (see the source code)

Alternatively you could write a Processor plugin that manually creates and associates the paragraphs contained within a node.


Looking for a good Mini - Panels tutorial There are lots of good to tutorials for view and panels, but I'm having trouble finding specific information on how to properly use mini panels. Does anyone know of a good tutorial or explanation of how it works? again I've seen to referenced a bunch of times as a possible solution to certain problems, but never really understood how to use it.

(D7 panels 3 would be ideal)

I have not found a tutorial specifically for mini-panels, but it works similarly to page panels.  nodeone.se has an excellent tutorial on using Page Panels (Page Manager & Panels modules enabled).

Mini Panels are closely related , but behave more like blocks.  When you define a mini-panel it will be available in the panels UI for placement as well as in the admin/structures/blocks form.  The major difference from blocks is that mini-panels are smart.  They can take context from the node, user and other sources and display accordingly.  They also connect to a View.

There is one thing to observe when defining a mini-panel.  The UI is slightly different from Page Panels and the first time I used them, I could not figure out how to add content to one.  To access the "content" and other setting forms select the Panels breadcrumb  menu at the top.


Creating argument to filter multiple NID's in a single filter-criteria I'm having a rather simple Views issue in Drupal 7, Views version 3.11.7

I'm creating a View of Node-teasers so I need to filter it by the desired nodes NID's.

As you could see in the following image, I just typed their numbers but surly nothing happened.

What should I type there that the filter would work?

The "Contextual filter" solution is only needed if you wish to filter your results dynamicly by passing the necessary filters through the URL.

If I understand your question correctly you wish to filter your view on 4 specific nid's only (witch will never change)?

In that case you could modify your views filter setup and split into 4 seperate filters (each filtering on 1 nid). In the dropdown menu (where you have the "add" button to add a new filter) you have a config page where you can rearrange your filters and more importantly you can specify conditionals using filter group's. In your case I would create a second filter group for the 4 nid filters and use the "Or" operator between them.


How to change comment text using hooks Under each node there is a 'Add Comment' text. For a particular content type I want to change the text to 'review by adding comment". How do I do this?

Try with the String Overrides module. Here is a quote about it (from the module's project page):

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

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


How to translate URL aliases? I have the following path mysite/basic-page/about-us
I need translate it to:

You can use the  i18n (Internationalization) module (requires the Variable module).

You can follow this tutorial.


Custom home page with block and jqDock I'm a newbie in Drupal, and I have a really important web site to build. I've started with a Zen template, so I can build the entire theme from scratch.

I've looked around for better practices and best ways to do this, and finally decided to start by doing the "Master-Layout" on the "page.tpl.php" (I've figured that it's the best place for the global website structure), plus, I'm using the default CSS's files do arrange the things on the page.

But now, I need to start the "home page" content section. It will have a few "blocks"  and I still have some things that isn't clear what I can do to build this way.

For example, I have a "News" structure, that the authors use it to insert the news articles. I need to list the news on the home page much like an accordion style, with the image related.

Other example, the site will have a dynamic menu, using a jQuery plug-in like this: http://www.wizzud.com/jqDock/, and each item on this dock, will come from the Drupal database. Should I create a modulo to accomplish this? Can you guys help me??

For home page:

Clone your page.tpl.php as page-front.tpl.php in order to customized work for your home page.

Listing nodes in accordion:
* Use views to build a list for you
* User Views Accordion to format them in accordion

jqDock menu:
jqDock menu can be build using your content templates. But it should be clear what type of data coming from your database.

For custom data you will have to build your own module to fetch data.


Adding a custom HTML block to a view I have a view in Drupal 8 that looks as follows (see screenshot). To make the long story short, I need to make this view output a fixed HTML block (piece of code, not Drupal Block) and not pull any dynamic data from the respective content type.

What is the most efficient way of doing this?

In your screen shot, there is HEADER and FOOTER section. Click add in one of them and add a Global: Text Area, and put your HTML there, for text filter use FULL HTML.


Ubercart Node/Product Field access to Role and purchaser I have an Ubercart ecommerce Drupal 7 site I'm building.  The user can either subscribe (monthly/annually) or purchase node by node (pay as you go).

I need to GRANT the subscriber or purchaser access to the main body field of the product node only, as teasers and image fields etc will be used elsewhere on the site. (This rules out a few node_access options)

I would like to combine the permissions in my own custom module, as the I can't see any contrib permissions modules that fit my needs. e.g. Node access product.

Is there an simple custom way to ALLOW access to a field after I have checked if the user has:

a) Purchased this node, or
b) is a subscriber with access (I'm using uc_recurring for ROLE assign on purchasing a subscription).

I think it could due done manually in a module checking directly for current logged in users role(s) and purchases (nid's) and seeing is the logic plays out, but will this be slow on performance when there are 1000's users and 1000's products?

Please let me know if you need any more information or if I'm on the right track.

I think the Field Permissions module may be able to handle all your needs.

Whilst you couldn't have a different permission for the teaser text of a node you could just separate this out into a separate field and then apply an individual permission there.


Is learning Drupal 7 a bad option now after release of Drupal 8 Hi I am WeB developer and have recently started  learning drupal 7.
I have finished learning basics of PHP and have started learning drupal along with learning how to program the individual elements. Thankfully i have also got no. of materials ranging from books and video tutorials but what i also find is Drupal 8 has now also been released though i think it will take a lot of lot of time for people to build learning materials for that.

But i also think that it will take atleast 1.5 years to learn entire aspect of drupal and by that time Drupal 8 will be the worldwide adopted version.So do you guys think that learning Drupal 7 will be a waste as ppl will sign it off by then due to advent of Drupal 8.
Please guide me on the same

Well, firstly learning never gets wasted. Whatever you learn will some day in some moment help you.

Yes, Drupal 8 is going to be released and not yet released. No one knows when it gets released and even people are skeptic about the features that vary with Drupal 7. Definitely, Drupal 8 is going to set a new standard in development and usage. But, till then we shouldn't avoid Drupal 7.

Previously, we developed a website in Drupal 6 as soon as we deployed the site Drupal 7 was released. Then the features provided by Drupal 7 attracted us and we started migrating to 7 and it took most of our time in migrating. But our knowledge and work in drupal 6 didn't go into vain. Infact, we just learnt the new features added/upgraded. It took us only 1-2 days to know about Drupal 7, as we know the core concepts.

So, I suggest you to start learning drupal 7 don't bother about the things that are yet to come. You can easily manage things even drupal 8 gets released.


Mobile Tools detects mobile and iPad, not Android tablet I have used the Mobile Tools module for Drupal 6 to distinguish between mobiles,tablets and browsers. I am not using themes, just provided the redirection urls from the drupal admin settings.

The aim is  to redirect to mobile site while accessing from mobile(mysite.com/mobile).
Must redirect to the existing site while taken from tablet and web browsers(mysite.com).
It works fine for iphone,andorid mobile,blackberry and iPad.

But it redirects to mobile site when taken from Android tablet while I need to redirect to the desktop url.

Can anybody suggest how can I handle the android tablet using mobile tool so that it does not get redirected to mobile site?

Have you looked at ThemeKey? It has OS based redirection rules. Here is a quote about it (from the module's project page):

... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server


Why only first of two jquery files loaded is running? In my theme Basic, I'm loading 2 jquery files. Both two are loaded at front page, but only first loaded run. If I change loading order, again only first file do anything.
Here are the examples:

1)
Drupal.behaviors.basic = {
...some jquery stuff...

2)
Drupal.behaviors.basic = {
...some other jquery stuff...

They both have the same name, both "basic". Rename one of the 2 and you should be fine.
Change

Drupal.behaviors.basic = {

To for example

Drupal.behaviors.modifications = {

The name should be something descriptive about what the underlying functions do.


Integrate Switchtheme with Context? Im using Switchtheme to allow users to switch the theme of my site. Im also using Context and id like to create a new context depending on what theme has been chosen, but I cant see any options for this in the UI.

Actually, bit of searching and here you go: Context Condition Theme

  This module will add a conditional check within context for themes. Ever had the need to load a context based on which theme is being rendered?


How to display panels region title? How can I say Panels to show region title while rendering the page?

I have a panel region containing 4 node previews and I want to print a title before them. It would be like a "wrapping section" in my home page.

Is it possible?

You can create a template for your panel and add whatever div or wrapper you need there, by wrapping it around the content div. This post is a great resource:
https://www.drupal.org/node/1678810

In brief, for panel panes, your template file should be named:
panels-pane--[pane type]--[pane subtype].tpl.php

This post also shows you how to find your panel's machine name.

If you aren't familiar with templates, this is also a great resource:
https://www.drupal.org/documentation/theme


Facets blocks populated with incorrect field data and strange behavior I'm building a product catalog with faceted search. I'm using Search API, Search API Database Search, and Display Suite.

I've created a search server as well as an index which indexes four fields that I'm interested in filtering by (artist, country, printing, subject).

My problem is that the facets set on the individual fields have erroneous data in them (data pulled in from other fields, splitting the names of artists, etc). Then when you click the facets, the contents of the facet change by removing or changing fields from the list of options in the individual facet block. Interestingly, in the artist facet clicking on an erroneous field (e.g. a brand in the print type facet) produces no results (yes is available as an option).

Part of this maybe my data quality in the db, I do have Artists' names as two words in a single field.

So, I'm curious why the facet options change when clicked, but much more so as to why my facets are messed up.

Thanks in advance.

When preparing the data for the Search Page, make sure that the fields you index are indexed as strings and not full text. This is what caused the problem.


How to aggregate document.ready actions? This may be as much a style question as anything, but:  I'm building a site that uses the Bootstrap theme and a bunch of Bootstrap features -- popovers, dialogs, and the like. This means that I often need to run little bits of initialization code when the page loads; I'm doing these by using drupal_add_js to add the needed bits of jQuery, wrapped in a document.ready() handler.  The usual sort of thing, I think.

This works fine, but they are all being added to the page in their own SCRIPT and document.ready blocks.  Thus the page looks like:

<script>(function ($) {
        $(document).ready(function() {
            somejQueryCode();
        });
    })(jQuery);
</script>
<script>(function ($) {
        $(document).ready(function() {
            someMorejQueryCode();
        });
    })(jQuery);
</script>
<script>(function ($) {
        $(document).ready(function() {
            stillSomeMorejQueryCode();
        });
    })(jQuery);
</script>

as to what it seems like it might be:

<script>(function ($) {
        $(document).ready(function() {
            somejQueryCode();
            someMorejQueryCode();
            stillSomeMorejQueryCode();
        });
    })(jQuery);
</script>

You get the idea.  Like I said, the individual blocks are working, but it seems a little wrong -- you'd surely never write the code by hand like that.  I've explored various arguments to drupal_add_js, and have started experimenting with the AdvAgg module, but haven't found anything that works.  Is there a better way to do this?  Comments to the effect of "this isn't a big deal, don't worry about it" will also be accepted...  Thanks!

In Drupal, $(document).ready() is not used. The Drupal API uses Drupal.behaviors.

You didn't mention your version of Drupal. But you can read about the Drupal 7 JavaScript API here: https://www.drupal.org/node/756722

Here is Drupal 8: https://www.drupal.org/node/2269515

And here is a pretty comprehensive breakdown/tutorial I wrote on using the D7 API: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api


How to dynamically change the title of a menu item I have a "new comments" menu item in the user-menu that is generated by a view.
I would like to change the title of the menu to include the number of new comments.

I tried using hook_menu_alter without success. I cleared the cache and rebuilt the menu using the devel function.

function newcomments_menu_alter(&$items){
  $items['newcomments']['title'] = '5 New Comments';
}

When I add a menu item with hook_menu() I can dynamically change the title with a custom "title callback" function. But I can't figure out what the "page callback" is to display the view.

Views doesn't implement hook_menu() to add it's items, it uses the menu link API directly to add links. This makes it a bit trickier to do what you want as hook_menu_link_alter() isn't necessarily called when the caches are flushed, but only when the link is edited via the admin UI.

The links in menus don't even necessarily go through theme_menu_link() so you can't override the title at the theme level with that hook. Instead the only way I could find to do it was to implement hook_preprocess_link(), check the path, and change the title.

It's not a very pleasing solution, as theme_link() seems far too generic a place to be hooking into to change just one link title, but it might do the trick:

function MYMODULE_preprocess_link(&$vars) {
  if ($vars['path'] == 'newcomments') {
    $num_comments = MYMODULE_num_comments();
    $vars['text'] = format_plural($num_comments, '1 New Comment', '@count New Comments');
  }
}

The only problem is that if there are other links on the page that point to the same URL their title will also be changed. Hopefully this can be a 'feature' rather than a 'bug' ;)


Proper way to define a Migration yaml? I am trying to do a POC using Migrate, Migrate Plus, and Migrate Tools to define migrations and having trouble getting my migration to register and appear in the list of migrations for the migration group I created (in the UI).

In my yaml file, I put in the basics just to try and get it to appear in the UI:

id: remote_entity
label: TESTING
migration_group: mygroup

I named the file remote_entity.yml in a folder called migrations (I got this from the example in the Migrate Plus) module. Yet, it does not appear.

I see other modules have theirs in the config/install directory with a naming pattern assigned. Where is this file supposed to really be? What should it be named to get picked up? If it is in the config/install directory, do I have to uninstall/install the module numerous times as I iterate over a POC and make changes to the migration definition?

Where is this file supposed to really be?

It's config, so config/install is fine

  What should it be named to get picked up?

Like other config it's module_name.type.machine_name.yml, so (e.g.) migrate_plus.migration.id.yml

  do I have to uninstall/install the module numerous times as I iterate over a POC and make changes to the migration definition?

No, just like a normal config import you can do it partially:

drush cim --partial --source=/path/to/your/module/config/install

I did exactly what you did when I first played with Migrate Plus - tried to put the config in a migrations folder, like the example, but it didn't work for me either.

As migrations are config, this does make sense looking back - otherwise Migrate Plus would need to do something non-standard when discovering/importing migration configurations.


Form API Select List will not show empty option I am trying to add a form that forces you to select an option from a dropdown. The documentation says:

  If #required is TRUE and there is no #default_value, an empty option
  is added to the select control to force the user to make an active
  choice.

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#empty_value

OK that sounds great. That is what I want. So I have the following code to add the select list to my form.

$form['test'] = array(
    '#type' => 'select',
    '#options' => array (
      1 => 'Very poor',
      2 => 'Not that bad',
      3 => 'Average',
      4 => 'Good',
      5 => 'Perfect',
    ),
    '#required' => TRUE,
    '#title' => 'Rating',
  );

It is a select list, it is required and there is no default value. I however do not see a empty option...

What am I doing wrong?

Updated

The element above is now the only thing going into my array. When I dpm() the $form I get the following back:

Update 2

Below is what theme developer is seeing:

Update 3

I have set up a clean instance of drupal 7.22 and installed my custom code and the same thing is happening. I used the minimal profile. Must be something I am doing wrong else where...

Update 4

I have tested the full code on a different environment (7.19) and the same thing is happening. So it looks like there is something fundamentally wrong with the modules themselves. Will try and anonymize the problem so I can post here.

Update 5

I have the following two files in my module.

stack_test.module

<?php

function stack_test_menu(){
  $items['stacktest'] = array(
    'title' => 'Stack Test',
    'page callback' => 'stack_test_form',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

function  stack_test_form(){
  $countryList = array (
    1 => t('Very poor'),
    2 => t('Not that bad'),
    3 => t('Average'),
    4 => t('Good'),
    5 => t('Perfect'),
  );
  $form['test'] = array(
    '#type' => 'select',
    '#options' => $countryList,
    '#required' => TRUE,
    '#title' => 'Rating',
  );
  return $form;
}

Then I have my stack_test.info file:

name = Stack Test
description = Test Module
package = Stack Exchange
core = 7.x

files[] = stack_test.module

Update 6

Creating a select list in a content type with validation required works as expected and '- Select a value -' is displayed at the top of the list.

Update 7

The code in Update 5 should work now. I have created a mini module just with that in and I get the same results.

It looks like you're not running your form through drupal_get_form()...that would account for the additional form processing functions not running, but you'll still get a rendered HTML element out at the other end so it could be difficult to tell the difference.

Just change the page callback for your router item, and add the form as arguments:

function stack_test_menu(){
  $items['stacktest'] = array(
    'title' => 'Stack Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('stack_test_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}

Clear the caches and give your test page another try.

The same goes for your original problem - A form is essentially just a render array, and when you return that directly from a page callback it's run through drupal_render(). That function will do what it can to render the form element, and it knows how to do it to a certain degree, but the form processing functions add a lot of extra stuff in there, which drupal_render() won't do.

Moral of the story - always use drupal_get_form() to build the output for a form :)


Input format to save page links by ID but render by the URL alias? I would like an input format that works roughly like this:

I can enter links to other pages on my site using a special syntax, but importantly, I reference them by their current URL alias.
When the page is saved to DB, the filter replaces them with node IDs, which never change.
If I edit the page again, the filter replaces them back with current URL aliases before showing it to me. That way I know what the links are and I don’t even have to care that the DB actually stores node IDs.
When the page is rendered, the links are rendered to the URL aliases, rather than node IDs.

Is there anything out there that does this already?

Why I want this: so that I can change URL aliases without breaking existing links. I do have automatic redirects created, but that's not quite the same thing. I want pages to link to the correct URL when I change an alias.

If you use an wysiwyg editor ie. CKeditor, there are contrib modules that offer you this functionality. For example, take a look at the ckeditor link module.
It let's you search for your nodes and make a link to the node path which is what is saved to your database. Drupal automatically shows the url alias frontend, so if you change your url alias at a later point, you will still have a working reference to your node.

Why is it important to you that you reference them by their current url alias?


Getting taxonomy name from entity for computed fields Im trying to create a computed value field using the the computed_field module.  I trying to do something like http://drupal.org/node/792922 but that example is for drupal 6.  Can someone point me in the right direction of how to do this with drupal 7?

If you have taxonomy id, I'd suggest to do this:

$term = taxonomy_load_term($tid);
$node->your_field_name[your_language_specifier][your_value_index]['value'] = $term->name;

if you don't have taxonomy term id you can get it like so:

 $field_name = 'term'; //or what ever your field is named
 $entity_id = 4;//or what ever your entity id is
 $query = db_select("field_data_field_" . $field_name, $field_name);
 $query->addField($field_name, "field_" . $field_name . "_tid", "tid");
 $query->condition("entity_id", $entity_id, "=");
 $result = $query->execute()->fetchAssoc();
 $tid = $result['tid'];


How to attach node to user profile? How can I attach a node to a user profile with profile 2 (or some other way)? It says here that it is possible but it does not say how.

You could add an entity_reference field to the profile and reference the node in that field.


Get a url alias as a field value? Is there any way to get this? I can get the node ID and link to a node using node/nid, but then I have to mix pretty links that pathauto gives me with ugly ones.

Is there any way to get the url alias as a field value when building a view?

Edited: My question was wrong.

Updated Answer for your Updated Question:

In views you will need to add one of 2 fields.  'Content: Path' is likely the one you are looking for though.  Below is where to find it.

1) First you need to open your view for editing.

2) Next, find "Content: Path" and add it to your view.

3) Side note - If you would like a simple link you can add "Content: Link" in stead.  You also have access to Content: Edit, and Content: Delete among others.

Pre-update:
I will update this answer if you clarify your question. Specifically what you mean by 'as a field value.'

As I currently understand your question I think this may be what you're looking for.

I believe you will need to use drupal_lookup_path() to find a path alias.

Example:

drupal_lookup_path('alias',"node/".$node->nid);

  Source: Drupal Community Documentation for drupal_lookup_path()

  Given an alias, return its Drupal system URL if one exists. Given a
  Drupal system URL return one of its aliases if such a one exists.
  Otherwise, return FALSE.

  Parameters

  $action One of the following values:

  wipe: delete the alias cache.

  alias: return an alias for a given
  Drupal system path (if one exists).

  source: return the Drupal system
  URL for a path alias (if one exists).

  $path The path to investigate
  for corresponding aliases or system URLs.

  $path_language Optional language code to search the path with.
  Defaults to the page language. If there's no path defined for that
  language it will search paths without language.

  Return value

  Either a Drupal system path, an aliased path, or FALSE if no path was
  found.


preg_replace() not working on node title in hook_preprocess_page() Here's code from my module:

function mymodule_preprocess_page(&$variables) {
  // load the node object
  $node = node_load(arg(1));
  $fied = $node->field_building_sell['und'][0]['value'];

  // regexp
  $pattern = '/(\w+\s\w+,\s\w+\s.{3}\s\/\/\s\w+)(.*)/i';
  $replacement = '$1';
  $subject = $node->title;
  $replaced = preg_replace($pattern, $replacement, $subject);

  $variables['title'] = $replaced;

  dpm($replaced);
}

My node title looks like this:

building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29

But i still get the full node title unchanged. Is preg_replace() not working in preprocess_page hook?

UPDATE

I have noticed, if i replace:

$subject = $node->title;

to

$subject = 'building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29';

It works! But it's not working with $node->title, though, node title output is exactly the same as the string i posted above.

Just did dpm($node->title) and noticed extra white-space here:

building  Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29

Though, when i was just printing it $node->title it didn't showed any extra white-spaces.


How do I get the base URL from the feed content? Basically, I'm using the Aggregator module to import content from an RSS feed. The content is just a bunch of articles. I display this content in a view.

This is my current output, it shows the title and the date in a jcarousel.
The thing I'm missing is the webpage source.
Currently, source url in views will have me a full link like:
https://whatiwant.com/the-article-name-i-dont-want
From the above, all I want to display is:
whatiwant.com

Here are my view settings:

I have tried adding different types of fields but none of them see to return the right value. Is there any way to perhaps strip the whole source url down to the base of it? I was thinking maybe it could be done programmatically however I need someone to point me in the right direction.

A way to do this would be to override the proprocess function get the domain like this:

function MY_MODULE_preprocess_views_view_field(&$variables) {
  $field = $variables['field'];

  if ($field->field == 'MY_LINK_FIELD_NAME') {
    $url = $variables['field']->getValue($variables['row'])[0];
    $parse = parse_url($url);
    $variables['output'] = $parse['host'];
  }
}


product vs product type vs product display in drupal commerce Is a product and instance of a product type? Like you'll have a media store where Books is a product type and 'The Definitive Guide to Drupal 7' would be a product?
Product display would then be literally a way of displaying your product?

I've been trying to get some clarity by reading tutorials and watching videos and somehow it's still not clicking with me.

Product types is like node types. The main thing about is that you can tell them apart and you can put different fields on them. A product type could be books, but if your books and board games are essential the same (they need the same data) they could be the same product type, where as t-sheets would need to be a different product type, since you probably want to add data for color, size, model which doesn't make any sense for books and games.

A product is an instance of a product type, meaning it could be a green medium sized t-shirt for men, or 'The Definitive Guide to Drupal 7', along with price etc.

Product displays is the main way of displaying your products to the end user, since out of the box products can't be displayed. For this commerce has built the product reference field and the add to cart form and such features to do the trick. Meaning that you can display your products on other entities. Most often you want to use nodes for this, but in theory you can use Profile 2 with the profile entity, to allow users to sell stuff on their profile with a product reference field.

You could also use Views to display products to the end user, this is what I did with my first Commerce site, where Commerce wasn't matured yet. I wouldn't recommend this, as you loose the ability to combine products with the add to cart widget. But if you are selling antique furniture, where every product is unique, this could work out well for you, as you only would need to create products and not product displays as well.


WSOD after chaning subtheme templates I've added the page.tpl.php and the theme.api.php file to my bootstrap subtheme's template folder, refeshed and everything was fine.

I added
TEST
 to the page.tpl.php to check where it would show up. Moved it a bit until I was satisfied where it was.

However I changed my mind and deleted the files in the template folder and got the WSOD...

The two files are still in the original folder and adding them back to the templates folder does nothing.

Is there a way to fix this? Right now the whole site is blank and no errors show up.

Checking the watchdog table leads me to this function:

// Use a default value if $message is not set.
  if (empty($message)) {
    // The exception message is run through check_plain() by _drupal_decode_exception().
    $message = '%type: !message in %function (line %line of %file).';
  }

Clearing the caching tables did the trick! Thanks CodeNext!

However I could not use Drush, so I cleared them manually in PHPmyAdmin using this post


How do I add a checkbox to the performance page and have it repopulate? I would like to add a checkbox of my own to the performance page in the Drupal administration.  I am using hook_form_alter like this:

function nci_assay_depot_form_alter(&$form, &$form_state, $form_id){
    switch($form_id){
        case "system_performance_settings":
            $form["caching"]["nci_assay_depot"] = array(
                "#type" => "checkbox"
                ,"#title" => "Refresh Assay Depot Cache when 'Clear All Caches'"
                ,"#default_value" => 1
                ,"#disabled" => 0
                ,"#description" => null
                ,"#weight" => -2
            ) ;
        break;
    }
}

It will display on the page, but the value will not be saved.  Any thoughts?

to have it "repopulate" after save provide a #default_value key that retrieves it on page load.
to actually save it append (add another) custom form submit handler to the form, after the original one gets fired. Something like $form['#submit'][] = 'mymodule_mysubmit_handler'; You will have to check where the submit handler is set already in the form, or the element you're trying to hook into (such as $form['caching'] ...


Is it possible to rate a page generated with Views using the fivestar module? Fivestar works well with nodes, but is it possible to rate a page generated by Views? I can add the widget in a template, but how do I save the results? In the project description page of fivestar, it states that in Drupal 7 you can use it on any entity, but I don't think a Views page is an entity, is it? I found an old issue on the issue queue about this, but it was never updated once the new API was written.

I normally use a "hidden" node to accomplish this.  Typically, I will make a content type called something like  "internal use".  Then, I will make a panel page that contains an "inernal use node and my view.  The node-ish actions then get associate with this node.


How to add custom views display formats to a view? I have a project in which some views have different displays. I want to create similar displays for other views, see in the image. Can I reuse them or I will have to do custom coding again for each view?

further to what @Danny Englander says, you can find the export option for a view to the right of the display list:


Disabling accounts programmatically I want to disable user accounts programmatically inside hook_cron() after a synchronisation job. I don't want to delete the users because of their generated content. But they should not be able to log in and receive any notification-mails and stuff like that.

Should I use the user status field for that? And if so should I use user_save to change this as I don't want drupal to send out mails to the users (via _user_mail_notify inside user_save) or just set the status fields inside the db? Are there any other hooks or functions that I would miss doing that?

Updating status through user_save() is a good way of doing it.

Also note that when you set status to a value different from 1, $op will get set to 'status_blocked', for which no email will be sent.


Get entities grouped by year Trying to write entity queries with group by condition using Drupal::entityQueryAggregate. It works well for simple fields, for example:

$query = \Drupal::entityQueryAggregate('node')->condition('status', 1)->condition('type', 'node_type');

$result = $query
      ->groupBy('field_custom_field')
      ->aggregate('nid', 'COUNT')
      ->execute();

But now I have to select nodes aggregated by year from custom field and I can't figure out how to do it:

->groupBy('YEAR(field_custom_date)') - doesn't work

->addExpression('YEAR(field_custom_date)', 'fcd_year') - doesn't work

Any ideas how to implement this query?

My final solution, by guidance @CG Monroe:

$query = $this->connection->select('node_field_data', 'n');
$query->innerJoin('node__field_date_created', 'fdc', 'fdc.entity_id = n.nid');
$query->addExpression('count(n.nid)', 'nid_count');
$query->addExpression('substring(fdc.field_date_created_value, 1, 4)', 'yr');
$query->condition('n.type', 'my_type');
$query->condition('n.status', 1);
$query->groupBy('yr')->orderBy('yr', 'ASC');
$result = $query->execute()->fetchAll();


My module development snapshot is never updated I made some changes to my module on Drupal.org and pushed them up; I have seen that Drupal.org updated the development snapshot. Shortly after, I made some more changes and pushed them up, but this time it has not been updated.

I do see my commit when I look at View commits.

I was told that Drupal.org updates the development snapshots every 12 hours; but it has been already 24 hours since the last git push I did.

git push origin 7.x-1.x
Everything up-to-date

Drupal.org shows a link to your drupal.org account for each commit you do only when Git has been set to use the same email associated to your drupal.org account.
If the email you are using with Git is different from the email you are using to get emails about your drupal.org account, you can add that email on https://www.drupal.org/user/1327432/edit/email-addresses. In this way, the commits you do for a module are associated to your drupal.org account which also means, for example, that the Maintainers for Slack to Drupal block that appears on https://www.drupal.org/project/slack_to_drupal show the exact number of commits you did and when.

The new email associated to the drupal.org account doesn't need to be made the default one, which means it would be used for every communication from Drupal.org. It just needs to be added to your account, so drupal.org associate the email to an account.
For the other commits to be associated to your account, you need to open an issue on the Drupal.org infrastructure queue asking to associate your commits to your account, similar to Request to associate commits with my account.


Change Drupal's default styling I'm starting to build a new Drupal site with the core theme "Stark" (Almost no styling) but I can't seem to find where the default body background(grey) is coming from so I can change it. (I'm good with CSS).

stark.css doesn't contain any background colour,  so you can set one yourself.  you don't need to remove anything first.


How to enable WYSIWYG in a text field summary? I have a body field (Text field with summary) with WYSIWYG CKeditor enabled.

However, the "summary" part of the field lacks a WYSIWYG editor.
How can I enable it?

The WYSIWYG module's logic acts on text fields with input formats, if you want to explicitly target a form element by its ID you can use the CKEditor module instead.


How Can I restrict a date picker in a date field, to disable a list of specific days from the calendar widget? I need to let the user choose a day from a datepicker in a date field, but disabling a list of specific days from the calendar picker, so the user can't select a not available day.

(Just for explain my use case. I am using Date field and Form api. My Disabled days are in a field in several nodes, and I can get the list of disabled days easily from a View listing this date field. If it is needed it can be exported too as json, xml, plain text or any other format, to serve as entry in the calendar picker.)

(After the user choose an available Day, I will have to do the same to let him select an available Time from a time picker.
This will be an appointment for a Photography Session.)

Using this answer: https://stackoverflow.com/a/15400806/1475662 and a bit of custom coding to add the js and the list of available (or not available) dates to the page.


rendered entity usage in "add node" form for an entity ref field In one of my "add node" form, I would like to display the 'name' field of referenced content type rather than the title.

Let's say, Content type 'Car' contains a field called 'owner'  which is entity ref to content type 'person'.  'person' has a unique title but also has a field called 'name'.

While displaying to the user '/node/add/car' form, I like to give the user a 'select list' for the field 'owner'.  I want to populate this field with the names of the 'person' nodes in the system and not their 'title'.

So in 'manage form display' of the content type 'car', I used 'select list' and in the 'manage display', selected for the 'owner' field, format of "rendered entity". But this displays only the title in the dropdown list in 'add/node/car'.

When that did not work, I tried using the new d8 feature,'display mode'.  I created a display mode called "nameview" and created a "nameview" display for content type 'person' which displays only the field 'name'.  I then used that view mode in the "manage display" for 'Car'. Still I get only the titles in 'add/node/car'.

What am I doing wrong? or is this a bug in d8?

What you configure in Manage display has nothing to do with what is shown in the form. That's not how it works.

You can do this using a view. In field settings, configure it to use a view show possible values and then configure that view to show the values you want to see.


File browse CCK field Is there a CCK field where I can add a link to a file, not an upload but something that will save the link as a URI.

Try the IMCE for FileField module. I've tested this module and working fine. It seems this is the module what you're looking for

  IMCE for FileField allows users to select files from IMCE File Browser. It supports FTP uploaded files by automatically registering them as IMCE files thus making them usable in a FileField.

Step-1:

Go to your filefield settings and Enable 'Allow users to select files from IMCE File Browsers for this field

Step-2:

Go you Manage Display settings of your content type and select FORMAT as URL to file

Step-3:

In node add / node edit form you can browse the previously uploaded files (from server) by clicking on 'Open File Browser' link.

So the file link will be displayed at node output for the uploaded file.


Composer updates .htaccess file when updating I am using composer with Drupal lightning. If I update Drupal via composer, it updates the .htaccess file.

Is there any way to prevent the .htaccess file from being overwritten?

"extra": {
   "drupal-scaffold": {
       "source": "http://cgit.drupalcode.org/drupal/plain/{path}?h={version}",
       "excludes": [ ".htaccess", "robots.txt" ]
       }
}

Put this above code in your composer.json file.


User Role Selection and Profile Fields I have two user roles with profile fields.

Role 1
Name, Username, Password, Email, Address line 1, Address line 2, Website.

Role 2
Name, Username, Password, Email

I want to let anonymous user to chose user role on registration.
Upon user role selection, I want to show role-related fields interactively (with javascript).

I mean that when select Role 2, Address line 1, Address line 2 and Website fields will be disappeared, and when select Role 1, they will be appeared again.

I currently use 'user_role_field' module and 'autoassignrole' module.
Is there another module to achieve that purpose ?
I'm using Drupal 7.7.

Here is what I'm looking for.
Click here to download and view screen draft.

Thank you for any help.
Rgds/Sithu

You could use Profile2 to get you started. It will allow you to assign profile fields to roles and have them available upon registration. You could then use jQuery to display the proper register form on selection.


Referencing theme from block We are complete newbies to Drupal, so please forgive us if this is a stupid question.  We have googled and googled and cannot come up with an answer.

Basically, we've got a block that has been placed in a region (Hooray, we got that far!)  The problem is that we need to reference an image file that is in the sites/all/themes/[theme]/img directory.  We have hardcoded this for now, but is there a placeholder that we can put in the block content area that will automatically fill in that path?

Are we going about this in the completely wrong way?  We are both very impressed and very overwhelmed with Drupal all at the same time.

Thanks in advance for your help.

If you have image file in each theme folder use option 1,otherwise it is place in particular theme folder use option 2.

Better use path_to_theme() function to get current theme path.ex: sites/all/themes/test Note: please use php as the input format for your block.
use drupal_get_path('theme','test') for image is placed only in this theme folder.


Block in node view showing but does not show up when rendering node in Views I have a node type that I have a specific block added to. I have some AJAX going on in the block. When you view the full node the block shows up.
When I go to Views and render the full node content that block doesn't show up, just the node content.
How can I get the block to show up in Views when rendering the full node?
I've read that maybe Panels would be a better solution than using blocks, especially considering I'm using Views.

You are mixing up full node (view mode) and single node (page, canonical URL). Blocks only get added to pages. In regions.
I'm not sure right now, but isn't there from core already a block reference field you can add to a node type? Use this. Or use the Block Field module. And then set your specific block as default value.
Alternatively you can use a pseudo field (a.k.a extra field) from a custom module to render your block. Has the advantage that it then can't be changed by editors.


Redundant log settings between Drupal and Apache I'm trying to discover how I can reduce the redundant logs (PHP errors, Drupal messages, debug logs, whatever) that are stored in Drupal's database and in Apache's log folders. I'm primarily a designer, certainly not a sysadmin, but I'd like to use whatever logging methods are most efficient, from a performance perspective as well as a disk space perspective.

I'm not sure if it is relevant to this issue, but I am using Drupal 6.

Is there anywhere I can find an ideal configuration for what to log on which of the two systems? If not, how can I find out exactly what is being logged in which locations, and how to turn off one or the other?

There's a good drupal.org page on how to switch from dblog to syslog module: see Syslog: using the operating system's logging facility.

  "Because the Database logging module writes logs to the database it can
  slow down the website. By using Syslog you can improve the performance
  of the site."

Combine that with a log rotation strategy of some sort.  And then you'll soon be knee-deep in sysadmin-esque territories.  But probably not neck-deep though if you catch my drift.  Lots of good documentation online for log rotation.  Also, I've not done this on D6, only D7, but that page referenced above does have instructions for D6.


how to do validation for duplicate primary key in database I want to alert user for duplicate primary key insertion in database. here is the code:

<?php

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

  $items['form/formModule'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Form', //page title
    'description' => 'A form with a text field and Submit button.',
    'page callback' => 'formModule_intro', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form

    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['form/formModule/form1'] = array(
    'title' => 'Form One',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

  return $items;
}

function formModule_form($form, &$form_state) {

 $result = db_query("SELECT n.nid, n.title FROM {node} n
                         WHERE n.type = 'product'");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->title;
    }
    //dsm($options);

    $form['productid'] = array(
    '#type' => 'select',
    '#title' => t('Select a product'),
    '#required' => TRUE,
    '#options' => $options,
    '#description' => t('Choose an option.'),
  );

  $form['stock'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'Enter the stock',
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t('stock should be integer value'),
    '#required' => TRUE, //make this field required
  );

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

  return $form;
}

function formModule_form_validate($form, &$form_state) {

if (!($form_state['values']['stock'] > 0)){
   form_set_error('stock', t('Stock must be a integer value only.'));
  }

}

function formModule_form_submit($form, &$form_state) {

global $user;

  // Here u can insert Your custom form values into your custom table.
  db_insert('formModule_stock')
    ->fields(array(
      'productid' => $form_state['values']['productid'],
      'stock' => $form_state['values']['stock'],
      'created' => REQUEST_TIME,

    ))->execute();
    drupal_set_message("successfully saved formModule_stock");

}

What you are doing is:

Show a "select" form element containing a list of nodes whose content type is "product"
Show an error if there is a row in a database about the node the user selected

That is poor UX.
Suppose that there are 20 nodes of that content type, and only two nodes don't have a row in the database table where you save the data; there is a high probability the user gets the error message about the data being already present at least two times. Imagine what would happen when all the nodes have a corresponding row in the other database table.

What you need to do is showing only the nodes for which there isn't a row in the other database table. That means, for example, using a query like the following one.

$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.type = 'product' AND n.nid NOT IN (SELECT s.productid from {formModule_stock} s)");

The module should also show a message in the case all the nodes have a row in the other database table. In this case, the user should not see the form to select a node, rather than seeing a "select" form without any item.

As side note, avoid using upper case letters in the short name of modules. While PHP is case insensitive, you would have problems when you write update functions for your module.


Further optimizing CSS delivery with AdvAgg? It seems to me that my main Drupal UI based task to leverage my site's optimization is further optimizing it's CSS delivery...

Given the following facts, It's wired for me that Google's PSI advices me to do so:

Aggregation is on for CSS.
AdvAgg is installed and (as can seen from the picture) Both CSS minification & compression are on.
If it relates in any way in this case --- HTML is minified (if CSS served via HTML it would be served better, I guess).

Besides that, the site is very light in graphic details (both images and CSS).

I've tried to do the following AdvAgg conf's, but when I ran PSI again the advice still appeared:

Putting more css bundles per page (5 instead of 4) while I admit I am not familiar with the term at all.
compressing the (small amount) of inline CSS via YUI method.
Enable preprocess on all CSS and Checking all checkboxes at "Optimize CSS rendering", at the Modifications tab (via Modifications sub-module).

Further details:

Full PSI score results

It seem I don't have much options left... Would appreciate your help, Ben.

This is the issue you'll want to follow: https://www.drupal.org/node/2396609 Inline critical css.

You can get rid of this message by using "Deferred CSS Execution: Use JS to load CSS". It's under the Experimental Settings of the CSS section. When you enable this, the page will no longer wait for the CSS to download before it starts to render. The bad part is you'll get what's known as a flash of unstyled content (FOUC). The issue I linked to above has to do with inlining the CSS that's needed to display the above the fold content so the FOUC doesn't happen.

Another way to get rid of the message is to inline all the CSS. This can be done by going to the Inline CSS/JS on specific pages section; just use the CSS section. Pick the pages you want to be optimized; node/* works for all nodes as an example.

The bundler comes into play when you look at the connection view from http://www.webpagetest.org/. If you're opening a connection in order to download a single css and/or js file then you should lower the number of bundles and see if that prevents a new connection from being used; this is super helpful with HTTPS connections which take up a lot of time to open. If there are a lot of files being transferred (image heavy site) then using more bundles will help with getting a better cache hit ratio in the browser. I found that 4 for both works pretty well in most sites but going higher or lower really depends on the site. Higher is usually better if the visitor is going to hit multiple pages. It's sorta an art form in order to get it optimal. Here's the issue for Drupal.org in regards to using AdvAgg for front end optimization: https://www.drupal.org/node/2493801


How to override configuration from a file? I have been playing a lot lately with an import configuration to Drupal 8. And I notice that all documentation show you how to edit value per value instead of overriding the entire config file. You can find more information about this at Configuration override system page.

I notice that DrupalConsole and Drush have the ability of overriding configuration by file.

Using Drush, you can run drush config-import
Using DrupalConsole, you can run drupal config-import

This will override the entire configuration base on the configuration file. How can I achieve this on the code? Hopefully, I will like to edit my configuration when I'm installation my module on hook_install.

To override config on code is simple. Above is an exemple how you get, set and save any config (that you just installed via .yml and from core).

On .install or .module file

  //Getting editable configs
  $module_cfg = \Drupal::configFactory()->getEditable('your.module.file');
  $settings = \Drupal::configFactory()->getEditable('any_core.settings');
  //Getting values
  $a_value = $settings->get('key_from_core');
  //Setting and save configs
  $module_cfg->set('any.key', $a_value)->save();
  $settings->set('key', 'new_value')->save();

From hook_install docs:

  Implementations of this hook are by convention declared in the
  module's .install file.

For further information see ConfigFactory docs.

There is a module called Features that helps if you want keep on track of your configs. I'm currently using this module for code-driven development, maybe is this what you're looking for.

Edit 1 - Replace entire config

First of all, you need to provide which config you pretend to override.

On my.custom.config.yml file

# Make sure this config exists in your database
target: 'config.to.override'
... # all your data (CAUTION with 'dependencies')

On .install file

function module_install() {
  //Get your custom config
  $cfg = \Drupal::configFactory()->getEditable('my.custom.config');
  //Get config name to override
  $target = $cfg->get('target');
  //Get Config object
  $settings = \Drupal::configFactory()->getEditable($target);
  //Override all data that can be overridden
  $settings->setData($cfg->get())->save();
  //If you won't store any previous state, get rid of your custom config
  $cfg->delete();
}

This was tested in my development environment.


Alternative title for Easy Breadcrumb I'm using Drupal 9 and recently discovered Easy Breadcrumb. I'd like to use a custom field to overwrite the page title to be displayed in the breadcrumbs, but it seems to be not working.
In the configuration, there is a field "Alternative title field name for breadcrumb" with "field_breadcrumb_title" by default, but when I add a field with this name to my page, it does not display. Instead, I get the page title or (when I disable "Use the real page title") the formated URL segment.
There is a discription of every configuration field in the documentation, but of all things this one is missing.
Does anyone know, if this functionality is working?
Thank you!

This could certainly be a bug in the new future. For those who come across this in the future, the follow up is on Drupal.org:
https://www.drupal.org/project/easy_breadcrumb/issues/2931141


Disable the quick links menu on blocks I've been searching all morning and cannot find the solution I need. I am sure I am overlooking something.

I want to disable the quick links menu on each block on my drupal 7.23 site when I'm logged in as an Administrator. I don't use them, and they are blocking the links on some small blocks.

How do I turn these off?

Thanks,
Brian

They're provided by the core Contextual Links module. If you don't don't need them at all disabling that would be the easiest thing to do.

There's also the Hide Contextual Links module if you want finer-grained control.


How to update a biblio field with Entity Metadata Wrapper? I can update a field using Entity Metadata Wrapper (EMW). Here's how I can accomplish this.

$node_wrapper = entity_metadata_wrapper('node', $nid);
$node_wrapper->field_custom_field='new value';

However, I'm not able to access and update biblio fields provided by biblio module in the same way. This code won't work

 $node_wrapper->some_biblio_field='new value';

How can I update biblio fields using EMW?

The Bibliography module isn't using D7's field API. It's misleading since the module's manage fields UI (/admin/structure/types/manage/biblio/fields) does make it appear as if it's using the field API; however it installs its own database schema for storing data for Bibliography nodes.

As such, Entity API's EMW isn't much help in your case.


Alter content of search api views I've used drupal7, Search API 7.x-1.16, Search views 7.x-1.16, Solr search
7.x-1.9, Apache Solr search
7.x-1.7.

I am listing contents of some content type. Now i want to trim description field only if the content belongs to some content type.
How to do this using theme_preprocess_views_view_fields?

Is there a reason you want to use the theme_preprocess_views_view_fields hook?

Why not add the attribute Content: type to your View fields (see image), and then check the content type within a View template:

Then your code in views-view-fields--[my_view]--[my_display].tpl.php could look something like this:

<?php
  //check content type
  if($fields['content_type']->content == 'My content type') {
    //trim description by 200 chars (respecting full words)
    $pos = strpos($fields['field_my_description]->content, ' ', 200);
    substr($fields['field_my_description]->content, 0, $pos);
  }
?>

<?php print $fields['title']->content; ?>

  <?php print $fields['field_my_description']->content; ?>

I haven't tested or tried the above code, but the proof of concept should be enough to help you along.

Using a Views template instead of a hook is also easier for site builders / themers to debug or change.


Change path of uploaded files in zip I've a form that allow the customer to download every photos that a photograph uploaded before.
Here is my submit form :

 public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $parameters = \Drupal::routeMatch()->getParameters();
    $shooting = Node::load($parameters->get('shooting_id'));

    $destination = \Drupal::service('file_system')->realpath('temporary://');

    $zipname = $destination . '/vos_photos_'.$shooting->id().'.zip';

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));

    $zip = new \ZipArchive();

    $zip->open($zipname, constant("ZipArchive::CREATE"));

    foreach ($shooting->field_shooting_photos as $media) {

      $uri = $media->entity->field_media_image->entity->uri->value;
      $file_path = \Drupal::service('file_system')->realpath($uri);

      // Ajout de chaque fichier dans le zip //
      $zip->addFile($file_path, $media->entity->field_media_image->entity->name);

    }

    $zip->close();

    readfile($zipname);
    exit;

  }

This works great.
The only problem is when I unzip it, I get var/www/drupalvm/web/sites/defaults/files/{My content}
I would like to just have a simple folder files/{my content} without the long path before, or if it's not possible, simply {my content} when you extract the zip. Thank you
I'm pretty the problem can be solved in the addFile by giving a localname, I just can't figure out how to

I finally found the solution, instead of

$zip->addFile($file_path, $media->entity->field_media_image->entity->name);

I simply put

$zip->addFile($file_path, basename($file_path));

and it does the job.


how do I get the parent node of an entity reference node I have two content types - A and B.  For content type A, there are 5 content items - Aa, Ab, Ac, Ad, Ae.  For content type B, I have two items Ba, Bb.  Content type B has a field that is an entity reference of  content type A.  In a single page I have the following setup:

Ba -> Aa, Ab, Ac, Ad, Ae
Bb -> Aa, Ab, Ac, Ad, Ae

I have a twig template for B and a separate one for A.  When rendering Aa - Ae, I need to know if the container node is Ba or Bb because it is rendered differently.  Ba and Bb know about the referenced entities (Aa - Ae), but the referenced entities don't know who their parent is.

I've tried using the preprocessor but I can't seem to find a way to get the parent (containter) node.

Any suggestions?

TIA.

You should be able to do this:

$loaded_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_node_reference' => $node->id(),
]);
$parent_node = array_pop($loaded_nodes);

Replace the field name with your actual field name.


"Digging Deeper" with Twig I created a custom twig file that outputs a few basic fields, such as images and text. Here's what my twig file looks like:

    {{content.field_image}}

    {{content.field_year}}

{{content.field_heading_text}}

I'm trying to have a little more control of the HTML that gets output. Here's what I'm seeing for a few of these fields:

I want to either, A, get rid of the div element that outputs "1963" or "Imagining a better world" or, B, get control over the div element so I can add a class to it and later style it.

Thank you in advance!

The easiest way to avoid the standard field divs is to only print out the first delta. That works well for single-value fields, for multiple, you'd need to loop over it yourself.

So, just do this: {{ content.field_year.0 }} and it will only print out the actual field content, without the wrapping field type. Might not work for every formatter, depending on what they do, but it should work for most of them.