How do I programmatically change the body text format on the page content type to full HTML? I have a custom install profile and I must programmatically change the body text format on the page content type to full HTML. However, I didn't manage to find how to do it.

How can I do it?

You can do it with hook_element_info_alter, here is a snippet.

<?php
/**
 * Implements hook_element_info_alter().
 *
 * Sets the text format processor to a custom callback function.
 * This code is taken from the Better Formats module.
 */
function MODULENAME_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'MODULENAME_filter_process_format';
      }
    }
  }
}

/**
 * Callback for MODULENAME_element_info_alter().
 */
function MODULENAME_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change the default text format of the 'field_company_spotlight' field to
  // 'Media HTML'.
  if ($element['#bundle'] == 'company' && $element['#field_name'] == 'field_company_spotlight') {
    $element['format']['format']['#default_value'] = 'media_html';
  }
  return $element;
}
?>

As THIS post suggests you could try

$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

in your hook_form_alter or in hook_FORM_ID_alter

Also there is Better Formats module

  Better formats is a module to add more flexibility to Drupal's core
  input format system.

you only need one line of code

$result = db_query('UPDATE field_data_body SET body_format='full_html' WHERE bundle='page');


How to add a custom row class or ID to type table render elements I'm trying to add row ID's for a custom table I implemented via a custom module. But when I append an ID to the '#attributes' array it becomes the table ID, not the row ID. How can I define IDs for rows?

This is what I have so far:

$form['table'] = [
  '#type' => 'table',
  '#header' => $header_table,
  '#rows' => $rows,
  '#attributes'=> ['id' => 'IdforRow'],
  '#empty' => t('No Data found'),
  '#prefix' => 'Total Tenders : '.@$count.'
',
  '#suffix' => '',
];

Can you try code the below.

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => 'some class');
);

Or maybe

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => array('some class'));

Reference answer https://www.drupal.org/forum/support/post-installation/2016-04-21/add-class-in-row-with-theme-table

Try to add the ID in an array format like below:

$form['table'] = [
    '#type' => 'table',
    '#header' =>  $header_table,
    '#rows' => $rows,
    '#attributes'=>['id' => ['IdforRow']],
    '#empty' => t('No Data found'),
    '#prefix' => 'Total Tenders : '.@$count.'
',
    '#suffix' => '',
];


How to access a selected label instead of value I have a select list of states:

AL|Alabama
AK|Alaska
AZ|Arizona
AR|Arkansas

In code to access the selected state value I can run code like this:

...
$entity->get('field_state')->value;
...

I get the values like AL or AK.  How can I get the labels like Alabama or Alaska?

Not sure if there is a better way but I got the value by getting the allowed values first.

$allowed_values = $state->getFieldDefinition('field_state')->getFieldStorageDefinition()->getSetting('allowed_values');
$state_value = $state->get('field_state')->value;
$info['state_name'] = $allowed_values[$state_value];

drupal 7 way:

$jid = $row->job_id_181;
if($jid)
{
    $jobNode = node_load($params['jid']);
    $key = $jobNode->field_job_location['und'][0]['value'];//2
    if($key)
    {
        $field = field_info_field('field_job_location');
        $label = $field['settings']['allowed_values'][$key];
        echo $label;
    }

}

Hope it helps some one in future.


Ajax drop down list problem with callback I need a little help here.
In a custom module, I add a little form where you type your zip code, press a button and a drop down list populates (via ajax) with the stores that are close to that zip code so you can choose one of them. The problem is when you click on that button the callback is made but the zip code field remains empty, seems like I missing something that can bring the zipcode value to that part when the  refreshes.
some ideas?? thank you

    function mymodule_form($form, &$form_state) {

       $form['zip_code'] = array(
        '#type' => 'textfield',
        '#title' => 'zip code',
        '#size' => 5,
        '#maxlength' => 5,
        '#required' => TRUE
      );

      $form['button'] = array(
        '#type' => 'button',
        '#value' => 'find stores',
        "#limit_validation_errors" => array(),
        "#name" => 'mybutton',
        '#ajax' => array(
          'callback' => 'reload',
          'wrapper' => 'stores-div',
          'method' => 'replace',
          'effect' => 'fade'
        )
      );
      $form['select_str'] = array(
        '#prefix' => '
',
        '#suffix' => '
'
      );
      if(isset($form_state['values']['zip_code'])) {
        $arr = find_store($form_state['values']['zip_code']); //here is my main problem, $form_state['values']['zip_code']is always empty even after the callback
      } else {
        $arr[99999] = 'theres none';
      }
      $form['select_str']['stores'] = array(
        '#type' => 'select',
        '#title' => 'stores near you:',
        '#options' => $arr,
        '#required' => TRUE
      );
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Send!'),
      );
      return $form;
    }
    function find_store($zc) {
        $fields = array(
                'zc'=>urlencode($zc),
            );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://somepage.php");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $result=curl_exec ($ch);
        curl_close($ch);
        $arr = array();
        if($result!='none') {
            $explode=explode(',',$result);
            foreach($explode as $value) {
                $stores = explode('|',$value);
                $arr[$stores[0]] = $stores[1];

        }

    } else {
        $arr[99999] ='theres none';
    }
    return $arr;

}
function reload($form, &$form_state) {
  return $form['select_str'];
}

The values will be passed to the callback function reload instead of the original form function, therefore you should rebuild the form in your callback function - reload and pass back the element:

function reload($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form = drupal_rebuild_form('mymodule_form', $form_state, $form);
  return $form['select_str'];
}


Module for username suggestions on registration Is there any Drupal module which checks the username in the database, if its present then it should display some suggestions to be selected just like the yahoo or gmail gives on registration?

There is no module that does that. The closest you will find is the one that just checks if the username is available while registering. An example of such module is username check. To achieve the username suggestion bit, you may have to write a custom module for that.

  This very simple module allows visitors to check username originality
  quickly using AJAX request during registration (completing
  registration form). This makes registration process more convenient as
  you don't need to submit your registration form to find out whether
  this username is already taken or not. This module is sensible to
  standard Drupal username validation as well as Access Rules
  validation.

or friendly register

  Friendly Register module allows users to see if a username or email
  address has already been used during registration before they submit
  the form. This module checks the database and returns an error if the
  username is already in use. In addition to checking the username the
  module checks if there is already an account using that email address,
  if there is, a message is displayed with links to the login or reset
  password pages.

If your searching a module that "checks the username in the database", I propose you to look at /modules/user. In 'user.module'.


Custom form from scratch in template I have a paragraph that I fully themed into a contact form with the necessary  tags etc... Now my question is: How do I add the actual functionality to this? Because right now it's just plain html in a template without any logic handling the form submit.

You can use Drupal's default contact form and customize the fields as per your need which will have all the required logic for form handling. Then you can check and apply the theme as per your need to it.


domready is not defined I'm building my own theme to be used with Angular 4 and can't tell where/why Drupal is deciding to import jQuery.

Here's the code for my theme, loosely based off this Angular 1 theme:

ng.info.yml

name: ng
type: theme
libraries:
  - ng/base
description: 'An theme that makes Angular do all the work'
core: 8.x

ng.libraries.yml

base:
  version: 8.x
  js:
    js/inline.bundle.js: {}
    js/polyfills.bundle.js: {}
    js/styles.bundle.js: {}
    js/vendor.bundle.js: {}
    js/main.bundle.js: {}

ng.module

<?php
function ng_theme() {
  return array(
    'ng_view' => array(
      'template' => 'view',
      'variables' => array('title' => NULL),
    ),
  );
}

ng.routing.yml

ng.view:
  path: 'ng'
  defaults:
    _title: 'Drupal Angular'
    _controller: '\Drupal\ng\Controller\DrupalNgController::viewDrupalNg'
  requirements:
    _permission: 'access content'

src/Controller/DrupalNgController

namespace Drupal\ng\Controller;
use Drupal\Core\Controller\ControllerBase;
class DrupalNgController extends ControllerBase {
  public function viewDrupalNg() {
    $build['myelement'] = array(
      '#theme' => 'ng_view',
    );
    $build['myelement']['#attached']['library'][] = 'ng/inline.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/polyfills.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/styles.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/vendor.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/main.bundle';
    return $build;
  }
}

templates/view.html.twig

<html{{ html_attributes }}>
  <head>
    <title>Angular app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="HandheldFriendly" content="true" />
    <meta name="apple-touch-fullscreen" content="YES" />
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>

Given you didn't install any contrib modules nor themes, dozens of Drupal core modules requires Jquery to function. You'll have to check what modules lists JQuery as a dependency.
Search in core/modules and core/themes directories for core/jquery and you'll find out what module/theme is adding it and disable it.

For example "contextual" module needs it.

Just add core/domready library to dependencies part of your theme libraries file:
my_theme.libraries.yml

...
script:
  ...
  dependencies:
     - core/jquery
     - core/jquery.once
     - core/drupal
     - core/domready


SMTP Module not sending email Using XAMPP on Mac

I have installed https://www.drupal.org/project/smtp

After setting up admin/config/system/smtp

It gives above error. Unable to send test email.

Do we have to any setting on gmail or i'm missing anything?

You probably have to be auth to be able to send mail from gmail's SMTP (smtp user/ smtp password).
Moreover, you have to "allow" the sender's email in your google account.

theMailYouSendFrom@whatever.com have to be allowed to send mail with account yourAccount@gmail.com; somewhere in gmail's parameters, you can validate this mail.

I remember there is a limit, 450 mails/day for each google account (this could have change now, that was 3 or 4 years ago), and more with payed gapps.

You can try with Swift Mailer module . Its work for me.
https://www.drupal.org/project/swiftmailer


Can views pages be indexed and be searchable by apachesolr? By default drupal will only send nodes to apachesolr, is there a way to send views pages to solr, so that they may show in the search index?

I know this question seems a little out there, just looking to see what clever minds within Drupal think about what can be done here.

Thought I would post about how we ended up solving this:

Installed the module https://drupal.org/project/viewfield (which has a 7.x-dev release)
Created a new content type called 'Section Overview'
Added a viewsfield to the content type 'Section Overview' that allows the author to choose the view they wish to embed from a dropdown list
Told apachesolr to index nodes of type 'Section Overview'

In the end it was not that hard, just took some lateral thinking.

Solr indexes your content.  Views displays your content. The stuff that views can display....is still content.  You build views from the indexed content, not build an index from a view.  Solr indexes your db, and doesn't parse pages.


Date format on user profile form shown incorrectly - how to change I added a date to the user profile form under admin/config/people/accounts/fields. The field is of type 'date', the widget of type 'select list' and I only collect year, month and day.

Without altering anything the date entry widget is shown on the form in the order year-month-day.

Since the order in the Netherlands should be day-month-year, I set out to change the date format by:

Adding a new custom format d/m/Y under admin/config/regional/date-time/formats
Create a new date type called 'test' and referencing the custom format from the previous step under admin/config/regional/date-time
Changed the date display format to the 'test' type, under admin/config/people/accounts/display - press update and save the settings

In the date preview of admin/config/people/accounts/display, the date is shown as DD-MM-YYYY which is the format I want.

Now, going to the user profile page under user//edit, the date order shown as month-day-year.

I have tested this on a clean installation of Drupal 7.33 and the only module added is the date module 7.x-2.8.

How can I change the display order for this specific field?

Kind regards,
Eric van der Staaij

Date entry format is configurable, what you did was changing the way the date will display on content but not on create content form. To change it go to your field configuration page on content type then find more settings and values collapsed fieldset and inside it look for date entry options and change to whatever.

https://docs.google.com/a/srijan.in/file/d/0B9FG53CLjf-YdEFfdzVEV1hmcWc/edit?usp=drivesdk

Please refer the Community Documentation of Usage example of date elements within forms in the Date API form elements for the solution.

Thank you.


Restore role visibility in blocks I upgraded my Drupal 8 site from 8.4.5 to 8.5 and I noticed the role visibility in blocks disappears. I did a clean install and it's in Drupal Core, so the problem is not with my upgrade. I am thinking it's in the database but I have no idea how to track it. Does anyone know how?

I had the same problem. Solved it by editing the content of the block.
(we logged in as admin you see a button in the right upper corner, click it and select Edit). It appeared the the translated content was not published.


How do I programmatically delete an order? My head is about to pop. I'm trying to figure out how to delete commerce orders programmatically. I created a rest export with the order IDs I want to delete. I've parsed that and put the IDs into an array. Now I want to loop through that array and delete the orders.

json parsing, and retrieving order_id work fine.

I'm so close but I can't figure out how to properly reference commerce_order_delete or commerce_cart_commerce_order_delete?

function afc_custom_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
          if ($entity->id() == 803) {
            $url = 'my url';
            $jsonString = file_get_contents($url);
            $jsonDecoded = json_decode($jsonString, true);
            $object = new stdClass();
            foreach($jsonDecoded as $row){
            if ($row['order_id'] == 121) {
                $object->order_id = $row['order_id'];
                // $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row['order_id']);
                commerce_cart_commerce_order_delete($object);
            }

            }
          }
    }

Error:

TypeError: Argument 1 passed to commerce_cart_commerce_order_delete() must be an instance of Drupal\commerce_order\Entity\OrderInterface, instance of stdClass given,

UPDATE #2
New Code

use Drupal\commerce_order\Entity\OrderInterface;

  if ($entity->id() == 803) {
    $url = 'https://myurl.com/pull-ghosts';
    $jsonString = file_get_contents($url);
    $jsonDecoded = json_decode($jsonString, true);

    $object = new OrderInterface;

    foreach($jsonDecoded as $row){
      if ($row['order_id'] == 121) {
        $object->setOrderNumber($row['order_id']);
        commerce_cart_commerce_order_delete($object);
        print 'deleted';
      }
    }
  }

SAME ERROR:

error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in afc_custom_node_view()

Loading it like a normal entity did the trick.

How to load and delete commerce order programmatically

$ord_id=121;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);
$order->delete();

Here is the entire snippet on my ultimate goal which was deleting abandoned orders in the cart.
How to remove commerce orders automatically

How to delete ghost commerce registrations in cart

Custom cron to delete commerce orders programmatically

Load a view programmatically loop through values and delete orders

/**
 * Implements hook_cron().
 */
 function my_module_cron() {
   //load a view showing orders still in cart
   $view = \Drupal\views\Views::getView('commerce_carts');
   //the name of your display, i chose a simple rest display with the order_id field
   $view->setDisplay('rest_export_1');
   $view->execute();

   foreach($view->result as $row){
     //load the order
     $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row->order_id);
     $oid = $order->id();
     //delete the order
     $order->delete();
     //log to dblog
     \Drupal::logger('afc_commerce_registration')->notice('Clearing ghost registration, deleted: @oid.',
       array(
           '@oid' => $oid,
       ));
   }
 }

You can add the Created date field to the view, and test time values before deleting. In my case, it doesn't matter.

Thanks for the help everyone

You need your object to be of the class Drupal\commerce_order\Entity\OrderInterface instead of an empty class.

Use this instead: (Update)

use Drupal\commerce_order\Entity\OrderInterface;

$object = new OrderInterface;

foreach($jsonDecoded as $row){
  if ($row['order_id'] == 121) {
    $object->setOrderNumber($row['order_id']);
    commerce_cart_commerce_order_delete($object);
    print 'deleted';
  }
}


How to embed Facebook videos? -Drupal 7.37 & Omega4-Subtheme

-Windows7 HP & Toshiba Laptop

-Acquia-DevDesktop WAMP-Stack

-Latest Wysiwyg, CKEditor & Media_Module & Media_Oembed

Now I have tried everything and nothing allows a Facebook Video to Embed.

I have tried using the Facebook-URI/Embed-Code in the Media_Module-Media-Browser as well as dropping the Facebook-Embed-Code (using cut-and-paste) in the text-area.  The Facebook-Embed-Code that Facebook gives you, BTW seems strange to me.

Oembed (not the Media_Oembed Module) did not work at all.
Tried using another Wysiwyg-Rich-Text-Editor, besides CKEditor, because CKEditor strips out code and that switch did not help make the Videos embed.
Tried editing the CKEditor Advanced-Content-Filter to stop it from rewiring any code and that did not help.
The Video-Lightbox Software application seems to refuse the Facebook URI's also.
Media_Oembed also fails to help Media_Module to recognize Facebook-Embeds or URI's.
When I just cut-and-paste the Facebook-Embed-Code directly into a basic HTML-Document outside of Drupal (and even outside of a WAMP-Stack), this also does not work.  Viewing the source-code in FireFox, again I see some of the Facebook-Embed-Code is missing, having been stripped out by something.  What? FireFox?  HTML5?  This is the most puzzling.  Maybe the WAMP-Stack is necessary for embeds, but the link works.
Something seems to be removing part of the Code or else Facebook is using bad code inadvertently, being unaware of some configuration in the outside world.
Basically the URI's just deliver a red-reject-box from the Media_Module-Browser or else they deliver an iFrame or Flash that is dead in the water. Direct cut-and-pastes deliver just direct unprocessed raw code on output or else just, oddly, a link to the Facebook-Page that shows the name of the Video's owner and nothing more.
Any thought from anyone?  I am just really interested if anyone out there is embedding Facebook-Videos in ANY kind of way and if so, how?

Copy and paste it in the textarea, make sure you have full HTML filter selected, if y do not have that option, go to Text format and create a filter


Placing Drupal core/modules code outside public_html I've been trying to improve my sites security as I build a Drupal 8 update for my page. One thing I've seen recently is keeping your core code outside the web accessible docroot folder. I've also heard about keeping a copy of the code setup on git so you can easily bring down a clean copy if somehow someone changes something.

What is the current best practice for such a thing? On my server I have an account for the page, within which is public_html where anything actually being sent out to the world is kept. Is it possible to have the Drupal code one level down and then have things run from public_html?

There is some work being done to move as much of core out of DOCROOT, but this is complicated by assets that need to be web accessible, mainly JS, CSS, and images.  So, moving core/modules outside DOCROOT is tough because many of those have all three.

Current thinking is to place the vendor directory outside of DOCROOT to help reduce attack surface area.  Since using composer for all site building is also essentially a best practice now, the drupal-composer/drupal-project template does this, and also will place modules, themes, libraries, and other Drupal stuff in the proper place, while keeping vendor non-web accessible, as it contains the non-Drupal specific dependencies.

You just move your code into under public_html folder with the same permissions.


I can't set a default value on hook_form_alter() I have form alter for the user_register_form which is called.
In this hook, I try to set a default value for a textfield but it doesn't work.
I've tried all the syntax possible #default_value, #value, value, default_value, event in the attributes array.

This is my code.

function pre_registration_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_code_postal']['#cache']['max-age'] = 0;
  $form['field_code_postal']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['#value'] = 'COUCOU';
  $form['field_code_postal']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['#value'] = 'COUCOU';
  $form['field_code_postal']['value']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['value']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['default_value'] = 'COUCOU';
  $form['field_code_postal']['default_value'] = 'COUCOU';

  $form['field_code_postal']['#attributes']['value'] = 'COUCOU1';
  $form['field_code_postal']['#attributes']['#value'] = 'COUCOU2';
  $form['field_code_postal']['#attributes']['default_value'] = 'COUCOU3';
  $form['field_code_postal']['#attributes']['#default_value'] = 'COUCOU4';
}

How can I set a default value?

According to this Documentation you can do something like

 $form['field_code_postal']['widget'][0]['value']['#default_value'] ='COUCOU1';

and for another guys help if you want to fill entity referenced field( also files are entity in drupal 8) use

 $form['field_image']['widget'][0]['target_id']['#default_value']= $file; //

In Drupal 8:

$form['field_name']['widget']['#default_value'][0] = 'value';


how to validate email id is already register or not function lawyer_register_form_submit($form,&$form_state)
{
$mail = $form_state['values']['mail'];
$new_password = user_password();
$edit = array(
  'name' => $form_state['values']['name'],
  'pass' => $new_password,
  'mail' => $mail,
  'init' => $mail,
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())
  {
  $to = $form_state['values']['mail'];
  $subject = 'Lawandmoney New account created';
  $headers = "From: admin@lawandmoney.info\nContent-type: text/html";
  $body = 'A new user account has been created for you at us.lawandmoney.info.
 Your login details are as  follows:
Username: '.$form_state['values']['name'].'
 Password:  '.$new_password.'

 Please login to us.lawandmoney.org and change your password.
';
     user_save(drupal_anonymous_user(), $edit);
     if($form_state['values']['send_message'] == 1)
     {
     mail($to,$subject,$body,$headers);
     drupal_set_message("Sussessful register.Please check your Email for login   deatils.");
     }
     else
     {
     drupal_set_message("mail not send.");
     }
     }
     else
     {
     drupal_set_message("You are already register.");
     }

we created a custom user registration form.now we have to checked if user is already register then its give error like You are already register, data will not inserted into database and mail not send to user.

This can be done with hook_form_alter:

function module_(&$form, &$form_state, $form_id) {
  $user_login_forms = array('user_login', 'user_login_block');
  if (in_array($form_id, $user_login_forms)) {
    $form['#validate'][] = 'my_validate_function';
  }
}

function my_validate_function(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  // Drupal 6:
  if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
    // User doesn't exist
  }
  // Drupal 7:
  if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
    // User doesn't exist
   }
}

It's better to query the DB directly in this case than than using user_load as it hooks into other modules as well.

function module_form_submit(&$form, &$form_state) {
  $new_password=user_password();
  $edit = array(
  'name' => $form_state['values']['name'],
  'pass' => $new_password,
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  $mail = $form_state['values']['mail'];
  if(!db_query("SELECT COUNT(*) FROM {users} WHERE mail = :mail;", array(':mail' =>  $mail))->fetchField())
  {
  $to = $form_state['values']['mail'];
  $subject = 'test';
  $headers = "From: test@test.info\nContent-type: text/html";
  $body = 'test';
  user_save(drupal_anonymous_user(), $edit);
  drupal_set_message("Sussessful register");
  }
 else
 {
 drupal_set_message("Please check your Email for login deatils.");
 }
 }


Rendering form manually When making my ticket-system I want managers to be able to reply to tickets when viewing the ticket. On the page to view any ticket I load my form. Because I want it to be a bit more fancier than just the default 'element under element' style I render each item by item manually.

<?php print drupal_render($form['open']); ?>

Now the problem is, my form doens't work. Clicking on my rendered submit doesn't perform any action.

My guess is that rendering each item manually doesn't include the 'form container'. How should I include is? Or is my style of working completely wrong?

The best way to implement custom rendering of a form would be to use a custom theme hook for the form:

/**
 * Builder function for the ticket form.
 */
function MODULE_ticket_form($form, $form_state) {
  // Build the $form array here...

  // Let the theme API knows that this form use it own theme hook.
  $form['#theme'] = 'ticket_form';
  return $form;
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    // Custom theme hook for the ticket form.
    'ticket_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Default implementation for the ticket_form theme hook.
 */
function theme_ticket_form($variables) {
  $form =& $variables['form'];

  //Custom rendering of forms elements goes here...
  $output = ...;

  // Render every other elements (incl. hidden system ones).
  $output .= drupal_render_children($form);
  return $output;
}

Instead of using only a theme function, you can also use a template file. The theme function can also return a render array instead of a string.

Try following will work:

<?php $form = drupal_get_form('yourform_id'); ?>

<?php print '<form id="'.$form['#id'].'" accept-charset="UTF-8" method="'.$form['#method'].'" action="'.$form['#action'].'">'; ?>
<?php print drupal_render($form['form_id']);?>
<?php print drupal_render($form['form_build_id']);?>
<?php print drupal_render($form['form_token']);?>
<?php print '</form>'; ?>


Disable read more link I tried to remove "read more" link from the "basic page" content type.
In Structure -> Content types -> Basic page -> manage display I checked "full content" and unchecked everything else and this didn't help.
Where am I doing mistake?

I found in another question the possibility to edit the template file, but I would rather do it in the settings.

thank you

There is no setting for that.

You can either do it with a preprocess function as explained in Remove the 'read more' and 'Add new comment' links on the home page or you can implement hook_node_view_alter(). Both is possible in a module or in a theme.

The read more link in is added in node_build_content(), and you should be able to remove just that link like this:

function yourmodule_node_view_alter(&$build) {
  if ($build['#node']->type == 'page') {
    unset($build['links']['node']['node-readmore']);
  }
}

You can combine Ram's, and user175...'s answer to get where you want to.

Just add this to the top of the page you want the read more's to dissapear. (e.g. inside the post that you want to have the button removed from, or in a custom block on the same page)

<style type="text/css">
.node-readmore {
     display: none !important;
}
</style>

No need to mess with css files or modules, will work on-the-fly.


Disable rich text editor by default I am using WYSIWYG module with TinyMce as Rich Text Editor.
I need to make the rich text editor disabled only for a particular text area in a create content page, i.e., when I click Enable rich-text link, it must get activated. How can this be done?I am using drupal 6

There's a solution here http://www.only10types.com/2011/12/drupal-6-enabledisable-wysiwyg-editor.html

Basically, you need to alter this specific edit form. This is what I did for Drupal 7 (the blog post is for Drupal 6):

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

  // Workaround to disable Wysiwyg just in this field.
  if ($form_id === 'FORM_ID_OF_EDIT_FORM') {
    $form['field_CUSTOM'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;
  }
}

You may want to use $language->language instead of LANGUAGE_NONE.

I always use Wysiwyg module with the following steps:

Install wysiwyg module
Download TinyMce library to libraries (sites/add/libraries) folder
Create a new input format, called Wysiwyg (admin/config/content/formats)
Set the correct roles to this input format
Set this as a full html format (don't convert line breaks to brs etc)
Connect wysiwyg profile to this (admin/config/content/wysiwyg)

This solution is for Drupal 7 but you can do it on D6 too with the same steps, just change the administration urls.


Active menu trail for multiple menu item with the same path It is possible to have menu items that point to the same node and have the active state dynamic?

If I click the link 'List item A1' I would like to become active the link 'List item A'.

If I click the link 'List item B1' I would like to become active the link 'List item B'.

 - List item A (node/1)
 --  List item A1 (node/2)

 - List item B (node/3)
 --  List item B1 (node/2)

You can use the module menu-position for this. When you add a new rule, just choose the option Mark the rule's parent menu item as being "active" on the settings page. You probably have to create a css rule for your theme, too.


How to create product template? Please see the red box. In Magento there is a feature where i can create Product Templates - templates can be created for products with different fields.

I know i can create Content Types for this, but i felt that will make too many Content Types. Is there another work around this so that it's like Magento? Is there a module for it.

Thanks!

In Drupal Commerce you can just make product types and it will generate product displays (content types) meant for building the presentation. The product type holds all the meta data about the product itself.

With different fields for each template you have two ways:

different content types
one (maybe extreme large) content type with all fields, and then hide unused fields, depends on template choosen (template options in taxonomy list). You can use conditional fields module:
https://www.drupal.org/project/conditional_fields
still not ready for drupal 8, but as you can see issue, will be ported soon. If not, you can write own module or use some ugly javascript to hide fields.


.htaccess: Options not allowed here I just moved a new drupal site onto a directory '/drupal_test' under my current site. So that I can test it while my current site is still running.

When I go to the directory www.mysite.com/drupal_test. I got this error:

**Internal Server Error**
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Apache/2.2.16 (Debian) Server at www.bromptontech.com Port 80

I used putty command line to access the error log on the server and I got errors like this:

/var/www/drupal_test/.htaccess:Options not allowed here

I searched around and it seems something to do with the Allow Override settings, some say it is in httpd.conf, but I can't find this file anywhere, I can only find relevant code here in /etc/apache2/sites-enabled/000-default, I can see the  tags.

Our IT guy gave me the root account to access the server, but he can't help me more than that, while I really have very limited knowledge about the server and these command lines, please can anyone help me with this? Thanks a lot!

As your running the drupal from sub directory so modify the line containing "RewriteBase" (may be line no. 102) of .htaccess, change "# RewriteBase /drupal" to "RewriteBase /drupal_test".

And if the above thing doesn't works for you than please try the following:
Search for "<directory /var/www/>" in the "/etc/apache2/sites-available/default" file and change it as below:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
</Directory>

Open up your .htaccess and remove

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

This will make your folder contents viewable (assuming it is not turned off at a global level), so you may want to investigate a solution for that, either putting an empty index.html in those directories or something that will turn off directory listing. The symlinks shouldn't be a big deal but you won't be able to use symlinks.


How to get the count on the select list in views? For example, I have a content type with field. The field is select list. The select list has four default values as well as it is required.

I want the output of a view as:

Provincial (2)
Federal (6)
Institutional (3)
...
Value (#)

where # is the number of nodes with this value

How can I accomplish this?

Assuming Drupal 7 and Views 3:

Create a view based on your content type with a page or block display
Add a contextual filter, based on your select field
Under "When the filter value is NOT available" select "Display a summary"
Configure the summary as you like, with "Display record count with link" enabled

You could use Views Aggregation feature to attain that result. Check https://drupal.stackexchange.com/a/15875/4915 for a solution similar.


Drupal 8 service dependency injection I am trying to build a service that will leverage the Pathauto service so my class looks like this.
namespace Drupal\some_system;

use Drupal\pathauto\PathautoGenerator;
use Drupal\pathauto\AliasCleaner;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ProcessUrl
{
  /**
   * @var PathautoGenerator
   */

  protected $pathautoGenerator;

  /**
   * @var AliasCleaner
   */
  protected $aliasCleaner;

  /**
   * ProcessUrl constructor.
   * @param PathautoGenerator $pathautoGenerator
   * @param AliasCleaner $aliasCleaner
   */

  public function __construct(PathautoGenerator $pathautoGenerator, AliasCleaner $aliasCleaner)
  {
    $this->pathautoGenerator = $pathautoGenerator;
    $this->aliasCleaner = $aliasCleaner;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('pathauto.generator'),
      $container->get('pathauto.alias_cleaner')
    );
  }

  public function testurl(){
    dump("Need to reach Here");
    exit();
  }

}

and my services.yml file looks like this.
services:
 some_group_system.process_url:
    class: Drupal\some_system\ProcessUrl
    argumrnts: ['@pathauto.generator','@pathauto.alias_cleaner']

Now when I call this service  \Drupal::service('some_group_system.process_url')->testurl(); it throws an error to me saying
Too few arguments to function Drupal\some_system\ProcessUrl::__construct(), 0 passed in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 265 and exactly 2 expected

I cleared cache and reran but not sure why it is saying this. Please help on this.

You have a typo in your services.yml file, you misspelled arguments.
Additionally, for a service, you don't need to (and shouldn't) define the create method. Your dependent services are injected from services.yml, but keep your constructor as is.
The only time you need to define the create method to inject dependencies is when working with plugins, controllers, forms, etc as mentioned in the dependency injection documentation on d.o.

Sorry it was a spelling mistake
 argumrnts: ['@pathauto.generator','@pathauto.alias_cleaner']

should be
arguments: ['@pathauto.generator','@pathauto.alias_cleaner']

Do not need even create method but got confused.


Can I set a status message to be displayed when a user clicks a link? Here's my setup:

I have a page about Pineapples.  There is a link to the Pineapples page in the main navigation menu. When a user clicks that link, they go to the page.

I also have a separate link on the homepage to the Pineapples page.  When a user clicks the homepage link, I want to send them to the Pineapples page, but I also want to show a status message with a little more information.

Is there a Drupal-y way to do this?

I think you need to make a custom form with a submit button (the button should be your "link" button), and then you can do what you want.


how to add #states property to a field element in drupal 7? I wanted to add #states property to a select list field in cck input form created by content type. I ve tried the following code but the states property is not set to the field. Can anyone suggest on how to do it.

$form['field_ctype']['und']['#ajax']=array('callback' =>'_ajax_menu_check_boxes',
                                              'wrapper' =>'edit-field-sub-menu',
                                            'effect' => 'fade',
                                            'event' => 'change',
                                            );
$form['field_sub_menu']['und']['#states']=array(
                                  'visible' => array(
                                 ':input[name="field_ctype"]' => array('value' => '2')));

could anyone suggest me where I am going wrong. Is it possible to add ajax property ans states property to a same field?

Note : The Ajax property for the field_ctype works fine. Only the states property is not working.

Fields always have have nested names like field_something[und][value] or something like that. I guess your query (:input[name="field_ctype"]) is wrong.

I find the easiest way to get it right is using the Firebug/Developer tools Console. Play around with jQuery(':input[...]') until it matches what you're expecting. Also check the name of the form element.

The following worked for me in order to show fields depending on the value of a select (which is a taxonomy field). On the code below, the select field is called 'template'. For convinience, the rightside array is the condition to check for and the leftside array is the action to take. This is just another way to write the standard code:

/* This function finds the term id from the term name on the select box */
function get_tid_by_name($name) {
  return db_select('taxonomy_term_data', 't')
    ->fields('t', array('tid'))
    ->condition('name', db_like(trim($name)), 'LIKE')
    ->addTag('term_access')
    ->execute()
  ->fetchField();
}

/* This functions hides fields on the node form of the 'basic page' content type,
 * depending on the selected template
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id ==  'basic_page_node_form') {
    $lang = $form['field_slogan']['#language'];
    $template = '#edit-field-template-' . $lang;  // template field selector
    $pp1 = get_tid_by_name ('PP1');
    $pp2 = get_tid_by_name ('PP2');
    $pp7 = get_tid_by_name ('PP7');
    $pp10 = get_tid_by_name ('PP10');
    $form['field_slogan']['#states']['visible'] = array($template=>array('value' => $pp1 ));
    $form['field_image']['#states']['visible'] = array($template=>array('value' => $pp7 ));
    $form['field_links']['#states']['visible'] = array($template=>array('value' => $pp10 ));
    $form['field_pictures']['#states']['visible'] = array($template=>array('value' => $pp7 ));
    $form['field_hightlights']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_bullets']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_video']['#states']['visible'] = array($template=>array('value' => $pp2 ));
    $form['field_quick_tip']['#states']['visible'] = array($template=>array('value' => $pp1 ));
  }
}


Form Redirect not working if 'destination' is in URL In one of my forms, I'm trying to set a $form_state['redirect'] so the form will go to that destination after the user clicks one of the action buttons.

If I inspect $form_state['redirect'] both before and after I add the redirect, it is NULL before, and after contains the proper array. Here's how I'm setting up the redirect:

$form_state['redirect'] = array(
  'my/custom/path/' . $nid,
  array('query' => drupal_get_destination()),
);

I want to preserve the destination from the form that the user's viewing to the next path (that's why I'm calling drupal_get_destination(), which returns an array with 'destination' => 'some/path/here' inside.

It seems that, because there's already a destination in the path of the current form, the form redirects to that destination no matter what I put in my own form submit handler (see above code). I even tried using drupal_goto() and that didn't redirect the user either.

When a form is processed, the value of $form_state['redirect'] is sent to drupal_goto(), and drupal_goto() always favors $_GET['destination'] over its own $path parameter.

For the sake of completeness, in Drupal 6, you were somewhat out of luck without setting your own headers in hook_exit():

function mymodule_exit($destination = NULL) {
  $my_destination = 'foo/bar';
  header('Location: ' . url($my_destination));
  exit;
}

In Drupal 7, hook_drupal_goto_alter() was added for this specific use case:

function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  $path = 'foo/bar';
}

Another option for Drupal 7, which is closer to what you want to do, is to reset the static cache for drupal_get_destination()  in your submit handler using drupal_static_reset():

function mymodule_form_submit($form, &$form_state) {
  // See note
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = 'foo/bar';

  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}

Since you call drupal_get_destination() immediately after the reset, Drupal is blissfully unaware of the destination parameter for the rest of the page build, including when it calls drupal_goto().

Note: I changed the code for defining $form_state['redirect'] because you never want to overwrite the variable: other submit handlers might've defined their own redirects. Drupal will always use the last item in the array, so if you want foo/bar to override the destination parameter (and every other redirect defined up to that point), it needs to be last.

set form #action

global $base_path;
$form['#action'] = $base_path . '/node/'.$form_state['node']->nid.'/mytab';


How to show taxonomy terms' description field on a node/add form instead of term title only in drupal 7? I find it a bit disturbing that you cannot set which fields of taxonomy terms are displayed when you add a new node and have the terms listed.

There will be a bunch of terms which the user has to select one from. However, sometimes only showing a terms title wont be enough, so I'd like to also show a terms description when adding a new node.

How can you do that?

The following solution slightly alters your requirement. Instead of having the term description field showing up as part of the term select widget, create a view block set to be visible on node/add pages which provides a table listing of each term and its description field.

To do this, create a new view of type "Taxonomy." It will have two fields: taxonomy term, and taxonomy term definition.

You could put help text associated with term_reference field which alerts the user to the block which holds the terms and description.

It would be very difficult to alter any select widget to include the description field in a way that wouldn't make a mess of the page.

a possible solution that you can loop through each item and get the description next to the term name.


How do I add a class to the search block form? I want to add a class to the <form> element on the form_id 'search_block_form'

this is my current code

function THEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'form-inline ';

}

You can use the template_preprocess_form

function THEMENAME_preprocess_form(&$vars) {
  // Add class to your specific form
  if ($vars['attributes']['id'] == 'search-block-form') {
    $vars['attributes']['class'][] = 'form-inline ';
  }
}

NOTE: the preprocessor you are using adds class to the block element

Try this code..

/*
* Implement hook_form_alter()
*/
function custom_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attributes']['class'][] = 'test';
}


How can I give Ajax access to currently set fields on my form? I'm working on a block form that needs to update certain elements in the form based on what the user selects with certain elements. I've defined the internal class method and it's getting called correctly; however, it can't access the values stored in the form from the $form_state.

For example, when I call $form_state->getValue('filter_field'), it returns an empty value, even though it has been set on the page. I suspect that this may be due to the fact that I'm setting the callback like so: 'callback' => [get_class($this), 'updateWidgetAjax'], and in the final comment in the API, it says to do it like this: 'callback' => '::updateWidgetAjax'. However, when I try this, I get the The specified #ajax callback is empty or not callable. error. I tried following the tutorial on the API page as well as here, yet neither of them worked properly, spouting out the same error as before. I also went through this checklist, but most of the items don't apply.

Additionally, and this is just something annoying but related, if I don't mark updateWidgetAjax as static I get the following message in my log: Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\global_filter\Plugin\Block\FilterBlock::updateWidgetAjax() should not be called statically, which I suspect will be resolved with fixing the above issue.

In short, how do I get the form values in my Ajax callback?

The element calling the Ajax:

$form['filter_field'] = [
  '#type' => 'select',
  '#name' => 'filter_field',
  '#title' => t('Select field to get the filter value from.'),
  '#options' => self::getAvailableFields(),
  '#empty_option' => t('Select a field'),
  '#ajax' => [
    'callback' => [get_class($this), 'updateWidgetAjax'],
    'event' => 'change',
    'wrapper' => 'default-value-ajax-wrapper',
    //The wrapper is elsewhere on the form
  ]
  '#required' => TRUE,
];

The Ajax callback function:

public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
  $widget = '';
  $multichoice = FALSE;

  switch ($form_state->getValue('widget_type')) {
    //code that sets $widget
  }
  //Return a render array
  $render = [
    '#type' => $widget,
    '#name' => 'default_value',
    '#title' => t('Default value'),
    '#description' => t('Select the default value for this filter. Leave blank for none.'),
    '#options' => self::getOptions($widget, $form_state->getValue('filter_field')),
    '#required' => TRUE,
  ];
  return $render;
}

EDIT: I forgot to mention that the form is defined with a blockForm, since I'm trying to create new blocks with this. I'm following the Drupal documentation found here. I think this might be a big part of the issue.

I have tried this on my local it works . So you can achieve the form values by using this . Please try this

    $form['filter_field'] = [
      '#title' => $this->t('Filter'),
      '#type' => 'select',
      '#options' => ['drupal7' => 'Drupal7', 'drupal8' => 'Drupal8'],
      '#empty_option' => $this->t('-select'),
      '#ajax' => [
        'callback' => '::updateWidgetAjax',
        'wrapper' => 'default-value-ajax-wrapper',
      ],
    ];
    $form['widget_type'] = [
      '#title' => $this->t('Widget Type'),
      '#type' => 'select',
      '#options' => ['pdf' => 'Pdf', 'ppt' => 'PPT'],
      '#empty_option' => $this->t('-select'),
    ];

    $form['wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'default-value-ajax-wrapper'],
    ];

    return $form;

//Ajax callback
  public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
   $widget = $form_state->getValue('widget_type');
    print_r($widget); //Print the value of the field
  }


How to pass variable from module to other theme I would like to pass variables from my custom module to some of my custom themes.
The most tutorials are concerning using hook_theme function but as I understand, it works only for creating new theme functions (new tpl files) inside module, where the hook_theme is defined. But I would need to alter theme definition of some custom theme in
/sites/all/themes folder from my custom module
/sites/all/modules

In particular, I need to add a variable into thems's html.tpl.php file. I would like to use custom module to define variable, because I need to make database queries to fill variable with value, and db queries should not be done in theme.

I have tried implementing hook_theme_registry_alter.
I have tried to add variable like this:

function mymodule_theme_registry_alter(&$theme_registry) {
$theme_registry['html']['variables']['test'] = 'test value';
}

but I got error "Undefined index: #children in template_process_html"

Can anybody help?

For your needs, you'll need to create a custom module and implement hook_preprocess_html:

function hook_preprocess_html(&$vars) {
  // This is where you do the db query
  $myvar = _get_my_var();

  // After this $myvar will be available in html.tpl.php
  // where you need to print it out
  $vars['myvar'] = $myvar;
}

I would use variable_set() & variable_get():
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable_get/7


How to remove all the divs inside the $widget of a views exposed filter? I need to remove all the divs inside the $widget of a views exposed filter. I need only the single form fields without any html around it.

I don't know PHP.

Any suggestions?

Go to the modules directory and look for the 'views' module.

There is a 'theme' folder within this.

In the theme folder, copy the 'views-exposed-form.tpl.php' file to your theme.

You can then edit the template as you require.

Note, when you copy a file like this you will want to clear caches for this to work.

*****UPDATE*****

To edit specific components of the form I suggest you override the following function in your themes template.php file.

template_preprocess_views_exposed_form(&$vars)

This can also be found in the views module folder 'theme.inc'.

You can also do easy css tricks :

.class-of-elements-you-want-to-hide {
   display: none;
}


How can I get the group id of a node using tokens? I try to use [node:og_group_ref], but that gives me the group node title and I need the GID, I am sure there should be a way to get it but I haven't found it

In Organic Groups 7.2 the Node idea and Group id are the same. So if you are using views you can do the following:

Add field "Content: Nid" and exclude if from display.
Any field arranged below the above can use [nid] as a rewrite giving you the Group ID.

Does this help?


Show all events that are active between two dates chosen from exposed date filter I have a problem in showing views results with an exposed date filter in D7 views 3.x.

problem

We have several events with a date field. It is required to fill in a start and end date.
We want a visitor to choose a start date and an end date with an exposed filter in a view.

wanted results

The results should show every event that occurs:

Events that occur between the two dates
Events that are already started. So the start
date is already in the past.
Events that are in the future but the end date is not between the chosen dates.

We have already tried to configure a startdate with "equals or greater than" and an end date with "equals or less than".

Am I overlooking something?

If you have configured your view to display all events that has start date >= x and end date <= x then what you have done show do the job.

In order to make it easy for others to help you, I recommend that you give description of your content types date fields, update your question with export code of your view so that others look and spot mistakes if any.

In the meantime, I have created a content type called event, and give it one field called i.e. date (I have configured the date field to collect both start date and end date - only year/month/day). I then setup a view and setup two exposed filters on start_date and end_date of this content type with operators as greator than or equal to and less than or equal to, and they seem to work without any problem. Follow is the export code of my view

    $view = new view();
$view->name = 'events';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Events';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'eventsbydate' => 'eventsbydate',
);
/* Filter criterion: Content: date -  start date (field_date) */
$handler->display->display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['operator'] = '>=';
$handler->display->display_options['filters']['field_date_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value']['expose']['operator_id'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['expose']['operator'] = 'field_date_value_op';
$handler->display->display_options['filters']['field_date_value']['expose']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
$handler->display->display_options['filters']['field_date_value']['group_info']['label'] = 'date (field_date)';
$handler->display->display_options['filters']['field_date_value']['group_info']['identifier'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['group_info']['remember'] = FALSE;
$handler->display->display_options['filters']['field_date_value']['group_info']['group_items'] = array(
  1 => array(),
  2 => array(),
  3 => array(),
);
/* Filter criterion: Content: date - end date (field_date:value2) */
$handler->display->display_options['filters']['field_date_value2']['id'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value2']['field'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['operator'] = '<=';
$handler->display->display_options['filters']['field_date_value2']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_date_value2']['expose']['operator_id'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['label'] = 'date - end date (field_date:value2)';
$handler->display->display_options['filters']['field_date_value2']['expose']['operator'] = 'field_date_value2_op';
$handler->display->display_options['filters']['field_date_value2']['expose']['identifier'] = 'field_date_value2';
$handler->display->display_options['filters']['field_date_value2']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'events';

screenshot of the configuration page is as follow

If the above approach does not help you then have a look at this useful module https://www.drupal.org/project/views_between_dates_filter

Do you want something like http://openwaterswimming.eu/eventslist ?

You can find the complete code at http://openwaterswimming.eu/files/code_eventlist.txt


Programmatically save image together with its ALT I am not sure what is the benefit of using system_retrieve_file mentioned on Save image from URL to a field from a custom module, so I just use the following simple code to save image programmatically:

    $file = file_save_data(file_get_contents($url), file_default_scheme().'://field/image/'.basename($url));
    $file->status = 1;
    $node->field_image['und'][0] = (array)$file;
    node_save($node);

Works fine, so now I am trying to figure out how to save the enabled alt value which is stored in $alt variable.

When I output what the $file array contains with dsm(print_r($file,true)); it shows only:

stdClass Object
(
[fid] => 9
[uri] => public://field/image/150304192032_monalisa_624x351_afp_0.jpg
[filename] => 150304192032_monalisa_624x351_afp.jpg
[filemime] => image/jpeg
[uid] => 1
[status] => 1
[timestamp] => 1425596902
[filesize] => 28642
)

Unfortunately, it doesn't contain neither title or alt. Could anyone help me to get this sorted out? Thanks!

As far as Drupal 8 is concerned, there is another solution :

//    $file : my File Entity
//    $node : my (Node) Entity having an Image File field associated
$node->field_my_image_field[] = [
 'target_id' => $file->id(),
 'alt' => 'Alt. text',
];
$node->save();

Well, I think that 'width', 'height' and 'title' are also available in the setting array (but target_id seems required).
cf: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x
(look at the source code, generateSampleValue() method).

Ok, I've got this done by using the following code after node_save():

$update = db_update('field_data_field_image')
  ->fields(array(
    'field_image_alt' => $alt,
  ))
  ->condition('field_image_fid', $file->fid)
  ->execute();

It seems this is the only way. More detailed findings are given on https://www.drupal.org/node/2447091


Unresolved dependency Invite (Version 3.x required) I have upgraded drupal , but when i am running update.php I am getting this error .
I have tried after disable invite but still no luck.

Unresolved dependency   Invite (Version 3.x required)
User Relationships Invites requires this module and version. Currently using Invite version 4.0-beta2

Sorry i just found solution . I have have disabled User Relationships Invites using db from system table and it works .


Print five star ratings and reviews I am using Fivestar rating in custom print. See image:

I'm trying to print a fivestar as follows:

$your_average = $variables['result']['node']->field_rating['und'][0]['average'];
$your_maximum = "100";
print theme('fivestar_static', $your_average, $your_maximum);

But, I'm getting the following error:

  Fatal error: Unsupported operand types in /var/www/html/book1/includes/theme.inc on line 1088

Any suggestions?

Looking at the definition of fivestar_static theme-function in fivestar.module file under fivestar_theme(), you need to provide the theme function with an array including the following keys: rating, stars, tag. A working example should look like:

$fivestar_variables = array('rating' => $your_average, 'stars' => $your_maximum);
print theme('fivestar_static', $fivestar_variables);

Try this:-

$your_maximum="100";
$your_average  = "21";
print render(theme('fivestar_static', $your_average, $your_maximum ));


All links point to the old site after migration I migrated a Drupal 7 site from 1 server to another. Let's call the old site URL http://oldsite.com and the new site url http://newsite.com. I have copied over the code base and the database. The site displays correctly on http://newsite.com, however all the links point to http://oldsite.com. The only way to access the links are to type the URL in the browser (e.g. http://newsite.com/admin).

I have read lot of forums and done the following:

Set the $base_url in settings.php
Cleared cache in Config > Development > Performance
Cleared the cache table in DB
Ran update.php
Disabled clean urls

Nothing has worked. Someone suggested changing an entry in system table. Don't know which entry they were talking about.

Can anyone suggest the correct steps and perhaps an explanation of why I keep getting the redirects?
I have also referred to Moving a site, links/admin do not work.

For sites being localized, you have to edit every language:
/admin/config/regional/language
It's because there's a "domain" field that is left with the wrong URL in the database.
That solved my case of moving from subdomain beta.mysite.com to www.mysite.com

If you are using domain access, be sure to check the table PREFIX_languages. I had the exact same problem and wasted 2 days before I found the problem. The old domain was hard coded in the PREFIX_languages table and once I changed it everything worked perfectly.


Embedded Youtube Block Thumbnail I seem to be having an issue with the auto generated Thumbnail of a you tube video that shows in a block as a teaser on my frontpage.

When viewing the front page using Firefox the thumbnails are shown. But when viewing on IE11 I just get the alternative text description without the thumbnail.

I am using Drupal 7

Try using the /watch?v= parameter (i.e. www.youtube.com/watch?v=Y9eXzmVzDR8) instead of www.youtube.com/embed/Y9eXzmVzDR8 when adding content to the field.


Use GMaps with just one country I would like to have a map on my website displaying all my stores. That worked out pretty well except for the fact the map is displaying more then just my country.
Is there a way to just show one country?

I made the map undraggable and users are not able to zoom, so the map is pretty much fixed but still, I would like to just show my country.

Is this possible with macro's? And if so, how do I create them?

EDIT:

So my country is Belgium and I would like to hide France and Germany (and if possible highlight Belgium...)

You can not do it through macro's but alternatively you can set the zoom option for the map.

Go to Gmap Setting and set the Default zoom option to your requirement.

Hope it works for you!

Very near to what @Bala has answered you can opt the following:

Use OpenLayers instead of GMap if your requirements suite and cater to it.
Set zoom level for default map in OpenLayer settings.
Use KML overlay for OpenLayer to highlight the country of your liking.

A sample of what you are looking for from my website: http://indiansnakes.org/content/rat-snake


Remove search form from search result page in Drupal 8 What's the best way to remove the search form from the search result page in Drupal 8?

There is not much you can customize in core search. So you probably need to override Drupal\search\Controller\SearchController::view and remove this line:

  $build['search_form'] = $this->formBuilder()->getForm(SearchPageForm::class, $entity);

Put your extended class into the route search.view_node_search in a RouteSubscriber.

But I don't think it's worth the effort. You can either simply hide the form in CSS or if you want a fully customizable search solution use Search API.

I'm not sure if is the best way, but you can remove it from your theme preprocess, just for that page:

/**
 * Implements hook_preprocess_search_api_page()
 */
function YOURTHEME_preprocess_search_api_page(&$vars) {
  unset($vars['form']);
}


What does "Use aggregation" option under Other in the Views UI do? It looks like it might be a function that can reduce duplicates rather than using the Distinct option.

Technical what it does it allows you to add "GROUP BY field" and "count(field)" to the sql query. This might be able to reduce duplicates but in general if you have duplicates it's most often a problem by design/your choosen view type(node, user, terms etc.)

Among other things it also allows you to create "representative node" displays. i.e. latest post per content type, or latest post per taxonomy term etc.


How to create temporary select field? I added a field:

$form['field_brand_selector']['#type'] = "select";
$form['field_brand_selector']['#title'] = "Brand";
$form['field_brand_selector']['#required'] = false;

This field is populated dynamically using Javascript. However, if I try to save the form, I get:

Illegal choice 49124 in Brand element.

I suspect that this is because I don't have this:

$form['field_brand_selector']['#options'] = $options;

So Drupal doesn't know which values are allowed for this Dropdown Selector. But seeing as this dropdown selector is not actually a field that must be saved, is there a way to "ignore" it's submission when I press save, so that I don't get the illegal Brand element error?

Probably a hack, but this is how I solved it:

$form['field_brand_selector'] = array(
    '#type' => 'inline_template',
    '#template' => '{{ somecontent | raw }}',
    '#context' => [ 'somecontent' =>
    '
        <label for="edit-field-brand-selector">Brand</label>
        <select class="" id="edit-field-brand-selector" name="field_brand_selector" readonly="readonly"></select>
    '],
    '#weight' => 8,
);

This way Drupal doesn't validate the field I added.


Where is the autocomplete function for user/addressfield/autocomplete? I searched but I cannot find the autocomplete function for addressfield module.
The path of this autocomplete function is user/addressfield/autocomplete.

So I need the file that declare this function.
Thanks!

I was using the Commerce Admin Order Advanced module.  This is was providing the autocomplete.


How to add Follow Me link inside content type in Drupal 7 My project contains two content types:- Professor and Lecturer.
Here the users are student so students can log in using their own credentials.

Now I want to show up a button/link with Text "Follow Me" in Professor & Lecturer Content Type.When User/student will select the link/button then the corresponding Lecturer/Professor will be attached to the student profile and will be visible inside their home page. Similarly that student will be visible in Teacher/Lecturer.

I look at The "Relation" Module in Drupal 7 but my use case don't need to display too many things in the widget. There should be a simple button/link which relate user and content type.

You should try the Flag module for this. It should solve your purpose.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

There is Shortcode Module also

Shortcodes are actually macros to be used in the text of contents.
These macros change the text of the content and format the given part
through the theme engine.
Shortcode is an API that handles the shortcode macros for text
formats. You can add your own shortcode tags via this API. All tags
are themeable and new tags can be provided by other modules.


How do I modify the "Formats" dropdown in CKEditor The CKEditor in Drupal 8 has a Formats toolbar button containing different text formats: "Heading 1", "Heading 2" etc. How can I add and remove items from this list?

I would use Styles instead of Formats, because styles are fully controlled by you, from admin interface, no need for editing files.

When you add it to the toolbar you can configure it and add as many elements as you wish.

Here is an example config:

After you install the ck-editor module, there is a file name ckeditor.styles.js in the root of the module folder.Copy that file and paste in your theme folder and edit that file per your need. For quick check you can edit the file directly there also but it is not recommended.


Drupal 7.22 and Templating I am developing a site using drupal. I need to create a template file for a specific page.
For instance this is my site url http://www.dev.com. I created a basic page called documents which URL path settings alias is docs. So what I want to do is that whenever the user clicks on http://www.dev.com/docs drupal should use a specific template file. For that matter I create a tpl file called page--docs.tpl.php and put it inside my theme folder. However drupal seems not loading that file.

PLease assist me if I am missing something.

You need to use the non-aliased path for the template name.

For example if you are dealing with node 1 (node ID = 1) try naming the file page--node--1.tpl.php and clearing the cache again.

For more info see: https://drupal.org/node/1089656#page-suggestion

If you don't know what the node id is, go to the node edit page and it will be in the url /node/NODEID/edit.

you can also overwrite the template in template.php as well

function themeName_preprocess_page(&$vars, $hook) {
$vars['template_files'][] = 'page--docs';
}


Views Load More pagination causes duplication I am encountering an issue with Views Load More with Waypoints module. My question is more focused on the next contents that are retrieved. Because there are new contents added to the top, the page 2, for example, now contains items from page 1, thereby showing duplicates. Please see explanation below. How can this be addressed?

Some suggestions:

1) Do not use the LOAD MORE option in views but use a self generated link with the help of global text in the footer. Then this link is going to a second page and then you have the view in a new fresh window. Hopes this helps.

2) You can try if the behavior of the view is the same without Ajax. Sometimes live is a miracle. if so you know that is a ajax issue and not a views issue.

In Drupal views we have an advanced section .In that Other options we ll find the Query edit that settings into distinct .This may avoid duplicates


EntityFieldQuery with fieldCondition returns nothing I have created a custom entity, called 'point'.

I'm able to get all of the entities in the db, with this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point');
$result = $query->execute();

But when I add a fieldCondition, to make sure I only get the one single entity I want, I'll get an empty array back.

It looks like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'point')
    ->entityCondition('bundle', 'point')
    ->fieldCondition('field_point_unique_number', 'value', $unique_number, '=');
$result = $query->execute();

Where $unique_number is a textstring. And it's not a typo in the textstring.
In the db the field 'field_point_unique_number' is a varchar, but only contains numbers.

Why does the fieldCondition return nothing?

I hadn't checked it for trailing spaces. So using trim() on $unique_number did the trick. Thanks for leading me the right way Clive!


open_basedir restriction in effect despite file directory within web root When trying to upload a logo to my Zen 3.1 subtheme (Appearance > Settings) I get the following error:

Warning: is_file(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in image_get_info() (line 126 of /home/testwww/web/informator/includes/image.inc).
Warning: realpath(): open_basedir restriction in effect. File(/tmp/phpillr69) is not within the allowed path(s): (/home/testwww/web/) in drupal_realpath() (line 2177 of /home/testwww/web/informator/includes/file.inc).
Warning: getimagesize(): Filename cannot be empty in image_gd_get_info() (line 349 of /home/testwww/web/informator/modules/system/image.gd.inc).
The specified file logo.gif could not be uploaded. Only JPEG, PNG and GIF images are allowed.

It happens even though I have the paths in Configuration > Media > File System set to be inside the web root.

Public file system path: sites/[my directory]/files [permission 775]
Temporary directory: sites/[my directory]/files/tmp [permission 755]

It seems that Drupal tries to save a temporary file in /tmp/ although the temporary directory is set to something different.

How can I fix the problem to be able to upload a file?

The key here is that PHP is attempting to create the temporary file in a public directory. If you refer to the your PHP settings, find out what is specified for the 'upload_tmp_dir'. Use a phpinfo() call to display this, also available in the Status Report by clicking on the PHP version number. This directory has special privileges that open_basedir will not block. Set your drupal temp directory to this path explicitly and it should work.

Sometimes it's caused by eaccelerator. Just remove it from PHP.


Contextual Filter not getting the correct NID from URL I THINK my Contextual Filter from my view is not getting the correct NID from my URL.

I have a view page with a path of "node/%/agenda".

The link on my menu is "node/[node:nid]/agenda".

The view page will get the nid from a content type "Venue".
Example:
Venue: Rave = NID: 101
View page will be = "node/101/agenda"

I have a working block of "Upcoming Events" and this works perfectly fine on my venue content type. But when I use it on a view page it's not working anymore. Basically this block shows the "Upcoming Events" from "Event" content type that is related to the "Venue" content type.

BLOCK:
Setting:

How it works on content type venue:
This is the wrong part:

As you can see it does not get the same result on the view page, it does not even show the "No Result". I am calling the correct block.

Am I missing something big? I hope someone can help!

THANK YOU VERY MUCH!! ^_^

According to what i can see from the screen shots, you didn't specify your relationship entity on advanced menu. If I were you, I would pick a entity reference, then i would pick a content contextual filters with Nid. Otherwise there is no way that block is gonna understand what the relationship is. Please update us your work. This is a very sensitive topic of drupal. Kind regards

Block displays have no source of arguments at all; they cannot pull arguments from the URL so Create a content pane instead of block in the view and in the "argument input" add the argument number.


Taxonomy manage fields wrong field edit url I have updated my project to the latest updates available using drush and suddenly found no field names and wrong field form url in

 admin/structure/taxonomy/%taxonomy_name/fields

As in the picture, have that issue happened before and how to fix

Edit: I coudn't also be able to add new fields and fatal error occurs

FieldException: Attempt to update an instance of a nonexistent field . in field_update_instance() (line 557 of /modules/field/field.crud.inc

despite being able to add/edit/delete terms

manage display return error

Fatal error: Unsupported operand types in /modules/field_ui/field_ui.admin.inc on line 1025

The issue is reported in issue nr 1275900.

It only happened with taxonomy and other entities work fine.

The problem solved by simply patching the field module file-> field.module function named  field_extract_bundle

function field_extract_bundle($entity_type, $bundle) {
  if (is_string($bundle)) {
    return $bundle;
  }

$info = entity_get_info($entity_type);
if (is_object($bundle) && isset($info['bundle keys']['bundle']) &&     isset($bundle->{$info['bundle keys']['bundle']})) {
return $bundle->{$info['bundle keys']['bundle']};
}
//ADDED THAT ELSE
else{
  return $bundle->machine_name;
 }
}

the function tries to return the machine name of the entity as appeared above.

By doing some debugging I realized that the the object sent in the calling function field_ui_field_overview_form file->field_ui.admin.inc is n't the same as sent in drupal script before our continuous development in that project.

We added many other modules and edit configuration but the most related that I think caused that issue is features exporting the taxonomy vocabulary as the bundle object is the same exported in features so it may be some missing or conflict happened when deploying vocabularies with features

Please contribute your ideas!

Re-install website if possible.

You can find the solution for field_ui.admin.inc here: Manage Custom Display: Unsupported operand types in field_ui/field_ui.admin.inc

  Edit field_ui.admin.inc line 1026:

$settings += field_info_formatter_settings($formatter_type);

  to

$settings .= field_info_formatter_settings($formatter_type);

  Open the error page, save it and then change back the code.


How to disable/hide /unset a block programatically? I have a page whose content is visible only in certain provinces. When people visit this page from a different province other than the one it is set for,it should be giving a message saying "the content is not available in the region" by overwriting the node's body in the same page, by using hook_node_view. But I have blocks enabled in the content area on this page. is there a way to disable the contents of the block? i tried hook__block_view and hook__block_view_alter but it did not work. Can someone help me?

You could try hook_block_list_alter to hide a specific block.

Act on blocks prior to rendering.
This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

If you can't get any of the block alter hooks to work, and/or you don't want to use PHP from the Blocks UI/Admin Page, you could dull ax it by creating your own block and then calling the view, eg, something along the lines of this in your own block:

 if ( "content is available" ) {

   $block['subject']='Subject....';
   $block['content']=views_embed_view('NAME_OF_VIEW','BLOCK_DISPLAY');

   return $block;

 }

and then include that block in your content region instead of the Views block.


Not able to log in to Drupal site as other user I am a site admin (Drupal 7 - all updates are current) and am able to log in with my own credentials.  I'm working an issue and need to log in as another non-admin user.  No matter what I try, I'm not able to log in as this particular other user though I have verified their user email address and password.  I have copied and pasted their email address directly from their user account.  I have also reset their password so I know it is correct.  I have tried turning off clean url's (as suggested by another forum), but that didn't help.  I have cleared the site cache.  I contacted the user and she is able to log in/out and back in with the exact same credentials I'm attempting to use.  We have had this problem with another non-admin user on this particular site but it hasn't happened in quite a while and never with this user.  I have logged in as this user prior to this happening but it has been a few months.

I saw another post on this site about the same thing but didn't really see a solution (Cannot log in to Drupal site).

Does anyone have any ideas?  This is quite an inconvenience.

Once I was able to get in touch with my other site admin and she was able to log in with the same credentials I knew the problem was local.  I had tried different browsers.  I flushed my DNS and rebooted my computer and was able to log in.

I have got a similar issue because other users of your Drupal 7 site will have same permissions as the administrator is assigned with.

See the values stored in role and role_permission tables in your Drupal database.

Check if the rid value is assigned with similar permission values in the role_permission table.[Also take care of the module field if many exist]

If so, this would be because of the reason that the users' roles are created with extra permissions other than:

access content
post comments
skip comment approval
use text format

-which are the default permissions assigned to the authenticated user.

All you can do now is either manually edit the table values[not suggested by the community] or use a module to update the user permissions for each roles.

Thank you.


How can I label content in views as "new"? I use a panel with views on the home page of my drupal site (workaround.org). But I would like to put a "new" label in front of any article that was created or edited in the past 2 weeks. The view field "Node: has new content" did not help me because it will flag any content as "new" for anonymous users. Instead I just want to show anonymous users what content has been added recently.

I have some suggestions, ranked below sort of from simple to complex.

You can simply add a static text field to the view, write "New" in the text field, and then filter the view to contain only content from the period you want to have the "New" label on them.
If you want the same list to also display more content, create an attachment display in the same view, override the text field and the date filter, and set the display to attach after the first one.
Use the Theme information in the view to directly override the views output. Find the content id in the template, load the node, and check the creation date.
Render the content through a view mode instead of on a field by field basis. In the the node-template, you can now check the creation date of the node and output the label. This solution would possibly benefit from an added 'per-view-mode' theme suggestion.

Views by default provide this functionality for the new content

You just need to select the field(Content: Has new content) in views, it will add a div with unique class and with text "new"

it works with individual user, means if user is watching it first time then only for that user new tag will appear

I hope this will help you.
Thanks


Find item position in the pager I was wondering how I am able to find the position of an item in a views pager?

I have nodes listed using views (with pager, 20 every page), and I'd like to find out for example where in the pager one node is?

EDIT (2015-04-05): Updated the snippet to work with newer version of Views.

Us too had to find the page number of a views result on which a certain node appears, so we can redirect visitors to this page.

By loading a view for a specific display and executing it's query manually, we retrieve an array with all node ids which we can search for a specific node id. When we have got the position of the node id, we divide it by the amount of items per page to get the page number the node is on.

I understand that loading all node ids at once in an array probably should not be done on large amounts of records, but for this exercise it's okay.

/**
 * Custom function to get the page number of a views result a node appears on.
 * Based on Drupal's views_get_view_result().
 */
function yourmodulename_views_get_item_page_nr($nid, $name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $nid
  array_shift($args); // remove $name

  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }

    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }

    // Set the limit to 0 to retrieve all node ID's.
    $view->set_items_per_page(0);

    $view->pre_execute();
    $view->build();

    // Get the views query.
    $query = $view->build_info['query'];

    // Get the return assoc array with return objects, keyed by nids.
    $nids = $query->execute()->fetchAllAssoc('nid');

    // Get position of nid in nids array.
    $index = array_search($nid, array_keys($nids));

    // Get amount of items per page.
    $items_per_page = $view->display[$view->current_display]->handler->get_option('items_per_page'); // As seen at http://api.drupal.org/api/views/includes%21view.inc/function/view%3A%3Aexecute/7.

    // Calculate page number.
    $page_nr = $index === null ? 0 : intval($index / $items_per_page);

    return $page_nr;
  }
  else {
    return 0;
  }
}

How to get that depends on what you will be using for.
If you will be using for calculation under the hud. You could get it using simple php:

$position = $absolute_position % $pager_limit;

$absolute_position is position of node in not paged the whole list if Drupal does not give you that by default at worst case scenario you could run a simple foreatch loop which would check for the node`s title or id to match.

If you will use it for theming Javacript can do the trick. Would personally use use jQuery library to make easier for my self. A simple script could find desired element by it`s tags and then change it accordingly.


How to get newly created node ID after Feeds importing? I programmatically executed feeds importer to create new nodes. I have to set some fields programmatically after importing. I check the hooks in feeds.api.php, and didn't find a solution. Is there any way that I can get the newly created node ID by the importer?
Thanks

I found the solution. Use $entity NOT $entity_id in hook_feeds_after_save.


Filtering on node whose user ID is equal to the current user In Drupal 6 you can have a filter node.uid = current user. How do you do this in Drupal 7?

You need to add the filter as a "context" (Advanced) where you can supply a default argument. If you context is for a user, like the node author, then you can select stuff like id of logged in user.

you can add simply

"User: Current" in "Filter" criteria.


Prevent Multiple Form Submissions (Server side) I'm running into a problem where a user can submit any form built by the Form API multiple times (fast clicking resulting in multiple requests).

I've put in the basic client side (javascript) solution of disabling the button, but I'm curious what the best approach to preventing this situation is on the server side.

Is there a recommended way to use Drupal's form token system to handle this?  Especially a global form solution (ie, adding a custom validator to every form using hook_form_alter()).

My approach so far has been something like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_form_validate';
}

function mymodule_form_validate(&$form, &$form_state){
  //initialize form array
  if (!isset($_SESSION['submitted_forms'])){
    $_SESSION['submitted_forms'] = array();
  }

  $form_token = $form_state['values']['form_token'];
  if ( isset($_SESSION['submitted_forms'][$form_token]) && $_SESSION['submitted_forms'][$form_token] = TRUE ){
    form_set_error('name]', 'This form has already been submitted');
  }
  else{
    $_SESSION['submitted_forms'][$form_token] = TRUE;
  }
}

I'm running into trouble where the form_token isn't unique to the form - it seems to stay the same no matter what happens.  I'm probably misunderstanding what the token is in the grand scheme of the form api.

Any insight is appreciated!

I had the exact same problem and managed to fix it using the Locking mechanisms from Drupal

In the validate function I used:

function mymodule_custom_form_validate($form, &$form_state){
  if (lock_acquire('your_custom_lock_name')) {
    // long operations here
  } else {
    form_set_error("", t("You submitted this form already."));
  }
}

And in the submit function I released the lock:

function mymodule_custom_form_submit($form, &$form_state){
  // submit code
  lock_release('your_custom_lock_name');
}

This was my problem also before. My solution to this is to disable the button via JS.

.module:

/**
 * Implementation of hook_init().
 */
function myModule_init(){
if (arg(0) == 'node' && (arg(2) == 'edit' || arg(1) == 'add')) {
    //hide btn when clicked on article nodes
    drupal_add_js(drupal_get_path('module', myModule') . '/js/disable-submit.js');
}

JS:

Drupal.behaviors.module_disable_submit = function (context) {

/*
 * Disable keypress on form fields.
 * Prevent browser to reload when pressing enter in input fields
 */

$('.buttons input:submit').click(function() {
  $('.buttons input:submit').hide();
  $('#node-form .buttons').prepend('<input type="submit" style="margin:1px 0; box-shadow:0 1px 1px #DDDDDD; border-radius:3px 3px 3px 3px; background:url(/sites/all/themes/rubik/images/bleeds.png) repeat-x scroll 0 -41px #F4F4F4; border-color:#DDDDDD #DDDDDD #CCCCCC; border-style:solid; border-width:1px; color:#B8A98F; cursor:default; font-weight:normal; padding:2px 10px; text-align:center;" value="Saving..." name="op" onclick="return false;" />');
  if ('.buttons input:submit') {
    $('.buttons input:submit').keypress(function() {
      $('.buttons input:submit').parents("form").submit();
      $('.buttons input:submit').hide();
    });
  }
});
}


Conditional rewrite on views according to singular / plural I am building a website using views and the answer module.

In my view, I add "Content: Answer Count" which is the number of answers.

I want to be able to rewrite the following output:
(1 Answer)
(2 Answers)
(3 Answers)
...

I know how to output "(no answers yet)" when the count=0.
But, how can I differentiate between singular and plural and output "Answer" or Answers" according to the count?

Drupal views provides a singular/plural option, if the field value is an integer type. In your case, if its not available in Field settings try using views_php contrib module.

This module will allow you to add a field in views with php code that will executed on the fly. You can get existing values of row data inside php from $data variable. Now you can get your output based on the singular/plural in php.

But it is suggested to check the field settings properly if same option is available.

use a global field (math), which will give you the option of the plural formatter


Can I disable Toolbar in specific theme? I have two active theme, and switching between them by themekey on specific paths.

theme #one is my main theme, and some contents load in theme #two in a modal box (lightbox2).
I need disable Toolbar on theme #two because it's load Toolbar too and I don't want it there.

my question is how can I disable Toolbar in theme #two?

You'll have to use hook_page_alter from within a module to unset $page['page_top']['toolbar'] — you can't do it from within a theme.

There is a module for that: Toolbar Visibility.

Or you can disable the 'toolbar' module for this.

https://www.ostraining.com/blog/drupal/adding-the-administration-menu-to-drupal-7-and-disabling-the-default-toolbar/

Is it the best way you think?
Or plan something like,

 1.
      if ($vars['page']['page_top']['toolbar']['#access']) {
         $vars['page']['page_top']['toolbar']['#access'] = false;
      }

But I don't know where could you find the '$vars' from.


How to add css using the Preprocess_image function? I'm trying to preprocess my image style like this example

<img class="media-object img-rounded img-responsive"  src="http://placehold.it/350x250">

My preprocess_image function looks like so:

function bootstrap_subtheme_preprocess_image(&$variables) {
  if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'logged-in') {
      $variables['attributes']['class'][] = "media-object";
      $variables['attributes']['class'][] = "img-responsive";
      $variables['attributes']['class'][] = "img-rounded";
    }
  }
}

But it is not adding the classes.

Why not?

Try this.

function mytheme_preprocess_image(&$variables) {
   if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'image_style') // this is an image style used in drupal's image styles {
     $variables['class']['img-responsive'][] = "true";
  }
 }
}