Drupal console set site:mode I installed a site use composer with command

composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

I would like to set site mode to dev. If site install drupal from drupal.org, I can run command

drupal smo dev

But with composer I run

vender/bin/drupal list

and don't saw any command about setting site mode. How can do that with Drupal site install by composer. I would like to run command line, don't want config file service.yml.

Note: I ready run composer update.

The correct command for setting site in development mode is

drupal site:mode dev

Check here for more details - Debugging compiled Twig templates


How to rsync files between two remotes which share the same host? I've two remotes: @remote.dev and @remote.test.

I'm trying to rsync between these two remote Drupal instances by:

$ drush -vy rsync @remote.dev @remote.test

But rsync complains that:

  The source and destination cannot both be remote.

Both remotes are on the same machine, but they're using different path.

Is there any workaround?

Normally you can't use two remotes for rsync, but because these two instances are on the same host you may use drush dd to return the filesystem path and use it as a source.

In example (syncing webroot):

$ drush -vy @remote.test rsync `drush dd @remote.dev` @self

or syncing just files folder:

$ drush -vy @remote.test rsync `drush dd @remote.dev:%files` @self:%files

This will work if you're using the same credentials for both.


Use Redis for Drupal sessions I've been looking online for a while and I haven't seen anything on setting up Drupal to use Redis for session handling. I've found tutorials and blogs about settings Redis up as a replacement for Memcached for caching.

Anyone know how to do this? I was hopping there was something in the $conf variable in the settings.php file that would allow me to override where sessions are stored and retrieved.

Thanks for any help in advance,FatGuyLaughing

a quick google search: http://lmgtfy.com/?q=drupal+redis+sessions

and the 2nd result talks about redis session handling:
https://www.drupal.org/node/2250195

from that issue thread i recommend looking Session Proxy. This allows you to override the default session handler by Drupal -- which is explained in the above issue:

  This is because Drupal will override your session handler and use its
  own, it goes straight to the database. I'd recomend that you try using
  this module: https://drupal.org/project/session_proxy

Session Proxy provides the following, I believe your attempting #2:

  ships three different session managing implementations:

  Database session handling: core default, ported to the object oriented
  API. It comes with an additional SQL query done more than core
  session.inc default implementation due to the API strong
  encapsulation.
  Native PHP session handling: by selecting this session
  management mode, you explicitely remove any core session management,
  and let PHP manage it. This can be useful if you intend to use
  low-level PHP extensions, such as Memcache or PhpRedis to handle
  session in PHP low-level layer instead of core. This allow to use any
  PHP native session storage to work gracefully: some of them are high
  performance.
  Cache based storage engine: Using the same session
  handling than core, but deporting raw session storage into a cache
  backend instance. You can use any already-functionning cache backend
  to store sessions. Sessions will use their own bin, and won't be
  cleared at cache clear all time.

Again from the linked issue after installing session proxy you likely need to configure your php.ini to something like:

session.save_handler = redis
session.save_path = "tcp://localhost:6379"


Best way to update/upgrade things in the drupal database I know this is a broad topic, but maybe there is a good way/module doing this. I want to make "automated" updates to a drupal installation. This includes updates of nearly everthing (contenttypes, user-permissions, content itself, views, module-settings).

I would love to have the "update-information" outside the db (e.g. php-code). I could imagine doing that via an own update_module that implements MYUPDATEMODULE_update_xxx() functions for every update. But I fear coding complicated updates (views, large contentypes) "by hand".

I've never used the Features module and don't know if this really fits my needs. Are there any other modules or workflows for something like that? Perfect would be something that lets me trigger the update via the console (e.g. using drush).

Features seems to be what the community is clustering around, and is well worth a look. You can use update hooks, but it can be complicated for large updates, as you fear. It also dosn't make it easy to reset values to a default.

Features seems to be much simpler to use. It can't do everything but most core content can be exposed and managed via features.

Features also has drush hooks.

drush features-revert myfeature

Will set the system to reflect the content of myfeature. The down side of features is that it is still fairly immature, or more to the point many of the add on modules are immature, so sometimes code is a little buggy.


Module: See Last Modified Articles And Submitted Articles I would like to be able to see who did what and what articles were submitted, possibly on the admin dashboard - is there any module that you would recommend?

What you're describing is pretty much available by default.  If there's specific changes you need, you should create a View that matches what you need.


Rewrite the field label text on node dispaly I created a content type.
In the content type I have field called ingredients. Machine name is "field_ingredients".

When a user see the output of the node (not in form and not in views), the label is:
"ingredients:".
I want the remove the ":" or even change the label to something else.

How can I do that?

I tried the "preprocess_node" function, but it didn't succeed.

You need to override field.tpl.php to do this (the colon is hard coded into that template file).

Create field.tpl.php anywhere in your theme folder, copy the code from the above link into it, tweak it (remove the colon etc), then clear your caches: all will be well!

I found Answer from Here


Using View to List a Member's Organic Group with Inherited membership I am looking to create a view which will return any content a user has membership to.

Following steps from another post, I managed to return content which matches users membership. But this doesn't take into account content where membership is inherited. So a node which is linked to another node's audience doesn't appear in the view.
Steps taken:

Add new view. Show -> OG membership (important!)
Then in some display add a contextual filter:

OG membership: Entity id.

Provide default value: Type -> User ID from logged in user
Next to get the actual titles of the groups (as the base table is OG
membership, not node),
Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title. Relationship -> Group node from OG
membership.

Using Views to List a Member's Organic Groups (7.x-2.3)

After digging around in the default views, I found a work around for my problem.

I cloned the view OG User groups (OG membership) which is normally attached to the user profile. I then filtered content against some custom fields to resolve my problem.

Its a work around admittedly, but I would advise people to check some of the other default views or the og_extras module for additional views.


Include content created through InDesign/RoboHelp Is there a way to display content under a Drupal site/url that is not managed by Drupal?

Specifically, we have a large manual (1700 pages) that is managed with Adobe InDesign which is used to create a printed version, one large PDF version, PDF versions of each chapter, and also an HTML version of the manual via RoboHelp. Because of the printing requirements, this is not content that we plan to migrate into Drupal (but we still need to display it on/through the site).

Example: Here is the page for the manual. You can see links for the Complete PDF and individual PDF chapters (which we would probably manage as Media - TBD). The question revolves around the HTML version of the manual. As you can see, at this point we have pretty much jumped out of the container of the hosting site (SharePoint), and are now displaying just the pure, rendered HTML that was generated out of InDesign/RoboHelp.

The content is updated annually and we have requirements to archive each version so that it is still accessible. Our current process makes it fairly easy because of the way that the /Manuals_HTML1 folder is excluded from SharePoint so we just make a copy of the content and give it a new folder based on the year.

So, it doesn't appear to make sense to include this as actual content in Drupal. It feels like it would be some sort of exclusion within Drupal that essentially sends it outside of Drupal. Maybe a mod_rewrite solution?

Brand new to Drupal and currently in a week-long training. Definitely learning tons about how to handle the rest of the site, but this one is an open item.

Looks like the correct term is HTML or static microsite. These can be managed via .htaccess as seen in Maintaining a static microsite alongside Drupal's docroot.


Hide the required sign I need to hide the red "required" star sign, but I can't understand how to hide this red star mark using hook_form_alter().
I know this can be done using CSS, but I want to know if it is possible to do it using hook_form_alter(), or if there is any other way to hide it programmatically.

You can use themename_form_element() to remove asterik as given in the link.

function YOURTHEMENAME_form_element($element, $value) {
  $output  = '
\n";

  //REPLACE THIS
  //$required = !empty($element['#required']) ? '*' : '';
//WITH THIS

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' ' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
    else {
      $output .= ' ' . t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
  }

  $output .= "
\n";

  return $output;
}


Passing page arguments to custom block inside panel I have created a page(Page Manager) in drupal 8 with a path say /dashboard/{nodeid}. Inside that I have created a Panel and inside panel I have added a Custom Block ( which I created programmatically by extending BlockBase).
Now my problem is I want to use the {nodeid} inside my buildForm function.

Please suggest me.

My code is as follows.

ABCBlock.php

class ABCBlock extends BlockBase
{

    public function build() {

        return \Drupal::formBuilder()->getForm('Drupal\examples\Form\ABCForm');

    }

}

ABCForm.php

class ABCForm extends FormBase
{

    public function getFormId() {
      return 'example_ABCForm';
    }

    public function buildForm(array $form, FormStateInterface $form_state)    {

      drupal_set_message('Hello World.'); // displaying fine.
      $tmp = arg(0);//or arg(1) which i am assuming as url parameter value. But it FAILS.

      //load node object using $tmp

    }

}

While a very different question, the answer is the same as mine in https://drupal.stackexchange.com/a/188629/31.

In short, define a context on your block, make sure that the parameter in page manager is defined as type node and the rest should just work.


What is the correct name to give to a taxonomy term page template file? I have a taxonomy term page, which is not a view. It just lists all the content for the taxonomy. I would like to customize this page, and I have tried all permutations and combinations of names for the template file. The template file just won't work.
I have tried page--taxonomy--term--5.tpl.php, page_taxonomy_term__5.tpl.php.

What is the right filename to give to the template file, in this case?

I am using Drupal 7.

I use, for instance,

page--taxonomy--term--6.tpl.php

Make sure you clear the cache in Configuration > Performance > Clear all caches after creating your template.


Multiple blogs per user, each with a blog profile page I'm trying to to create a site where users upon admin approval, can have multiple blogs, typically differentiated by language.

Each blog should have a profile/landing page specific to that blog.

I can simply create a taxonomy term where a given term is a given blog name and I can use the Taxonomy Permissions module to restrict a given term to a given user.

The part that I'm having trouble thinking through is the admin side setup so that someone who doesn't know a lot about Drupal would be able to simply set up a new blog.

In the end, I decided it was easier to do this with node references and let the user choose a parent from the "add blog post" screen.


Better code to output a pdf downloaded by the browser In a submit function of a custom form, I would like to output a pdf which can be downloaded by the user/browser when clicking on 'Get PDF'.
The following code is doing the job only once, because after clicking on the 'Get PDF' button, all the buttons of the form does not work anymore. Clicking on any of them doesn't produce any effect.
Any Idea?
  static public function submitPdf(array &$form, FormStateInterface $form_state) {
    if ($pdf_content = my_function_to_output_a_pdf_as_string()) {
      $response = new Response($pdf_content);
      $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'my_pdf.pdf');
      $response->headers->set('Content-type', "application/pdf");
      $response->headers->set('Content-Disposition', $disposition);
      //$response->headers->set('Content-Transfer-Encoding', 'binary');
      $response->headers->set('Content-length', strlen($pdf_content));
      $form_state->setResponse($response);
      //Thanks to kiamlaluno, it is working slighty better if I remove the following line (setRebuild())
      //$form_state->setRebuild(TRUE);
    }
  }

Edit to add in order to provide more context: The form is made of +/- 30 numeric fields and the user can play with them to produce some calculated results. If he wants, he can click at any time on the "get pdf" button to generate a pdf which will contains all his inputs and the calculated result. In other words, he can fill the form->get the pdf->continue to fill->get another pdf-> etc

Provide a controller to download the PDF as discussed in the comments:
https://stefvanlooveren.me/blog/serve-pdf-download-controller-drupal-8

<?php
namespace Drupal\MYMODULE\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

/**
 * Class PdfGeneratorController.
 */
class PdfGeneratorController extends ControllerBase {

  public function Render($uuid) {

    // In my case, I render a file by UUID
    // This actually does not matter too much here
    // String below contains the url of the file
    $uri = 'private://'.$uuid.'.pdf';

    $headers = array(
      'Content-Type'     => 'application/pdf',
      'Content-Disposition' => 'attachment;filename="download"');

    return new BinaryFileResponse($uri, 200, $headers, true);
  }
}

Then add to the button link the HTML5 Download Attribute to download the file in the background without redirecting.
See https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request
If the PDF file is created dynamically this can be integrated in a Drupal Ajax form workflow by generating the file on user request and providing the button link to the custom built PDF file via Ajax.


Cannot view individual article, instead the node's link displays all articles I cannot figure out what I am doing wrong. I'm using Drupal 7 and the Omega theme. I'm using pathauto to have nice paths. I have the built-in article content type which I renamed to "news". The pattern for news articles is set to news/[node:title]. I created a view to list all the news and gave it the path "news".

When I went to /news I saw my view. When I clicked on an individual article, I got a file not found error with the entire web page layout embedded and repeated twice and then a third time with the individual article displayed. I also got a php "Warning: Cannot modify header information - headers already sent" error.

Thinking that using the pattern news/[node:title] and also creating a view with the path "news" was the problem, I changed the path of the view to "all-news". Visiting an individual article with its path "news/[node:title]" still gives me the file not found errors and the multiple embedded pages with the cannot modify header errors. The only way to see my individual article was to use the path all-news/[node:title].

Next, I disabled the view. Now I only get file not found errors for my articles when I use the url pattern "news/[node:title]" and no multiple embedding of the entire web page.

I think there is something I'm completely not understanding. My goal is to have a news section of the site, and to use taxonomy to organize the articles by topic. Can you tell me where I might have made a mistake?

I suggest that you first delete all (if you can, else just news) path aliases (via the pathauto interface). Get your view working as you like. Then regenerate the aliases (again via the pathauto admin interface). Keep things simple first and then proceed to complicate :)

If things persist, try with a test node type.


Submit form load results instead of messages I am testing out the new Drupal 8 custom modules and currently stuck with the submit form handler to load form submitted results in the same page and my current functions of last submit is this (inside the controller form) :

    <?php
/**
 * @file
 * Contains \Drupal\resume\Form\ResumeForm.
 */
namespace Drupal\resume\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ResumeForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'resume_form';
  }

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

    $form['candidate_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Candidate Name:'),
      '#required' => TRUE,
    );

    $form['candidate_mail'] = array(
      '#type' => 'email',
      '#title' => t('Email ID:'),
      '#required' => TRUE,
    );

    $form['candidate_number'] = array (
      '#type' => 'tel',
      '#title' => t('Mobile no'),
    );

    $form['candidate_dob'] = array (
      '#type' => 'date',
      '#title' => t('DOB'),
      '#required' => TRUE,
    );

    $form['candidate_gender'] = array (
      '#type' => 'select',
      '#title' => ('Gender'),
      '#options' => array(
        'Female' => t('Female'),
        'male' => t('Male'),
      ),
    );

    $form['candidate_confirmation'] = array (
      '#type' => 'radios',
      '#title' => ('Are you above 18 years old?'),
      '#options' => array(
        'Yes' =>t('Yes'),
        'No' =>t('No')
      ),
    );

    $form['candidate_copy'] = array(
      '#type' => 'checkbox',
      '#title' => t('Send me a copy of the application.'),
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

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

      if (strlen($form_state->getValue('candidate_number')) < 10) {
        $form_state->setErrorByName('candidate_number', $this->t('Mobile number is too short.'));
      }

    }

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

   // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));

    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

   }
}

I wanted to show results in a table in the same page form where user submit the form, rather than just throwing in messages

thank you

The example of @Ajay was not working for me.
This one do. Hope this help.

public function buildForm(array $form, FormStateInterface $form_state) {

    // Your $form fields here ...

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    // Render this field bellow the submit button and above return $form.
    if (!empty($formValues = $form_state->getValues())){

      $header = ["Key","Value"];

      $output = [];
      foreach ($formValues as $key => $value) {
        if ($key=='submit'){
          break;
        }
        $output[$key]['key'] = $key;
        $output[$key]['value'] = $value;
      }

      $form['mytable'] = [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $output,
        '#empty' => t('No Data'),
      ];
    }

    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
}

Soon I'll write a post about other ways to render form's data in a controller or even with a Private Temp Storage


Drupal 7 Forms API radios value not saving to the $form_state array after submitting I have a form where I am using radio buttons and when I use integers as the index, the form is saving and passing the value just fine. However if I use a string as the index it is saving nothing in the $form_state['storage']['values'].

Example - This works as expected:

$testArray = array(0 => 'test1', 1 => 'test2', 2 => 'test3');

$form['step0']['testthis'] = array (
    '#type' => 'radios',
    '#options' => $testArray
);

After submitting this example the $form_state will look like (with array index 2 selected):

- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] => 2
                )

        )

)

Example - This does not work as expected... for me!

$testArray = array('test01' => 'test1', 'test02' => 'test2', 'test03' => 'test3');

$form['step0']['testthis'] = array (
    '#type' => 'radios',
    '#options' => $testArray
);

After submitting this example the $form_state will look like (with array index test03 selected):

- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] =>
                )

        )

)

I expect it to output

- Form Storage -
Array
(
    [values] => Array
        (
            [step0] => Array
                (
                    [testthis] => test03
                )

        )

)

Any insight would be most appreciated!

Thank you.

Edit: I forgot to mention that the HTML element is output just fine. So using the string index the element looks like:

<input type="radio" id="edit-step0-testthis-test3" name="step0[testthis]" value="test03" class="form-radio">

My mistake!

I am using AJAX to submit the form and selecting the radio button using the .attr() function.

I was using an improper name in the element selector thus nothing was technically being selected.

Hope that helps someone else!


Module is shown as installed but I can't access its settings I have Drupal 7 installed and I am trying to install Webform module. Firstly the page shows " The website has faced some unexpected error" and then after re-accessing the Modules page, it shows the Module to be enabled and links to it's settings as well.

But when I go to Create Content, I don't see any Webform option.

This is the error generated in the Reports / Log.

  DatabaseSchemaObjectExistsException: Table webform already exists. in DatabaseSchema->createTable() (line 657 of /home/evosysgr/public_html/includes/database/schema.inc).

Kindly suggest what is to be done.

Generic way when you face

  The website has faced some unexpected error

when enabling module is:

Find in logs what error was it
Fix it's cause
Disable and uninstall module you was enabling
Enable it again

Alternatively, if you have backups, better way would be:

Find in logs what error was it
Fix it's cause
Restore site from backup to it's state from just before error
Try again

If you have specific problem with this way, ask new question, explaining exactly what you need to know, what you did, what was in logs and so on.


Remove Configuration Management Destination I'm using drush cex or drush cim to export and import configuration on D8 site.

Every time I run those commands, I get asked a question to select option for cancel, sync or staging, which is quiet annoying.

Is there a way to remove staging destination and only use sync so that I can use drush cex -y or drush cim -y without errors?

Check please the arguments: https://drushcommands.com/drush-8x/config/config-export. You can use directly sync in your command

   drush cex sync -y


Importing products into Drupal Commerce and handling Tax Im working on an integration module where I'm trying to import products externally and into Drupal Commerce. I revceive the product object externally like this:
    2692604 (Object) stdClass
      id (Integer) 2692604
      revision (Integer) 2
      currencyCode (String, 3 characters ) NOK
      vatType (Integer) 3
      name (String, 14 characters ) Produktkatalog
      priceCurrency (Integer) 235
      priceIncVatCurrency (Integer) 294
      number (String, 4 characters ) 1003
      cost (Integer) 230

I've found a code snippet from the commerce_example module where you can create a product programmatically like this:

//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;

// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);

commerce_product_save($new_product);
return $new_product->product_id;

I have defined a tax type and a set of tax rates - including a mapping from the code found in the importing object.

I'm thinking the correct way of adding the tax part should be by modifying the code to something like this:

//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => $product_obj->vatType,
  'data' => array('include_tax' => 'MVA_hoy'),
)));
$form_state['values']['commerce_price'] = $price;

// Notify field widgets to save their field data
field_attach_submit('commerce_product', $new_product, $form, $form_state);

commerce_product_save($new_product);

Problem is that when I import the products, the tax rate is not set as I would expect it to.
Investigating the newly created product (or an old loaded product) does not give me much clue either...

Found the solution it seems.
It is apparently not enough to add a field under the data array, you also need to add the include_tax field on the same level as amount and currency:

//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => $product_obj->vatType,
  'data' => array('include_tax' => 'MVA_hoy'),
  'include_tax' => 'MVA_hoy',
)));
$form_state['values']['commerce_price'] = $price;

Now, when importing products, the tax field is updated.


Handling circular entity references with Migrate I am using Migrate D2D on a Drupal 6 to Drupal 7 migration right now.

I have three types: type1, type2, type3.  Each of the three types has a entityreference field on it, which is configured to be able to point to all three types.  This means that there can be circular references, and when a particular node is being migrated, the destination node may not exist yet and could potentially be any of the three types.

My migration class looks like this:

class MyNodeMigration extends DrupalNode6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->addFieldMapping('field_legacy_nid', 'nid');

    $this->addFieldMapping('field_the_reference', 'field_the_reference')
      ->sourceMigration(array('type1', 'type2', 'type3');
  }
}

$node_arguments = array(
  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type1',
    'machine_name' => 'type1',
    'source_type' => 'type1',
    'destination_type' => 'type1',
    'dependencies' => array('roles', 'users'),
  ),

  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type2',
    'machine_name' => 'type2',
    'source_type' => 'type2',
    'destination_type' => 'type2',
    'dependencies' => array('roles', 'users'),
  ),

  array(
    'class_name' => 'MyNodeMigration',
    'description' => 'type3',
    'machine_name' => 'type3',
    'source_type' => 'type3',
    'destination_type' => 'type3',
    'dependencies' => array('roles', 'users'),
  ),
);

$common_node_arguments = $common_arguments + array(
  'user_migration' => 'users',
);

foreach ($node_arguments as $arguments) {
  $arguments = array_merge_recursive($arguments, $common_node_arguments);

  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

When I run the migrations, most nodes are fine, but I get a decent amount of Stubs (*) created.  Some of the destination nodes have the entityreference pointing to these Stub nodes.  The source nodes are fine.

What I have uncovered is that the bundle on the destination nodes that are being made as stubs are incorrect, and look like they are all type1.  A node of the proper type does end up being created, but it never gets set as the entityreference target.

Another way to explain this is that I end up with

node: nid=123, type=type1
node: nid=234, type=type1, field_the_reference=123
node: nid=345, type=type2

where it should be

node: nid=234, type=type1, field_the_reference=345
node: nid=345, type=type2

How do I handle this situation?

(*): a "Stub" in the context of this question here refers to a node which is created for the purpose of being a reference target, but does not get its data initially. The term is used throughout the Migrate documentation and source code.

The main problem has to do with how stubs are handled in Migrate, and is related to a known issue.

In short, when the destination can be one of several content types, the migration doesn't know what content type to create the stub as in a generic way.

My current workaround for this is to prevent stubs from being created:

abstract class MyNodeMigration extends DrupalNode6Migration {
  ...

  protected function createStub(Migration $migration, array $source_id) {
    return FALSE;
  }
}

When the migration runs, stubs don't get created, but the entity reference fields in my destinations also don't get populated.

I then manually reset the highwater mark

db_update('migrate_status')
  ->fields(array('highwater' => 0))
  ->condition(...)
  ->execute();

and then rerun the migrations.  Since the destination nodes exists, the entity reference fields can be populated properly.


How to add terms directly from the content overview? I have a few taxonomies with custom fields. I would like the user to be able to add terms directly from the content overview page at admin/content, and for the terms to be listed there - without having to navigate to the taxonomies page. As if the taxonomies were a content type. Any suggestions?

I think you are looking for something like Inline Entity Form.


Alter core "Configure Block" contextual link path or text? We're using blocks and Beans throughout a very large site. The issue is that the contextual links have "Configure Block" which takes you to the block configuration page for that particular block, and another contextual links labeled "Edit Block".

The "Edit Block" link is the correct link as it brings the user to the Bean admin page for that block with fields and settings.

I'm not able to find the hook to alter that main "Configure Block" link or text.

I've tried:

hook_menu_link_alter()
hook_contextual_links_view_alter()
hook_menu_contextual_links_alter()
hook_block_view_alter()

None of these seem to expose the "Configure Block" text or URL.

I've also tried the Custom Contextual Link module, but it doesn't allow you to edit or remove this link.

I am not interested in hiding it with styling. That isn't fixing the problem. I want to programmatically alter that one contextual link.

I was able to accomplish this for Panels by using the following:

/**
 * Implements preprocess_panels_pane().
 */
function hook_preprocess_panels_pane(&$vars) {
  if ($vars['pane']->type == 'panels_mini') {
    unset($vars['admin_links']);
    $vars['admin_links'] = '';
  }

  // Load the currently logged in user.
  global $user;

  if ($vars['pane']->type == 'block') {

    // Check if content array is set
    $type = isset(array_keys($vars['content'])[0]) ? array_keys($vars['content'])[0] : '';

    // Check if the pane subtype is a bean
    if (strpos($vars['pane']->subtype, 'bean-') !== false) {

      // Get path of bean edit link
      $path = isset(array_keys($vars['content']['bean'])[0]) ? array_keys($vars['content']['bean'])[0] : '';
      unset($vars['admin_links']);

      // Check if the user has the 'administrator' or 'content editor' role.
      if (in_array('administrator', $user->roles)) {
        $vars['admin_links'] = '

Edit Block

';
      } else {
        $vars['admin_links'] = '';
      }
    }
  }
}


Why does not hook_menu_link_alter() work? i want to expand my theme's primary links, so I put the following code in my custom module.

function mymodulename_menu_link_alter(&$item, $menu) {
  if ($item['menu_name'] == 'primary-links') {
    $item['expanded'] = 1;
  }
}

In page.tpl.php I used print theme('links', $primary_links), but the primary links didn't expand. Why?

Not really a complete answer, but hook_menu_link_alter() is not called when the menu is rendered; it is called when the menu item is saved. Just an FYI.


user details as block with auto refresh I am new to drupal. I want to show a module that refresh every 3 seconds and displays the other existing user details with their photo graph .

Try Block Refresh module.

  Block Refresh allows an administrator to configure a block to refresh
  it's content in a given number of seconds. Block Refresh uses
  jQuery/AJAX so the refresh happens "behind-the-scenes".


What is the most sustainable way to obtain aggregate information on fields? EntityFieldQuery is not intended to be used to run aggregate functions (SUM, AVG, etc.) on field data because it is SQL-agnostic. That said, such operations legitimately need to be run from time to time. According to SQL function with EntityFieldQuery and especially EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX, SQL queries need to be used, and that approach fits my use case the best. I was speaking with @chx yesterday and he recommended using a couple of internal functions to find the field name and column name. I'm just wondering if this is sustainable and if it's appropriate to do in a codebase that I might release to otehrs.

If it's the best way, then it's the best way. I just don't want to do it before I'm absolutely sure because it feels messy.

The View field module allows you to expose field tables as base tables to views. This differs from Views default behavior in that the base table is the field table and not an entity to which the field data is then loaded from. For example when selecting node as a base table you can then add fields, but the primary (base table) in the query is still node which depending on your data can screw up the aggregate functions (aka a many-to-one relationship of some fields to the node).

Views field allows you direct access to the field tables which means aggregate functions work properly. Additionally if you need to do "interesting" joins to other field tables you can control them completely using the following.

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {
  views_field_add_multi_join($data, /* see docs */);
}

Which is fairly simple to use and allows you to then perform aggregate functions across multiple field tables at once. You can then manually invoke a view $view->execute() and pull the results off the view. There are examples of this in the views documentation.

The benefits of this approach over EntityFieldQuery is that you can manage the process in Views (which almost everyone will already be using) and allow it to perform the physical query building in less direct way which helps elevate possible breakage down the road. In addition many times you will want to display such aggregate data on an admin screen which you can then use the view to provide both a display and access the results in code for additional purposes.


Can drupal be setup for users to interact with and submit suggested changes to an article? We will have static content. But we want the content dynamic in the sense that users can submit suggested revisions and the "community" can either vote or comment on that suggested change.

Yes - this is a common use case and is mostly done through adding and configuring  the workflow module and some combination of a moderation module (ex. Moderator or Modr8) to control who has final say over publishing the node.

To add a voting component to this, you would add voting api and then a voting widget (ex. fivestar or vote_up_down) based on what kind of user experience you are looking for. Then when a revision gets a certain number of votes, your moderators could publish the content. If you wanted this to occur automatically, you should take a look at the Rules and Voting Rules modules.


How to place a library in DRUPAL_ROOT/libraries? In Drupal 8, when I declare a library in a .libraries.yml file, it seems the library files have to be located INSIDE the module or the theme folder with the .libraries.yml file.

For instance, if a MYMODULE module contains this .libraries.yml file:

form-alter-css:
  version: 1.x
  css:
    theme:
      css/form-alter.css: {}

The file css/form-alter.css has to live at DRUPAL_ROOT/modules/MYMODULE/css/form-alter.css.

Instead, for shared libraries, I'd like to place the files in DRUPAL_ROOT/libraries, like we did in Drupal 7. But how?

I have tried entering an absolute path in the .libraries.yml file (e.g. /libraries/css/form-alter.css) but it doesn't work. Any ideas?

In drupal 7 the shared libraries were provided by a contrib module. Because a lot of modules had this as a dependency, it was very common:

Libraries API

I don't know, if this will be used this often in drupal 8, you can follow the development here:

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

So at the moment you are stuck with the libraries in *.libraries.yml, when you don't want to use the dev version of the Libraries API.

The libraries in *.libraries.yml were not designed for libraries in a shared directory. But they have one very useful feature, you can borrow a library from another module. There are a lot of useful packages already in core modules, like jquery ui elements. If you define a library in one of your modules, they also become available for all other modules. But the files will remain local to that module, which defines the library.


node_save does not save body content I'm trying to create a node using PHP. The below code works fine until I use any language code other than 'LANGUAGE_NONE'.

$node = new stdClass();
$node->type = 'recipe';
node_object_prepare($node);
$node->uid = 1;
$node->language = LANGUAGE_NONE;
$node->title = $item['title'];
$node->body[$node->language][0]['value']= $item['description'];
$node->body[$node->language][0]['format']= 'plain_text';
node_save($node);

If I use "en" instead of "LANGUAGE_NONE" then the node is created without any field being populated. That is, there is only a title; the body is blank.

Locale module is enabled and i18n is installed and enabled.

What should I do?

You also need to set the language of the fields.

$node->language = 'en';
$field_langcode = field_language('node', $node, 'body');
$node->body[$field_langcode][0]['value']   = $body_text;
$node->body[$field_langcode][0]['summary'] = text_summary($body_text);
$node->body[$field_langcode][0]['format']  = filter_default_format();

See this comment (https://drupal.org/comment/5464106#comment-5464106) for more info.


Multiple buttons to link to different page and different query I have a page in my site (from a custom module) with a hook_menu (red boxes).

The code for the menu is as follows:

$items['upcoming_games/' . date('Y-m-d')] = array(
  'menu_name' => 'main-menu',
  'title' => 'Upcoming Games',
  'page callback' => 'my_page',
  'access callback' => TRUE
);

The page callback calls a function where I insert the date as an argument for a query.
When clicking the menu, it defaults to TODAY.

What I need is to query for a different date depending on the click of the coloured buttons. I get "page not found"...

In the function where I have my query I get the date with the follwing code:

$date_to_show = arg(1);

What am I missing here?

Use the following code:

function sample_menu() {
  // This is a default option, without argument.
  $items['upcoming_games'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(),
    'access callback' => TRUE,
  );
  // This is for any other date.
  $items['upcoming_games/%'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
  );

  return $items;
}

function my_page($date = NULL) {
  // If the $date has not been defined, it means that the user is trying to see
  // today's games.
  if (!$date) {
    // Redirect to today's date.
    drupal_goto('upcoming_games/' . format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
  }
  // Otherwise, check the date. The strtotime() function is just as an example.
  else {
    $date = strtotime($date);
  }
  // Continue the operation.
  // ...
  return 'Upcoming games for ' . format_date($date, 'custom', 'Y-m-d');
}


How do I send notifications for followers of a group when group content is updated? I want to build such functionality that allow the user to follow the other users, and when the followed person is updating the information, the follower can get notified for what they are doing.

I think to build the specified functionality, I can use the Flag module, but for the notification, what kind of modules are good to work with?
I am confused. There are too many modules like notification, or messaging; even the NodeJs module can notify.

Its depend on how regular you want to notify the user. If you want actual real time notification then go for nodejs module. See the documentation and you will get better idea about it.


Wanna save text_format custom form in comment I'm using a custom form in CTools Modal to alter comment.

$form['subject'] = array(
   '#type' => 'textfield',
   '#title' => t('Title'),
   '#default_value' => $comment->subject,
);
$form['comment_body'] = array(
   '#type' => 'text_format',
   '#default_value' => $comment->comment_body['und'][0]['value']
);

All is good. I get my comment title and my comment body which is pushed in ckeditor field. My submit :

$comment = comment_load($form_state['values']['cid']);
$comment->comment_body['und'][0]['value'] = $form_state['values']['comment_body']['und'][0]['value'];
$comment->subject = $form_state['values']['title'];

comment_submit($comment);
comment_save($comment);

The subject is goodly saved from my form but for the body, it save an empty value.

Ps: when I change text_format for textfield, it work.

You forgot to add the format:

$comment->comment_body[LANGUAGE_NONE][0]['format'] = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['format'];


Views custom field select list like views custom field I'm looking for a module which can allow to add a select list like views customfield provides a text field.
The select list are on the based of above fields.
Example :
I have Edit and delete operations in each views row corresponding to the result.I need these operations in select list.
Any module suggestions ?

P.S. : Please don't suggest about views_php.I can write custom handlers instead of this module.

This is very easy to achieve but does not do much on it's own :

Create a new field for something like Content:NID
Go to Theme Information in the view settings
Find the template fie name suggested for your field
Create that file in your theme folder eg views-view-field--my-view--page--title.tpl.php
Press rescan templates in theme information (file name will go bold)
Add the following to the file

<select name="ops_<?php print $row->nid; ?>">
  <option value="edit">edit</option>
  <option value="delete">delete</option>
</select>

It doesn't do anything on it's own, you could wrap it in a <form> and specify a path as your method to process it, or use jQuery to do something.

But ... There is also an excellent module called View Bulk Operations (VBO) which will probably give you all the functionality you need.


How to change date format in Views Calendar Pager? I have multiple displays rendered in a Calendar View (Mo/Day/Upcoming/etc.) and everything's working as it should... except I changed a setting somewhere and applied it to all pages instead of current display and now the heading for the month display uses long format of the first date in the range of context (i.e. Tuesday, October 1 2014, Thursday, November 1, 2014, etc.)

I have "fixed" the issue by hooking theme_date_nav_title() in the theme template.php and setting $params['format'] directly, but this is hacky... Where is this setting in Views?!

This is an issue in the calendar module that has been fixed in the 3.x-dev version. There is still no setting to set the header the way you want but at least it doesn't default to the 1st of each month without hacking the module.


What are my options to visualise a views table with many fields grouped in columns? I have a view with 30 fields. Displaying its results would look best using a table, but with fields grouped in columns.

Default table in Views can't do this because there are to many fields.

So instead of what it looks now:

  field-1 header, field-2 header, field-3 header, field-4 header, field-5 header, etc. (with default field under each header)

I need:

  header1 I header2

  field-1 I field4

  field-2 I field5

  field-3 I field6

Any suggestions?

Notes:

It's something I would like to do on several views with a module or "simple" theming.
I tried the groupfield views module (broken when using table format, works great on html, unformated, etc.).
I tried DS views layout, but can't use CSS on each field on that one.
I'm thinking of Panels, but that seems like overdoing it just to get simple view display for my case.

The DataTables module might help for answering this question. Here is a quote from its project page:

The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:

Variable length pagination
On-the-fly filtering
Sorting with data type detection
Smart handling of column widths
Themeable by CSS
And more ...

Another feature that it offers is that you can "hide" specific columns from the default table display. But still the user has the option to do things like:

expand the hidden columns.
use the DataTables search feature to search for rows containing one or more strings contained in ... even those hidden columns.

So in this question here, I'd use an approach to only show, by default, a subset of all those columns, and leave it to the user to yes/no also display these (initially hidden) columns.
A few more links you may want to look at:

Show / hide columns dynamically (use the links following Toggle column to see it at work).
Tutorial about Using DataTables In Drupal 7.
How to hide (and show) a table column (using the jQuery DataTables plugin).
jQuery DataTables hide column without removing it from DOM.

Refer to the (short) video about Create Powerful Tables with the DataTables jQuery Plugin and Views for an intro about it, and how to use it as a views style plugin. Using the "settings" link for this views style, you can specify all sorts of dataTables options/features. In the above video starting from around 3:00 you see many of them.
The last link in these settings relates to hidden and collapsed columns (you can see the link in the video, though it is not expanded). So there is where you can then specify which of your (many?) columns you want to be processed as collapsed columns (not sure if you want any of them to be "hidden "in you case. Experiment a bit with those options in your environment to check if it is an acceptable compromise (or alternative) for "grouping" your fields (table columns), i.e.:

fields you always want to be shown.
fields you want initially to be excluded from the display, but for which you let the user decide to optionally also shown one or more of them.
fields you never want to be shown.

Example
Below is a screenprint of such display using DataTables. It's a display I created using Views (of course) with a table with:

8 fields in (defined in my view).
5 table columns for the 5 fields I have decided to always show.
3 table columns which I defined as "hidden and expandable" (within the DataTables settings after you select DataTables as the Views style).

Here is how the DataTables display looks like:

For each row there is a link 'Show Details' (in its 1st column). If you click on one (or more) of them, the hidden fields of such row are shown below that row (with grey background here) and the link you clicked changes to 'Hide Details'. Obviously, I've not done any styling for such expanded row (hence the grey background, etc). But you can see the 3 fields that were initially hidden.
Bonus: assume none of the rows are shown expanded, and you type "Basic" in the DataTables search box. It will then dynamically (in the browser, no server calls) reduce the table display to only those rows with Basic Page as value for "Type". But wait, there is even more: if you'd type a string like part of "21:15" instead (hidden in some of the rows), it will also dynamically reduce the table display to only those rows, like the expanded row shown in the screenprint. But wait, there is even (quite) a bit more: a search string like  "basic 21:15" will filter the rows to a combination of both search strings. For only this one feature I often recommend the amazing DataTables module, one of Drupal's hidden gems I think. And then there are the other features like pager, sortable columns, etc.
Remarks

Make sure to use the 1.9.x version of the DataTables library (not 1.10.x or above), as mentioned also on the project page, which states:

While there is work in the 7.x-2.x branch to upgrade to the latest DataTables version (1.10.x), the 7.x-1.x branch only works with DataTables <= 1.9.x. Since it's not listed in the projects download page, you will have to download it directly.

When creating a view, disable the pager of your view, since DataTables provides its own paging features (the video talks about that starting from 2:05).


Get Field Manage Display configuration in node preprocess I am preprocessing the data and I have overridden the node template, during the preprocessing I am not able to figure out how can I respect "Manage Display" configs. As an example if date field is configured to have a specific format, or image field is configured to have specific Image Style.

So my question is how can I call the Manage Display configurations during node preprocessing.

As @googletorp commented, the field should be rendered automatically considering the Manage Display configuration.

In my case [I was a node which has reference to paragraph A and A has reference to paragrapgh B which has a date field. The twig template markup needs heavy customisation so I was preprocessing the data to make it consumable by custom twig templates, now in order to get the date field show on node I have to load referenced paragraph entites and map the fields, because of which the fields was not rendering through the '#theme' => 'field' and Manage Display configs were not working.

But in order to make it working while mapping the field values we can can actually call for rederable field definition, something like

$date = $entity->field_date->view('full');


In Activity Stream, how is the 'active group' determined when a node has multiple organic groups assigned to it? I created new blog node in Drupal commons and assigned it to two organic groups. While it appears under both groups' Blog tab (view group_tab_blogs), it only appears under one group's Home tab but not the other.

On exploring the activity_log_stream view which is essentially the query for this tab, I noticed that it filters on the stream owner and does not search any other table.

My question is then, would I have to duplicate the row in this table or is there a way to have "multiple stream owners"?

Update:
After a bit more digging, I started playing with the rules area. Here I see that this rule fires after the creation of a Node. But, again, how is the 'active group' determined when a node has multiple organic groups assigned to it?

Update 2:
On Drupal.org, a bit more asking and digging lead to this bug report http://drupal.org/node/1294794 and even http://drupal.org/node/1256754.

Update 3
The above patch failed...

I believe the active group is just the group context which is present when content is created (i.e. if you're 'in' group B and post a node into groups A and B, it'll only go into the stream of group B). So it's not great for cross-posting.

You shouldn't use the patch in that issue because it was never finished, it's out of date, and has bugs and bad code that would most likely break your site.

If you plan to keep using Commons 6.x, best to post a feature request in the Activity log queue requesting default rules that would work to create multiple log messages when content is cross-posted across groups. Otherwise, wait for Commons 7.x where it's not planned to use activity log.


Limited popup like once per month and user Is there a module for Drupal that has the following options:

show a popup once in a month/day/...  should be configurable
save this information in a cookie or else
the popup should display some text and nothing else

check if

splashify module can help you here

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.Instead of using cookies to determine when the
  splash page shows up, we use jStorage.

Popup Message

  Display popup message for users once per browser session.


How to display data in tables using Forms API? I want to organize my data in table rows. How can I user Forms API to do it?

EDIT:

I want to show the data in the following way in multiple rows:

row1 checkbox info1 textfield1 info2 textfield2 ....

....

rowN ....

row 1 [add a new row fields here]

...

row 5

One should be able to cancel existing records and in the bottom fill in fields to add new records.

And I finding the solutions  in this link  or in this really difficult to understand.

The simplest way to do this (on small forms) that I have found is by taking advantage of the #prefix and #suffix elements in the render array. Here's an example:

$form['foo_fieldset'] = array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
);
$form['foo_fieldset']['header'] = array(
  '#markup' => '

      A checkbox
      A text input
      A text input

',
);

for ($i=0;$i<10;$i++) {
  $form['foo_fieldset']['row_' . $i] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['foo_fieldset']['row_' . $i]['checkbox'] = array(
    '#type' => 'checkbox',
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['foo_fieldset']['row_' . $i]['text_1'] = array(
    '#type' => 'textfield',
    '#prefix' => '',
    '#suffix' => '	',
  );
  $form['foo_fieldset']['row_' . $i]['text_2'] = array(
    '#type' => 'textfield',
    '#prefix' => '',
    '#suffix' => '	',
  );
}

The other way to do it (maybe known as the "right" way) involves building a theming function to render your form in a table. Take a look at this page (ignoring the tablesort options as you don't care about that) to see how it's done: http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules


Show who has flagged you I have a content view of user images. They have a 'flag user' flag attached to them. I suppose it all works just the same if I had the user flag in the user page.

I wanted to create a block view (or page) that shows who has flagged a logged-in user when that user is viewing their own profile.

I have tried every relationship under the sun. I alwasy seem to end up of a list of users the logged-in user has flagged, not the other way around.

Could anyone help put me out my misery?

I am using the latest releases of the Views and Flags modules.

Have you tried with a contextual filter with Flags: content ID, and then take the default value of type 'User ID from logged in user'.

It worked for me.


Why does boost turn off standard caching? When you enable the Boost module, it disables the standard Drupal caching (as at http://drupalperformanceblog.com/drupal-performance-tips), but it only reports boost as being incompatible with "aggressive" caching, and allows you to turn it back to "normal."
Does boost turn this off because it's unnecessary, or because it's actively harmful? Or does it not matter anyway?

(See also Is it redundant to use the "boost" module if varnish is used? with reference to using multiple caching systems.)

It's the System module that disables the aggressive caching when there is a module that implement hook_boot() or hook_exit().

The explanation is reported in the description text that appears in the form field to choose the type of caching.

  The normal cache mode is suitable for most sites and does not cause any side effects. The aggressive cache mode causes Drupal to skip the loading (boot) and unloading (exit) of enabled modules when serving a cached page. This results in an additional performance boost but can cause unwanted side effects.

The code that executes that verify is the following one (system_performance_settings()):

  $problem_modules = array_unique(array_merge(module_implements('boot'), module_implements('exit')));
  sort($problem_modules);

  if (count($problem_modules) > 0) {
    $description .= '
' . t('The following enabled modules are incompatible with aggressive mode caching and will not function properly: %modules', array('%modules' => implode(', ', $problem_modules))) . '.
';
  }

Boost only changes the content of a Drupal variable with variable_set('cache', CACHE_DISABLED); as it does it in its implementation of hook_enable(), it will disable the normal caching all times it is enabled. The reason for disabling it is reported in a comment before the code that changes that variable: "Forcibly disable Drupal's built-in SQL caching to prevent any conflicts of interest."
That means the module disables it just to avoid that both Drupal and Boost use their own cache, with the result of obtaining data from a cache that is then replaced with the content of another cache.

It could have been a better idea to hide the cache selector when Boost is enabled. In that way, users could not enable the cache that Boost disables when it is enabled.

As side note, hook_boot() has been removed from Drupal 8, and hook_exit() is probably going to be removed from Drupal 8 too. What I reported here for Drupal 6/7 will not be anymore true for Drupal 8.


How to override taxonomy page with users view? When I enable provided views, it works all right. But for one taxonomy dictionary (let's name it dictionaryname), I want to display users in that taxonomy, not nodes. So I disabled default view again and then:

I created "show users" view with path taxonomy/term/% and it fails to replace taxonomy page.
Then I changed path to dictionaryname/% - as path alias is set. But it fails as well.
I changed path to aaa/% and it works, so I know view on it's own works. It just fails to override default pages.

Any idea what am I doing wrong? And how can I get dictionaryname/% path to work?
It looks like Drupal's router give original term pages precedence over my view.

As per reviewing taxonomy_menu function, you need to replace path taxonomy/term/% with taxonomy/term/%taxonomy_term in "show users" view.

If you want to use path alias, set view path like this: dictionaryname/%taxonomy_term

Also, check Taxonomy and Views modules weights, make sure Views module weight is higher than Taxonomy module.


How can I render my output in a series of DIVs rather than an "item_list"? The following code works in the sense that it outputs my series of photos in an unordered list. My question is - What changes would I need to make in order to render my output in a series of DIVs with class IDs? I plan to hook this up to JQuery Masonry and I'd prefer to break away from the limitations of them being in a list.

The following code pulls in my data.

function photo_gallery_contents($display) {
  $max_num = variable_get('photo_gallery_max', 3);
  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }
  // Now proceeds to execute().
  // If called by peg, query proceeds directly to execute().

  // Fetch the results for the nid field into an array.
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return.
  return node_load_multiple($nids);

}

The code that renders all (but would like it to create a series of DIVs) is the following one.

function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  // Array to contain items for the page to render.
  $items = array();

  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image',array('label' => 'hidden',   'settings' => array('image_style' => 'thumbnail')));

    // Render the array down to the image HTML.
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }

  if (empty($items)) {
    // No content in the last 2 weeks.
    $page_array['photo_gallery_arguments'] = array(
      //Title serves as page subtitle.
      '#title' => t('All photos from ever'),
      '#markup' => t('No photos available.'),
    );
    return $page_array;
  }
  else {
    $page_array['photo_gallery_arguments'] = array(
      '#title' => t('All photos from ever'),
      '#items' => $items,
      // Theme hook with suggestion.
      '#theme' => 'item_list',
      '#type' => 'div',
    );

    return $page_array;
  }
}

As far I understood you want render the following code in multiple <divs>.

$page_array['photo_gallery_arguments'] = array(
  '#title' => t('All photos from ever'),
  '#items' => $items,
  // Theme hook with suggestion.
  '#theme' => 'item_list',
  '#type' => 'div',
);

Replace it with the following code.

   foreach($items as $item_key => $item) {
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'container',
       '#attributes' => array(
         'class' => array(
           'my-class-' . $item_key,
         ),
       ),
     );

     $page_array['photo_gallery_arguments'][$item_key]['content'] = array(
       '#type' => 'markup',
       '#markup' => $item,
     );
   }

Or use the following code.

   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'markup',
       '#markup' => '
' . $item . '
',
     );
   }

Alternatively, you can use the following code.

   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'item',
       '#markup' => $item,
     );
   }

You can find more information about rendering arrays, and Form API.


Is it possible to show 403/404 messages on the front page? Is it possible to have - instead of a dedicated 403/404 page - just a custom div inserted into the front page? 'Cause when I think of what I'd like to show up at 403404, I want everything that the front page has. So, whatever the front page looks like over time, I would just want it to adopt a 403/404 message div.

You can make this with the following configuration and using Rules module.
1. create a page with a custom path ex, "404" and set this page as 404 on configuration -> site information
2. create a rule, if the request page its "404" then
 2.1 system page redirect
 2.2 system show a message


Pass contrib module tokens to custom event in rules I am creating a custom rules event using hook_rules_event_info. This custom event is extending the features of the Stripe Subscription contrib module. The custom rules event is working fine so far.

Stripe Subscription creates several tokens for use within the module using hook_tokens. Is it possible for me to pass the tokens available in the module onto the custom rule event I have created so I can use them in the actions?

The event rule I have created looks like this:

function stripe_subscription_rules_event_info() {
  return array(
    'stripe_subscription_event' => array(
      'label' => t('A user subscribed'),
      'module' => 'stripe_subscription',
      'group' => 'Stripe Subscription',
      'variables' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who is subscribing.')),
        'plan' => array('type' => 'text', 'label' => t('The purchased plan.')),
        'subscription_action' => array('type' => 'text', 'label' => t('The subscription acton')),
      ),
    ),
  );
}

When the Rule gets invoked, you can send any number of parameters along with it. Just make sure they match the expected data type.

rules_invoke_event('stripe_subscription_event', $acting_user, $plan, $stripe_subscription_event);

This will trigger the Rule and send the variables along. It is up to you call this function and obtain these values somehow.

Since your Rules description is A user subscribed, I suppose you should the submit function of that event to invoke the Rule. You might be able to grab the values from the $form_states['values'] array. I have no idea what the Stripe subscription module does, so I am not sure how you should obtain these values.

I don't think you can use tokens. Those are specifically for rendering content and I have never seen them used in code. (You might obtain the values by copying some of the logic though.)


Search API isn't returning results with words in the title I just installed search api and setup a server and index. Then I setup a Views page and exposed the search filter option. Searching all fields work, but for some reason its not searching the title. What could be the issue? I tried turning all fields off on the index and just left the title field option and its still not working.

I had to turn on the setting Search on parts of a word on the Server's page in order to get it to work. Now it searches titles. I'm not sure why it doesnt search titles with that unchecked.


theme hook_suggestions not woking I have a content type called event_page. In event, I have a drop down for selecting templates.

In the templates folder of my active theme, I have included my custom tpl.php files, such as node--event-page--default.tpl.php and node--event-page--blank.tpl.php.

I have used strreplace to remove 'node--event-page--' and '.tpl.php' to populate the types like bank and default from the files in the templates drop down.

Now I am using hook suggestions to take these theme on form submit, but it seems to not working

if (isset($variables['node'])) {
  $node = $variables['node'];
  $field_template_list = $node->field_template_list->und[0]['value'];
  if ($node->type == 'event_page') {
    $variables['theme_hook_suggestions'][] = 'node__event_page__' . $field_template_list;
  }
}

I hope I understood your question correctly, that you want to apply theme on form submit.

theme_hook_suggestions is used when a template is being rendered. I think you don't need to save it on form submit. You just need to provide logic of selecting a template file in preprocess function of template.php file. Drupal looks for the suggested template file to apply to particular page/node etc

As a pseudo code, it would be

if(template_type is default)
   apply default type
else if(template_type is blank)
   apply blank type

For help, visit this link  https://www.drupal.org/node/1089656

Moreover, the example of preprocess function is as follows

function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}


db_insert() returns wrong key I'm trying to migrate from drupal_write_record() to db_insert() / db_update(),
but db_insert() returns a weird key instead of the last inserted key.

On an empty table, I'm doing an insert, and instead of real row number (suppose to be 1, right?), I'm getting a wrong one.

$fields['created'] = REQUEST_TIME;
$fields['uid'] = 1;
$insert = db_insert('table')->fields($fields);
$last_insert_id = $insert->execute(); // suppose to be 1, but = 43587087

Any ideas?
Thanx.

The autonumber isn't related to the number of records in the table, but rather the AUTO_INCREMENT value of the table's primary key column.

If you have a completely new table, and add 100 rows, the next ID will be 101. If you just remove all the rows in that table the next ID will still be 101, unless you TRUNCATE the table, or reset the AUTO_INCREMENT column.

For an easy way to test, fire up your preferred DB client, and insert a record into the database. If you get 1 as the next insert ID, there's a bug with your Drupal installation/DB engine. If not, it's just what's mentioned above.


Drush can not find settings.php I use two shared hosts at present. One, webhostinghub.com, already has drush installed and it works. The other, 1and1.com, did not come with drush pre-installed so I installed composer and then drush with composer as recommended on drupal.org.

This puts a symlink to drush in ~/.composer/vendor/bin which points to ../drush/drush/drush. In the ~/.composer/vendor/drush/drush folder that this points to is a file drush which requires drush.php which is in the same folder.

So as recommended, I set up an alias for drush that runs this with php-cli.
Because 1and1.com sets up php and php-cli to default to php4, I also set up an alias for both php and php-cli to the php7.1 versions.

When I go to the root folder of one of my drupal sites and type in simply drush, I get the non Drupal specific commands listed and then the message:

  NOTE: Drupal root not found. Pass --root or a @siteAlias in order to
  see Drupal-specific commands.

I did see some posts saying that for this to work you have to just have one settings.php in the sites/default folder of the drupal tree. I have searched and have not found any stray settings.php files - just the one in the sites/default folder.

Does any one have an idea about why this is not working? Let me know if you need more information about my setup or the process that I went through.

I was right in my comment earlier. The issue was compatibility between drush 9 and drupal 7. Once I downgraded to drush 8.1.10 it worked fine. Note there is also an oddity with 1and1 specifically where in SSH they default to php4.4 which is too old! So I also had to set up an alias for php and php-cli to refer to a more modern php. Also I had to ensure drush used it by adding 'export DRUSH_PHP=' followed by the full path and filename for the more recent version of php.

If anyone reading this does not know how to downgrade drush with composer you have to remove and re add it with the following commands:

composer global remove drush/drush

composer global require drush/drush:8.1.10

Replace the 8.1.10 with the version that you want.

Also, anyone new to composer might get fooled as I did by the prompt 'Discard changes? (y/n/v/d/s/?). Yes actually means 'discard and apply changes'! I found details of this in the following post:
https://stackoverflow.com/questions/25828102/composer-discard-changes-what-do-the-y-n-v-d-s-do

I hope this helps anyone else new like me stumbling across this issue!

Once again thanks for the comments - the one question from @Christia about drupal version triggered me to look in the right direction!

Rory


Blocks created using multiblock module are not working Installed multiblock module.
Create duplicated blocks (structure > block > instance > create .. ) and placed them in footer1 region.
Original blocks are in very-top1 region.

Duplicated blocks are menu links. When I click those links, nothing happens. They definitely worked before. I am not sure why they dont work now. I must done something wrong.

My site address:  http://godrupal.info/. If you scroll to the bottom you will see the all the links. Do you know why those duplicated links are not working?

I checked your site out specifically the footer area as you've instructed. This is not the module's issue but a Bootstrap/theming issue. Notice in the screenshot:

The block-9 block is using the col-md-12 which spans the whole content area and covering everything under it that's why the links aren't clickable.

I tested and just changed col-md-12 into col-md-2 and now the links are clickable.

Please check your markup and CSS to confirm.


Webform views - creating a filter using date from user-submitted data We have a job submissions webform. In the form, there is a "closing date" field with a calendar picker (yyyymmdd format). When the closing date passes, the submission should be removed from view.

I created a relationship for the Submission Data: Expiry Date field so it can be used as a Filter.

Now that I have the data available as a filter, this is where I get stuck; I need the view to filter out the submission if the Expiry Date has passed. How can I do this?

I just found a patch for this exact functionality. Out of the box, you are right, it acts as its a straight up text field. If you were to use entityform instead of webform, I believe you would be able to do this as it uses normal drupal fields.

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


Manipulating Theme Suggestion Priorities I'm adding in some theme suggestions using mytheme_theme_suggestions_alter(), when certain criteria is met. My issue is, for some reason these additional theme suggestions are appearing at the top of the theme suggestions list whilst debugging.

Basically my theme suggestion is ignored, as Drupal believes my additional theme suggestions aren't a priority over the default ones.

<!-- FILE NAME SUGGESTIONS:
   * views-view--venues-grid-rows.html.twig
   x views-view.html.twig
-->

I've tried some 'dirty' solutions, such as trying to clear or reverse the $suggestions[] array without any luck.

My guess is that the hook I'm using is actually running too early, however I'm unable to find a more appropriate one. Something dedicated to hooking into view theme suggestions would be great.

Thanks in advance.

You shouldn't need to add a theme suggestion if you're trying to override the view template for a given view ID. Confusing things is the fact that Views' suggestions don't show in the debug code (see: https://www.drupal.org/node/2118743).

If you add a file named views-view--view-machine-name.html.twig (replacing machine-name, of course) in your theme's templates directory and clear caches, it should pick it up. Note: it has to be templates and not in your theme's root or my_templates or anything else. Drupal is picky that way.

You should not need to worry about module/theme weights as all module alter functions run before theme alter functions.

Finally, if you are add theme suggestions I would recommend using the more targeted hook_theme_suggestions_HOOK_alter. (For views, the HOOK is views-view so your function would look like:

function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = ...
}

Hope that helps.


How to do Test Driven Development (TDD) in Drupal? What are the tools used TDD in Drupal (PHP modules, Drupal modules, etc)?
What does your commit/test/deploy workflow look like? Do you use Phing, PHPUnderControl, Hudson for managing this workflow?
In which way does unit testing make your code more reliable?
Do you need a separate, expensive, stand-alone unit test server, or can you do it from a laptop?

I know that Robert wrote an excellent technical post here about unit testing in Drupal with SimpleTest; I am more interested in covering the workflow and configuration part. Currently I have a development machine, staging and production server. Both production and stage sites run on a 300MB RAM/300MHz CPU Dreamhost VPS.

Since Mark's blog is offline, I'll mention some of the tools his team has implemented:

Functional testing: Selenium
Unit testing: Simpletest
Build server: Jenkins
Performance benchmarking: XDebug + Cachegrind

In the two years since I asked this question I've seen some additional tools gain popularity to the TDD scene. Nowadays when you speak of Test Driven Development (in a Drupal context, of course) there's two sides to the same coin — front-end testing, and back-end testing.

Here are two presentations that stand out from the latest Drupalcon Portland 2013 representing this matter:

Development, By The Numbers, backend testing.
Automated testing with Jasmine and PhantomJS, frontend testing.

The first presentation is not related to unit or functional testing (strictly speaking), it's more about tools to measure code quality. Nevertheless, I feel it's somewhat related to the topic.


How can I return a 404 error page in a node view? How can I return a 404 error page when a non-registered user tries to see a node page of a specific content type? And of course, the registered users can see the node page normally.

Drupal permission system provides fine grained permission control for "create", "edit", "delete" actions for every node content type, but viewing action is covered by general "View published content" permission option that covers all content types.

In order to deny access to anonymous users when they are trying to view a node of certain content type, you need to include a function in a custom module that implements hook_node_access():

/**
 * Implements hook_node_access().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_access($node, $op, $account) {
  if (user_is_anonymous() && $op == 'view' && $node->type == 'EXAMPLE') {
    return NODE_ACCESS_DENY;
  }
}

You need to replace MYMODULE with the module name that contains this function and EXAMPLE with the name of the content type that you wish to deny access to.

UPDATE: The code above would in fact return 403 (Access Denied) page, I'm sorry for confusion. The following code will return 404 (Page Not Found) page (only when user is trying to access the node of content type "example" in "full" view mode (usually by accessing the node by URL "node/NID]":

/**
 * Implements hook_node_view().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (user_is_anonymous() && $view_mode == 'full' && $node->type == 'EXAMPLE') {
    drupal_not_found();
    drupal_exit();
  }
}


Field Collection vs. Paragraphs I used Field Collection in my previous sites and I faced some performance issue, So this time I am looking a alternative for Field Collection. I find a answer Alternative to Field Collection.

but I can't find much on how different or similar these solutions specially [Field Collection and Paragraphs].

Maybe someone can help to explain? So that I can make a good decision.

In many respects the Paragraphs module appears to be a fork of Field Collection. Functionally, the difference between the modules lies in how their respective field widgets operate. The Field Collection widget allows users to embed multiple instances of a single field collection bundle in a node, while Paragraphs allows users to select a different bundle for each instance they embed using the Paragraphs widget. Both of these methods are extremely valuable and I now find myself combining field collections and paragraphs on the same node.

Read more in the issue about "Merge with Paragraphs module?".


What is the rule on licensing and third party code? When you create a module that uses third party code, is there any instance in which it is "okay" to include it in the module as opposed to have the user download it themselves?

For instance, if you make a module that integrates a CKEditor plugin - I would think that you can't or rather, shouldn't put it into your module on drupal.org.

I see this here: https://www.drupal.org/node/422996

My gut tells me it is likely not good practice to bundle it up into your module.

My gut tells me it is likely not good practice to bundle it up into your module.

You shouldn't. That page starts out with:

This is the policy for 3rd party code libraries in Drupal's contribution repositories.

In general 3rd party libraries and content are forbidden, so do not commit any. Instead, document for your users how to find and install the library/content themselves.

The other way is exceptions and they're clearly defined and you need to request approval.


Adding dynamic filter in module_invoke() I have created a node named "weekday," and one named "place" on Drupal 7. Next, I created a block view of the fields in "weekday" I wanted to show in the "place" node template.

I implemented it using the following code:

$weekday = module_invoke('views', 'block_view', 'weekday-block');
print render($weekday);

Now I would love to add a flexible filter that allows to load the block module with a extra filter of the different weekdays. Weekdays are a taxonomy term field in the node type "weekday".
The reason is that I would like to request the block by jquery in a link like http://www.example.com/place#Monday.

You want to use views_embed_view(), rather than module_invoke(), for this so you can pass the 'weekday' term as an argument to the view, such as in the following code:

print views_embed_view($view_name, $display_id, $argument);

There might be an easier way to do this in Drupal 7/Views by using contextual filters directly from the view itself; I'm not sure how you are planning on using jQuery to load each of these new blocks. Are you doing a load operation with the URL on each one? Is there any reason you need to use the # anchor attribute rather than a URL argument like http://www.example.com/place/Monday?

That could make it easier to set this up within views.


Disable displaying user picture in page--user.tpl.php I don't want to display the user picture on the user account page. It is not a field, so I can't simply hide it in display settings. How can I disable it in Drupal 7?

If you don't want it at all in the user registration you can navigate to : admin/config/people/accounts/settings and uncheck "Enable user pictures" on that page.

If you dont want it only on the user profile page you can add this snippet to template.php in your theme folder

function THEME-NAME_preprocess_page(&$variables){
  if (arg(0)=="user" || arg(0)=="users" ){
    unset ($variables['page']['content']['system_main']['user_picture']);
  }
}


How do I enable language without importing translations? I need to enable a lot of languages on my site and I do not want Drupal to download translations since only few forms and pages will be actually translated on the front end so I'll handle that manually.

Is there some way to disable this or do I have to enable all languages and then just flush the locales tables so that those unused translations don't take up the space?

drush cset locale.settings translation.import_enabled 0

Or any other method of disabling that flag should do the trick.


How do I grant to roles dynamically created permissions? In my module, I am dynamically creating user permissions for vocabularies. I would like to also grant all roles the view permission, but I cannot figure out a proper way where to do it.

I cannot use a config yml, because these are dynamic permissions created within permission callback and both the hook_install and hook_modules_installed are run before the permission callback, so the roles don't pick up the permissions.

This is how I tried to grant the permissions in hook_install() and hook_modules_installed().

$vocabularies = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_vocabulary')
  ->loadMultiple();

if (!empty($vocabularies)) {
  foreach ($vocabularies as $vocabulary) {
    $permission = 'view name defined in the callback ' . $vocabulary->id();
    $anonymous_rid = RoleInterface::ANONYMOUS_ID;
    $authenticated_rid = RoleInterface::AUTHENTICATED_ID;

    if ($anonymous_role = Role::load($anonymous_rid)) {
      $anonymous_role->grantPermission($permission);
    }
    if ($authenticated_role = Role::load($authenticated_rid)) {
      $authenticated_role->grantPermission($permission);
    }
  }
}

Where should I grant these permissions within my module?

After granting the permissions, you should call the save() method to make the code work.

if ($anonymous_role = Role::load($anonymous_rid)) {
  $anonymous_role->grantPermission($permission);
  $anonymous_role->save();
}


Drupal 7 user register form in overlay on page load One of my requirements is to show the user registration form in an overlay kind of interface.

From the Examples module issue queue, comment #14 http://drupal.org/node/930058 I found a module, learned the hook_admin_paths() and hook_admin_paths_alter(). I installed that module in my local test site. Added "user/register" path to $paths of hook_admin_paths() and granted permissions to use overlay. It works pretty much as expected with the click event however my requirement is to trigger the overlay for onpageload event.

I tried calling a js script which would trigger click event from hook_overlay_parent_initialize() and module's info file by settings scripts[] = myoverlay.js.

The js script looks as below,

(function ($) {

Drupal.behaviors.loginLoad = {
  attach: function (context, settings) {
    alert("trigger client event"); // works
    $(".menu-589 a").attr("title", "click"); // works
    $(".menu-589 a").trigger("click");
    // This one didn't work. Tried triggerHandler() and click() as well.
  }
};

})(jQuery);

My jQuery expertise is very limited. I'm trying to figure out how the overlay fires for onclick event.

From what I learned the paths to be opens in overlay are defined in Drupal.settings.overlay.paths.admin. And overlay-parent.js and jQuery BBQ does some tricks to show things in modal window.

Any help to figure out this will be appreciated.

On a side note : For Drupal 6 projects I have used modal frame api module often with onclick event. This module doesn't seems to be available for Drupal 7 and it is going to be deprecated in favor of overlay in core. Is overlay an API module ?  It doesn't appear to be the case from my experience.

I you need something like this site http://www.hospitalsreview.com/ has done for the sign up then you should try my module it will surely help you as you can see it is working on my site.

Sign Up Module


How to show descriptions when a user hovers over a form element How is the descriptions tooltip done in rubik theme by development seed? I have looked through the entire theme and couldn't identify which is handling this. Is it js or css?
https://github.com/developmentseed/rubik

The entire tooltip code is found within the Rubik theme in the files core.css and core-rtl.css.  The majority is within core.css.  The specific piece that shows the tooltip is:

.page-content .form-item:hover > .description { display:block; }

But each tooltip has text contained in

, so you can search through core.css/core-rtl.css and find statements regarding .description


How do I replace function commerce_customer_options_list with my own? How can I replace

/**
 * Implements hook_options_list().
 */
function commerce_customer_options_list($field) {

in commerce_customer.module around line 949 with my own options_list build routine?

the hook is just sent directly to the commerce_customer module, and I don't see how I can hijack it.

Thanks

Try using hook_field_widget_form_alter in your custom module for either $context['field']['type'] == 'options_list' or of type options_select ... it looks like the widget is set as options_select in commerce_customer_field_widget_info_alter. I'm pretty sure its 1 of the 2 values.

Then you can set a #pre_render attribute to a function that alters the default commerce_customer supplied values. A derived example from the API comments is:

$element['#pre_render'][] = 'mymodule_pre_render_commerce_customer_options_field';

Then in your pre_render function you can add/remove values from the list. I think i've done this once before myself for god knows what ... haha.

Alternatively, you could also probably set or unset values from any old FAPI #options array in a $form with hook_form_alter. Hopefully 1 of these 2 approaches gets you there.

Also, you'll probably want to be sure your module invokes after commerce_customer.


Patch a module loaded by a distribution I am trying to make an installation profile that inherits the commerce kickstart distribution. In order to get this to work, I need to apply a bunch of patches through drush make.

First I have to apply a drupal core patch: http://drupal.org/node/1356276#comment-6654100

However the libraries module also needs to be made aware of the parent installation profile. So it needs to be patched as well.

My make file looks like this:

api = 2
core = 7.x

projects[drupal][type] = core
projects[drupal][patch][] = http://drupal.org/files/1356276-base-profile-d7-38-do-not-test.patch

projects[commerce_kickstart][type] = profile
projects[libraries][patch] =  patches/libraries-from-inherited-profiles.patch

The problem is that with this makefile drush will download the libraries module again to sites/all/modules and patch it there instead of just patching it in its original download location at profiles/commerce_kickstart/modules/contrib/libraries, thus I end up with the libraries module existing twice within one drupal installation.

The patch file for the libraries module looks like this:

diff --git a/libraries.module b/libraries.module
old mode 100644
new mode 100755
index 687fa29..bcf8824
--- a/libraries.module
+++ b/libraries.module
@@ -66,7 +66,6 @@
  */
 function libraries_get_libraries() {
   $searchdir = array();
-  $profile = drupal_get_path('profile', drupal_get_profile());
   $config = conf_path();

   // Similar to 'modules' and 'themes' directories in the root directory,
@@ -77,7 +76,8 @@
   // Similar to 'modules' and 'themes' directories inside an installation
   // profile, installation profiles may want to place libraries into a
   // 'libraries' directory.
-  $searchdir[] = "$profile/libraries";
+  foreach (drupal_get_profiles(drupal_get_profile()) as $profile)
+   $searchdir[] =  drupal_get_path('profile', $profile) . '/libraries';

   // Always search sites/all/libraries.
   $searchdir[] = 'sites/all/libraries';

How do I tell drush to simply patch libraries within the commerce kickstart directory and not download it again into sites/all?

For now I have solved this by patching the make file of the commerce kickstart profile:

projects[commerce_kickstart][type] = profile

projects[commerce_kickstart][patch][] = patches/commerce_kickstart.patch

The content of patches/commerce_kickstart.patch is this:

diff --git a/drupal-org.make b/drupal-org.make
index bde036e..787f6ea 100755
--- a/drupal-org.make
+++ b/drupal-org.make
@@ -31,6 +31,7 @@
 projects[taxonomy_menu][subdir] = "contrib"
 projects[libraries][version] = 2.1
 projects[libraries][subdir] = "contrib"
+projects[libraries][patch][] = patches/libraries-from-inherited-profiles.patch
 projects[views_megarow][version] = 1.0
 projects[views_megarow][subdir] = "contrib"

The patch happes to be applied on the commerce kickstart before its own makefile is executed. When it finally get executed it will also applied my libraries module patch within its directory structure.


How to improve comments when using Acquia Marina theme I'm using Acquia Marina theme but comments( sample here) and their replies look awful. It is difficult to distinguish between a comment or it's reply.

Is there any easy solution beyond a custom theming from my side.

The only options for changing the styling of the comments in Acquia Marina are to customize the theme or to install a third-party commenting system such as Disqus http://drupal.org/project/disqus

If you decide to customize the styling of Acquia Marina, here are a few tips and resources:

Documentation on customizing a Fusion-based theme. Be sure to read the section on "Using local.css" http://fusiondrupalthemes.com/support/documentation/customizing-your-theme

If you are not very familiar with CSS, a good, general tutorial on what CSS is and how to use it - http://www.w3schools.com/css/default.asp

The Firebug plugin for Firefox is very helpful for troubleshooting CSS and discovering what CSS rules need to be written to make changes to your theme's styling. Here is a tutorial on using that plugin: http://www.kristarella.com/2009/02/how-to-use-firebug-for-css/


Custom views sort handler without table I am trying to expose data fetched from remote API and stored to $user object. I have accomplished that with a custom views handler suggested in this post Custom views handler without table.

However, I need to add sorting and filtering, so any help will be great.

This is the custom views field handler code.

/**
 * A handler to provide a field that shows the license type.
 *
 * @ingroup views_field_handlers
 */
class views_handler_apms_license extends views_handler_field {

  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    // Remove the checkbox
    unset($form['alter']['alter_text']);
    unset($form['alter']['text']['#dependency']);
    unset($form['alter']['text']['#process']);
  }

  function render($values) {
    $user = user_load($values->uid);
    if (isset($user->apms['userLicense'])) {
      return $user->apms['userLicense'] ? t('BASIC') : t('FREE');
    }
    else {
      return NULL;
    }
  }
}

You can use the post_execute() method on your handler to remove entries from the list of all results. This is certainly a bit tricky but it works.


Step back button for Commerece offsite payment method I'm writing an offsite payment method for Drupal Commerce (I need that to interact with my bank API). The thing is that when I create a form to send to payment server via PAYMENT_redirect_form I have the only button - SUBMIT there. I want to add one more button there - smth like GO A STEP BACK to return to checkout state. So, i've created one more button, but it performs the same action as SUBMIT - goes to payment server... I think i'm missing smth very simple, but how can i make that one more button in payment submition form to perform a step back like those we have in checkout proccess?

Will be very thankful for your advice :)

It's likely you can't, because the form's action will be on a PayPal domain. So it'll always be submitted to them, and your site will never know about it.

The simplest solution would be to use a styled link instead of an input.


Views filter on field being either empty or equal to uid I have a views filter on a particular field being empty (Is empty (NULL)).

However, I would like to have it check on the field being either empty or equal to the current user's uid. I would like to do this programmatically in a custom module, so without installing a contributed module.

The field in question is $node->field_quality_personal[LANGUAGE_NONE][0]['value']. So this field can be either empty, or it can contain a uid.

I found the way to fix this. The answer is twofold:

First create two filters: one for the field being empty and one for the field being equal to the string "uid". Then as a Filter Criteria option, choose And/Or, Rearrange and add the Or condition:

This is the result:

Second implement hook_views_query_alter() to replace the "uid" string we added earlier with the actual user uid:

/**
 * Implements hook_views_query_alter().
 *
 * Search for 'personal' field to be empty or equal to uid.
 */
function example_views_query_alter(&$view, &$query) {
  if ($view->name == 'myview') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'table.field_quality_personal' && $condition['value'] == 'uid') {
          global $user;
          $condition['value'] = $user->uid;
        }
      }
    }
  }
}

That's it!


Programmatically download last module version Is is possible to download the last version of a module during an hook_update_N() of my custom drupal 6 module?
I am in a case where the module I created needs the last version of CCK and I would like to programmatically download this version and enable it?
Or maybe  is it possible to add the plugin version in the .info dependencies array?

It's dangerous process what you're looking for.

What if the user has a older CCK version ?
What if the user patched is CCK ?
What if the latest version of CCK won't works ?

Also, it's not fair to download modules without letting knowing the user what you're doing. From my point of view, the best solution it's to add dependency in the info file and with the hook_init you can check the version of CCK and display a message to as the user download the latest version of CCK.