Select fields with group names in Drupal 7? When you make a select list on a webform module you get the option to group values by a group name or category: "Option groups for lists and menus may be specified with . <> can be used to insert items at the root of the menu after specifying a group." Reference : http://drupal.org/node/325766 -> "Entering options through the interface"

Is this something I can do with the defualt node select fields aka (list module) ie. http://drupal.org/documentation/modules/list ? I have never heard of it but it would be nice. I have to make a list of working group positions on my site and I have 3 groups each with it's own group name, Hospital, Dental and Physicians and I am trying to figure out the best way to list these groups and their positions in a nice select value widget, I was thinking of using taxonomy but it's not really the same thing as what I want.

You can do that if you use php to generate the allowed values, as you have already read in Select fields with group names?. However, that feature did not go into Drupal core when most of the CCK module for Drupal 6 was included in Drupal 7. The D7 version of CCK tries to provide this feature. As the module page says, it contains:

  some miscellaneous helpers to do things that core will not do, like maintain the PHP code snippets some fields may have been using to define allowed values (partially working)


Submit handler in hook_form_alter not working in d8 I have hook_form_alter as follows :

function auto_ga_form_alter(&$form, &$form_state, $form_id) {
    global $base_url;
    if($form_id == 'node_p_request_form' || $form_id == 'node_p_request_edit_form' || $form_id == 'node_f_pro_request_form' ) {
      $form['#submit'][] = 'custom_form_submit_fn';
      $form['actions']['submit']['#submit'][] = 'custom_form_submit_fn';
   }
}

function custom_form_submit_fn(&$form, $form_state) {
  echo 'reached in submit handler';exit;
}

But its not going to the submit handler . both usage ( $form['#submit'][] OR  $form['actions']['submit']['#submit'][]) of submit handlers not working

And idea ??

What you are doing looks like it should work.

Doing an echo is undetecable in the submit handler, since Drupal will do a redirect after the POST request and thus clearing all of the output generated but Drupal in the actual submit handler.

A simple way to test if the submit handler is called or not is to insert a die()

Reasons for submit handler not being called could be:

You submit the form with a button you haven't added a submit handler on and that already have one or more attached to it.
Another alter hook removes your submit handler (unlikely)


HOOK_entity_presave: field not accessible I have been brooding on this problem for a while now and i can't figure it out:

I am trying to retrieve and finally modify two values of my entity. With the first one (field_registro) it works, with the second one (field_final_note) it doesn't.

Both fields are of type Number (integer) with no restrictions.

This is how my hook looks like:

function mymodule_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  var_dump($entity->field_registro); // works
  var_dump($entity->field_final_note); // NULL
}

When i dump the whole entity i can see both fields (the second one should be empty and be set programatically, the first one has a user value).

See the dump here: https://pastebin.com/wcpyDt9h

I can see that there is clearly a difference in the structure, but i can't figure out WHY and HOW to fix it.

Can anybody point me in the right direction please?

Since Drupal 8 you need use OOP methods to get value from an entity field.
For example:

// If you have a field with machine name "field_final_note".
$values = $entity->get('field_final_note')->getValue();

Also, have a look for the type of the entity:

if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'node_type') {
 // Your code.
}

P.S. Well it is very helpful to know the next points

// An old entity state.
if (isset($entity->original)) {
  $old_entity = $entity->original;
  // Some code.
}

// If the entity is new.
if ($entity->isNew()) {
  // Some code.
}


Copy values from taxonomy term field to new text field in content-type I have a content-type with a certain taxonomy term field that allows multiple values.

I don't need this field to be a taxonomy term field anymore, but just a simple text field. So, I want to "transform" the nature of the field.

I do know it is not possible and that I have to create a new text field and copy the values of my first field into my second through a custom php script.

But I hardly think that I'm going to need some help from you guys for the SQL query that will be a bit complex.

I need to recover all the term's names for each piece of content
and, if there are several of them, concatenate them with a comma (for example),
and then copy the result in the new text field before deleting the old taxonomy field.

The truth is I have no idea how to proceed. Can I run the query directly in PhpMyAdmin? Or in a PHP file? Do I need to use a simple SQL query or an EntityFieldQuery class? I'm not very familiar with this kind of stuff.

Thanks in advance for any clue...

According to me you can achieve it by doing something like:

Creating a PHP script which: Get all terms related to a node and then create a comma separated value for them and then store this as value of your new field in database.

You need to iterate over all nodes and the run following code to get all terms

$result = db_query(
SELECT ttd.tid, ttd.vid, ttd.name, ttd.description, ttd.weight
FROM taxonomy_term_data AS ttd
INNER JOIN taxonomy_index ti ON ti.tid = ttd.tid
WHERE ti.nid= :nid
ORDER BY ttd.weight, ttd.name',array(':nid' =>$node->nid));

Or you can use Drupal code as well for doing the same

$node = node_load(arg(1));
if ($node != NULL) {
$field = $node->field_my_vocabulary;
$lang= $node->language;
$terms_all = $field[$lang];
foreach ($terms_all as $term) {
$terms[] = $term['tid'];
}
return implode('+', $terms);
}

Now assign this vale to you new field.

The above code is not tested by me, but I hope it can do what you want with no/little modification :)


Get content type with PHP from database I have created a content Type Student, I have imported the list of student with node import. Now I want to get the name, location and other values of the content type Student from my database. How can I do that with PHP? I have already created a simple module with a menu and block.

To retrieve a Student node (in OO-lingo that would a Student instance), use node_load(). If you want to retrieve all Student nodes, you have to loop over the result of a database query like this

$results = db_query(db_rewrite_sql("SELECT nid FROM {node} WHERE type = 'student'"));
while($nid = db_result($results)) {
  $node = node_load($nid);
  // Do something with $node
}

If you have a lot of Student nodes, it's probably not a good idea to process all of them in a single run. If you really need to process all of them, you should use the Batch API.


Render view array programatically within template I would like to print the array of a specific View within a template, so I can then access each specific field and theme as I wish. The view I am using will only be outputting one row. All my attempts seem to be returning 'previously declared' errors.

Your help is appreciated.
Thanks

There are a few steps involved with applying a template to view. But thankfully they are all fairly simple.

I found one of the most helpful tutorials was this one, which goes through the process. I think this process should give you sufficient control over the theme for each field.

I'm not sure why you might be getting the 'previously declared' errors though.


How can i display user name and email address fields to the user on "My Account Page"? I want to show the user, his/her email address on their "My Account" Page. I am not using any modules for the registration page, but just the default Drupal 7 registration fields.

How can i display user name and email address fields to the user on "My Account Page"?

You will need to create a custom module to achieve that functionality.

If you want to override tabs in view page

function mymodule_menu_alter(&$items) {
  $items['user/%user/view']['title'] = t('My account');
  $items['user/%user/edit']['title'] = t('Edit account information');
}

If you was to display additional info in view page

function mymodule_user_view($account, $view_mode, $langcode) {
  // hide unwanted fields
  hide($account->content['summary']['member_for']);
  hide($account->content['summary']['blog']);
  hide($account->content['user_picture']);

  // add information
  $account->content['summary']['#title'] = t('My Account');
  $account->content['summary']['personal'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Personal'),
    '#markup' => get_profile_details($account),
    '#weight' => -100,
  );
  $account->content['summary']['login'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Login'),
    '#markup' => get_profile_details($account, 'login'),
    '#weight' => -99,
  );
}

This function returns details in list. Feel free to add/delete details based on your requirements

function get_profile_details($account, $view = 'personal') {
  // profile details
  $items = array();
  switch($view) {
    case 'personal':
      if($account->picture) {
        $items[] = theme('image_style', array('path' => $account->picture->uri, 'style_name' => 'thumbnail'));
      }
      $items[] = t('Name: ').$account->field_account_first_name['und'][0]['value'].' '.$account->field_account_last_name['und'][0]['value'];
      $items[] = t('Email: ').l($account->mail, 'mailto:'.$account->mail);
      $roles = array();
      foreach($account->roles as $role) {
        if($role != 'authenticated user') {
          $roles[] = ucwords($role);
        }
      }
      if(count($roles) > 0) {
        $items[] = t('Role: ').implode(', ', $roles);
      }
      else {
        $items[] = t('Role: ').t('General user');
      }
    break;
    case 'login':
      $items[] = t('Username: ').$account->name;
      $items[] = t('Timezone: ').$account->timezone;
      $items[] = t('Member since: ').format_interval(REQUEST_TIME - $account->created);
      $items[] = t('Last login: ').format_interval(REQUEST_TIME - $account->access);
    break;
  }
  return theme('item_list', array('items' => $items));
}

Let me know if you need any help


Module used to redirect pages to SSL Is or are there currently a module(s) that redirects users of a drupal site to enforce a SSL connection on parts of the website?

Essentially accomplish the following use case:

  A user visits a glob pattern: /cart/*, / it enforces https://
  connection as well as redirects any images/javascript to utilize a ssl
  connection.

Looks like this is currently the canonical answer:

Use Secure Pages

  This module makes sure that the user is running on a secure page when
  they create or edit content, view user details, or administer the
  site.

The other part of my question regarding redirecting assets on a page to a secure connection has actually be integrated into drupal core. It was previously a contrib module: http://drupal.org/project/securepages_prevent_hijack

  #D7CX: This functionality is in Drupal 7 core so this module will not be ported. Please stay tuned for the securepages port.

  This is an add-on to the Secure Pages module that will prevent
  hijacked sessions from accessing SSL pages, yet still allow users to
  stay logged in when browsing non-SSL pages.

Drupalscout looks to have a great site recipe on working with SSL's as well:

  The Secure Pages module is a relatively old module and quite popular.
  It's goal is to only make certain pages of the site use HTTPS by using
  two lists of urls which should either by HTTPS or not. The benefit of
  this module is that you can use regular old HTTP for most of the site
  and only encrypt the traffic where you really need it. By default it
  will encrypt traffic for adding content, editing content, anything
  related to users, and for the admin area.

  SSL processing is taxing on a server. Using SSL on just the most
  important pages helps make sure that the data sent back and forth on
  those pages is encrypted. However, the session cookie is still
  unencrypted so a user who authenticates over HTTPS and then visits a
  non secure page sends their sesssion identifier in the clear which
  allows for an attacker to steal their session and login to the site
  which gives them the access to the very data that was supposed to be
  protected. This is largely "security theater" but it sure makes people
  feel good.

  Pro: Reduces load on server compared to a full SSL solution while
  encrypting important data transmission. Con: Doesn't protect against
  session hijacking so data can still be compromised.


Can I control what caches are flushed via "Flush all caches"? I use the module Boost and anytime I click "Flush all caches" it deletes all the cached pages already built. Is there any way to make "Flush all caches" to flush all cache instead of the Boost-created .html.gz cached pages?

If you're using the admin menu module you can selectively target which cache to flush by hovering over the the Flush all cache menu under the home icon. The Class registry and Page and else will wipe out the Boost cache, but everything else will leave it intact.


How can i add WYSIWYG editor for my custom form textarea? I wrote a custom form module in that I placed one text area:

I've tried in this way:

$form['message'] = array(
  '#title' => t('Message'),
  '#type' => 'textarea',
  '#format' => 'full_html',
  '#default_value' => isset($ntemplates->message) ? $ntemplates->message : '',
  '#maxlength' => 255,
  '#attributes' => array(
  'class' => array('field_info'),
  'rows' => '5',
  'cols' => '200',
  ),
  '#wysiwyg' => TRUE,
);

But it doesn't work. How can I integrate WYSIWYG editor in to my text area?

Note: I'm using wysiwyg-7.22 and ckeditor-3.6.6.2. In the basic page body section it's working. I wrote one custom module for form. In this I am unable to integrate wysiwyg editor.

Drupal 7 introduces the form element #type text_format, which is a text-format-enabled version of a textarea.

To integrate WYSIWYG into your custom form, just modify the attribute #type of form as:

'#type' => 'text_format'

Note: Tested it with CKEditor v 7.x.

In case if it doesn't work for you, please check your WYSIWYG configuration.

To hide format options, see: How to hide Input Format Options and help text under a textarea?

Above text field type works in Drupal 7 and 8.


Add a caption to an image field that allows multiple images OK, the heading isn't the best example of english ever, but I hope you get what I mean...

I've run up against the bug in Drupal where it doesn;t check the length of the title value in an image field (http://drupal.org/node/916446) and I was using that field to store the caption for the image which I was displaying in a div underneath the image.

Is there a way to either allow the title field to hold more information, or even better (semantically especially), create an additional field to hold my caption information?

The reason I don't just create a separate field for caption is that I'm allowing multiple images on the image field and from a content management point of view, I wouldn't easily be able to match up the images to their captions.

I'm sure it's something simple like creating a version of the image.field.inc? Has anyone done it or know how to make this happen?

I believe what you are looking for is the Field Collection module.  It allows you to group fields together and repeat the group many times.  The following article gives a good description of what the module does: Create Multigroups in Drupal 7 using Field Collections

From the Field Collection project page:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.


How much memory and storage does a website take on a server? Hello Drupal community!

This is my first time working with Drupal and AWS. I would like to know if an AWS t2.micro instance would be good enough for running a new Drupal 8 website with moderate requirements. My main goal with this is to stay within the AWS free tier, i.e, spend no money for one year whatsoever. The EC2 information page states that a t2.micro instance has 1GB of memory and "EBS only" storage (bear in mind that this is the storage for the server). After looking into this I found that EBS has 30GB's of storage. Will that much be sufficient?

Totally I have to run a Drupal 8 site, an AWS RDS MySQL database and AWS S3, all on this instance comfortably (which obviously means a good amount of people should be able to view the website  at the same time too). Any requirements for Drupal 8 would be welcomed.

Please get me out of this jam. Thanks a bunch!

You should be fine with 1GB server ram, and 256M set for PHP. Keep in mind you won't be running a huge site with it, so also invest in getting caching like memcache and something like varnish going as well. I'm not sure if memcache is PHP7 ready yet - but using php7 will gain some performance increase as well.

However if you're looking for free hosting, I think you could also try Acquia Cloud Free.


How to convert date/time from timezone to another timezone in migration process I'm using format_date process plugin to import data from external API to drupal 8 node.
The date/time in API is "Asia/Jerusalem" time - 2017-06-24 20:52:55
The date/time from the API is saved in drupal node as it was a UTC 2017-06-24T20:52:55
When the node is displayed (I have "Asia/Jerusalem" timezone defined for me) it shows 2017-06-24 23:52:55

This is the configuration file I used

source:
  fields:
    -
      name: status_updated
      label: 'Status updated'
      selector: status_updated
destination:
  plugin: 'entity:node'
process:
  field_ext_status_updated:
    plugin: format_date
    from_format: 'Y-m-d H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    #timezone: 'Asia/Jerusalem'
    settings:
     validate_format: false
    source: status_updated

I need either to convert the source date first from "Asia/Jerusalem" to "UTC" and then pass it to format_date or change the configuration file in way that it will save the date as 2017-06-24T17:52:55so for users with timezone "Asia/Jerusalem" it will show the correct date/time 2017-06-24 20:52:55

How can I achieve it?
removing the comment for timezone: 'Asia/Jerusalem' not helped

Timezone conversion is not yet supported - the issue where it's being developed is https://www.drupal.org/node/2883892.


why don't set the placeholder attribute for contact field? this is my hook_form_alter function for set the placeholder attribute and other stuff:

 function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'contact_site_form':
            $form['tel'] = array(
                '#title' => t('Tél'),
                '#type' => 'textfield',
                '#required' => TRUE,
            );
            if ($form_id == 'contact_site_form') {
                $form['name']['#title'] = t('name/family name');
                $form['name']['#attributes']['placeholder'] = t('Enter your name');
            }
                $order = array(
                '1' => 'name',
                '2' => 'mail',
                '3' => 'tel',
                '4' => 'subject',
                '5' => 'message',
                '6' => 'copy',
            );
            foreach ($order as $key => $field) {
               $form[$field]['#weight'] = $key;
            }
            break;
       }
  }

why don't set the placeholder attribute for contact field?

kpr() for this element shows:

edit

$form['name']['#attributes']['placeholder'] = array(t('Enter your name'));

to

$form['name']['#attributes']['placeholder'] = t('Enter your name');

then execute "flush all caches"


Fetching field values only if they exist and applying them automatically as entity labels I have a content type with these fields, among others:

field_address – required
field_entrance – not required
field_apartment_number – not required (or actually required if a previous field meets a certain criteria, otherwise not shown at all)

With the Automatic Entity Label modul I can use tokens to save the node title using this pattern:

[node:field_address] [node:field_entrence] [node:field_apartment_number]

If any of the non required fields are left blank there's no value from those fields saved to the node title. However, the whitespace between the tokens is still saved, and I don't want that. I'm not good at PHP but this I what I have, copy-pasted from various sources:

<?php

$address = field_get_items('node', $node, 'field_address');
$entrance = field_get_items('node', $node, 'field_entrence');
$apartment_number = field_get_items('node', $node, 'field_apartment_number');

print $address['value'];

if ($entrance) {
   print ' ' . $entrance['value'];
}

if ($apartment_number) {
   print ' ' . $apartment_number['value'];
}

?>

But it doesn't work. Instead, no title is saved at all. How do I correct my code?

As far as I remember, field_get_items() returns an array of items.
In your case something like:

    if (count($address)) {
       print $address[0]['value'];

       if (count($entrance)) {
          print ' ' . $entrance[0]['value'];
       }

      if (count($apartment_number)) {
         print ' ' . $apartment_number[0]['value'];
      }
   }

should work.


How can I create multiple chatrooms using the Drupalchat module? I want to create multiple chat rooms in DrupalChat module.

Anyone can help me to complete this requirement?

This question is pretty similar to the (still active) issue about Multiple public chat rooms - role controlled, here is a partial quote from that issue:

  Any chance you can allow the administrator to create more global chat rooms? I would like to create a chat room for Children so Adults cannot gain access and adult rooms where teens and children cannot access.

Comment nr 4 (from the module owner of the DrupalChat module) states the following: this option only exists in "iFlyChat Servers" polling method.

Here are some more details about iFlyChat (= quote from https://iflychat.com/):

  With iFlyChat, websites need not worry about setting chat server of their own. iFlyChat server will take care of the hosting part and will provide a hassle free setup of chat system. We use latest onCloud technology which gives a faster chatting experience to all users of your website.


create thumbnails of Vimeo videos programmatically I am wondering if there is a way to create thumbnails of Vimeo videos programmatically. e.g. is there a function like image_style_url() to create an image derivative given a style and image path?
thanks.

You you can use the Vimeo Simple API to get the video thumbnails.

There is a fantastic write up here on stackexchange so I won't reinvent the wheel, but for a quick re-cap you can use the following code (thank you @Fluffy from link above.)

<?php

//Video ID - Easy to find in URL (example ID below)
$video_id = (int) 6271487;

//Format you would like returned. (Can be php, xml or json)
$format = (string) 'php';

//Build request URL
$request_URL = "http://vimeo.com/api/v2/video/$video_id.$format";

//Get data and unserialize
$response = unserialize(file_get_contents($request_URL"));

//Echo's url to image.
echo $response[0]['thumbnail_medium'];

?>

Optionally, check out the Vimeo Advanced API method: vimeo.videos.getThumbnailUrls


How to display product attribute as filter in product listing page? I am creating an e-commerce website using ubercart and Drupal 7. I have created product attribute size and color for the product from the "Administration » Store » Products" and assigned to product.

I have created a views page to display product listing .

Now, the problem is that I want to display product attribute as filter in the above product listing page. I have searched on Google but did not find any solution for that.

bit late for the answer perhaps, but perhaps someone else finds it usefull.

Ubercart uses 'Attributes' and 'Options'. Filters uses 'Taxonomies' and 'Terms'. Menu modules like taxonomy filter, hierarchical select use the terms. There is no connection of these two as far as i know.

To use these filters, we have terms synchronized with options. So for every option there is a term as well. On the product edit screen, we have enabled the taxonomies corresponding to the product attributes. So on the product edit screen you can manually add terms for taxonomies. We set these tags automatically when we import the options data through a csv or cash-register connection. (And set options based on received term data as well.)

When you have this solved there is issue 2. Options without stock should (often) not be shown in menu options.

So when f.i. Shirts->Red-Size XL has Size XL out of stock, then term XL should no longer be visible in the filters (when this is the only product). We made small adjustment to 'order-invoice' trigger where stock is reduced, to also check and remove terms where needed.

For handling this automatically and with a nice user interface I created a custom module.


Reloading a page from selecting a taxonomy term from a views filter general

I have a book containing docs for multiple versions of software.

I want the pages of those books to be searchable and sorted per version.

specifically

I have a node override provided my panels of a certain content type.

One of those panels is a view displaying the content type that has been tagged with a taxonomy term.

How can I

Create an exposed filter that provides a dropdown selection of
terms, in this case, version numbers?

and

Have the page reload the view after a new term, in this case, the
version number, is selected and then submitted via a submit button?

This would preferably be done with contrib modules.

No need for contrib modules: it's all in Views.

So firstly you'll need to add a Filter criteria in your View.

Add
Select the term field (Topic in my case)
Configure extra settings: Dropdown
Configure filter criterion: Expose this filter to vistors

Secondly you'll need to enable AJAX submits.

Advanced > Other > Use AJAX > Yes

There are a couple of contrib modules that may be useful however.

Chosen for very long select lists
Better exposed filters if Select lists aren't good in your case


End User Database Management So, this is my first question on Stack Exchange! So, I'm currently working on a project in which users of my Drupal site are playing a game as art collectors, and have a collection of artworks, which they can trade and sell during the game. Since my users will need to be able to reassign ownership of works (which would be stored in a database, as each work has several fields attached to it (artist, date, value, material, size, etc.)

And while I want them to be able to change ownership, it'd be preferable if I could let them do this in some kind of GUI, where I could limit control of what fields they could edit. In an idyllic scenario, they would have a drop-down menu they could select from to choose the new owner of the work, but I'm not sure how realistic that is.

Any modules that could assist in this would be fantastic, or if you have a different approach (other than a database), I'm more than happy to hear. This Drupal site is currently running on Ubuntu 16.04 LTS with the latest Drupal 7.5 installed.

I hope I was concise enough in my first question, and that somebody can help!

In a nutshell, you could do this with a user reference field, but you would be exposing everyone in the system (assuming all of these people are Drupal users). Maybe that isn't a big deal, maybe it is. I would create a view reference for the user reference field to only show users who are of a given role only, which should limit results. Furthermore, they would have to know the Drupal username - but you can get around that by installing RealName which swaps usernames for a realname field.

A reason for tying nodes to user accounts would be built-in permissions. "Owner" as just a Drupal textfield wouldn't really cut it in terms of true ownership.

I have done this in the past, similar scenario, different circumstance, where the system would create listings for businesses in the local area, and the business owners would come, register, and 'claim ownership' of their listing node by contacting us (webform). After vetting, we would change the node author (owner) from the admin to their Drupal account. Since they could have multiple, their user account dashboard listed all nodes that belong to them, free to edit and update.

I would also advise using a revision workflow so admins can track the history of a node and revert mistakes (as they are bound to happen from time to time).

Note, I am assuming your game pieces are custom entities or content types. It will work in either case.

You would need to give users enough permission to 'edit own ____' entity, and be able to update the user reference field. On submit, you could fire a custom rule with Rules that looks at the user reference field value, and updates the entity owner to that value (uid). Alternatively, you could implement a custom submit handler via hook_form_alter on specific forms, and do the logic yourself. The referenced UID value gets set as the owner, and once that happens, that user will no longer have access to edit or anything.

See:

https://www.drupal.org/project/realname
https://www.drupal.org/project/rules


Need to create a RedHen Contact for each Drupal User I'm wanting to upgrade a current site to use the RedHen CRM module to track contact engagement (etc.) but first need to create RedHen contacts (redhen_contact module) for each of the users.  I'm familiar with Drush scripts so would be fine writing up a script but I'm unfamiliar with the internals of how RedHen works in Drupal.  Is there anybody who knows it already who might be able to help point the way?

Note: This is not a third-party api. It's a CRM built within Drupal as a Drupal module. What I'm asking is the proper form to utilize the Entity API to create contacts within the RedHen CRM module programmatically.

Rules might be the quickest way to achieve this.

You could have one that on user create, generate a new contact for that user, and a separate rule that after a user updates their information update their contact.

According to RedHen documentation, they have direct rules support so this seems like an easy addition.


How can I delete old entries in locales_source Drupal 7. I have used the t() function to translate many string in different languages. I used English as default language, and added t('This is a new string') all around my module files, template files, etc.

The problem is that I have changed the original string names several times, and in some instances, I didn't delete the "duplicate" entries, so there is garbage. Is there a way of listing or retrieving all the t() strings that I added? Maybe comparing with a fresh Drupal installation and exporting a template *.po and using a program to compare the changes ?

Thanks!!!

One way to get rid of unnecessary entries in locales_source is to run the following:

DELETE locales_source
FROM   locales_source
LEFT JOIN locales_target lt
using (lid) where lt.lid is null;

To get an idea of what this will remove from the table, you could check using:

SELECT count( * )
FROM locales_source
LEFT JOIN locales_target lt
USING ( lid ) WHERE lt.lid IS NULL;

I got the idea from : http://julian.pustkuchen.com/en/drupal-7-performance-blown-localessource-table

In my case, I had a lot of stale content in locales_source. I also had many pages where content was tagged as being translated, but the page included many call t('...') calls, which added unnecessary entries to the table. Long story short, I was able to safely remove over a million rows of data and site performance went from absolutely awful to humming along nicely.

YMMV, but it worked for me.


How to attach a list of fields to an entity I have a node, and I'm looking to attach a list of fields to it. The number of fields should be dynamic. I realize I can create a new content type, and use entity reference module to build a list of related nodes, but I feel like that's overkill. I really just need to attach simple list (or list of fields). Is there a way to do this? or am I misunderstaning

There are a few possible solutions to what I believe you are asking:

Use a field collection.
http://drupal.org/project/field_collection

It allows you to create a field containing a few fields of information and attach those to a node. I think it is most likely what you are after.

A simple multi-value text field
The simplest option to attach a bunch of names to a node is just to set up a text field with unlimited values. Then you can add as many as you like. But I imagine that's simpler than what you need.

Taxonomy terms
If the values need to relate to each other across the site, use a term reference field with unlimited values and allow your users to create new terms on the fly when they don't exist already.

Content Type
If all of the names you need to add have additional data attached to them, you might need to go down the additional content type and node reference path you mention in your question.

I hope one of those ideas is what you after.


Navigate to page with content displays page not found error I have a URL (/url1) that I navigate to that is showing content because of the Context module.

The Context module has a condition that when the user navigates to /url1, some view blocks are rendered on the page. However, it is also rendering a "Page not found" error at the bottom of the page.

I can't figure out how to remove that message and get it to work properly. It even has the title "Page not found" on the tab with the page. The blocks render just fine in the way I want them.

You need to have some sort of content assigned to the URL url1. The simplest way would be to create a new Basic page node and set its URL alias field to url1.

By the way, what you are seeing now is the "page that is displayed when no other content matches the requested document" (Administration >> Configuration >> System >> Site Information >> Default 404 (not found) page). You can have a specific page assigned as your Page not found page, or Drupal will build the content for it on the fly, and show it using the most appropriate template in your theme (most likely page.tpl.php).


Disable coupons field from checkout page when order total amout is less than $500 I am working on Drupal commerce site. Using commerce_discount_extra and commerce_discount for discount and coupon code.

I just want to display Coupon apply filed into checkout page while the total amount of order will be >=$500. Below $500 the coupons field will not display into checkout page.

So can anyone please tell me how can I disable the Coupons fields from checkout page when the order amount will be less than $500?

Thanks in advance.

Hope it works.

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

  if ($form_state['order']->commerce_order_total['und'][0]['amount'] < 500) {
    unset($form['commerce_coupon']); // enter coupon form name
  }
}


Drupal commerce show taxonomy image in product variation I'm trying to change the view of the product variation.
Let's say I'm selling t-shirt in different color so I create the taxonomy with the color and a small image of the color.
I create the term reference in product and enable the "Attribute field settings".
Now when i display a product i should be able so see the image of the taxonomy to choose the color but it shows me just the title in a select list or radio button. How can I override it?

Thanks in advance.

You need the Commerce Fancy Attributes module.


How to get a list of entities programmatically? I wrote custom rules action to get a list of active simplenews subscribers, but I can not process it with "loop" cycle. Action should get list of active simplenews subscribers ("entity_fetched" array). Then I pass it to "loop" for processing (and to get "list-item" variable) and there are no errors. But when I try to set status message (add action - system - set message) with "list-item:uid", system says: "Data selector list-item:uid for parameter message is invalid". More, I can not select "list-item" token at all. I think, there are some mistakes when the code returns "entity_fetched" array. There is my code:

<?php

   function custom_simplenews_rules_rules_action_info() {
      $actions = array(
         'custom_simplenews_rules_actions_get_subscribers' => array(
            'label' => t('Get subscribers by Simplenews Newsletters category'),
            'group' => t('Custom'),
            'parameter' => array(
               'category' => array(
                  'type' => 'text',
                  'label' => t('Category'),
                  'options list' => 'custom_simplenews_rules_options_list',
                  'description' => t('Specify category to select users from'),
               ),
            ),
            'provides' => array(
               'entity_fetched' => array('type' => 'list', 'label' => t('Fetched entity')),
            ),
         ),
      );

      return $actions;
   }

   function custom_simplenews_rules_options_list() {
      $taxonomy_vids_objects = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE module = :module", array(':module' => 'simplenews'))->fetchAll();

      $taxonomy_vids_array = array();
      foreach ($taxonomy_vids_objects as $value) {
         $taxonomy_vids_array[$value->vid] = $value->vid;
      }

      $taxonomy_vids = implode(',', $taxonomy_vids_array);
      $taxonomy_tids = db_query("SELECT tid, name FROM {taxonomy_term_data} WHERE vid IN (:vids)", array(':vids' => $taxonomy_vids))->fetchAll();

      $categories = array();
      foreach ($taxonomy_tids as $value) {
         $categories[$value->tid] = $value->name;
      }

      return $categories;
   }

   function custom_simplenews_rules_actions_get_subscribers(&$category) {
      $categories_array = array();
      foreach ($category as $key => $value) {
         $categories_array[$key] = $key;
      }

      $categories = implode(',', $categories_array);
      $subscribers_snids = db_query("SELECT snid FROM {simplenews_subscription} WHERE vid IN (:vid)", array(':vid' => array_keys($categories)))->fetchAll();

      $subscribers_uids = array();
      foreach ($subscribers_snids as $value) {
         $subscribers_uids[$value->snid] = db_query("SELECT uid FROM {simplenews_subscriber} WHERE snid = :snid AND activated = 1", array(':snid' => $value->snid))->fetchAll();
      }

      $users_list = entity_load('user', $subscribers_uids);

      return array('entity_fetched' => array_values($users_list));
   }

Can not determine what I've done wrong. Please help!

From the very beginning, I went the wrong way. The problem is solved with the vievs_rules module. I made a view of simplenews subscribers, with relations with subscriber:email and subscription:category, then added filters by term (subscription category), by user (active or not) and subscription status. I used a user entity as resulting variable. Then I just imported the view into views loop (Rules UI) and voila!

Very thanks to @Pierre.Vriens for pointing me to views_rules


Reply for comment redirects to the next page I am using advance forum module and having commenting functionality for the forums. But the problem is when I use to reply to the comments it redirects me to the next page. Where I want to display a comment form exactly below to the comment to which I am replying. Where should I configure for this? With comment module or just with advance forum module?

It seems the AJAX Comments module is what you're looking for.
I've installed it it's working good without Advanced Forum module.

Features:
Provides ajax comments to Drupal sites. Features:

Makes AJAX submits
Allows replies to comments on the actual thread page
AJAX comments deleting
Works with CAPTCHA
Cool jQuery sliding
views integration


What do I use as URL path in a template file? I've created a custom theme override for views-view-fields.html.twig to views-view-fields--about-us.html.twig which is a listing of members on a site and the code I've used is as follows:

{{ fields.field_photo.content }}

{{ fields.title.content }}

{{ fields.field_job_title.content }}

  {{ 'Learn More'|t }}

However, when I view the page, the only thing not working is the link to the content. The "Learn More" is supposed to go to each persons full bio, but instead, all that it links to is the current page/view.

Is {{ path }} not the correct code to use as the URL? I've tried numerous other solutions that I thought I found on this site for it but it either doesn't work or breaks my site.

EDIT 1:

When I try No Sssweat's answer from below, which I had tried before, I get the following issues:

Extra bit of code is printed below the button like the image below:

And, this is what the code looks like when you hover over the link:

In Views, you need to add Path as a field, which you probably already have, and you can print it like this:

{{ fields.path.content }}

so

{{ 'Learn More'|t }}


How to use addTranslation() on an entity's multi-value paragraph? I'm trying to programmatically update a multivalue paragraph field and add a translation. In the code below field_product_description is the paragraph's field that I'm updating and field_images_descriptions is the node's field that references the paragraph. The code only updates the first iteration ([0]) of the paragraph. How can I also update the other paragraph values?
<?php
                  $lang_node->field_images_descriptions->entity
              ->addTranslation($lang_code, [
                  // field_product_description is a multi-value field
                  // how can I update it's other values
                  'field_product_description' => $desc1,
              ])->save();
    ?>

SOLVED: Working code:
<?php

foreach ($lang_node->field_images_descriptions as $delta => $item) {

          $item->entity->addTranslation($lang_code, [
              'field_product_description' => $desc1[$delta],
          ])->save();
        }

        $lang_node->save();

You have to loop over the multi-value field:
foreach ($lang_node->field_images_descriptions as $delta => $item) {
  $item->entity->addTranslation($lang_code, [
    'field_product_description' => $desc[$delta],
  ]);
}

$lang_node->save();


CSV node import using feeds module on a Mac I'm using the feeds module to try to import several thousand nodes, but I'm getting mixed results: sometimes it seems to work, sometimes it doesn't.
I understand there are some sort of issues related with the line endings in the CSV files when they are created on a Mac. I tried saving my CSV for Unix (LF) and Windows (CRLF), but that doesn't seem to fix the problem entirely either.

Does anyone else have this problem? Is there a definitive solution or workaround for this?

I've had the most success importing CSV files by importing them into Google Docs (spreadsheet) first and then exporting from Google Docs as a CSV file. It might seem like a silly workaround but Google spreadsheets seems to handle inconsistencies in CSV files a little better than Excel or Numbers.

Give it a shot. I've just used the same method for a Feeds CSV import.


User cannot edit one custom profile field other users can Drupal 7.

The profile field is a very simple long text, text area, filtered html.
When I try to edit it in my own regular user (no admin roles) page, with the standard permissions everyone has, I can do it no problem.
A specific user has reported that he cannot do it at all. A message is displayed that his permissions are insufficient instead of the editable text area.
A third user was kind enough to click his own edit button and has no problem just like me.

I double checked permissions (field permissions module is in use) and they seem absolutely ok. I tried to peek inside the database but don't see anything suspicious (I may not be looking in the right tables).

Check the text format in use for the field that the user cannot edit.  Even if the user has permission to edit the field, the user will NOT be able to edit the field if the data is saved in a text format that the user does not have access to.

Make sure the user's field format is also filtered HTML.

If that doesn't work, use drush uli to log in as the user directly without changing his/her password and look at the problem with your own eyes-- sometimes users say something can't be done when they simply don't know how to do it.


Rendering theme_item_list items My module provides a simple block which needs to contain an unordered list with some images.
From a block function, I am returning a renderable array:

$block['content'] = array(
    'list' => array(
        '#theme' => 'item_list',
        '#type' => 'ul',
        '#attributes' => array('class' => 'foo1'),
        '#items' => array(
          /* ...  what should go here? */
        ),
    ),
);

I would like to have some renderable arrays as items in the item list, but I seem to be unable to insert any arrays into the #items array.

The Drupal 7 theme_item_list API docs says:

  items: An array of items to be displayed in the list. If an item is a
  string, then it is used as is. If an item is an array, then the "data"
  element of the array is used as the contents of the list item. If an
  item is an array with a "children" element, those children are
  displayed in a nested list. All other elements are treated as
  attributes of the list item element.

I tried using both "data" and "children" elements, but I get either empty <li>'s or there is a word Array inside them.

What is the proper way to do this? Is theme_item_list the right/up-to-date solution?

Something like this:

foreach ($images as $image) {

  // New array for readability
  $options = array(
    'path' => $image->url,
    'alt' => $image->alt,
  );

  // Push the image tag onto the items array
  $block['content']['list']['#items'][] = theme('image', $options);
}


views exposed filters - return user selection or another value I have a content type with multiple fields and a view to display them. I have an exposed filter for one of the fields and want to achieve this functionality:

when a user select a value for this filter I want to return those nodes but also the ones that have a certain value on another field.

Is there any way I can achieve that from the interface? I know how to do it with hook_views_query_alter()

Thanks

Easy to do but hard to find the answer.

In the views's FILTER CRITERIA click the down pointing arrow and select the second option (and/or, rearrange). Then create a new filter group and play around with the options there :)


Translate dynamic variable that is an array in twig or using t() How do I translate this in twig? I have this variable in twig that is an array:
$array = [
  ['number' => 7, 'name' => 'foo'],
  ['number' => 8, 'name' => 'bar'],
  ['number' => 10, 'name' => 'baz'],
  // ... and so on and so forth
]

Would like it to be something like this:

The variables are 7 times for foo, 8 times for bar, and 10 times for baz.

Or

The variables are 7 times for foo and 10 times for baz.

Or

The variable is 7 times for foo.

Tried with something like this:
    {% set last = array|last %}
    {% set array = array|slice(0, array.length - 1) %}

    {% trans %}

The variables are
        {% for i in array %}
          {{ i.number }} times {{ i.name }},
        {% endfor %}
        , and {{ last.number }} number of {{ last.name }}
      .

    {% endtrans %}

The error I am getting is:

The text to be translated with "trans" can only contain references to simple variables

Could also use t() although I'm not sure how as well. Also tried with something like this:
{% for i in array %}
    {% trans %}{{ i.number }} times {{ i.name }},{% endtrans %}
{% endfor %}
{% trans %}, and {{ last.number }} number of {{ last.name }}{% endtrans %}

Although it doesn't look good from the "User interface translation" page as you would have to translate them separately.
Thanks!

I think it's better to split the content in translatable parts:
  <p>{% trans %}The variables are{% endtrans %}
    {% for i in array %}
      {% trans %}{{ i.number }} times {{ i.name }}{% endtrans %},
    {% endfor %}
    , {% trans %}and {{ last.number }} number of {{ last.name }}{% endtrans %}
  .</p>

Haven't tested this so I'm not sure if it works. Also, you could use trans as a filter, check this question.


time in wrong time zone when using get I have a date/time field, when I save it as 1:00:00 AM, it displays in the edit form as 1:00 am, however when I do a get of that field value in my module
with $posted_date=$static_media->get('field_pup_posted')->getValue();

, it comes out as`Array
(
    [0] => Array
        (
            [value] => 2017-06-14T05:00:00
        )

)`

Why is it being stored as a 5 when it should be a 1?  and how can i get it programatically in the correct time zone

drupal stores in UTC have to convert this to current time zone

$dt=new \DateTime($changed_date, new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('America/New_York'));
$correct_date =  $dt->format('Y-m-d H:i:s');


Attaching the comment form programmatically How do I add the comments form (of the comments module) programmatically in a custom-made module?
In other words, what proper code should be added to your module code to add a complete "Post New Comment" form (of the Comments core module)?

That said, how do I force the installation of the Comment module with the installation of your own module?

I'm re-asking my question in an edited version with some new results i've reached :).
I've created a custom menu in a custom module of mine, with items of course.
I wanted to add the comment form (of the Comment module) to the page that my item takes me to.
The problem is that the page i'm redirected to is not a node, but it is a render-able page that displays the data according to it's 'page_arguments'.
It is as follows:

$items['car/%'] = array(
        'title' => 'Cars',
        'page callback' => 'car_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
);

I want to attach the comment form (of the Comment Module) to that page.
I used the following code:

module_load_include('module', 'contact');

$build = array(
    'header_text' => array(
        '#type' => 'markup',
        '#markup' => 'Building comments in page.',
    ),
    'the_form' => drupal_get_form('comment_form', ''),
);

return $build;

All is correct code.

But the problem is that the comment form and the posted comments are loaded depending on the node Id (nid), and in my case there is no node Id (nid)!

How could i assign a specific identifier of that custom page so that the comment form functions correctly and comments related to that page are correctly loaded?!

And in the code above, i managed to call the form using drupal_get_form(), and assigned an empty second argument! I don't think that's right, right?

Any ideas!?

comment_form() is expecting the parameter to be an object rather than an array so you should be doing something like this:

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

Note the lack of a 3rd parameter passed to drupal_get_form(), comment_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.

Finally drupal_get_form() returns a render array rather than a string so you need to pass it through the render() function:

print render($form);

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment_form() function


How to unpublish a node with vocabulary term X after Y hours? How could I automatically unpublish a node after Y hours (e.g. after 24h after it appears on-line) but only when it has a specific category - category is based of course on taxonomy's vocabulary.

Important is that an editor has no influence on number of hours after which the node is unpublished - so it must be predefined by the admin.

Use the Rules module for this, by performing these steps:

Create a Rules Component to unpublish a node, which is like a getting started with Rules Components.
Create a Rule like so:

Rules Event: After saving a new node.
Rules Conditions: check if "it has a specific category - category is based of course on taxonomy's vocabulary" (as in your question).
Rules Action: schedule the execution of the Rules Component, to be executed after 24 hours. You'll have such Rules Action available if you enabled the rules scheduler (sub-module of Rules). This will actually execute the Rules Component "next time cron runs". So make sure to take that into account also to set the frequency of your cron jobs, and/or schedule the Rules Component a bit before the 24 hours have passed (whatever fits for your case). Note that the one who can edit the rule will be able to "predefine" when the Rules Component will be executed.


Make drupal cck field behave as "an add more button"? Is it a way to make a Drupal 7 entity field behave as 'an add more button', but with finite number of values?

For example, initially there is only one form field for inputting the value showing, then I can keep adding up to 4 more form fields. I can set it to maximum 5 fields, but it will show 5 fields all at once. The client only wants to show 1 field initially.

This functionality is not available out of the box. But it's something people have been asking for (repeatedly) since at least D6 CCK 2:

Enable 'add more' button for non-unlimited fields.
Provide "Add more values" button for fields (and multigroups) with fixed number of multiple values
'Number of repeats' uses 'Add more' button
"Number of Values to Display" option for CCK fields

User goron has developed a contrib module for Drupal 7 called Multivalue Settings.

But be aware - from the module description page:

  Warning: this module is still very buggy. Actually, it only works in
  very few use cases. I suggest to only attempt using it with core
  fields (not fields from contrib modules). Even this may not work.

And it hasn't been updated in over a year.

Screenshot of Multivalue Settings functionality:


Pass Fields Via URL to a View? Use case #1: Display the Demonstration Title and Demonstration ID on the Deliverables view.

Use Case #2: The Deliverables view displays all Deliverables associated with a state specific State Demonstration.

So it seems like I need to pass two fields via URL to the Deliverables view page?

Content Type: Demonstration
Fields: field_demonstration_title, field_demonstration_id

Content Type: Deliverables

Screen Capture of Workflow

contextual filters takes arguments from entities whether in the url or not

you could build the url and match arguments with url parts


How to redirect user for specific pages not found I have developed a module that creates a certain set of pages. What I would like to do is create a specific redirect for those pages if they are not found while keeping the generic Drupal 7 wide redirect for all other pages. Is this possible and how would I go about doing it?

Thanks.

You can try by going on "admin/config/system/site-information"page. There you can give links where to redirect on the "Default 403 (access denied) page" and "Default 404 (not found) page". For example if you type "node", it will take you to front page.


Is it possible to use Apache Solr to search across multiple sites? I'm completely new to Solr and roughly understand the basic principles of setting up a search engine but not (yet) the specifics.

I'm beginning work on a site which will display search results from the content in the site (Articles), however, we also want to allow visitors to use the same search form to return - in the same page - results from both our own site, and from other external sites which could be indexed in Solr but are not Drupal sites.

Is this even possible or am I wasting my time? Many thanks for any insights.

Solr can be thought of as a document oriented database , it has a schema based, and a schema-less mode.

When used from the drupal module it uses a schema.xml file to specify what it expects to find in the documents (and hence index).

so if you go down that option one way you could search across the external domain and the drupal site is index the external domain to that schema, extending it where necessary

if you've got a title field in both sets of data , then it will index title that way. if your external site has different fields you could add them to the schema
you'll want to define a minimal shared set that documents from either site share, to make themeing, and UX easier.

The process I would probably go for is

create a schema that covers both sources of data
configure Drupal to use that schema and index the site
index the external site (Solr 5 has a crawler now, or might just be easier to build a CSV file with curl)

that would get you to a place where you can search across the 2 sites from the Drupal search.
It would be a case of getting the theme/markup right to represent offsite vs onsite results.


How to 'inject' the "read more" link into a textfield / paragraph (inline) Due to client's demand the situation is that I can't use the default (trimmed) body text as a teaser text in a view listing nodes. Instead I have an extra text field which contains 2-3-4 paragraphs so that the client has 100% control of what the teaser text would look like etc.

I would need to place a "read more" link at the end of that custom teaser text. I tried different methods to place such a link inline with the teaser text – but couldn't find a way to actually have a working setup.

I tried the read more module – which works fine with standard situation, replacing/placing the "read more" link inline – but that won't help me here.
I tried overriding the field in views – but that won't let me place the "read more" inside the last paragraph. Either I keep properly formated paragraphs, or I use "inline" or "inline-block" for the p but then the paragraph-structure collapses.
I also tried the read more control module – but that seems to solve problems that I don't have (hiding "read more" links if there is not 'more' to read)

I suppose this must be possible – and would gladly appreciate any tipps or pointers that would lead me in some direction.. thnx!

If the goal is simply to get the read more link to appear visually inline with your last paragraph, I think you can do that with pure CSS.  As you noted, formatting all your
 tags as inline elements will break the paragraph structure.  You can avoid this simply by using a :last-child selector, e.g. http://jsfiddle.net/hdys6w2j/

That said, if you are set on having the readmore link injected into your last p tag, I guess you could throw some code like this in your custom module:

function mymodule_preprocess_node(&$vars) {

  //Programmatically generate the readmore link
  $read_more_link = l('Read more', 'node' . $vars['node']->nid);

  if (!empty($vars['content']['my_field'][0]['#markup'])) {

    //Replace the last
 tag with Read More

    $vars['content']['my_field'][0]['#markup'] = preg_replace(
       '/\<\/p\>$/',
       $read_more_link . '
',
       $vars['content']['my_field'][0]['#markup']
    );
  }

}


In views, how to create link to field visible through relationship connection? I don’t want to link to the original piece of content (which is a join table) but to the content type which is referenced in the join table.

Using: Views, Entity Reference, Entity Tokens, Token.

I have these content types:
- Person (firstname, lastname, etc.)
- Story (field_story_title, orig copyright, description, etc.) Note: [content:title] is automatically generated and not used.
And this content type which functions as a join table
- PersonStory (field_personstory_person_id, field_personstory_ story_id, relationship [e.g. author].)

The view has Content: Type (= PersonStory)
Relationships have been created
- Story from field_personstory_story_id
- Person from field_personstory_person_id

The view successfully finds Story Title (field_story_title) and Person Name (using [Global: custom text] in concatenation of field_person_lastname, field_person_firstname, etc).

I created a link:
- Added field [content:path] above Story Title on the field list. Checked "Exclude from Display" and expanded "Rewrite results" and only checked "Use absolute link" for this field.
- Added field field_story_title, expanded "Rewrite results" and checked "Output this field as Link" with the Link path: [path] .

The view looks just fine with the field_story_title appearing as a link.

However, clicking the link goes to the record in PersonStory instead of the record in Story. @skorzh suggested that I investigate replacement pattens in the Rewrite results, but I don't see any tokens which connect to the fields in Relationships in the View.

I’ve tried many different patterns and tokens and nothing has worked in details of [field_story_title]. I don't know what the replacement pattern should look like. Is it possible to join replacement patterns? How do I determine what the url should be?

My latest attempt is
[site:url:join:/]/[content-type:name]/[node:field-story-title:name]
but it's not working, naturally.

Thanks.
(Entire post has been updated to reflect my current (lack of) progress)

You need to have the path field set to use the story relationship. http://cl.ly/372U1S1b2s3V


newsletter with export email to csv and import from csv features i had use simplenews before, but there is no function to export or import email to csv file.

anyone know any module have such functions?

Here's how to do that:

Install Views (you probably have this installed already).
Install Views data export module.
Create a new view that will show either "Simplenews subscriber" or "Simplenews subscription".
Add a new display of "Data export" type to that view. There you can choose the format (.csv, .doc, .txt, etc.) and configure other settings. Don't forget to set "Attach to" value to the page display you created in step #3.


Dependency Injection if service exists Is there any way to use dependency injection in a conditional way, i.e. only if a service exists similar to \Drupal::hasService().

I have a created a service in module A and in module B I have an EventSubscriber that should use the service from module A, but only if present of course.

Static I would do sth. like:
    if (\Drupal::hasService('module_a.my_service')) {
      \Drupal::service('module_a.my_service')->mymethod();
    }

Is there any possibility to do this when injecting the service?

One possible way to handle this situation is for your Module B to define a default, stub service with the same type signature (ie, Interface) as the one you need).  Use that in the YAML.  Then, in your Module A, you can alter the service to the one that the module provides.

That said, I do agree with the comments that you may be bypassing one of the benefits of DI, and creating a tight coupling between your two modules.  Read the linked article to see when it is appropriate.  Core uses it for the language and workspaces subsystems.


Service module contextual filter This answer  from 2 years ago (to which I am not allowed to comment) to the question "How send argument to Services Module (Views+Contextual filters)" contains something about passing contextual filter value to the service module. It is about this URL:

http://test.url/endpoint/path?uid=123

My question here: what exactly is that "path"?
Is that machine name of the view?

To resolve your issue: make sure when the view is created there is no other page or block.

It seems something setup in your MASTER page was causing it to not work. i.e localhost/extra/api/views/service.json?tag=11584


Exclude /ru/ in links I have site http://diamant-group.com/. It has two languages RU and EN, I want that it will monolingual, with Russian default language. I turn off EN language in Configuration, turn on RU as default, but problem is still exist http://diamant-group.com/ru/catalog. When I begin to research I have opened that many code for multilingual function was added inside theme template. When I turn off module Content translate i have error of function diamant_link_lang.

How to correct this code, that links do not consist /ru/ (for example site/ru/catalog/watches/mechanical/omega/ - > site/catalog/watches/mechanical/omega/), but language of the result pages must be Russian:

function diamant_link_lang($language, $path, $path_alt) {
    $path_lang = translation_path_get_translations($path_alt[0] . '/' . $path_alt[1], $language);
    file_put_contents(DRUPAL_ROOT . '/sites/default/files/text.txt', 'path_lang: ' . print_r($path_lang, true) . "\n");
    if ($language == 'ru' && isset($path_lang['en']))
 {
        return 'en/' . drupal_get_path_alias($path_lang['en'], 'en');
    }
    if ($language == 'en' && isset($path_lang['ru'])) {
        return drupal_get_path_alias($path_lang['ru'], 'ru');
    }
    return $language == 'ru' ? 'en' : 'ru';
}

You can change the way the language is added to the url. For the Russian language (your default language), you can remove it completely from the url by setting the path prefix to empty value.

This can be done under admin/config/regional/language/edit/ru, set empty value on Path prefix language code.

Theoretically you don't need to have custom code the generate URL (with language checks), just let Drupal handle the url generation.


Role delay using Rules I'm aware of the Role Delay module however it is not working for me. I'm running D7. I read somewhere that it is possible to do the same thing with Rules.

The 3 stages I want users to go through are...

1) Non-authenticated user
2) Authenticated user
3) Trusted authenticated user

I've got the movement from 1) to 2) working fine as it's taken care of by the Logintoboggan module (upon account activation). Moving 2) to 3) is proving trickier as I want it to be time based, after the 1) to 2) event.

All I want users to move from 2) to 3) in 24 hours after they become an authenticated user.

Step 1

Create a Rule Component to "Grant a user the Trusted authenticated user permission" (whereas the user is specified as a parameter for this Rules Component).

Step 2

Enable the rules scheduler (a sub-module of the Rules module).

Step 3

Adapt the rule you seem to have in place already for that "movement from 1) to 2)" (or create a new rule that catches that as a Rules Event): at the end of this rule, add another Rules Action to schedule the execution of the Rules Component in Step1, after 24 hours.

Optionally you may also want to add some extra Rules Conditions that the user does not have rule "3)" yet (or any other Rules Condition that may fit).

Step 4

Next time your cron job runs, the permission "Trusted authenticated user" will get granted.

PS: I'm assuming this question is about D7.


How one can display the file path once it is successfully uploaded How one can display the file path in node/add page, once it is successfully uploaded, before saving the node.

Please try below: file_create_url($file->uri)

function import_form_submit(&$form, &$form_state) {
  // Load the file.
  $file = file_load($form_state['values']['file_fid']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  $uploaded = file_save($file);
  if ($uploaded == TRUE) {
    drupal_set_message(t('The file has been uploaded.'));
    dpm(file_create_url($file->uri));
  }
  else {
    drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
  }

}

Also, refer the answer for pre-node save function


Automatic Item Number Creation (For article posting as a Reference for Quick Searching) I'm looking for a solution for automatic item number creation that will auto-create a reference number/code for any posted article, whatever the Node type. The purpose being that for any posted article (any Node type) that is created & posted by an author (with permission Roles authorised to post content) will have an item reference which can be traced throughout all aspects of workflow (including any Ticket Support document output - printer etc). This could quite simply be a standard item number as of that used on eBay (string of numbers) or similar used in organisational-wide portal. It might be for use in a local sales listing references (as in Gumtree), a vehicle listing platform (autotrader.co.uk) or simply to give a volumous document based content site a posting reference (internal intranet/external netsite), which for example, a 3rd party reader can jot down on paper, (email, cut and paste in Notes etc) and come back later and do a simple 'search' with the reference number, but not a 'purchase order' reference (as in Ubercart), purely for article reference purposes.

I'm not looking for anything tremendous (I'm not a PHPer (yet!) and I know this is more of a backend SQL DB but being more a Drupal 'plumber'/experimentalist I'm looking for simple solution for now that can be built upon later; something that Barcode module can also take advantage of and I can use in future projects of informational DataBases. Does anyone know of such a suitable solution/module for D7?

Any comments or How-tos welcome. Thanks.

Option 1. You can use an existing node ID (NID).

Each node already has an ID and can be accessed via /node/[nid], [nid] being the ID of the node. Or you can generate a path alias by inserting <?php print l('link', 'node/' . $nid); ?>, $nid being the ID of the node. To retrieve NID of a current node, insert <?php print $node->nid; ?> into node.tpl.php.

Option 2. You can also use the combination of Automatic Nodetitles and Token module. This will allow you to automatically generate node title with the values from the Token.

Once the modules are installed, go to Structure -> Content Types, click on Edit, next to your content type. While on the Automatic title generation tab, select to Automatically generate the title and hide the title field, and in Pattern for the title, post a token from the options below; see the image below. There are many options with tokens, such as Unix timestamp (my favorite), random numbers and more.

Update:

For a truly random serial number, instead of using the Token module, I'd suggest using uniquid(); it generates a 13 character long random serial, no duplicates. This would be my choice. To do so, put this into "Pattern for the title" field, don't forget to check "Evaluate PHP in pattern":

<?php echo uniqid(); ?>

If you have spare time, there is also a Serial Field and Universally Unique IDentifier module, which also generate unique values.


How to override a node using alias? I have created node there path is "content/book/book-name-alias".
Where
I have override a node using view page "content/book/%"
where
contextual filter using "Node Id".

When I have request a page using "book/content/9" a node will override but same node "book/content/book-name-alias" it is not working.

How to override a node using an alias?

The path where a node is rendered is at node/%node, where %node is the nid of the node.
Example : http://example.com/node/1, and the path which is displays book/content/book-name-alias is an alias of the node/%node path.

So, to implement this override the node/%node path using either a view page (how to), or a panel page (how to) with the same path.


How to add some configuration option to vertical tab on content type edit page Is it possible without touching Dupal core's code, add some configuration option to content type edit page? preferably to vertical tabs of bottom? such as a checkbox.

I mean this page: /admin/structure/types/manage/article

Yes, you can add a fieldset to the content type edit form with hook_form_FORM_ID_alter.

e.g:

function MYMODULE_form_node_type_form_alter(&$form, &$form_state) {
    // Define field set in additional settings group
    $form['advanced'] = array(
      '#type' => 'fieldset',
      '#title' => t('Advanced settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 10,
      '#group' => 'additional_settings',
    );
    // Add checkbox option
    $form['advanced']['special_option'] = array(
      '#type' => 'checkbox',
      '#title' => t('Use special option'),
    );
    // Set default value from automatically saved config variable
    $form['advanced']['special_option']['#default_value'] = variable_get('special_option_' . $form['#node']->type, 1);

}


Best way to create a Facebook Follow button on nodes I have some nodes with information about a political candidate. Some of the candidates have a Facebook profile, which I link to using an URL-field.

But they also want a follow button directly on the page. I was thinking of typing in their handle to a text field and create a field formatter to render the code for the actual button.

Is this the best way to do it?

Facebook Subscribe Button

  This module will automatically add the Facebook code for Facebook
  Subscribe button which will be displayed in the block and each page
  node.

  Administrators can also control which content type(s) the Facebook Subscribe button will or won't appear on, as well as which role(s) are
  allowed to view the button (regardless of whether or not the user is
  logged into Facebook at the time).
  Along with a Subscribe button appearing for each node, there is an optional block that can be set to appear on each page.
  By default, the button will only appear on a node's "full" page view. This option is also customizable, however, so that the button(s)
  will show up on teasers as well.


Which hook to use when a date is going to be saved into the database I have a situation where I would like to know when a date (for an event) is going to be saved into the database so that I can modify the corresponding date in another module to match it. That is it in a nutshell. I need to do this because of the way this other module works. What is the best hook to use to accomplish this? Is it hook_node_update?

Thanks.

If you are only using nodes then yes, implementing hook_node_update is a good approach. You also will need to implement hook_node_insert if you need to do logic when the nodes are first created.


Site stuck in maintenance mode I have put a site in maintenance mode. Before I could visit the administration pages as user #1 (which was the user account I was already using before to put the site in maintenance mode), I had to reset the computer; when I tried to visit the administration pages, Drupal didn't give me access to those pages.
I cannot change the content of the settings.php file because the installer tool that I used from the control panel for the domain probably created the files using credentials different from the ones I use to connect through FTP, which is the only way I have to upload files to the server, or change them.

Apart re-installing the Drupal files manually (and in a different directory), what can I do to access the administrative pages?

You should be able to log in by going to http://example.com/user directly (or http://example.com/index.php?q=user if clean URLS are turned off).


display a vimeo frame in a view I have a field that holds a vimeo video ID, I'm trying to display this content using a view where I'm rewriting this field, but the markup is getting stripped out.

<iframe src="//player.vimeo.com/video/[view_field_id]" width="WIDTH" height="HEIGHT" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

How can I display a vimeo iframe in drupal using views?

As per this support request in Views issue queue: Views: Rewrite field, strips some HTML tags (SOLUTION/WORKAROUND FOUND FOR STYLE TAG) Views strips out certain tags. It does this using filter_xss_admin, which if you look at that API entry calls filter_xss, passing in an array of allowed tags. iframe is not one of those unfortunately.

So I think that you might need to do a workaround. I would look at two ways of doing this:

Rewrite the outut in a Views template. You click on Theme:Information at the bottom of the advanced pane in Views UI and you would select the theme file for the Vimeo field. More at An Intro to Drupal Views Templates and Theming
Create your own theme function to output the iframe. Enable Views PHP and call the theme function from a rewritten Views field.


Form built by Ajax commands not sending values My problem has to do with Ajax commands and the form being rebuilt after calling ajax_command_append().

I have a form with two elements an option and a textfield. These are built-in with the form on page load. Then, in an Ajax callback function I add two other fields, i.e. another textfield and a text area.

The form runs and rebuilds perfectly fine, but when I try to read the values typed in or stored-from-beginning, nothing happens except that only the values for the first two fields that were originally built-in with the form are displayed.

I think the problem is either 1) I am not rebuilding the (same?) form properly, or 2) I am not calling the elements/fields properly when reading values.

Any hints will be greatly appreciated

Here is a simplified version of the test code I gathered from various examples:

function module_form($form, &$form_state) {
$form = array();
 $form['changethis'] = array(
 '#type' => 'select',
 '#options' => array(
  'one' => 'one',
  'two' => 'two',
  'three' => 'three',
  ),
   '#ajax' => array(
     'callback' => 'ajax_example_simplest_callback',
     'wrapper' => 'replace_textfield_div',
     'method' => 'replace',
     'effect' => 'fade',
    ),
  );
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("The default value will be changed"),
    '#description' => t("Say something about why you chose") . "'" .     (!empty($form_state['values']['changethis']) ? $form_state['values']['changethis'] :     t("Not changed yet")) . "'",
    '#prefix' => '
',
    '#suffix' => '
',
   );
 $form['box'] = array(
   '#type' => 'markup',
   '#prefix' => '
',
   '#suffix' => '
',
   '#markup' => '
Initial markup for box
',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'ajax_example_submit_driven_callback',
      'wrapper' => 'box',
     ),
    '#executes_submit_callback' => TRUE,
    '#value' => t('Submit'),

   );
  return $form;
}

function ajax_example_simplest_callback($form, $form_state) {

   $commands = array();

   $commands[] = ajax_command_append(NULL, '
<input name=replace_textfielddd id=replace_textfielddd value=79898>test data</input>

');

  $commands[] = ajax_command_append(NULL, '
<textarea rows=4 cols=30 name=replace_textarea id=replace_textarea>Changethis value: '. $form_state['values']['changethis'] .'</textarea>');
  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);

  //print ajax_render($commands);       // not helping
  //drupal_exit();

 // return $form['replace_textfield'];  // not helping
 }

function ajax_example_submit_driven_callback($form, $form_state) {
   $form_state['rebuild'] = true;  // not helping
   $element = $form['box'];
   $element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " .  $form_state['values']['replace_textfield']. " - ".  $form_state['values']['replace_textfielddd'] ." -.";
   return $element;
}

Thanks

EDIT

I also tried calling this function from the inside of command:
 function display_my_form(){

 $form = drupal_get_form('CPR_Calculator_form');

 $form['replace_textfielddd'] = array(
    '#type' => 'textfield',
    '#title' => t("bye"),
    '#description' => t("ummm"),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $display = '
';
  $display .= render($form);
  $display .= '
';

  return $display;
}

and then in the callback I replaced the ajax_command_append() with this line:

$commands[] = ajax_command_replace(NULL, display_my_form());

You need to build conditional elements in the form definition (mymodule_form) and not in the ajax callback. When the form is rebuilt using ajax, $form_state['values'] will be set, whereas it's not set on the initial form build.

Here is an example:

function mymodule_form($form, &$form_state)
{
  if(isset($form_state['values'])
  {
    // put your conditional form elements here
  }
}


How can I use $_SESSION? I want to use this code in Drupal 8.

if (isset($_SESSION['loop'])) {
     $loop = $_SESSION['loop'];
} else {
     $loop = 0;
}
for ($count = 0; $count <= $loop; $count++) {
     $_SESSION['code'][$loop] = $code;
     $_SESSION['price'][$loop] = $price;
     $_SESSION['loop'] = $loop + 1;
}

This code worked correctly, but in Drupal 8 we should use this code.

// Setting a value.
$tempstore = Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

// Getting a value.
$tempstore = Drupal::service('user.private_tempstore')->get('mymodule_name');
$some_data = $tempstore->get('my_variable_name');

I don't know how to change my code to use this service's API. How do I convert my code to use the user.private_tempstore service?

You listed all the elements you need. You just need to swap out the set and get you were originally using with the ones you provided.

This:

$loop = $_SESSION['loop'];

Will become this:

$loop = Drupal::service('user.private_tempstore')->get('mymodule_name')->get('loop');

And this:

$_SESSION['loop'] = $loop + 1;

Will become this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('loop', $loop + 1);

For your other elements, you can do the following.

This:

$_SESSION['code'][$loop] = $code;

Becomes this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('code', [$loop => $code]);

And this:

$_SESSION['price'][$loop] = $price;

Becomes this:

\Drupal::service('user.private_tempstore')->get('mymodule_name')->set('price', [$loop => $price]);


Redirect after form submission I created a custom form in Drupal 8. I remember we can redirect to custom path  in Drupal 7 with $form_state['redirect'] = 'mycustompath'; in a submission handler.
How can I achieve the same in Drupal 8?
I know I should use submitForm().
public function submitForm (array &$form, FormStateInterface $form_state) {
   // Redirect users.
}

In your "submitForm" method write below code

 $form_state->setRedirect('machine_name');
 return;

where machine_name is the machine name mentioned in the routing file.

I hope this helps .. :)


Programmatical use of Search API Problem: Need to run my own searches programmatically with Search API. Every google result I find is geared toward teaching non-developers how to use the module with Views with no results on doing it like I want.

Information:

Using local database service instead of Solr or any other.
Have data not stored in database that will appear alongside other results.
Content will be grouped in "type" tabs.
Not using Views for various reasons.
Have Facets API enabled but no clue how to use it either.

Why: Because I want to have the search page be at /site-search and without /node/keyword after the page argument. Also will be asked to customize this beyond the scope of other modules that may provide the same type of functionality. And I want to learn how to do this but have not found any tutorials or other insight on how to accomplish it.

The rest:
I have created my search page and on it I am executing the search with:

$term = $_SESSION['my-search']['term'];
$server = search_api_server_load('database');
$index = search_api_index_load('default_node_index');
$query = new SearchApiQuery($index);
$query->keys($term);
$query->fields(array('title','body:value'));
$srv= new SearchApiDbService($server);
$result = $srv->search($query);

The session variable is set when a search form is submitted then redirects the user to /site-search to perform the search and show the results.

If I output $result I see it's an array with different information including a result set that is an array of node ids and their scores.

I could run through those, grabbing the node and displaying the results myself but I figure there's got to be some other method for rendering the results of the search. I haven't found it though and that's the problem.

I've been looking through the different classes in Search API and Facet API and can't find anything in them that seem like they would build result output.

Any help with this will be appreciated.

Results example:

Array
(
[result count] => 11
[results] => Array
    (
        [37] => Array
            (
                [id] => 37
                [score] => 15.7503318786621
            )

        [39] => Array
            (
                [id] => 39
                [score] => 7
            )

        [40] => Array
            (
                [id] => 40
                [score] => 5
            )

        [31] => Array
            (
                [id] => 31
                [score] => 4
            )

        [33] => Array
            (
                [id] => 33
                [score] => 1
            )

        [36] => Array
            (
                [id] => 36
                [score] => 1
            )

        [1] => Array
            (
                [id] => 1
                [score] => 1
            )

        [15] => Array
            (
                [id] => 15
                [score] => 1
            )

        [16] => Array
            (
                [id] => 16
                [score] => 1
            )

        [27] => Array
            (
                [id] => 27
                [score] => 1
            )

        [35] => Array
            (
                [id] => 35
                [score] => 0.980873763561249
            )

    )

[warnings] => Array
    (
    )

[ignored] => Array
    (
    )

[performance] => Array
    (
        [complete] => 0.0033111572265625
        [preprocessing] => 0.00053095817565918
        [execution] => 0.0027379989624023
        [postprocessing] => 4.2200088500977E-5
    )

)

Have you looked at the Search API pages module. It uses the Search API module and creates a custom search page. You could probably look at that module for clues on how to implement what you are trying to do. The module itself might even provide a lot of the functionality that you are looking for.


Making the size of two fields in comment form the same programmatically in my node comment form I have a 'your name' field and an 'email' field for users to fill out. They are different in length and like them both to be length '30'. How can I do this with hook_form_comment_form_alter?

I've tried this, with no success (in template.php):

$form['field_email']['#size'] = 30;
$form['author']['#size'] = 30;

I've tried just changing the size of the field for the email field in the content type comments manage fields area but it does nothing.

In the core comment form the 'author' element is an array of form elements:

  $form['author']['name']['#size'] = 30;
  $form['author']['mail']['#size'] = 30;


How to use devel on a taxonomy term page to see available nid's? I'd like to get nid of a node associated with my taxonomy term page, So i'd like to use devel module to see the structure of taxonomy term page.

Terms have a term ID number (tid) and nodes have a node id number (nid). Terms are applied to nodes so nodes can be associated to terms and vice versa.

Devel module can show the structure of a taxonomy term. To achieve this:

Download and enable the devel.module
Ensure you are logged in with a user who has the Access developer information permission
Browse to the taxonomy term you want to inspect
Click the Devel tab if it is visible

If it is not visible, that is likely either a permissions issue or a theme issue - to fix a theme issue you could try changing to a core theme like Bartik

Then you should see some output like this:
You can click tokens or Render or other sub-tabs as well
This shows the tid and other values associated with the term, but not the nid of nodes associated with the term


Get field names of view from within module After using views_get_view($view_name) how do I get the names of the fields?  The list of field names (arranged correctly) is going to be pushed onto an array following which will be all the results.  I can see in the return value from views_get_view() the field array, but how do I get them as they would be displayed in a table, that is, correct capitalization, spaces instead of underscores, etc.?

There is an array of fields in the display object:

$view->display['YOURDISPLAYNAME']->display_options['fields']

for example if you want to retrieve list of field names of the view arbitrary display, you'd need to do something like this:

function get_views_field_names($view_name, $display = 'default') {
   $view = views_get_view($view_name);
   $result = array();
   foreach($view->display[$display]->display_options['fields'] as $field){
       $result[] = $field->label;
   }
   return $result;
}

and somewhere in the code

$fields = get_views_field_names('YOURVIEWNAME', 'YOURDISPLAYNAME');


Occasional Drupal Error in bootstrap.inc Every now and then our site gives out this error:

  Notice: Constant CACHE_PERMANENT already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 13

  Notice: Constant CACHE_TEMPORARY already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 18

  Notice: Constant WATCHDOG_ALERT already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 57

  Notice: Constant WATCHDOG_CRITICAL already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 68

  Notice: Constant WATCHDOG_ERROR already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 79

  Notice: Constant WATCHDOG_WARNING already defined in
  C:\Inetpub\wwwroot\includes\bootstrap.inc on line 90

  Notice: Constant WATCHDOG_NOTICE already defined in
  C:\Inetpub\wwwroot\includes\bootst... as of 10:40:01 on 2011-07-14.

Don't know what happens that bootstap.inc get run twice? Why else would it complain about constants already being defined. Thanks for any insight.

The bootstrap.inc file is included, from index.php, using require_once './includes/bootstrap.inc' (Drupal 6) or require_once DRUPAL_ROOT . '/includes/bootstrap.inc' (Drupal 7). That one of the first instruction executed from Drupal when bootstrapping, as the bootstrap code is all contained in that file.

The errors you are seeing could be caused from a module that is using include or require to load the bootstrap.inc file, which would not be necessary, as the file is already loaded from Drupal.
Alternatively, the errors are caused from a module that defines those constants in one of its files, which is then causing those errors once it is loaded. For example, it could be a module that implements an alternative to the cache mechanism implemented from Drupal, which defines those constants with the wrong assumption that they would not be available.


How to restrict access to blocks depending on the roles? How can I restrict the Access to the blocks in my website depending on the roles? I.e only a particular role can see (edit view delete configure) a particular block and nobody else can do so.

I tried the Block Access module but to no avail.

Is there any other module that can help?

This patch could help you in controlling access to blocks.

Patch is here https://drupal.org/node/1916028#comment-7302100.

Need to apply this patch on dev version of this module 7.x-1.x-dev of Block Access


How to delete views_data_export_index_% How to delete these tables "views_data_export_index_%" create by views data export
module, the database getting huge.

The short answer here is to disable & uninstall the Views Data Export module. Once you uninstall it, all the tables should be wiped out. The longer answer is why worry so much about so much size? The views_data_export_object_cache seems like it should contain large chunks of data that can be cached from previous exports.


Webfm and views; can I create a view that has a list of links to the files? Really new to Drupal and getting a little lost on this one. I want to create a view of files that are listed in webfm. These files will all be pdfs. Is this even possible.

My aim is to use standard drupal 6 modules to allow the users to upload reports in pdf and list them in a view. But the view needs to link directly to the file.
Another option is to use nodes to display pdf files. But this has to be in a way that end users can easily upload and create a node that displays the pdf.

Any help much appreciated.

Actually just started working on this myself this morning.  The answer is yes, you can, but as far as I've read into it, the view can't be part of another view, i.e., you have to create a separate view just for WebFM files.  You'll see it when you go to Views > Add > View Type.

Like I said, I just started working on this this morning, so I haven't gotten any further than that, but HTH.  Maybe post progress here for sharing?  Funny that your question came up in teh Googles.


How to get the valid URL of a Link field from within a Twig template? I have a Link field named field_my_link (machine name).

Within a Twig template I can get the link's URL value with this:

{{ node.field_my_link.uri }}

If inside the Link's URL there is an external URL, e.g. http://example.com it works good.

But, if inside the Link's URL there is stored an internal URL, e.g. "/node/11", I get a value like this:

"internal:/node/11"

with the "internal:" prefix.

How can I get the valid URL?

For example, if the link's URL is "http://example.com" I want "http://example.com" (this already works), if the link's URL is "/node/11" I want the relative URL "/node/11", if the link's URL is "<front>" I want the URL "/", etc.

EDIT

I can get the value I want within a PHP preprocess function, using this:

$url = $variables['node']->get('field_my_link')->first()->getUrl();

How can I access the same value within the Twig template?

I know I can do this within the preprocess function:

$variables['my_url'] = $url;

Then access the url within Twig using {{ my_url }}, but I would avoid to write a preprocess function each time I have a link field.

Your PHP from your latest edit would translate into twig like this:

{{ node.field_my_link.0.url }}

This works like this, 0 returns the first item of the field item list, url gets the url object and because twig will cast this object as a string this will call the magic method toString() and will output the url as a string value.

You only need to use url, because twig looks automatically for the method getxyz() if there is no property with that name xyz.


Sync content between two Drupal sites I have two Drupal 7 sites running a very similar structure (views, content types, etc) but with a different theme and a few other changes.

I need to have all the nodes of specific content types that are created in site A to be copied to site B. If it is possible, it should work automatically or by running a script. For example, the sync would run as a scheduled cron job.

I do not need both sites to run in the same database, they must have their own separate database, just the same nodes for specific content types.

I've been investigating, and I see that I can use Node Export, Feeds and even a drush command (ne-export/ne-import). I'm not sure yet about how to put all the pieces together. Has anyone done this already?

For Drupal 8 you can use the Content Synchronization module.  From the project page:

  The content synchronization module provides a mechanism to export single content items, or all content items, from an environment, and move them to another, effortlessly.


Show custom menus in seven theme I am using Seven for the theme of a internal application. I have custom items setup in the mainmenu, but cannot get it to show?!?!

The blocks for seven are limited to content and help (despite the .info file suggesting a few more???).

/admin/structure/menu/settings

I have set main menu to both Main and Secondary links.

/admin/appearance/settings

I have checked both main and secondary links

What am I missing? How do I get he mainmenu (or any menu) to show in the default Seven theme (without deriving a new theme from it and tweaking it's template.php, etc)???

I can do this with any other default theme...

I am afraid that Seven's page.tpl.php does not render these menus. You will need to subtheme it and modify tpl.php files to render the menus. I know you stated that you want to avoid this; however, you really should do this anyway because if you are using the theme in your app then you will at some point likely want to modify it in some way, and you don't want to customize a core theme because it will break on updates, etc.

It's worth it, because Seven is actually a great theme for internal web apps (I use it for this).

Seven's navigation was meant to be provided by Drupal's tab system. I suggest rendering your main menu and secondary menu as tabs to leverage the navigational design of Seven.


How to control the order in which the markup for fields appears in the outputted html source for content? Is it possible to control (as in change) the order in which the fields appear in the html markup?

On admin page for a content type admin/structure/types/manage/<content type>/fields and in the Manage Fields tab, the fields can be dragged and re-ordered in the list.

However, looking at the outputted html source, the order does not change according to the order in this list. Is it supposed to? (I'd like to think it does).

I also looked at field_weight to control the order of the output but it unclear in what the author(s) of this module mean by 'weight'. Trying this module didn't appear to change the order in the resultant html source.

You can change tho order these fields are displayed from Manage Display (admin/structure/types/manage/CONTENT TYPE/display). Edit the weight there and the fields should be displayed in the selected order on the node view page.

Edit: In the fields screen (admin/structure/types/manage/CONTENT TYPE/fields) the weight is used for displaying the form fields in the edit/add content type form.