Assign an action to a simple button I am trying to render a simple button with a submission handler. I tried two  methods, and this is the code I used.

First method

mymodule.module

function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
    $build['mymodule_btn'] = [
      '#type' => 'submit',
      '#value' => 'Generate PDF',
      '#submit' => ['mymodule_generate_pdf'],
      '#weight' => -1,
    ];
   }
}

function mymodule_generate_pdf() {
  // ...
}

Second method

mymodule.module

function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
     return \Drupal::formBuilder()->getForm(Drupal\MyModule\Form\MyModuleForm::class);
  }
}

MyModuleForm.php

namespace Drupal\MyModule\Form;

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

/**
 * Generate the button.
 */
class MyModuleForm extends ConfigFormBase {

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

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['mymodule_btn'] = [
      '#type' => 'submit',
      '#value' => 'Generate PDF',
      //'#submit' => ['mymodule_pdf_generate_pdf'],
      '#weight' => -1,
    ];

    return $form;
  }

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

  /**
   * {@inheritdoc}.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // ...
    \Drupal::formBuilder()->submitForm('mymodule_form', $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
  }
}

The first method generates the button, but the submission handler is not executed. The second method doesn't even generate the button.

How can I fix the code I wrote?

In Method 2 you want to add the form as an element in the $build array.

Should be something like this:

$build['my_form'] = \Drupal::formBuilder()->getForm(Drupal\myModule\Form\myModuleForm::class);

Also you don't need to return anything, $build is passed by reference, so anything you add to it will stick.


How can I allow users to cancel their accounts without requiring e-mail confirmation? In Drupal 7, users can cancel their accounts from the account settings page.  However, by default this requires e-mail confirmation.

There is an option "Require e-mail verification when a visitor creates an account" but no option "Do not require e-mail verification when a user cancels an account."

Is there some way to allow users to simply cancel their accounts while logged in rather than requiring them to verify the cancellation via e-mail?

The behaviour seems to be hard-coded into the user_cancel_confirm_form_submit(), which sends a message to the user if they don't have the administer users permission.

I can't see any pretty way of getting round it really, but there is something you can do.

First you need to set an undocumented variable called user_mail_cancel_confirm_notify to FALSE. I'd recommend using Drush to do it:

drush vset user_mail_cancel_confirm_notify FALSE

But you can do it in PHP if you need to:

variable_set('user_mail_cancel_confirm_notify', FALSE);

That will stop the _user_mail_notify() function from sending the cancellation confirmation email.

Next, you need to hook into the form submission for the cancellation confirm form, and force-cancel the account (otherwise it would be waiting for the user to click the cancellation link in the email you've just stopped):

function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_user_cancel_form_submit';
}

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  // Rather than negating the complex access expression from the original form we can
  // just make the change in the else portion

  global $user;
  $account = $form_state['values']['_account'];
  if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
    // Account has already been cancelled by the system.
  }
  else {
    // Cancel the account
    user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
  }
}

I haven't tested any of that but after reading the functions involved in the user module I'm pretty sure it will work.


Adding a vertical tab the the content type form page How can i add a vertical tab to the content type manage form page?

I want to add a vertical tab that has a form like the ones it currently has.  For example: it has menu settings, display settings, etc.  I want to add a tab that ties a theme to a content type.  Can you someone help me out?

Thanks

Try this. Or read about hook_form_FORM_ID_alter()

function mymodule_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['mymodule'] = array(
    '#type' => 'fieldset',
    '#title' => t('mymodule'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

}


Can I suppress PHP error messages for authenticated users, BUT display all of them for an admin? I would like to suppress all the PHP error messages (errors, notices) for a regular authenticated user, BUT display ALL of them for an administrator ($user->uid == 1 or user with an "administrator" role).

This way I have the opportunity to set "Error messages to display" to "None" at admin/config/development/logging, but unfortunately this is a GLOBAL setting, which is not the right one for me.

I haven't tested this but I would think you could turn that setting off completely, and enable it again yourself in a custom module:

function MYMODULE_init() {
  if (user_access('a permission only admins have')) {
    error_reporting(E_ALL);
  }
}

Update

Per your comments, it looks like this way doesn't work, but what does work is to do exactly the reverse of the above. That is, to set the error reporting to "All messages" in the UI, and then use hook_init() to surpress the unwanted levels of error message.

I would say your suspicions are correct, that Drupal is handling the errors at a lower level and so turning them off all together stops calling error_reporting() in hook_init() from having any effect.


How to add rows to a form table with AJAX Callback in Drupal 8 I try to implement a button to add rows to a form table.
Each clic on the button should add a new line.

My problem is that my modifications in the AJAX Callback doesn't seem to modify the actual $form object :

At the first clic, row n°6 is added but without default values, wich is already a problem. The next clics have no effect, the $form parameter in the callback doesn't contain the 6th row.

What is the way to actually modify $form ?

Here is the build form :

public function buildForm(array $form, FormStateInterface $form_state, Array $profile = NULL) {

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

// table
$form['myTable'] = array(
'#type' => 'table',
'#header' => array(t('COL 1'), t('COL 2'), t('COL 3')),
'#prefix' => '
',
'#suffix' => '
',
);
// Build the table rows and columns.
for ($cpt = 0; $cpt <= 5; $cpt++) {
// Table row
$form['myTable'][$cpt] = $this->getTableLine($cpt);
}
$form['addRow'] = array(
    '#type' => 'button',
    '#value' => t('Add a row'),
    '#ajax' => array(
            'callback' =>  '::ajaxAddRow',
            'event' => 'click',
            'wrapper' => 'my-table-wrapper',
    ),
);

return $form;

}

Here the function called to fill the rows :

function getTableLine($key) {
    $line = array();

    $line['col_1'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 1 - row ' . $key,
    );
    $line['col_2'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 2 - row ' . $key,
    );
    $line['col_3'] = array(
            '#type' => 'textfield',
            '#default_value' => 'col 3 - row ' . $key,
    );
    return $line;
}

And the Ajax callback :

function ajaxAddRow($form, $form_state) {
    $cpt=0;
    for ($x = 0; $x <= 10 & $form['myTable'][$x]; $x++) {
        $cpt++;
    }

    // $cpt always return 6 - expected to increment
    // $form['myTable'][$cpt] is always empty

    $form['myTable'][$cpt] = $this->getTableLine($cpt);

    return $form['myTable'];

}

Details and Warnings

  Changes to the form must only be made in the form builder function
  (ajax_example_autocheckboxes() in the example here), or validation
  will fail. The callback function must not alter the form or any other
  state.

Reference: https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

It's for D7, but the concept how Ajax works has not changed:

  The Big Idea

  The big idea here is that:

  Your form gets rebuilt when you manipulate a form element (e.g. select, submit etc.)
  Your form builder function builds it a different way based on that input ($form_state)
  Your #ajax settings and your callback function arrange to deliver all or a part of the newly rebuilt form to replace or otherwise
  enhance some part of the page.


How to use an image styled by ImageCache Actions as background for a node? I am trying to implement a custom banner with some text written on it.

I have created a custom content type called banner with 2 fields: an image field and a text field.
Then I process the image field through ImageCache actions in order to apply a watermark on a photo. (fine till now)

I want to use this image (the output of imagecache_actions) as a background image of a node, so that I can apply the text on top of it.

So now node is something like the following.

 blabla

I want to change it to the following.

 blabla

Seen from a different perspective, if I could dynamically overlay some text on top of the image, then that would also do the trick!

Can you suggest any idea?

I would create some dynamic CSS on the fly and add it to the head of the document.

$styled_image_path = image_style_url('style_name', $image_path);

$css = '
.node {
  background-image: url(' . $styled_image_path . ');
}
';

drupal_add_css($css, array('type' => 'inline'));

You can add this to a hook_preprocess_node() to check for a specific node before adding to the page.


Display Content with Taxonomy on User and content matching with Multiple Vocabularies I am trying to create a view to show content that is tagged with taxonomy terms from the users profile (each vocabulary has its own field in the users profile where the user can select via check boxes what they are interested in.)

I read and watched multiple tutorials and articles on this, and the closest I can get is described here by Triskelion:

  create a user view, add relationships: Content: Tags (my Vocab) and Taxonomy term: Content with term with a contextual filter on the User:UID, then display the content:title. This works perfectly given one vocabulary, but I cannot for the life of me get it to work correctly with multiple vocabs.

I added multiples of the above relationships for each of the vocabs, and display multiple content:titles with each relationship, but the problem is that each row in the view will contain only one different title. Aggregation and Querey distinct settings don't seem to help!!

Can anyone point me in the right direction. I know there is a solution to scrap my multiple vocabularies and just put all terms into one but this is not really desirable, as id lose the structure of my taxonomy.

If I understood correctly you are trying to eliminate duplicates from your view.
Display only one title by content.

When I'm in a case when even Aggregation or Query Distinct settings don't seem to work (most of the time this is caused because the query left/inner joins),  I use a small script that does the trick to do an easy group by using the query comment field. In your case you could group by node.id

/**
 *  Found this trick on theoleschool.com.
 *
 *  Description: Allows the view developer to specify the query
 *  group by action in the query comments. Great way to force the
 *  removal of duplicates.
 *
 *  Just go into your query comments and type in "groupby:" with
 *  that colon followed by the field you want to group by.
 *
 *  Examples...
 *  groupby:node.nid
 *  groupby:file_managed_file_usage.fid
 *
 *  Ref-Comment: http://theoleschool.com/comment/496#comment-496
 *  Ref-Article: http://theoleschool.com/blog/using-hookviewsalter-add-group-statement
 */
function mymodule_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views')) {
    static $count;
    $view =& $query->getMetaData('view');

    if (strstr($groupby = $view->query->options['query_comment'], 'groupby')) {
      list($action, $field) = explode(':', $groupby);

      if (strlen($field) > 0) {
        $query->groupBy($field);
      }
    }
  }
}


Redirect anonymous users to login when they try to access home page for omega sub theme I would like to redirect my anonymous users to login when they request my Drupal website. I have found many solutions for many themes but not for omega's sub theme. I like my site to limit for authenticated users.

When I used this rule:

{ "rules_test" : {
    "LABEL" : "Test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "init" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/login" } } ]
  }
}

browser shows:

  The page isn't redirecting properly.

What 's I missing?

Implement a hook_init().

function YOURMODULE_init(){
  global $user;
  if($user->uid == 0){
    drupal_goto('user/login');
  }
}

This will work but if you have cache / reverse proxy cache enabled then you might need to consider about a JS solution too.


How to display a view within a template only if there is something to display I'm looking to embed a view within a template file BUT only if there is something being returned within the view.

I'm using this solution that I saw within the Drupal forum:

<?php
 $view = views_get_view_result($name, $display, $args);
 $result = count($view);
?>

      <?php if ($result) : ?>

Related Articles

        <?php print views_embed_view('related_articles', 'related_articles'); ?>
      <?php endif; ?>

So is this the right way to check if that view is returning anything? Or am I missing something there?

Instead of embedding a view in a template, please consider having your view output a block display, which you can place on your site using the Block System, Panels or Context.


Implementation of quicktab by codes I am trying to add quick tabs from codes. I got the code from here Creating QuickTabs programmatically not working . But noone explains how to implement this , where to add the code. I am trying to add like this.

test.module

<?php
    function test_menu(){

    $items['test/quicktabs'] = array(
        'title'=> 'quicktabs',
        'page callback' => 'test_quicktabs',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
      );
    return $items;
    }

    function test_quicktabs(){
    $tabs = array();

    $tabs[] = array(
      'title' => t('Tab1'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab1',
    );
    $tabs[] = array(
      'title' => t('Tab2'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab2',
    );
    $tabs[] = array(
      'title' => t('Tab3'),
      'type' => 'freetext',
      'text' => 'Hello wecome to Tab3',
    );

    // Configure the QuickTabs options
    $quicktabs_options = array(
       'style'   => 'Bullets',
       'ajax'    => FALSE,
    );

    $quicktabs_name = 'dynamic_quicktabs_menu';
    $quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
    return $quicktabs;

    }
?>

I am not sure , this is a correct approach . How to implement quicktabs inside other modules?

I found the solution, As previously i was not using   'renderer'    => 'quicktabs', . Also

 $tabs[] = array(
          'title' => t('Tab3'),
          'type' => 'freetext',
          'text' => 'Hello wecome to Tab3',
        );

was not working.
Use this working function.

function test_quicktabs(){

    $quicktabs_options = array(
        'style'   => 'Basic',
        'ajax'    => FALSE,
        'renderer'    => 'quicktabs',
    );

    $quicktabs_name = 'newinstance';

    $custom_tabs = array(
        array(
            'title' => 'Tab 1',
            'contents' => 'tab1',
            'weight' => -10
        ),
        array(
            'title' => 'Tab2',
            'contents' => 'tab2',
            'weight' => 0
        ));

   return  quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $custom_tabs);

}

If anyone find better implementation using quicktabs hooks. Please do answer.


Adding placeholders to the user login block's username and password input fields Task

I'm trying to add the placeholder attribute to the username and password input fields of the user login block.

Problem

When I have twig debug on, the only twig file overrides list are the following.

<!-- FILE NAME SUGGESTIONS:
* input--textfield.html.twig
x input.html.twig
-->

I don't want to use either of these twig files as it would apply to every input or every textfield.

Caveat

I'm wanting to accomplish this from within my theme not a custom module. Which I'm not sure is able to be done.

In twig it's difficult to target a specific input field. You can do this more efficient in a form alter hook, which you can use in themes too:

mytheme.theme

function mytheme_form_user_login_form_alter(&$form, $form_state) {
  $form['name']['#placeholder'] = t('placeholder for username');
}


Sending attachment on webforms with drupal 7 Dears,

I have a webform where quest can send a attachment. For registered users this works bit for guest they send the mail whitout an attachment. The file is uploaded in the webform folder. How can I fix this taht the file is send with the email?

Thanks in advance.

This is a problem of Webform ver. 7.x-4.14. Try to use 7.x-4.x-dev version of webform or apply patch #2 from https://www.drupal.org/node/2675170


What is the right way to count filled multi value field values in drupal? I've a term reference multi value field.  What is the right way to count filled values which is also portable to D8, D9 etc.

The dsm output shows like this:

$wrapper = entity_metadata_wrapper('entity_type', $entity);
dpm($wrapper->{FIELD_NAME}->count());

Dealing with entity reference field you can get the identifires like this:

dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));


How to translate comment field label? I'm using the Russian localization for Drupal sites and everything seems to be finely translated except the comment form (while viewing a node).

The field "Subject" is translated but the field label "Comment". I mean, comment's body field displays as "Comment". And what's interesting, I cannot find it in the translation list (for manual translation).

Edit content type > comment field > edit > change the text


How to create a specific menu for specific users? I'd like to know how can I create a menu like so:

Menu X which appears when a Member X performs a login, for example when a simple user login, a Menu with 4 sections appears
but when a Member Y (for example a user as manager) performs a login, instead of Menu X (= simple user menu), this time a Menu Y (menu manager with 7 sections) appears.

any suggestions?

This you can do easily with Roles for Menu module.

  This module allows you to restrict access to menu items based on user
  roles. It is used when you don't want to copy your whole menu just
  because for one specific role you want to hide one menu item.

Define the user role (in your case X and Y) in your site.
Then as per user role you can set the menu items, so the menu will be automatically gets display based on Role.

Other similar module is Menu item visibility

  This module exposes configurable and extendable visibility settings
  for menu links.

Both does pretty much similar activity.

Illustration for Menu item visibility module.

Steps:-

1. Module: Download and enable the module.

2. Creating User Role: Now, for example you want to set two user role X and Y. Hence, create by going at People/Permission/Roles -> add two user roles, like userX & userY as shown in following image.

3. Creating a User: Now, create two user, as shown in following image by going at People/ -> add new user, and give corresponding role which we created in step-2. You can see all specifications in the image.

4. Menu item creation: I have created a 7 Menuitems in the section  Main menu by going as Structure/Menus/Main menu.

Now, during the each Menu item creation, you will find the following option at the end of page, and from there selection, FOR WHICH USER YOU WANT TO SHOW THAT MENU-ITEM. Like in follwoing case we want to show Menuitem1 to userX and userY both.

I gave the user role visibility as below, because, I want to show first 4 item to userX Role and all other to userY Role.

Item               Roles Selection
Menuitem1     userX     userY
Menuitem2     userX     userY
Menuitem3     userX     userY
Menuitem4     userX     userY
Menuitem5               userY
Menuitem6               userY
Menuitem7               userY

5. Test: Now, if you Login using userXexample(which has useX role) you will see only four items, and for userYexample(which has userY role) you will see 7 items.


How to create a field with hook_update? I want to create a field with hook_update in my module.  I have the following code that creates the configuration for a field_link field:

$module_path = drupal_get_path('module', 'my_module');
$configs['field.field.paragraph.image.field_link'] = $module_path . '/config/install/field.field.paragraph.image.field_link.yml';
$configs['field.storage.paragraph.field_link'] = $module_path . '/config/install/field.storage.paragraph.field_link.yml';

foreach ($configs as $name => $config_path) {
  $data = Yaml::parse($config_path);
  $config = \Drupal::configFactory()->getEditable($name);
  $config->setData($data)->save(TRUE);
}

As far as configuration it seems to be working correctly. When I try to create a node it all displays as it should. But if you save, you get an error that the table doesn't exist. Perhaps I have to use the ConfigInstaller class.  Anyone know how to have the table get created?

Don't use the low-level config, that doesn't trigger the necessary API calls.

Use FieldConfig::create() and FieldStorageConfig::create()


Forena Reports, does not appear in the Drupal menu Structure I installed the downloaded the 8.x-1.x-dev version of the Forena module, and it installs correctly. When I go to the menu Structure to start creating the report, the Forena Reports link doesn't appear.
How can I solve this problem?
I also have the Forena UI sub-module enabled, but Forena's Release Notes include this:

Basic rendering of reports and document types are complete, however the GUI version of the report writer has not yet been ported. Sufficed to say, this version can be used by Drupal 8 report writers who are comfortable writing .frx files and sql elements by hand.

This is, pretty sure, a permission issue. So go check if the user has the relevant permissions granted. If not that's why the link is not shown either.
Some more debugging hints:

just enter relative URL /reports and see what happens next (it may be available, even though the menu item is still missing for some reason).
temporary logon with user/1 (to bypass any potential permission issues).

BTW, the GUI version of the Forena report writer is just a user interface to facilitate the design (construction) of Forena report specifications (saved in so called FRX files). So for sure that is not related in any way to your missing menu item, which if shown lists the available reports that you can execute, e.g. the sample reports.
Documentation and examples are included in the module you installed / enabled. For an illustration of that, still D7, refer to this online demo, which also includes:

Some report samples.
Forena Documentation, such as a Setup Guide (with more details about things such as Permissions to be configured) and more details about the WYSIWYG Report editor.

Disclosure: I'm a co-maintainer of (the D7 version of) this module.


How do I limit the number of Views results on specific pages? I have a Views-generated block which lists news. I would like the number of items to depend on the page it is displayed on - for instance: on the front page there's a place for 3, on another one - even 10. Is there a way to do that via a View tpl or template.php code?

I would rather not have an almost-identical copy of the View just for a different purpose.

This works for me:

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $view->items_per_page = 5;
  }
}


Using Commerce, how do I create a filterable view of "Who Bought What"? I need to create a list of users that have made purchases on my site. I need to be able to filter this list by product and show which users bought it. It is similar to how the Who Bought What module in Ubercart does it (but now I need it for commerce). Any thoughts are appreciated.

Use Views! I guess you saw that coming, right? If you're in need of great examples, check out the default Views shipped with the Commerce Reports module.

In your case, I'd create a View using Commerce Order as the base entity. I'd filter it by order state or status so you only show completed orders. I'd then add relationships to the user table and to the line item table. Through the line item table, I'd add a relationship to referenced products. This will get you all the data you need in your query, and you can then add display fields pertaining to the user / order / line item info and filter based on the SKU / title of the product. You'll probably need some sort of aggregation to group multiple purchases of the same product by the same user.

That is by no means a complete recipe, but it's basically the only way you're going to solve this short of coding a custom interface and doing it all through EntityFieldQuery.


DB query for tabular results of all a db table's info I'm really having a hard time getting my head around the DB abstraction layer.

I've got a simple 2 column table and I'd like to output the values in the at table to a template.
I've seen plain php/mysqla  like this:

$result = db_query_range('SELECT age, savingvalues FROM {savingvalues} 21, 65);
while($row = mysql_fetch_array($result))
{
echo $row['age'] . " " . $row['factor'];
echo "<br />";
}

and it's something like this I'd like to emulate, even if I have to strongarm it a bit, can anyone please help me figure this out? I'm in drupal 6

Thanks!

Steph

Use this table theming, next code created from comments below with some fixes:

  $header = array(
    array('data' => t('Age'), 'field' => 'age', 'sort' => 'asc'),
    array('data' => t('Savings'), 'field' => 'savingvalues'),
  );

  $result = pager_query("SELECT age, savingvalues FROM {savingvalues} " . tablesort_sql($header), 30);

  $data = array();
  while ($row = db_fetch_array($result)) {
    $data[] = $row;
  }
  $output .= theme('table', $header, $data);
  $output .= theme('pager');
?>


Install profile that automatically inserts data / config settings I am trying to create a custom installation profile for small internal usage and I'd like to hide certain steps and also implement new functions as a quick-and-dirty way to pre-populate some default content (nodes, blocks, menus) and configuration settings (wysiwyg) by inserting them into the database during the profile installation.

I am using the standard profile as a guide to work from as well as following this guide, but having trouble getting this to work smoothly and since it's all pre-installation I can't use devel to troubleshoot (it's not enabled yet).

Let's call the custom installation profile customprofile and the files I have are:

customprofile_profile.info
customprofile_profile.profile
customprofile_profile.install

I've figured out (for example) how to override the "Select locale" step and hard-code that to be English in customprofile_profile.profile:

function customprofile_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_select_locale']['display'] = FALSE;
  $tasks['install_select_locale']['function'] = 'customprofile_select_locale';
}

function customprofile_select_locale (&$install_state) {
  $install_state['parameters']['locale'] = 'en';
}

...but I haven't been able to track down the syntax for:

1) inserting a new step at the end of the profile install

2) inserting some SQL (I found this old post but it seems to be for Drupal 6 and both the profile syntax and SQL insertion are incompatible with Drupal 7)

Any guidance for next steps on either/both of these would be appreciated!

You might find drush-make useful, especially if you already have a codebase setup that you would like to replicate.  As outlined in this blog post:

  Drush Make includes 2 commands which are already built in Drush
  itself:

  make — Turns a .makefile into a Drupal codebase.
  make-generate — Generates a .makefile from the current Drupal site.

  Both commands are related to a .makefile — flat text file with Drush
  Make instructions. You can read more about .makefile syntax here.


How to set views configurations settings on custom module install? I have a custom module. On its installation I want to set some configuration settings of views like:

ui.show.master_display
ui.show.sql_query.enabled

to TRUE.

For this I have added a file mymod_views.settings.yml to modules/mymod/config/install/.
the content of the file is:

ui:
  show:
    additional_queries: true
    advanced_column: true
    master_display: true
    performance_statistics: true
    preview_information: true
    sql_query:
      enabled: true
      where: above
    display_embed: false
  always_live_preview: false

But on the installation of the module I am getting the following exception.

exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (mymod_views.settings) provided by mymod already
exist in active configuration' in
/var/www/drupal8/core/lib/Drupal/Core/Config/PreExistingConfigException.php:70

Can someone tells me how I will set these options through my module?

It is not possible to change or override configuration from other modules like that, you can only provide new, not yet existing configuration in config/install. The only exception to that rule are install profiles.

Instead, you need to implement hook_install() and alter the configuration there. See locale_install() for example:

\Drupal::configFactory()
  ->getEditable('views_ui.settings')
  ->set('ui.show.master_display', TRUE)
  ->save();


How to provide a filter based on json:api for referencing nodes with a term reference field? I am working with the Entity Share module to synchronize content between Drupal instances and I need a filter to define which content can be shared.

My use case is almost identical to the one mentioned in this support issue. The only differences being that the content type is a basic page and the term reference field is called field_share_to which in turn references a taxonomy vocab called Sites. I also have only two sites; 1 server and 1 client.

I am struggling to configure the correct path for term reference field and value for the term ID(64)

  Enter the machine name of the field / property you want to filter on. You can reference field / property of a referenced entity. Example: uid.name for the name of the author.

So. How to define the machine name for the jsonapi property that would return nodes filtered by term id 64?

I ask this question as a site builder rather than someone who spends a lot of time working with code.

The module maintainer was able to provide with the answer.

field_share_to.entity.tid = 64

And also with a link to further reading


drupal 7 on virtual server with debian linux - inconsistent response time I have drupal 7 test installation on shared hosting. Caching turned off (I do not want to use caching), cron disabled. According to devel, query execution times on page with 228 queries are approximately 1200ms.(some views blocks with relationships, page displayed using context) Loading time of this page is allways more than 1200ms. It is approximately 3 and more seconds. Due to time to first byte, which I am not able to cut down.
However, I decided to try the same install on virtual host running on debian linux 500mb ram. Devel shows on the same page (228 queries) time 50ms - which is great.
But, accessing time to pages is very inconsistent. Sometimes it is amazingly fast, sometimes it takes 8 seconds of waiting and then page loads. What is interesting - even if page loads after 8 seconds, the query time is allways small according to devel.  This leads me to conclusion, that there must be some bad setting on my linux installation. Can anybody point me to the right direction? Thank you

I am new to virtual servers and I think I am missing here something obvious.

500 MB is not much, unfortunately :)
and the default debian settings for Apache and MySQL are prepared for bigger servers. You should make sure the server doesnt swap.

Probably the most important setting for that is in the part mpm_prefork_module in the apache configuration (/etc/apache2/apache2.conf). You will want to have less Startservers, MinSpareServers and MaxSpareservers.

Installing APC helps, too (and is relatively easy). Even though you have to sacrifice some RAM, it speeds up the loading and reduces the RAM needed for every pageload. With 500MB, you will want to use APC only as opcode. Make sure you dont use much more stuff than 1 installation of drupal, or set APC so that other stuff doesnt get cached (the default settings caches every php file you use, thus probably pushing the important stuff away).

Enable the css + js aggregation - apart from saving roundtrips for the client, it also saves your server from serving extra files.

Also take into account that drupal does some caching internally and the times when it takes longer may be because of that - it is useful to "prime" the caches ie by crawling all pages before you start measuring.

2bits have great articles about optimizing for drupal.


Adding a link to a node in a Views export I'm using Views data export to export a view-based search as a CSV file for users. Basically it's working. However I'd like to customize how some of the fields come out in the CSV.

Specifically for this question I'm interested in learning how to export the link to the NODE that is returned. It doesn't have to be an active link per se (although that would be ideal), but just the URL to the node would be great too.

I've tried adding Content: Link to the Fields area but that just exports as 'View' for every single returned node. Not helpful.

I've tried returning my title which is currently set to link to the original content but the export doesn't return it as a link. It just returns the title.

I've tried returning the title and making it return as a link with Content: Link as the URL (absolute path selected). But that doesn't nothing.

Anyone have suggestions?

You need to add a new field "content:path" and check the option in the rewrite results section "Use absolute link (begins with "http://")". This should do what you want.

If you want to output it as a working link, you can check the option " Output this field as a link" and fill the replacement pattern [path] into "Link path".


Using Drupal 7 hashing method in Drupal 6 I want to use Drupal 7 hashing method in Drupal 6 for generating hash(not for password).
I will be using a key(say username) generate hash and store it in DB, later on when user provides username i will be generating hash for input and compare with the one that's stored in database.

include 'd7_modified_password.inc';
$key = "random_string";
print user_hash_password($key);

This generates a random string every time even though $key is unchanged. How can I use this so that I can use this method to compare two keys.

Need to use user_check_password() method to compare existing key. Guess I overlooked it earlier.


User registration form change Username to name I want to change the label of a registration form from 'Username' to name. I had used 'String overrides' module. But its not effecting. Is there any way out. please help me out.

You can do that by implementing hook_form_alter() in your custom module:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form') {
    $form['account']['name']['#title'] = t('Name');
  }
}


Snippet to hide the editing of one vocab I need a snippet that hides/omits the editing of a certain vocab on the node/edit form of a certain content type if they are not in a certain role.  All the access modules are too heavy for just this small requirement.

You will need to create a custom module with:

Drupal 6:

/**
 * implements hook_form_alter()
 */
MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'type_node_form') {

    global $user;

    // Check to see if $user has does not have the administrator role.
    if (!in_array('administrator', array_values($user->roles))) {
      //to turn all vocabularies off
      $form['taxonomy']['#access'] = FALSE;

      //turn off a single vocabulary *BELOW*
      //if you select 'tags' from your vocabulary settings
      if(issset($form['taxonomy']['tags']) {
        $form['taxonomy']['tags']['vid'] = FALSE;
      }
      else {
        //if you do not selet 'tags' from your vocabulary settings
        $form['taxonomy']['vid'] = FALSE;
      }
    }
  }
}

So there is 3 options, depending how your vocabularies are setup.  You must subsitute 'vid' for the vocabulary id.

Drupal 7:

inside hook_form_alter() like

if ($form_id == 'type_node_form') {

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['name_of_field']['#access'] = FALSE;
  }
}


Is there any way not to use the Drupal Image-style system? I upload mainly light images (around 40 kb's) to my site and also want to save room on my server and don't use 4 different folders for images --- is there any way to avoid using the Drupal image styles system? Can I safely remove the image style folders (or most of their files) and that's it? --- I will check all site pages afterwards and re add images if needed, I just don't have many pages (I have about 30). Thx.

The Drupal image style system let you upload an image in whatever form you choose, and the image style will transform it into the size, shape, etc. of the selected style according to preset rules that you find in the configuration for image styles.

One of the benefits of the Image style system is that it allows reuse of images in different styles.  You just upload the image once, and than you can use a thumbnail size version in the teaser, and a large size in the main article - or two different styles of the same image in two different nodes, etc.

There is one folder per style (I believe there are 4 default styles, but you can create and add your own styles if you want to, and this will add more folders below the styles directory).

Drupal does not create a copy of the image for a particular style until that style is requested.  While there are 4 folders, if you don't reuse an image, it will only be created in one style - meaning that there will be two copies of that image on your disk: The original, and the scaled, cropped, whatever, copy that Drupal has created for that style.

In other words, you need to condsider the (IMHO) substantial benefits of Drypal's image style system before you decide to get rid of it.

But if you don't want to use it, you can do without.

However it is a bit more involved than just removing the image style folder.

Basically, what you do is to resize, crop, etc. the image yourself, before you upload it to the site.  Then you create (by hand) a link to the original that you've uploaded from whereever you want to use it.  If you do this with all images, Drupal will never attempt to create a copy for a particular image style and the image style folder will be empty.

If you're sure you're never is going to allow Drupal to style an image, I suppose you can remove the image style folder at this point, but I would leave the empty folder it in place to avoid breaking the site if I at some point forget that I'm not supposed to use Drupal's image styles.

If you think that a lot of unused copies of images are living below the image styles folder, you can flush all (or a subset) with the following Drush CLI command:

drush image-flush

This leaves the file structure below the image styles folder in place, so if a flushed image is requested, it will automatically be recreated in the requested style.


How do you restrict specific content types per user role I'm trying to restrict specific content types per user role so that some users can only edit certain content. I've tried configuring content access module but can't seem to restrict content types.

You can set the permissions for each content type and role with Drupals default permissions.

Go to /admin/people/permissions there is a section called Node where you can set the individual permissions for each content type:

Create new content
Edit own content
Edit any content
Delete own content
Delete any content

Keep in mind that the permission Bypass content access control overrides the access restrictions of the individual content types. So if a role has this permission, the user can view, edit and delete all content.


How would I have got blog and news pages to list articles/blogposts, how do I edit? I have a 'blog' page that lists blog posts and a 'news/events' page that lists articles.

I cannot remember how they got there, if they were automatically generated. I think I had to do something at least for the articles page, but I cannot find anything about why mysite.com/news lists all the articles and how mysite.com/blog lists blog posts. I've looked through structure and content and views and don't see where this is coming from and I have no hover in the admin interface to edit the whole page (just individual posts). These pages seem not to have any titles set, either.

The main concern here is in the menu right now they are absolute links and I want to be dynamic, relative paths.. but I don't know what to put for that. I also need to make sure they properly get an 'active' state in the menu, which currently they do not!

In Drupal 7, go to /admin/structure/menu/manage/ to manage your menus. Select "Main Menu" as that will probably be your primary navigation.

Click +Add Link. For both Blog and News, set the appropriate name in the "Title" field.

For path, set the Blog path to "blog" or for News you can set it to "home" to retrieve articles promoted to the front page, or something like "news" if you have a specific page with a path set to that for those articles to be displayed on.


D8 - Entity Load Cache First of all. Are

$ent = Drupal\custom_entity\Entity\MyEntity::load(1);

and

 $ent = \Drupal::entityTypeManager()->getStorage('custom_entity')->load(1);

the same?

Also I know that
\Drupal::entityTypeManager()->getStorage('custom_entity')->load()
is getting cached.

When I talk directly to the class's load function also?

Thanks

First of all. Are ... and ... the same?

Assuming your entity type class doesn't override Entity::load to do something different, yes they are the same. If you look at that method you can see it uses exactly the same op:

public static function load($id) {
  $entity_type_repository = \Drupal::service('entity_type.repository');
  $entity_type_manager = \Drupal::entityTypeManager();
  $storage = $entity_type_manager
    ->getStorage($entity_type_repository
    ->getEntityTypeFromClass(get_called_class()));
  return $storage
    ->load($id);
}

So Entity::load is simply a shortcut to loading the entity via the manager service.

  When I talk directly to the class's load function also?

They're identical operations, so yes, they share the same caching.


Using the URI to highlight menu items I have a content type on my site called "Articles".
I created a view that lists the nodes of this content type.  It's path is "/articles"
For that view, I created a menu item in my main menu, "Articles".
I used the pathauto module for all my nodes of this content type to have the path articles/[node:title]

My question is, I want the menu item to remain highlighted if the user is viewing a single article node, or if the user is viewing the view.

I solved the issue by using theme_menu_link() function in my template.php file for my theme (code below).  Being new to the Drupal API, is there a better way to do it?

What I did:

function mytheme_menu_link(array $variables) {

  //Some variables, we're using
  $element = $variables['element'];
  $sub_menu = '';

  //#href is an element inside the item
  $the_path = drupal_lookup_path('alias', $element['#href']) ?: $element['#href'];

  //Compare the path to the actual URI (using sub-function), and if they match, then add a new CSS class
  //either: 'uri-active' or 'uri-active-trail'
  switch(mytheme__menu_detect_uri($the_path)) {
    case 1:  $element['#attributes']['class'][] = 'path-active'; break;
    case -1: $element['#attributes']['class'][] = 'path-active-trail'; break;
  }

  //If there are sub-menu items under this, render those too
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  //Return the output
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

/**
 * Detect if a given path matches the current URI, as detected
 * from reading the current_path() alias from Drupal
 *
 * @param string $path_to_check  The path to check
 * @param string $check_against  The path to check against (leave blank for current path)
 * @reutrn int   1 = Matches, 0 = No Match, -1 = In Active Path
 */
function mytheme__menu_detect_uri($menu_item_path, $actual_path = NULL)
{
  if (is_null($actual_path))
    $actual_path = drupal_lookup_path('alias', current_path()) ?: current_path();

  //Compare em
  if (strcasecmp($menu_item_path, $actual_path) == 0)
   return 1;
  elseif (strlen($actual_path) > strlen($menu_item_path) && strcasecmp(substr($actual_path, 0, strlen($menu_item_path)), $menu_item_path) == 0)
    return -1;
  else
    return 0;
}

the context module allows you to highlight a menu item if certain condition (like a path) has been met.


slideshow_view: how to rewrite the output? I have a content-type "gallery " which is composed of:

Field Image
Field Link (which is an EXTERNAL link like www.google.com or http://exemple.org)

so i've created a view with the link field hidden(the widget of the link field is: "Title, as Link (default)") and the image field

how should I rewrite the output of the image field to put the external link into the image?

i've tried with this:
    [field_image_1] but this is not working

Method : 1

  Place the link above the image field in the views.
  Exclude it from display
  Now rewrite the results of the image
  a href="[field_link]" image field
  This will create the link to the image, so when clicking it will lead the page.

Method :2

  Place the link above the image field in the views.
  Exclude it from display
  Select "output this field as link"
  Click the replacement pattern here, and use the link in the text field
  This will create the link to the image, so when clicking it will lead the
  page.


How to convert Drupal 6 profile taxonomy value to array? In Drupal 6, Profile module stores taxonomy values for users with this format:

a:3:{s:17:"Local Development";s:17:"Local Development";s:35:"Environmental Policy and Management";s:35:"Environmental Policy and Management";s:22:"Environmental Research";s:22:"Environmental Research";}

Is there a way to programmatically convert that to an array using PHP and/or Drupal 7 functions?

This is the array I would like to obtain:

Local Development
Environmental Policy and Management
Environmental Research

The drupal stores the users data in serialized format to get it in array format  you can use
unserialize ( string $str [, array $options ] )
function in php.
here is the example for you to get better understanding PHP : unserialize() function


How to open a link of node in custom region? I create a custom region in sub-theme. I have constructed a map, on which there is a markers when you click on a link (Image 1) description opens on a full page (as on Image 2). How to open a description in the custom region? (example of custom region is on Image 1) Also I need to transition link eg http://localhost/node/32 to open map (front page) and opens the description in the custom region?
Someone had to deal with such a task? How this functionality can be implemented?

Image-1

Image-2

You can create your block programmatically as explained in this post, and then in the block_view function, add the content of your node as the block's content, for example:

$imported_node = node_load($imported_nid);
$block['title'] = $imported_node->title;
$block['content'] = $imported_node->body;

You will have to tweak the values to fit your node content, structure you want to output


How to add taxonomy term reference field in a custom drupal form A menu item is defined with drupal_get_form as callback function and returning the form from call back function. How can I add taxonomy_term_reference field to this form?

$items['files/add'] = array(
      'title' => 'Add file',
      'description' => 'Allows users to add files',
      'type' => MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_add_file'),
      'access callback' => TRUE,
    );
function mymodule_add_file($form, &$form_state) {
    drupal_set_title("Add file");
    $form['mymodule_form'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#collapsable' => FALSE,
      '#title' => 'Adding file to locker room',
    );

    $form['mymodule_form']['file'] = array(
      '#type' => 'managed_file',
      '#title' => 'Upload file',
    );

    $form['mymodule_form']['tag'] = array(
      '#type' => 'taxonomy_term_reference',
      '#title' => 'Tags',
    );

    return $form;
}

I am not sure how to add taxonomy_term_reference field for $form['mymodule_form']['tag'] . I want this field to be a text field with auto complete from a vocabulary terms and new term to be added when entered term is not found

For Drupal 7, the code is something like this, where field_tags is a taxonomy field in the node with widget type autocomplete.

<?php
   $node=node_load($nid);
    $tags = array();
    foreach ($node->field_tags['und'] as $item) {
      $tags[$item['tid']] = isset($item['taxonomy_term']) ?  $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
    }
    $form['tags'] = array(
      '#type' => 'textfield',
      '#default_value' => taxonomy_implode_tags($tags),
      '#title' => 'Add Tags',
      '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#maxlength' => 1024,
      '#element_validate' => array('taxonomy_autocomplete_validate')
    );
?>


Content type disappears in content list I created a taxonomy with the same name as a content type. Now the list shows with no content type on the nodes with that type. I have since renamed the taxonomy, but there is still an issue.
When trying to edit the node from the admin menu I get the following error:

Notice: Undefined index: case_studies_node_form in drupal_retrieve_form() (line 750 of C:\wamp\www\ppi\includes\form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'case_studies_node_form' not found or invalid function name in drupal_retrieve_form() (line 785 of C:\wamp\www\ppi\includes\form.inc).

I checked the database and the nodes have the correct type in the content table, and the content types table still has the "Case Studies" type.

Suggestions:

Make sure the module handling custom node type exists and is enabled.

Based on case_studies_node_form callback, it's most likely case_studies module.

If you don't know type of the node, you can load it using drush, e.g.

drush ev "var_dump(node_load(123));"

Make sure the module which handles custom node type defines hook_node_info() in its .module file.
Clear caches (drush cc all, restart Memcached/Redis if present).


Where can I configure user and admin email message in Ubercart cart module? Where can I configure user and admin email message in Ubercart cart module in Drupal 7?

I want to change the email body of user notification email and admin.

Go to

  sites/all/module/ubercart/uc_order/templates/

than select file user or admin


How do I format a field in views? I have an FAQ page, where in the title it has some html tags, I would like to show the title in the views. When the view is displayed, it is showing html tags as well. How can I get the html processed value.

Is it possible?

Have you checked title field's settings section in views.
There is a option for "Style settings" you can check the option for restrict or add new html tags.


How can I alter bundles of commerce_order_item entity type using custom module I am trying to alter bundles of commerce_order_item -

core.entity_form_mode.commerce_order_item.add_to_cart_confirmation.yml

langcode: en
status: true
dependencies:
  module:
    - commerce_order
  enforced:
    module:
      - commerce_add_to_cart_confirmation
id: commerce_order_item.add_to_cart_confirmation
label: 'Add to Cart Confirmation'
targetEntityType: commerce_order_item
cache: true

.module file

function commerce_add_to_cart_confirmation_entity_bundle_info_alter(&$bundles){
  $storage = \Drupal::entityTypeManager()->getStorage('entity_form_display');
  foreach ($bundles['commerce_order_item'] as $bundle_key => $bundle_value) {
    if($bundle_key !== 'default'){
      $form_display = $storage->load('commerce_order_item.' . $bundle_key . '.add_to_cart_confirmation');
      if (!$form_display) {
        /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
        $form_display = $storage->create([
          'targetEntityType' => 'commerce_order_item',
          'bundle' => $bundle_key,
          'mode' => 'add_to_cart_confirmation',
          'status' => TRUE,
        ]);
        // Hide the unit price by default.
        $form_display->removeComponent('unit_price');
        // Hide the quantity by default.
        $form_display->removeComponent('quantity');
        $form_display->save();
        $form_display->enable();
      }
    }
  }
}

But at $form_display->save(); is am getting below error -

Error: Call to a member function getConfigDependencyName() on null in /var/www/drupal/core/lib/Drupal/Core/Entity/EntityDisplayBase.php on line 314 #0 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(346): Drupal\\Core\\Entity\\EntityDisplayBase->calculateDependencies()\n#1 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityDisplayBase.php(266): Drupal\\Core\\Config\\Entity\\ConfigEntityBase->preSave(Object(Drupal\\Core\\Config\\Entity\\ConfigEntityStorage), true)\n#2 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityStorageBase.php(434): Drupal\\Core\\Entity\\EntityDisplayBase->preSave(Object(Drupal\\Core\\Config\\Entity\\ConfigEntityStorage))\n#3 /var/www/drupal/core/lib/Drupal/Core/Entity/EntityStorageBase.php(389): Drupal\\Core\\Entity\\EntityStorageBase->doPreSave(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#4 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(259): Drupal\\Core\\Entity\\EntityStorageBase->save(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#5 /var/www/drupal/core/lib/Drupal/Core/Entity/Entity.php(377): Drupal\\Core\\Config\\Entity\\ConfigEntityStorage->save(Object(Drupal\\Core\\Entity\\Entity\\EntityFormDisplay))\n#6 /var/www/drupal/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(637): Drupal\\Core\\Entity\\Entity->save()\n#7 /var/www/drupal/modules/custom/commerce_add_to_cart_confirmation/commerce_add_to_cart_confirmation.module(116)

This is annoying because same code is running for hook_confirmation_entity_bundle_create($entity_type_id, $bundle). Please advice what should I do to save the bundle.If there is another way to achieve what I am trying to achieve, please tell me.

Thanks Guys

add_to_cart_confirmation needs to be a a defined entity form mode, that's most likely the error in your case. Provide it as default configuration in your module or check its existence or create it if necessary.

See how node defines the teaser view mode as an example, or user the register form mode.


DB Query replaces %s inside LIKE operator I have one query like :

db_query("SELECT * FROM {foo} WHERE bar LIKE '%supply%' LIMIT %d,%d", 0, 10)

Now if I use db_query API it will replace %s with the argument supplied and resulting query will be like

SELECT * FROM foo WHERE bar LIKE '0upply%' LIMIT 0, 0

Any ideas to overcome this ? I dont want to use mysql_query()

I am using temporarily _db_query()

You just need to escape % signs with another % sign in a Drupal db query:

db_query("SELECT * FROM {foo} WHERE bar LIKE '%%supply%%' LIMIT %d,%d", 0, 10);

If you wanted to use a placeholder it would be like so:

db_query("SELECT * FROM {foo} WHERE bar LIKE '%%%s%%' LIMIT %d,%d", 'supply', 0, 10);


Make a view or panel that displays image *or* video field if present My goal is to have a content type that will display an image in a certain panel pane or an embedded video, if the video is present.

I can imagine setting up two fields, one for the image and one for the video embed code. But I'm not sure how to hide the image if the video is present or to make the video field take precedence over the image field in panels.

It can be done with Views rewriting options.

Add both fields (Image before Video) to Views and exclude Image field from output.

For Video field set “NO RESULTS BEHAVIOR” to Image field token:

It means that if Video field is empty Views will get value from this textarea, which contains special placeholders (in this case [field_image]).

Available tokens for your fields can be found under “REWRITE RESULTS” fieldset:

Don't forget to uncheck “Rewrite the output of this field” flag.


Login to external server from Drupal site Is there any way to customize Drupal login to use authentication from an external server?

I'd like to know about any modules or if Drupal core can implement this function.

Source code:

// Include FirePHP for debug

function authdave_form_alter(&$form, &$form_state, $form_id) {
    // Authentication based on username and password
    if ( ($form_id == 'user_login' || $form_id == 'user_login_block') ) {
        $form['#validate'][] = 'authdave_user_form_validate';
    }
}
/**
* Custom form validation function
*/
function authdave_user_form_validate($form, &$form_state) {
    if( !authdave_authenticate($form_state) ) {
        form_set_error('name', t('Unrecognize username.'));
    }
}
/**
* Custom user authentication function
*/
function authdave_authenticate($form_state) {
    // get first four characters from user name
    $complete_username = $form_state['input']['name'];
    $password = $form_state['input']['pass'];

    // retrieve users credentials from DB
    $credential = get_all_credentials();

    while($row = $credential->fetch_assoc()) {
        // check if there are any match
        if ( $row["username"] ==  $complete_username && $row["password"] == $password) {
            user_external_login_register($complete_username, 'custom_athentication');
            return TRUE;
        }
    }

    return FALSE;

}

function get_all_credentials() {

    //credenziali di accesso al dbms
    $server = "****";
    $username = "***";
    $password = "***";

    //nome db
    $db_name = "credenziali_db";

    //creo una connessione con il dbms
    $conn = new mysqli($server, $username, $password, $db_name);

    if ($conn -> connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    echo "Connection successfully";

    //sql query
    $sql = "SELECT username, password FROM credenziali";
    $result = $conn -> query($sql); //risultato della query

    return $result;

}

?>

This depends what you mean by external server? There's a tonne of contribution modules at the moment that support a variety of external logins.

You can implement Open Auth 2 to allow a single sign on:

https://www.drupal.org/project/oauth2_authentication

Or you can use Facebooks Oauth authentication:

https://www.drupal.org/project/fboauth


How can we change the default URL what we get through the view blocks on a basic page? I am working on a site, I had used a view block on a basic page, this view block has a pager. When we navigate through the pager links we are getting url structure like this

http://www.website.com/page-name?page=1
*http://www.website.com/page-name?page=2*

I want to remove this ?page=1 from the url and want to modify it to page-name-1 and so on.

You can use the Clean Pagination module to get reasonably close:

  Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.

If that doesn't do the trick that module should at least serve as a good starting point to convert the pager to exactly what you're looking for.


How do I know what setSetting is suppose to be? I am creating a custom content entity and in the BaseFieldDefinitions, I am trying to create a field for assigning a user as the designated assigner and will follow up with a assignee. So far, the code has been pretty easy to follow and makes sense, except for setSetting.

Basically the field below works, but its copy and pasted from drupal console as boiler plate code. What I don't understand is the setSetting part. If I comment out ->setSetting('target_type', 'user'), the field displays but no longer works.

So my question is, how am I suppose to know, or figure out, that I should be typing in 'target_type' and value 'user'? I went through the API but haven't managed to find any references to this. And I don't understand the setSetting below it either, 'handler' = 'default. I can comment that out and it works fine. So what gives?

How am I suppose to know what to set in the setSettings part? As I also noticed, not every field definition even has this.

$fields['assigner'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Assigner'))
  ->setDescription('The person who will issue this Task.')
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
      'label' => 'hidden',
      'type' => 'author',
      'weight' => 0,
  ])
  ->setDisplayOptions('form', [
      'type' => 'entity_reference_autocomplete',
      'weight' => 5,
      'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
      ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

You can look at the source code of the corresponding field type class to get an idea of the available settings.

target_type is something specific for an ER field

Base classes for field types provided in Drupal core

Almost all field types are derived from one of the above base classes, e.g. there are several number field types deriving from NumericItemBase

Custom field types are usually located in module_name/src/Plugin/Field/FieldType


Get title of referenced item two levels deep with Search API I have three content types: A, B and C.

A refers to B
and B refers to C

Now with use of the search api module I search my content types and I want to only output C. But in the result I want to show under which items the C is put. So some kind of breadcrumb. A view row should look like:

Type: C

Title of node

Found in: A > B

I am able to output the title of B but for some reason I'am not able to get the title of A. I tried to work with relationships in view but the A reference is not shown even not when I add B as a relation. I tried adding the content types to my search index and tried adding them direct as field to my search index ( field_content_B:entity:field_content_A:entity:title ). But nothing works. Can someone help me with figuring out what goes wrong?

None of the relations information is stored in C, so when you have C views it can't show relations info out-of-box.

Usually the way to show the "Child" for a "Parent" node is by using the Contextual filter for the Entity Reference field with the "provide default value" and "Content ID from URL" options. In your case A is a child of B, and B is a child of C.

Then you can use the Custom text field to construct your text, you can use the Contextual arguments in that field, this will give you information about the "Child" of the node in view row.

Maybe you can work through that to get to the "Grandchild" info, I haven't tried it.

I'd suggest chaining the reverse Relationships, they are called something like "Content referenced from field_my_reference", first you add the one for the child, then add another Relationship for the grandchild, and make the second Relationship use the First one. That's how you get to correct nodes.

Add the fields for the B and A titles with using the correct Relationship for each. Thena again you can use the Custom text field to override how their output is worded. You can "Exclude from display" the fields you use in Custom text after you have it showing the way you want inside Custom text.


Author name in comment preview not rendering apostrophe properly: a bug or by-design? This happens on a Drupal 7.26 using the default theme when previewing a comment. The &#039 part is equivalent to an apostrophe. What I don't know if this is something that is part of Drupal to prevent exploits or if this is a bug that should be fixed. I tried searching the Drupal.org forums if this is a bug, I wasn't able to find anything relevant.

Interesting problem to solve ... Here are the findings of above problem.. I do see this issue in latest Drupal..  I believe it's a bug since check_plain method is not used in any other comment rendering features where as we can see proper name while viewing comment...

Comment preview is rendered from comment_preview function defined in 2062 Line in comment module..

/**
 * Generate a comment preview.
 */
function comment_preview($comment) {
  global $user;

  drupal_set_title(t('Preview comment'), PASS_THROUGH);

  $node = node_load($comment->nid);

  if (!form_get_errors()) {
    $comment_body = field_get_items('comment', $comment, 'comment_body');
    $comment->format = $comment_body[0]['format'];
    // Attach the user and time information.
    if (!empty($comment->name)) {
      $account = user_load_by_name($comment->name);
    }
    elseif ($user->uid && empty($comment->is_anonymous)) {
      $account = $user;
    }

    if (!empty($account->uid)) {
      $comment->uid = $account->uid;
      $comment->name = check_plain($account->name);
      $comment->signature = $account->signature;
      $comment->signature_format = $account->signature_format;
      $comment->picture = $account->picture;
    }
    elseif (empty($comment->name)) {
      $comment->name = variable_get('anonymous', t('Anonymous'));
    }

    $comment->created = !empty($comment->created) ? $comment->created : REQUEST_TIME;
    $comment->changed = REQUEST_TIME;
    $comment->in_preview = TRUE;
    $comment_build = comment_view($comment, $node);
    $comment_build['#weight'] = -100;

    $form['comment_preview'] = $comment_build;
  }

  if ($comment->pid) {
    $build = array();
    if ($comments = comment_load_multiple(array($comment->pid), array('status' => COMMENT_PUBLISHED))) {
      $parent_comment = $comments[$comment->pid];
      $build = comment_view($parent_comment, $node);
    }
  }
  else {
    $build = node_view($node);
  }

  $form['comment_output_below'] = $build;
  $form['comment_output_below']['#weight'] = 100;

  return $form;
}

As you can see

$comment->name = check_plain($account->name);

Comment name is rendered using above statement which takes $account->name as input and wraps using check_plain function which "Encodes special characters in a plain-text string for display as HTML."

Coming to the solution..

Comment Preview is rendered using Comment_view Function which gives us hook "hook_comment_view"
By Implementing above hook in your custom module you can check for $account->name and use htmlspecialchars_decode to decode back to original value...


Create Bundle Product link - Not found, missing I have done a basic install of Drupal v7.43 with Commerce Kickstart (commerce_kickstart-7.x-2.34)
Both Commerce Bundle modules are enabled.

In "Add Product" actions I cannot find the "Bundle Product" link in order to create a new Bundle Product with some of the existing (previous added) Bundle Groups.

Also, the "Create Bundle Group" link is missing but I found it in the page: /admin/commerce/products/add.

Why are they missing?

They are missing because of how Kickstart manages it's menus.

The easiest way to fix this is to just disable the Commerce Kickstart Menus (commerce_kickstart_menus) module. You may need to clear all of your caches, but you should see the other items start to show up again.


Simple debug results in internal server error All I want to do is print a view out so I can check the variables and see the structure of what's being created but it results in an internal server error.

I'm using Acquia Dev Desktop. I've checked the .htaccess file and it has the rewritebase uncommented. I've tried updating max_execution_time, and memory_limit. Nothing helps.

I have Drupal 8 installed fine and haven't had any issues except when trying to inspect variables.

BTW here is my function in theme file:

function theme_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  print_r($view);
}

What am I doing wrong?

Hi!! you can use a official symfony dumper, insert this line on the file "composer.json"

"require-dev": {
    "symfony/var-dumper":"3.0.4"
  }

run the follow command:

composer install "symfony/var-dumper"

or

composer update

you can use in your code with these line:

dump($variable_name);

enjoy!!! ;)


how to wrap drupals taxonomy term node list in a div i need to wrap the nodes teaser in a div for my taxonomy term page but cant figure out how.

this is my page , this is a list of nodes for the products taxonomy term, using node--product.tpl.php i warped the individual node in

 but now i need to wrap the list of nodes in

 and just for the products taxonomy term page listing ...

how can i do this ???

One option you have is to override page.tpl.php and wrap the "content" render:

      <div class="row">
        <?php print render($page['content']); ?>
      </div>

This will encapsulate your whole taxonomy-term.tpl.php, where your node list is.


Showing a message while downloading a file from hook_form_submit I have a form which creates a csv file and starts a download if it is successful. I also attempt to show a success message at this point but it never shows up because I use drupal_goto to download the file and since it is a file download the page does not refresh:

drupal_set_message("Student accounts created. Please keep the roster CSV filed that has just been download for your future use.");

drupal_goto( file_create_url($file->uri));

Another problem here is that any warning messages from previous failed validation (in hook_form_validate) remain on the page even after success. How Can I the page to refresh while starting a download from hook_form_submit?

Your workflow lacks one step. What you want it to be, is:

Send user to "Your download should start shortly" page. On that page, place a script that will execute file download in new window after some arguably small timeout, and a target="_blank" link to the file, for cases when auto-downloading is disabled client side for security reasons.
When the script executes successfully and starts to download file for user, or when user clicks the link to direct download, use JS to send him to "thank you" page. Of course if JS fails, it might not get executed, so be sure all courtesy you really need is also displayed on the page mentioned in point one.


Custom region twig template for region into node twig template I did add a custom region to my theme via my .info.yml file :

regions:
  node_col_1: 'Bloc pour colonne 1'

and in my .theme file to make it available for node template:

function starterpf_d8_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = ['full']; // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to starterpf_d8_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    // Liste des régions utilisées directement dans les node.html.twig
    $allowed_regions = [
      'pole_col1','pole_col2','pole_col3','pole_col4',
      'node_col_1','node_col_2','node_col_3','node_col_4','node_col_5',
      'revue_presse','sortie_action','actuAssociation','projets','intervenants'
      ];
    starterpf_d8_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function starterpf_d8_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

Then I try to apply a custom template for this region but it seem not to work,and twig doesn't provide suggestions like for block,field,etc..
My file is called : region--node_col_1.html.twig
His content:

{%
  set classes = [
    'region',
    'region-' ~ region|clean_class,
  ]
%}
{% if content %}
  <div{{ attributes.addClass(classes) }}>
    {{ content }}
  </div>
{% endif %}

What do I miss ?
Thanks for help

EDIT: After test, template suggestion work for custom region added to page.html.twig but not for region added to a node.html.twig...folder structure seem not to be the way,most probably a hook in .theme file.

EDIT : someone could help me for the theme_suggestions_block_alter ?

I think your filename is incorrect. It should be:

region--node-col-1.html.twig.

Enable twig debugging to see the suggestions output in the HTML source, which will paint a better picture of what Drupal is expecting to see as template overrides.


Display shipping subtotal including taxes I'm settings up a shop with VAT and shipping. All works well except just one thing fails, when I include VAT in the shipping rate the price component displays the amount excluding taxes. But I want the full amount including taxes to be displayed.
How can I achieve this?

This is happening because the "Order Total" process combines like price components together and then lists them out. As a result, the base shipping rate component is appearing unaltered and the VAT is being combined into any other product VAT (or shipping VAT) components. It's an unfortunate display side effect of the implementation of price components, but it's on the roadmap to be updated in Commerce 2.x.

In the meantime, your solution will involve implementing hook_commerce_price_formatted_components_alter(), which you can find documented in commerce_price.api.php. This is purely a display alteration, so all the necessary data will still be there unaltered - you can just fiddle with the display amounts of the price components so your VAT component gets added to your shipping component instead.


All Pages Redirecting To Frontpage I am hoping that someone could assist me with a Pressflow problem on here as i cant find anywhere at all to discuss Pressflow. I have just updated my site to the latest version of Pressflow which was updated with the recent Drupal update. I uploaded all the files and now i can only access the frontpage of my site.

http://onlinebanter.com

If you try to click any links it just displays the front page. Would it be something to do with the htaccess file possibly?

All help appreciated as my site is effectively down with this problem and i dont know where to turn nor have the technical know how.

Thanks

Thanks Malks. Yip it was the htaccess file i overwrote folks. I just edited that again with my website url in 2 spots and everything was hunky dory again.


Load Preceding Nodes in a View Block Sorted by Date in Relation to the Current Node Currently I have a basic View block just showing a bunch of articles in a teaser format. I added this view block to show up below the content of each article page. What I want is to be able to show the preceding articles in relation to the node you are currently viewing by the next future date.

The only extra thing in this view is that I added in contextual filters for NID. I am passing in multiple values into this view block, so YES i do have it "multiple values" checked off.

But I'm not sure why its not working. Technically it should be as it is in fact returning a string of NID's as outputted below:

if (arg(0) == 'node') {
  $node = menu_get_object();
}
$curNode = $node->nid;
$curNodeDate = $node->created;

dsm($node);

$type = "article";
$nodes = node_load_multiple(array(), array('type' => $type));

dsm($nodes);

$finalNid = array();

foreach($nodes as $products):
  if( intval($products->created) > intval($curNodeDate)  ){
dsm($products->created .'>'. $curNodeDate .'---'. $products->nid .'~~'. $products->title );
    $finalNid[] = $products->nid;
  }
endforeach;

foreach($nodes as $products):
  if( intval($products->created) < intval($curNodeDate)  ){
dsm($products->created .'<'. $curNodeDate .'---'. $products->nid .'~~'. $products->title );
    $finalNid[] = $products->nid;
  }
endforeach;

dsm(implode("," , $finalNid));

return implode("," , $finalNid);

When running that code I get the following dsm output:

1416508384>1416508382---65~~Rimmel's Georgia May Jagger & COTY partner with DBC
1416508383>1416508382---66~~Daisy Marc Jacobs Tweetshop Grabs the Attention of the Industry
1416508390>1416508382---68~~COTY's Mario Reis
1416508386>1416508382---71~~Beauty Trends for this Holiday Season
1416508385>1416508382---72~~COTY’s Catherine Walsh Honored
1416508388>1416508382---74~~ONE COTY - Looking at COTY as a Whole
1416508387>1416508382---75~~Roberto Cavalli
1416508389>1416508382---80~~A modern story of seduction
1416764226>1416508382---86~~Sir Ken Robinson
1416810455>1416508382---87~~COTY’s Svetlana Omelchenko makes the 2014 Top 100 OUTstanding LGBT Business Leaders List
1413318695<1416508382---2~~philosophy bringing hope & grace to mental health efforts
1413318711<1416508382---3~~Q&A with Ann Gottlieb
1413402303<1416508382---6~~Meet COTY CMO of Skincare
1416508381<1416508382---67~~Spotlight On Leadership: David Booth
1415666899<1416508382---73~~Creative Collaborations: COTY and Avon
65,66,68,71,72,74,75,80,86,87,2,3,6,67,73

<?php

$curnode = menu_get_object();
if (!$curnode) return '';

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('created', $curnode->created, '<=')
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 10); //CHANGE RANGE FOR YOUR LIMITS

$result = $query->execute();

$items = array();
if (isset($result['node'])) {
  $nodes_nids = array_keys($result['node']);
  $nodes = entity_load('node', $nodes_nids);
  foreach ($nodes as $node) {
    $items[] = l($node->title, 'node/' . $node->nid);
  }
}

return theme('item_list', array('items' => $items));

?>


Which modules should I use to create a community based site? I am a grey-haired professional programmer, quiet conversant in PHP, MySql, HTL, CSS which means I can tweak things or code plugins if need be, but I’d like something off the shelf as far as possible.

I am trying to create a social site for ex-pats to help them adjust to their new country. Preparing to get there, legal/visa issues, employment opportunities, accommodation, shopping, plus social stuff.

The demographic is mainly girls in their 20s, so a social angle is important. Integration of FaceBook, Flikr & the like might be nice. What I am thinking of is

main content provided by me and a few moderators
a Wiki to which everyone can contribute
forums for discussions
small ads/freebie
user registration (which may limit access to certain parts of the site)
groups of friends, with shared .. stuff (photos, discussion rooms, etc)
per user blog
per user photo album
mailing lists

As I said, I was originally set on Drupal, which also has some pre-configured distros, but I didn’t find one yet that really matches my needs.

Do you have any suggestions?

If you mostly want to configure, a distribution is probably your best bet. Looking at your requirements, I'd say take a look at Drupal Commons. It will get you most of the features you need, and you can turn on/off features as needed. The rest of your feature set can be added with specific modules.


How to add body class that carries the menu depth of the current page? I am on Drupal 7. On the body tag, I need to create a new class that will detect the current page's menu depth. The class could carry the ID of the menu, then something that would detect the current page's menu depth. It could be something like: "primary-depth-0" for the top menu items, then "primary-depth-1", "primary-depth-2" and so forth... Is it easy to code that on template.php? I assume I have to add a new item into the $classes array...

Thank you.

I did something similar in the past, but I can't remember on which project, so I don't have working code.

Inside a template_preprocess_html, you get the breadcrumb via menu_get_active_breadcrumb.  You then walk the breadcrump  keeping track of depth, comparing the paths against the current path.  When you find a match, you end the walk and then

$variables['classes_array'][] = "menu-depth-" . $depth;

I am pretty sure this is what I did.


2 seperate feeds updating the same set of nodes (feeds module) I'm using the feeds module to pull in a set of publications into a Drupal content type.  They are set to run at regular intervals using cron.  I have two separate feeds, which should work as follows:

Feed 1 (pure_feed) - pulls in the bulk of the fields
Feed 2 (harvard_format) - accesses a separate url source and updates one field on the content type.

The problem I have is that feed 2 always creates a new set of nodes rather than updating the existing nodes (that were created using feed 1).  I have used the debug options at /import and can see that the GUIDs for feed 2 match the GUIDs for feed 1, but it still creates 2 sets of nodes rather than updating the 1 set of nodes.

Here is an excerpt from the feeds_items database table:

As you can see they both have the same GUID but they are mapped to separate nodes.  Is there any way to have the second feed map to the same nodes as the first feed?

EDIT: there's a patch in this thread: https://www.drupal.org/node/1539224

I knocked something together that allows my second feed to update the nodes from my first feed. Not sure if this is the right way of doing things but it works. Here's what I did in case it helps someone else in future:

Created a custom processor that extends FeedsNodeProcessor
Copied across all of FeedsNodeProcessor's functions to the new class.
Overrided the existingEntityId function as follows (harvard_format is my secondary feed and pure_feed is my primary feed):

protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {

if($source->id == 'harvard_format') {

  $query = db_select('feeds_item')
    ->fields('feeds_item', array('entity_id'))
    ->condition('feed_nid', $source->feed_nid)
    ->condition('entity_type', $this->entityType())
    ->condition('id', 'pure_feed');

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'url':
        $entity_id = $query->condition('url', $value)->execute()->fetchField();
        break;
      case 'guid':
        $entity_id = $query->condition('guid', $value)->execute()->fetchField();
        break;
    }
    if (isset($entity_id)) {
      // Return with the content id found.
      return $entity_id;
    }
  }
  return 0;
}
elseif ($nid = parent::existingEntityId($source, $result)) {
  return $nid;
} else {

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'nid':
        $nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
        break;
      case 'title':
        $nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->config['content_type']))->fetchField();
        break;
      case 'feeds_source':
        if ($id = feeds_get_importer_id($this->config['content_type'])) {
          $nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
        }
        break;
    }
    if ($nid) {
      // Return with the first nid found.
      return $nid;
    }
  }
  return 0;
}

}

Copied across the the Process and newItemInfo functions from FeedsProcessor.
Overrided newItemInfo as follows:

protected function newItemInfo($entity, $feed_nid, $hash = '') {

$entity->feeds_item = new stdClass();
$entity->feeds_item->entity_id = 0;
$entity->feeds_item->entity_type = $this->entityType();
// Specify the feed id, otherwise pure_feed's entries in the feeds_item table will be changed to harvard_format
$entity->feeds_item->id = ($this->id == "harvard_format") ? "pure_feed" : $this->id;
$entity->feeds_item->feed_nid = $feed_nid;
$entity->feeds_item->imported = REQUEST_TIME;
$entity->feeds_item->hash = $hash;
$entity->feeds_item->url = '';
$entity->feeds_item->guid = '';

}


Conditional fields module - Required fields that are hidden are still required to be filled I'm using the Conditional Fields module to create dependencies that hide/show certain fields in a shipping/billing information form.

In the form, I have 1 "List (text), select list" field which is used to select the dependees for 3 dependents. The dependents are 2 "List (text), select list" fields and 1 "Text" field. All fields are set to be required in their field settings.

I have each dependent set to be invisible unless its' dependency is triggered. My problem is that after triggering one dependency, the 2 remaining dependents, which are hidden, are still required even though they are hidden. When submitting a form, this causes an error message to display saying:

"x field is required

y field is required"

::My settings for each dependent are as follows::

Condition: Value

Values input mode: None of these values (NOT)

Set of values: "My selected value(s) that trigger(s) the dependency"

Interaction with other dependencies: XOR

Form state: Invisible

Effect: Show/Hide

✓ Hide the dependent if the dependee is not in the form

✓ Hide the dependent if the dependency is not triggered

✓ Hide the dependent if the dependee is not viewable by the user

All fields are set to be required in their field settings.

This is your mistake.  If you set the field to be required in the field settings, it will be required whether it is invisible or not.  So you need to uncheck this setting unless the relevant field will always have a value.

Instead, you should trigger the "make required" action provided by the Conditional Fields module whenever showing the relevant field for input.  Unfortunately, the last time I tried this in Conditional Fields, it did not work due to a bug.

Alternatives

Field Conditional State is a stable module that works similarly to Conditional Fields.  You can use this to properly set required fields.

Or, if you prefer a code-based solution, look into the #states API.


template.php stop js on admin pages I am using the following to put js on my site...

drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/custom.js');

But I have noticed that this is also adding the js to pages like update.php and other admin pages. Is there a if variable I can use to only load the js on customer facing pages?

Ive used drupal_is_front_page() before, which is great, is there a drupal_not_admin_page() or something like that?

A google search for "drupal is not admin page" isnt getting me anywhere.

You can use path_is_admin():

if (!path_is_admin(current_path())) {
  // Do something...
}

Or check the theme:

if ($GLOBALS['theme'] == 'some_theme') {
  // Do something...
}


How to limit db_update() to update first n rows I want to update first n rows using db_update(). Is it possible?

I know we can use db_query(). something like

UPDATE <table_name> SET <field_name> = <value> LIMIT <num_rows>

I want to know whether this is possible using db_update()

It doesn't look like it's possible I'm afraid.

db_update() uses the UpdateQuery class, which doesn't support the range() method that a SelectQuery does.

You could probably subclass UpdateQuery and add that behaviour, but for the amount of work that would take you might be better off just using a raw SQL statement with db_query() like you've suggested.


How to export content to XML, CSV or RTF for print I'd like to export a (views)-list of events to re-import it with Indesign or Pagemaker, so XML, CSV or RTF-format would be great. The list should be restricted to one, the current month (this is no problem with views or even views bulk operations). The important thing is: the events must be grouped by the event-day and their respective categories (concert, theatre).

I already tried the Views Data Export module, but there is no way of grouping the fields. So every "event" has all it's fields in one column.

Is there another module you could recommend or do i have to do this programmatically (which I can't unfortunately).

Thanks in advance for every hint...

Update
Thanks to WestieUK i installed the Views Data Source module, which is working great, but not as expected. There's also no grouping of fields (at least not obvious).

So this is what i have:

<root>
    <events>
       <eventdate>21/7/2012</eventdate>
       <categorie>Clubland</categorie>
       <location>Club A</location>
       <title>Klanglabor</title>
       <time>21:00</time>
    </events>
    <events>
       <eventdate>21/7/2012</eventdate>
       <categorie>Clubland</categorie>
       <location>Club B</location>
       <title>Soundlabor</title>
       <time>21:00</time>
    </events>
</root>

I'd like to have it something like this:

<root>
   <eventdate date:21/7/2012>
       <categorie name:Clubland>
           <events>
              <location>Club A</location>
              <title>Klanglabor</title>
              <time>21:00</time>
           </events>
           <events>
              <location>Club B</location>
              <title>Soundlabor</title>
              <time>21:00</time>
           </events>
       </categorie>
    </eventdate>
</root>

Any ideas? If this can be achieved prorgammatically, like making a custom module (based on perhaps the Views Data Source module), I'd give it a try with your help!

Thanks!

Views Data Source is pretty awesome for XML, the 7 release is in dev but we are using it on our D7 to create feeds for android / iphone apps and a intranet running D6.


How do I override a function in a module I want to batch override (there are hundreds of terms) menu paths generated by the Taxonomy Menu module for a custom menu I require.  I know not to edit the module itself. I assume I create a separate module containing the replacement function to substitute the desired path I want, but I am not certain how to direct Drupal to use it instead of the original.  Or am I using the wrong strategy for this?

UPDATE:
I have solved the specific example in the question using a panel tied to a view. However, I am still interested in the question itself. A theme function can be overridden by including the replacement function with my theme name replacing the original theme name in the function name. Drupal handles the substitution from there; the same renaming option is not available for module functions.

I have continued to research this and found several posts at Drupal.org, that suggests it is not possible to override module functions in the same way you override theme functions.  There was a module for this in Drupal 6 (Override_Function), but it required additional software and appeared to have some problems working with PHP 5.2 & 5.3. The only workaround I have found so far is to hack it, but keep track of your changes so that it can be reinserted after updates.

It sounds more like you want to use hook_menu_alter to override what the Taxonomy Menu module's hook_menu function does.


Can I creat a View output using the root path? just need a simple task. I need to change the homepage based on a view.

If I edit the path inside view settings something like /home it works. But if I try to use the default site root path it displays:

Display "Page" uses a path but the path is undefined.

That means I am forced to set up my site homepage to www.domain.com/home

Can someone help?

Your view will need a path set, in this case 'home' and then within your site's Site Information settings just set 'home' as the Default front page (for Drupal 7 got to http://www.yoursite.com/admin/config/system/site-information).

When you access the URL of your site you will see your View, setting the homepage menu link to '' will also direct users to your homepage without adding '/home' to the URL.


Which table does the Phone module store data in? I have installed the Phone module to create a field to take input data as mobile number.

I would like to fetch the mobile number back from database to be displayed in a block. I am not getting the table in which the phone number is stored. So in which table is the phone number data is stored?

If this module defines a field, then the table is named after that field. So if your field is called field_phone, the table is called "field_data_field_phone". However, getting the value direct from the database is not the right "Drupal way" to do it.

You say you want to display the phone number in a block, but I assume this is within a specific context, such as on a page for a node or user. One way to do this would be to use the Views module to define a block with whatever fields you wish to display, using a contextual filter to get the node or user ID from the page arguments.

But more information is needed in order to say whether this is the right answer or not.