Updating node field value using custom module validation I currently have a custom module which calls a submit custom validation function. I am trying to update a value after the validation is run. Basically, if a value is present, update a field to say "Yes".

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

if( $form_id == 'stage_2_node_form') {
   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';
}

} // end hook_form_alter()

function sitefuncs_custom_submit($form, &$form_state) {

        $banned = array(
        'better cures',
        'better nhs',
        'because it',
        'so what'
        );

  if (in_array($form_state['values']['field_stage_two_question_one']['und'][0]['value'], $banned)) { // if a banned word is the value of the input

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "No"; // set the value of the text input to No

} else {

$form_state['values']['field_stage_complete_text']['und'][0]['value'] = "Yes";

$messages = drupal_get_messages('status');
drupal_set_message(t('Your changes have been saved.'));

}

}

If anyone has any idea why the $form_state isn't updating the fields after I save the node, any help would be great!

I worked out that I was using

   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';

When it should have been

   $form['actions']['submit']['#validate'][] = 'sitefuncs_custom_submit';

Then all my data saved using

$form_state['values']['field_stage_complete_text']['und'][0]['value']['#value'] = 'No'; // set value to No

Use hook_node_insert instead of alter the form.

  This hook is invoked from node_save() after the database query that
  will insert the node into the node table is scheduled for execution,
  after the type-specific hook_insert() is invoked, and after
  field_attach_insert() is called.

  Note that when this hook is invoked, the changes have not yet been
  written to the database, because a database transaction is still in
  progress. The transaction is not finalized until the save operation is
  entirely completed and node_save() goes out of scope. You should not
  rely on data in the database at this time as it is not updated yet.
  You should also note that any write/update database queries executed
  from this hook are also not committed immediately. Check node_save()
  and db_transaction() for more info.

Example :

function modulename_node_insert($node) {
  // Just change the node object and value will be saved.
}


Map or Edit Query String Values in Views? As part of a port of a non-Drupal site to Drupal, I need to map a url query string to filters.

For example, if I have this query string and slect filter selected on Site A (Non-Drupal)

Site A

Value 1 | Value 1

Value 2 | Value 2

Value 3 | Value 3

www.sitea.com/?value=value%1

Site B:

Value 1 |1

Value 2 |2

Value 3 |3

www.sitea.com/?value=1

Site A cannot be edited. Is it possible to either edit the values in Site B to match that of site A (within views only, not actual field data) or map the query string, so that Views will see  "www.sitea.com/?value=value%1" and display "www.sitea.com/?value=1"

I know I can change the Filter identifier (i.e. ?value)  on the filter settings tab but how can I changed the values themselves?

In reality, they are far more complex than this so I'd like to avoid HTACESS.

You can use the hook_views_pre_view function in your custom module to change the query parameters using PHP, so a rough untested example of the code could look something like:

function MODULE_views_pre_view(&$view) {
  switch ($view->name) {
    case 'YOUR_VIEW_NAME': {
      // change your query strings to
      if ($_GET['value']) {
        $value = $_GET['value'];
        $new_value = substr($value, 0 , 6); // remove the 'value%' from Site A querystring
        $_GET['value'] = $new_value;
      }
      break;
    }
  }
}

Use the module Views Contextual Filter Query It will fit your needs.


How do I theme the teaser? As shown in the picture, I have the teaser view of a taxonomy term (Virtual Tour) which shows the node title, the node summary, the submission date, and an image added in an image field.
What I would like to achieve is to let the image float to the left of the summary. Is there a way to achieve it?

You should already have a template suggestions available like :

<!-- FILE NAME SUGGESTIONS:
   * node--2--teaser.html.twig
   * node--2.html.twig
   x node--BUNDLE--full.html.twig
   * node--BUNDLE.html.twig
   * node--teaser.html.twig
   * node.html.twig
-->

Make sure you have settings.yml set to twig.config: { debug: true ... and you will see the suggestions in the source.
You can set suggestions for any hook like:

function MODULE_theme_suggestions_node_alter(array &$suggestions, array $variables, $hook) {
 $node = $variables['elements']['#node'];
 $type = $node->bundle();
 $view_mode = $variables['elements']['#view_mode'];

 $suggestions[] = 'node__'.$type;
 $suggestions[] = 'node__'.$type.'__'.$view_mode;
}

In node html twig in temple file example:node--portfolio.html.twig
node--content-type.html.twig
You can use teaser view mode
 {% if view_mode == 'teaser' %}

 {{ content.field_some_portfolio_images }}

 {% elseif view_mode == 'teaser_2' %}

 {{ content.field_some_portfolio_images }}

 {% else %}

 {% if content.field_some_portfolio_images %}
 {{ content.field_some_portfolio_images }}
 {% endif %}

{% endif %}


Reset boost cache in a busy site without crash We are having a high traffic Drupal 6.x site (25,000) uniques per day, mostly landing pages.

Everythings works OK, with great performance, until we try to reset the boost cache.

Once we reset it, Drupal tries to regenerate HTML from PHP and MYSQL, and we reach a performance crisis where the site crawls and becomes unusable due to slow performance.

Is there a better solution? I imagine there could be a script which clears cache slowly, resets files one by one, wait(10 seconds), wget the url, and then go to the next url.

More info added (edits):

The site has about 20,000 nodes.
We have two Linode 4096 machines: 4 GB RAM, 8 CPU (4x priority), 192 GB Storage, 8 TB Transfer each. Only one of them stores MySQL.
The reason we do manual purge is because when Boost purges pages by itself, we can get to a point where a lot of pages are not in the cache. This can cause a big performance hit.
When the server is too busy, PHP returns WSOD and then Boost caches it! So we get a page, in cache that is actually WSOD!!! Since this is a critical problem, we decided to affectively disable Boost from purging cache on it own and do it On Demand.
Why clear the boost cache? The CSS and JS files are global. If we change the CSS, or add some JS, then we "drush cc css-js" to load the new changes. Doing that, the CSS/JS files are deleted and we are left with cached HTML pointing to non-existing CSS/JS files. So we get "broken" pages. The solution is to refresh the Boost cache.

Will the advagg module help?

Any other solutions?

Pleae advise.

Here is the script that does the job:

<?php

/* function to list all relevant HTML files in a given directory */
function ListIn($dir, $prefix = '') {
  $dir = rtrim($dir, '\\/');
  $result = array();

    foreach (scandir($dir) as $f) {
      if ($f !== '.' and $f !== '..') {
        if (is_dir("$dir/$f")) {
          $result = array_merge($result, ListIn("$dir/$f", "$prefix$f/"));
        } else {
          if (stripos($f,".gz") === FALSE) {
            $result[] = $prefix.$f;
          }
        }
      }
    }

  return $result;
}

/* main function */
function go() {
  $isToNotify = false;
  // get all relevant HTML files, recursively
  $files = ListIn('/var/www/drupal_site/cache/normal/my.domain.com','');
  foreach($files as $file) {
    // save filename for later
    $filename = str_replace("_.html","",$file);
    // normalize path to file
    $file = "/var/www/drupal_site/cache/normal/my.domain.com/" . $file;
    echo "\n************************************\n\nChecking $file" . "...\n\n";
    // get HTML from file into string variable
    $html = file_get_contents($file);
    // create DOM object for easy parsing
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    // get all <link> tags
    $links = $dom->getElementsByTagName("link");
    foreach($links as $link) {
      $css = $link->getAttribute('href');
      $css = str_replace("http://my.domain.com","",$css);
      // find only the relevant tags with the CSS file
      if (stripos($css,"css_") !== FALSE) {
        // normalize path to CSS file
        $path = "/var/www/drupal_site" .$css;
        // check if CSS exists
        if (file_exists($path)) {
          echo "The file $path exists\n";
          // no need to do anything else
        }
        else {
          echo "The file $path does not exist\n";
          // set notification ON
          $isToNotify = true;
          // delete HTML with links to not existing CSS file
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html");
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html.gz");
          // GET the HTML from scratch so Boost will re-cache it
          echo file_get_contents("http://my.domain.com/$filename");
          echo "Adding log entry...\n";
          // log activity
          $content = "\n\n".(date("Y-m-d H:i:s"))."\n    Refreshed HTML: my.domain.com/".$filename."\n    CSS file which was not found: ".$css;
          file_put_contents("/root/scripts/logs/monitorCSS.log",$content,FILE_APPEND);
          echo "Going to sleep for a while ZzZzZz...\n";
          // sleep for a while to avoid bombardment of the server by this script
          sleep(20); // in seconds
          // go to next file - no need to refresh same file more than once (if more than one CSS file was not-found in HTML)
          break;
        }
      }
    }
  }
  if ($isToNotify) {
    // send email notification if needed (we found some missing CSS files)
    mail('my@email.address', 'Monitor CSS Notification', wordwrap("Some missing CSS files discovered - see log file for more info...", 70));
  }
}

// call main function
go();
?>

You mention the amount of visitors but not the number of nodes. That is likely more important here, since Boost will want to rebuild it's cache.

That said, why are you trying to flush the cache often? With boost, you typically don't need to do an entire wipe of the page cache unless you're actually changing things often. Rather, you can set a minimum cache lifetime and then just let it do it's ting.

Unless of course, you have a use case I'm not picturing.

Lastly, what size Linode do you have? It's possible that you're hitting a hardware limit for the amount of content and traffic you have.


drupal course module adding payment object Please Somebody help me. I have spent almost a week working on this functionality but haven't got any success yet.
I have a Learning management system in drupal7 using the course 7.1 beta2 module, the LMS has courses in it. The requirement is to have the user buy the courses in-order to take the course but I am not able to configure it. Please can any body show me a way on how to configure the payment object so that the user will have to buy before even starting the course. I need a step-wise solution on this

Thanks in advance

Here is the solution on the Course issue queue:

https://drupal.org/comment/7477856#comment-7477856


How do I configure a view that gets a taxonomy on a node, and retrieves fields from the taxonomy? I have a view, which only appears when you navigate to certain nodes.

Each node which it appears under, has a taxonomy with a field called 'related_content_entity' referencing some related content. The node only has one taxonomy. I need the view to display data from the related_content_entity for the current node's taxonomy.

The brick wall which I have seemed to hit, isn't the entity reference, but filtering the results down to the one field referenced in the taxonomy associated with the node.

I get expected behaviour up to this point; creating a required relationship to the entity reference like this:

Gives me this result:

Which is entirely expected. But specifically what I can't figure out it how to filter these results down to the current node's taxonomy field. There's not a single contextual filter which I've tried which would filter the result down to only the node's taxonomy's field.

To put what I'd like to acheive more clearly:

Node-1 is under taxonomy-1, and taxonomy-1 has node-2 as an entity reference (though the entity reference module) in one of it's fields.

When view-A appears on Node-1, I'd like view-A to display the entity reference.

How do I do this?

Edit: This is my current set-up. This the input:

And this is the output:

@rooby, thanks for your help, but I don't actually get any results if I add any contextual filter under the sun.

Hi,

If you construct your view like the below and get the value from URL, you should be able to achieve.

EDIT: Allow me to guide you step by step:

You go to /admin/structure/views
You click on Add new view, and enter your view's name and description in the related fields in the next screen
Choose Content from the Show dropdown and your display format from the Display format dropdown and click Continue & edit.
Add Content: All taxonomy terms as a field, make your settings, and click Apply.
In the advanced section (to the right most section), add Nid as a Contextual Filter and click Apply (all displays).
Choose Provide default value and Content ID from URL, and click Apply (all displays

That's all there is to be done. You can test this by passing a node ID in the Preview with contextual filters field.

Select Taxonomy term in Contextual filter and then use hook_views_pre_view() to pass that taxonomy term argument to the view.

https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_view/7


Allow CSS styling in node filtered HTML view? I'm working through my first major Drupal 7 implementation.  My users need to create nested HTML ordered lists, with the various styling in Roman, numeric and alpha formats as listed at http://www.w3.org/TR/html401/struct/lists.html#type-values . The current project is taking place on a node of content type "book page."

This install is using CKeditor, which properly shows the various format types in edit mode.

In node view mode, though, the styles disappear, reverting to 1,2,3 format.  I found in the Filtered HTML settings the statement "... and CSS are always stripped."  Since CKeditor applies style commands to create the formatting method, it seems that Drupal filters them out.

Is there a method to allow styling in node view?  I just discovered http://drupal.org/project/css_injector but can't yet determine if it will do what I need.

Found this discussion which appears to be related.  http://drupal.org/node/259527

I recommend using the WYSIWYG Filter module.
In the "HTML elements and attributes" textarea there is a list of allowed HTML tags. 'ol' should be present. If it is, add '[class|style]' to it which will make it look like this:

ol[class|style]

Or, you can add @[class|style] to the list to enable the style and class attributes on all allowed html tags.

You can allow html tags on admin/config/content/formats/filtered_html


Images not loading until the page is refreshed The links are identical, the path is correct, the image is there,but i have to refresh the page for the image to show, i am suspecting the "itok" parameter might be causing the problem,. It was working fine at the beginning, at some point during the development i started having the problem.

Any help with be appreciated.

Thanks

Have you tried  the Image Allow Insecure Derivatives module?

  Provides a user interface to allow Drupal to bypass the token security check when generating image derivatives.

  Details

  Drupal 7.20 comes with a security fix that changes all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

  s an example, links that previously pointed to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png

  will now point to a URL like: /sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD_VaCaD

  For more information on the security improvement, visit the release notes.

  This is a fantastic security improvement, but in certain cases, has some ramifications. This module provides a configuration setting in order to toggle whether or not Drupal bypasses that token check.


Redirect form out of modal window after submit I have a form within a Colorbox Modal window which successfully submits using the _submit handler. I then successfully redirect the form to another page (which pre-loads a few fields on another form) using drupal_goto(). The problem I am having is that redirect stays in the Colorbox Modal window. I need to somehow close the modal window and transfer the url of the new form to the parent window. I can get this to work with a jquery function of

$(#my_form_id).submit(function (){
   parent.window.location="/user/register";
});

The problem with this issue is that the function calls when my form is submitted while disregarding anything that happens in the submission handler. So what ends up happening is I get the new page/form without the pre-loaded values until I refresh the page.

Do you have any thought or idea?

I would suggest using #ajax to submit the form and then allow the response to close the modal and go somewhere else. For example, here's a submit button that runs a function on click instead of submitting the form and reloading the page:

$form['submit'] = array(
  '#prefix' => '

',
  '#type' => 'button',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_super_cool_ajax_callback',
    'wrapper' => 'super-cool-wrapper',
    'method' => 'replace',
  ),
);

And then in your callback function:

function my_super_cool_ajax_callback($form, $form_state) {
  // Do what you normally would with the form submission.
  return '';
}

Now you can process the form as needed and return a response that simply redirects the user.

for redirecting you can pass inside

function() {
  window.location.replace ="url";
}


How to render user profile edit form in block? I want to render fields of user profile edit page  like "User Name ","current Password","email" in a customblock

I would suggest creating a view that displays user content. You should be able to add any fields you want from the user profile to the view. Then add a new display to the view with the 'block' type.


hide field based on its value or value of another hidden field I need to hide a radio button field of a content type (not a form) only on the edit view based either on its own value or based on the value of another field that is already hidden.

Dependencies does not work,  I think because the other field is already hidden and because it does not allow the dependent and dependee field to be the same field.

Any ideas?

You can give a try to this module: https://www.drupal.org/project/ffc

You may want to try hook_form_alter on that particular form. For example i had a case where i wanted a field to only show if it had more than one taxonomy term

    function members_form_members_node_form_alter(&$form, &$form_state,$form_id){
if(count($form['field_church_']['und']['#options']) > 1){
 $form['field_church_']['und']['#required'] = TRUE;}
     else{
    unset($form['field_church_']);}
return $form;}


How do you enable translation for a field which was defined by a contrib module? I am trying to enable translation for a field which was defined by a different module.

The problem is this field does not list in the UI. When I checked the definition for this field in hook_entity_field_storage_info I can see the setTranslatable(TRUE) is missing. So I added the same in hook_entity_field_storage_info_alter . After this I can see the field listing in the UI for translation, but when I enable the checkbox and submit the value is not saved.

How can I enable translation for this field?

After a bit of struggle and research, here is the approach taken -

custom_module.install file -

/**
 * Enable translation for workbench_reviewer field.
 * Implements hook_update_n.
*/
function hook_update_xxxx() {
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition_node = $entity_definition_update_manager->getFieldStorageDefinition('workbench_reviewer', 'node');
  $field_storage_definition_node->setTranslatable(TRUE);
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition_node);

}

custom_module.module file -

/**
 * Implements hook_entity_field_storage_info_alter().
 */
function hook_entity_field_storage_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

Once running drush updb I can see the field appearing in translation UI with the checkbox enabled.

You can set it to “Translatable” at the “Entity” level and as such you need the following hook.

hook_entity_base_field_info_alter

It alters existing field definitions -like ones defined by other modules.
There is also

[hook_entity_base_field_info]

to provide new field definitions

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_base_field_info/8.8.x

The hook you used [hook_entity_field_storage_info_alter] works at the field level.

For example, if some module wanted to create Entity for new field ( called my-title) and make it Translatable  at the “Entity” level it would be like:

$fields[‘my-title’] = BaseFieldDefinition::create(‘string’)
   →setTranslatable(TRUE);

So, the the hook(described above) is changing such a “base definition of the given Entity”.

The Steps you will need in your code is:

1) Load the given Entity.

2) Set it by using [setTranslatable(TRUE)].

3) save it (similar to $node→save();).

For example, for the “Article” NodeType,  step 1 can be

$type = \Drupal::entityTypeManager()→getStorage(‘node_type’)→
load(article’);

Check out the following for deeper understanding:

\Drupal\core\Entity\Query\QueryInterface.

 BaseFieldDefinition’s setTranslatable method
  & isTranslatable method

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/class/BaseFieldDefinition/8.8.x

The docs have it buried it

  In Drupal 8 field language is no longer exposed in the public API,
  instead fields are attached to language-aware entity objects from
  which they "inherit" their language

https://www.drupal.org/docs/8/api/entity-api/entity-translation-api


How do I access a field value for an entity (e.g. node) object? node_load((int) $nid) loads a fully-populated node entity. $node->title->value gets the title, but how do I access field values in Drupal 8?

I guess you do not need to convert $entity into an array,
this would simply work.

$entity->get('field_name')->getValue();

FYI : Using kint() from the devel_kint module will let you know all the available methods that could be used to access the object elements, so comparatively var_dump() is less helpful.

When not using nodes but entities (like the OP asked) things get a little more murky.
For example when using an address entity it only took me 8 tries to get the organization value.
$v1 = $address->get('field_address_organization')->getString();
$v2 = $address->get('organization')->getString();
$v3 = $address->get('field_organization')->getString();
$v4 = $address->field_organization->getValue();
$v5 = $address->organization->getString();
$v6 = $address->field_organization->getString();
$v7 = $address->organization->getValue();
$v8 = $address->organization;

The only one that didn't throw an exception was the last one.  And I'm lying when I say it only took me 8 tries to get the right answer - but 8 is all I'll admit to publicly.  :)


How to display contact form module in a block using drupal 7 Possible Duplicate:
  Put Site-Wide Contact Form in a Block

I want to display the contact form in a sidebar of the website. Is it possible? Please help me.

Check this answer which recommends to use Form Block module.
This could also be useful.

I think this feature is not included in the contact module of Drupal. It means it is still possible, but you have to add code to the module, where you implement the contact form in a Drupal block.


How to remove the "Close comment thread" button in Open Atrium? On my casetracker nodes in Open Atrium, the atrium.module inserts a "Close comment thread" / "Reopen comment thread" button.  What's the simplest way to remove this button, without having to modify atrium.module?

Keep it simple. Just throw a CSS "display:none;" on it.

For what it's worth, I think I found an easy solution:

In atrium.module (profiles/openatrium/modules/atrium/features) on line 338 in the function atrium_comment_thread_toggleform() I deleted return $form;


enable field groups programmatically I have created a field groups programmatically using this code:

in *.module file

/**
 * Implements hook_ctools_plugin_api()
 */
 function field_test_module3_ctools_plugin_api($module, $api) {

      if ($module == 'field_group' && $api == 'field_group') {
        return array('version' => 1);
  }
}

in *.field_group.inc

/**
 * Implements hook_field_group_info()
 */

function field_test_module3_field_group_info(){

 $field_groups = array();
 $field_group = new stdClass();
 $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
 $field_group->api_version = 1;
 $field_group->identifier = 'generale|node|field_esempio3|form';
 $field_group->group_name = 'generale';
 $field_group->entity_type = 'node';
 $field_group->bundle = 'field_esempio3';
 $field_group->mode = 'form';
 $field_group->parent_name = '';
 $field_group->data = array(
   'label' => 'Generale',
   'weight' => '2',
   'children' => array(
     0 => 'coverage',
   ),
   'format_type' => 'fieldset',
   'format_settings' => array(
     'formatter' => 'collapsed', //collapsible
     'instance_settings' => array(
       'description' => 'provo a creare un field group',
       'classes' => '', //generale field-group-fieldset
       'required_fields' => 1,
     ),
   ),
 );
 $field_groups['generale|node|field_esempio3|form'] = $field_group;

 return $field_groups;
}

===================================================

Field groups is created but not dysplayed.
Bottom of the page there is a section "Disabled fieldgroups" where it appears

If it's enable there are no problem but I need that fieldgroups is activated automatically.
There is a way to enable this fieldgroups programatically?

Thank you.

You can use the following code.

foreach($field_groups as $field_group){
    ctools_export_crud_enable('field_group',$field_group->identifier);
}


Get form element's label/value pairs from &$form or &$form_state I need to pass an array with all the fields (with their values) from a form from the submit function to a rules_invoke_event.

to do this I'm calling a get_fields() function, in this function I have acces to the form and form_state objects. Just wondering how I could loop through one of these with a foreach to get an array with the pairs?

function get_fields($form, $form_state)
  $fields = array()
  foreach(element in form)
  {
    $fields[$element[key]] = element[value];
  }
  return$ fields
}

something like this but with correct syntax?

Help would be greatly appreciated :)

This might work.

function get_fields_this_step($form_state) {
    $fields = array();
    foreach($form_state['values'] as $key=>$value){
        $fields[$key] = $value;
    }
    unset($value);
    return $fields;
}

Or you can just use

$form_state['values']['submitted_tree']

which is already formatted in the way you want. I'm not sure if this only applies to forms created with the webform module, but worth a shot!


Notifications during a file download As a newcomer to Drupal 7, I'm trying to understand how auditing and events can be used together.

For example, I have a content type of document, which is basically a name field and a file.  I would like an email to go out whenever an authenticated user downloads the document and also have a report that shows how ( and when ) downloaded the document.  Does anyone have any suggestions on the best way ( modules, design patterns, etc ) to go about setting this up?

Thanks in advance

Download Count can produce file download statistics.

Additionally, because Download Count has Rules integration, you can create a Rule that will send an e-mail when a file is downloaded.

A couple thoughts and approaches.

I have tracked file downloads before, but I did mine using Google analytics and setting goals. You can easily track what is clicked when and get very page specific. Within google analytics the reporting is done for you, much better than anything Drupal could ever provide, and it can even email you when your 'goal' is met (which could be as little as one download).  Check out GA goal conversions, which specifically have instructions to track downloads, even. http://support.google.com/googleanalytics/bin/answer.py?hl=en&answer=55580

If you want to go a Drupal route, then perhaps Ubercart or Drupal Commerce? An ecommerce module would require a person to download 'buy' the file and then download it after 'payment' is complete. If you are giving this away for free, then of course the price is 0, but, full tracking is available within drupal and notifications sent out consistently.

Hope that helps


Widget type radio buttons and N/A I have a field so-called "Status" in my custome contact type. It is a List (integer) and widget type is "Radio buttons". I added two values for allowed values list:

 0|Sold
 1|Available

Default value is "Available". But Drupal lists this as below:

 () N/A
 () Sold
 () Available

Why does Drupal add this unnecessary "N/A" to the radio buttons? I encountered this problem since D6. Now, I'm using the latest version 7.14. I'm still seeing this.

I know I can remove the "N/A" by writing a hook from a custom module.
Nonetheless, I don't want to write additional codes for this kind of small thing. When I use "Select list", it is ok with an option "-None-", but the radio button is ideally suited for the two options.

How can I remove it without installing additional module? Am I missing some functionalities from Drupal core interface?

Something like this should help.

(function($) {
  $('.form-radio[value=_none]').parent().hide();
})(jQuery);

http://drupal.org/node/1623360

One of the interesting Features of Drupal 7 is the Field API. Prior to Drupal 6, to make a custom field the Core Profile Module and Content Profile Modules are used. Now in Drupal 7 we can make any custom field to appear in User Registration Form. When Adding Custom Fields Such as Gender usually we use Radio Button Input. However there is a small Problem with the core module as it displays the third option N/A in the input. To Remove the N/A option the field needs to be set as mandatory. To Remove this option there is another way. Go to modules/field/modules/options/options.module and comment the the code $properties['empty_option'] = ‘option_none’ as shown below under buttons.

case ‘buttons’:
$properties = array(
‘filter_xss’ => TRUE,
);
// Add a ‘none’ option for non-required radio buttons.
if (!$required && !$multiple) {
//$properties['empty_option'] = ‘option_none’;
}
break;

case ‘onoff’:
$properties = array(
‘filter_xss’ => TRUE,
);
break;
}

However the proper way to achieve it would be to override this function in custom module. But for a quick fix we can also follow this method. [blog]: http://yamafm.wordpress.com/ "click here for updates"


How do i customize theme_link() for a particular node, or view only? i have a View that displays some DVD product teasers. What id like to do is customize or change the wording of the 'Read More' link of each teaser.

i also have another view where i want to remove that link altogether. now i know how to do this with CSS but i'm trying to learn how to override theme functions.

i have Themer Info turned on see a candidate function name for theme_link() but i think that would override all the theme_link functions for the entire site. how do i customize theme_link() for a particular node?

and how do i find out what function calls theme_link() ?, if i want to remove it entirely?

in other words, i need to get into $content variable!, how do i do that?

much thanks in advance!

You can use hook_node_view_alter(&$build) and overwrite the link. Here is an example to change the Read More title and removing Add comment link. You can use dpm()  function of devel module to see the array structure.

function mymodule_node_view_alter(&$build){
  if($build['#node']->type == 'DVD' && $build['#view_mode']=='teaser'){
    $build['links']['node']['#links']['node-readmore']['title'] = t('New Title');
    unset($build['links']['comment']['#links']['comment-add']);
  }

}

In a view admin page (/admin/structure/views/view/your_view/edit/display_id), you should have access to the Pager setting.
In D7, this is in the middle column under Block Settings, Header, and Footer.

It's called "More Link".  You can toggle that off/on per display and once it's on, you can then customize the text.  Doesn't appear to use tokens, though, so might not help if you wanted something more dynamic.


How to make metatags output proper images urls I'm tring to create set of open graph tags for better sharing of my page. Unfortunatelly I cannot make Metatags output proper path to images attached to nodes. I have node with field_promoted_image. In metatags configuration I put:
[node:field-promoted-image]
[node:field-promoted-image:file:url]
[node:field-promoted-image:file]

but all I get is field name or file name but without proper path.

if you get the file name with [node:field-promoted-image:file:url] just put the right path bevore the token. yoursite.de/thepathtoimage[node:field-promoted-image:file:url]or maybe you can put the base path token before it


How to hide country in Address Field display? Using Drupal 7 with Address Field module.  How to prevent the country part of the address field from displaying on a node with an address field?

For example, address is:

123 Main St
Somewhere, NY 10001
United States

I want the node to show:

123 Main St
Somewhere, NY 10001

I overrode the field.tpl.php file as described in this video:

Drupal 7: Theming Fields and Nodes with Templates by linwclark

I copied the field.tpl.php file from <site_root>/modules/field/theme/field.tpl.php and put it into the templates directory of my zen subtheme (<site_root>/sites/all/themes/somezentheme/templates/field--field_address.tpl.php)

In that template I used the hide() function on country:

  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php hide($item['country']); print render($item); ?>

    <?php endforeach; ?>

you could also hide it with css. I use css_injector module to just insert the css on the page(s) where you want to hide the element.


How to properly add inline Javascript code to a webform with javascript injector module I have recently started leaning Drupal 7. I have built my first Webform and I'd like to add a field that calculates automatically number of days between two dates as shown in below  I tried to follow this tutorial but I didn't understand it so I tried to use the module js injector to solve the problem!

This is the JS injection rule that I used

jQuery(document).ready(function($) {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});
});
});

But it doesn't work. Can you help me finding the error? It seems I didn't write it well on Drupal as js rule.

This is the javascript code that I want to write:

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet"             href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
});
});
</script>

You need to use proper Drupal jQuery Syntax.

Screw the js injector module, you can do the same like this:

Create a block, for Text format select Full HTML and put this code

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>

(function ($) {
$( document ).ready(function() {

$( "#edit-submitted-startdate,#edit-submitted-enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#edit-submitted-startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#edit-submitted-enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#edit-submitted-enddate').change(function() {
var start = $('#edit-submitted-startdate').datepicker('getDate');
var end   = $('#edit-submitted-enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#edit-submitted-days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#edit-submitted-startdate').val("");
$('#edit-submitted-enddate').val("");
$('#edit-submitted-days').val("");
}
});

});
})(jQuery);

</script>

Place the block in some region.

For Visibility Settings

Pages, select only listed pages and type the url for your webform.

There are two basic ways to do it in Drupal:
Drupal - Community Documentation - Adding JavaScript to a Webform


Bootstrap horizontal form layout In Bootstrap there is a nice horizontal form option. But in Drupal + Bootstrap base theme I couldn't find any ways to use this horizontal forms and layout form elements as it described, eg. col-2 for labels and col-10 for inputs.

The only way I found is Strapped theme (https://www.drupal.org/project/strapped)  but it is in dev stage and I don't need one more base theme.

Bootstrap is so popular along with horizontal forms and I don't want to believe there is no way to solve this problem.

Or everybody uses hook_form_alter() and render horizontal form somehow in code?

Thanks in advance.

Can you paste an example here with the code that didn't work for you?

Did you respect the structure below?

  Enter long URL:

    <input type="text" maxlength="100" size="60" value="http://" name="example_input" id="edit-example-input" class="form-control col-md-10 form-text" tabindex="1">


programmatically change link URL in view I have a view that shows all of a particular user's content (content the user has created on the site). This works fine, but I need to link the results (title field) to the pages where the content is displayed - not to the original node of the created content.

Since the content types may be different, I guess I need to set the URL's programmatically.

For example one content type is "projects" projects are displayed at site.com/projects/!arg

Another content type is "photos" photos are displayed at site.com/photos/!arg.

How do I write a conditional that will set the URL's correctly?

I don't recommend to use views php module,

Menu item with callback:

The idea here is to override all the links of the titles in your view with one link which pass an argument to custom menu callback, then in the callback, you write your PHP code which does the routing.

to implement this solution you need to do the following:

1- Override the link in the view

2- Create callback using hook_menu():

/**
 * Implements hook_menu().
 */
function mymodule_menu() {

  $items['my-routing/%node'] = array(
    'title' => 'Custom callback',
    'page callback' => 'my_custom_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

3- Create your custom callback to do the routing:

function my_custom_callback($node) {
  switch ($node->type) {
    case 'product' :
      drupal_goto('project/' . $node->nid);
      break;
    case 'post' :
      drupal_goto('blog/' . $node->nid);
      break;
  }
}

Here is how I got this to work. The code may not be the most elegant due to inexperience, but it does work.

I added node type, node id and author user id fields to the view and set them to exclude from view. Then using a global php field (provided by the "views php" module) I used the following code:

if ($row->type == "single_house_room_photo") {
  print  'title . '/' . $row->nid . '/' . $row->uid . '">  ' . $row->title . ' ';
} elseif ($row->type == "add_a_product") {
 print  'title . '/' . $row->nid . '">  ' . $row->title . ' ';
} else {
 print 'title . '/' . $row->nid . '/' . $row->uid . '">  ' . $row->title . ' ';
}


Display Ubercart Attributes and Add To Cart button in separate locations on product node page? I need to display my product page as such:

[-----------ATTRIBUTES-----------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]
[--------BODY, IMAGE, ETC-------]

[------ADD TO CART BUTTON-----]

How can I split the attributes and add to cart button in that way? Is there a way to do so in a tpl file? I'd prefer to avoid absolute positioning.

Create a new product template for your product node type.


Operations between the same field of a content type I feel like this is a very basic question, but after a couple of years it is the first time I need something like this and I cannot wrap my mind around the structure and get an idea of how to acomplish it.

Lets say I have a content type called "Fruit" where I store data in the fields "Name" (text), "Description" (text), "Price" (integer), "Date" (date).
In a view I'd like to select the fruit with names "Pear" and "Apple" with their respective prices for the dates inserted, but also make mathematical operations on the prices of the fruit (Like, "The price of apples was the 3/4 of the price of pears"). I cannot think of a way to do this since it is actually the same field, only grouped by some other field.

Any suggestions?

Install views_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the PHP field and exclude the Price field from display, Then the $results,$data,$row objects will give you the value of the row, Do the mathematical calculations and output the result.

If you want to perform mathematical operations, then you have to create view in normal way and in the view query alter functions, you have to append your condition, then you will get your expected output.


Help with hook_form_alter So I've got a custom module that builds a page (/simple-ajax-form) and has a form on it with the ID "payment_form" and other fields with IDs like "number_1". My module name is "Drupalup Simple Custom Form" for reference.

The problem I can't figure out (as I'm new to hook_form_alter) is that on the form ID instead of it being "payment_form" the ID gets rendered as "payment-form" and then on the input fields instead of it being "number_1" the ID get rendered as "edit-number-1".

What code do I need to make the form render as "payment_form" and inputs without "edit" and to also have underscores? And where does this code go - in my custom module?

Figured it out - put it the ID request in to an array:

$form['#attributes'] = array('id' => array('payment_form'));

Instead of

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


How to send emails to 20,000 + registered members efficiently? I have a Drupal 7 site with about 20,000 members.  Sometimes I need to email them all at once.  Thus far, I have been adding a rules component (Condition: Make sure user has not opted out of emails, Action: Send email, translated as appropriate for each language) and then used VBO and a view to select all the users on the site.

Unfortunately, with such a large number of users, even when VBO is queued to send emails 10 at a time the batch often encounters some error every few thousand users, so I need to find which user was last e-mailed when the batch error occurred and restart the batch manually.

Is there a more robust (i.e., automatic way that will not break and require manual intervention on my part) to email all the user accounts on the site when the number of users is large?

Below is a summary of how you can improve what you already have in place ...

Part 1 - Use a flag to keep track of the progress

Introduce an additional flag to allow "flagging" of some new or updated "entity" (eg "nodes") by all users "which you need to email all at once" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).

This of course assumes your eMails are to be triggered by such new or updated entities. But if you don't have such entities (= you have another reason to send such eMails), you could introduce a dedicated content type and use it as a kind of eMail template (with fields up to your own imagination). And each time you have a new eMail to be delivered, just create an appropriate node (of this dedicated content type) for it.
Create a rule to flag the newly saved (or updated) content, using the new flag (from step 1) for each of the users you already have in your existing "a view to select all the users on the site".
Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rule to "send an eMail" that you already have).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will eMail X users "as requested".

Part 2 - Recovering from an error

Sooner or later, Mr. Murphy will come along again, and it might cause some error again (eg after a few thousand users). If that happens, all that's needed is to repeat Step 5 ... And even if you didn't realize the error at first (only after X hours or days or so), all that's needed is to repeat step 5 as soon as the error got noticed.

You can split the mails and set the cron to send mails to all the users or You can go with 3rd party tool for sending mass mails to all your site users...


Get raw URL from field link I have set up a node--home_page.tpl.php template with the following:

  <a href="<?php print render($content['field_primary_section_link']); ?>">

       <?php print render($content['field_primary_section_image']); ?>

<?php print render($content['field_primary_section_title']); ?>

        <?php print render($content['field_primary_section_body']); ?>

I want the anchor tag to contain the raw URL from the field_primary_section_link but it is pulling in everything around it. I just want the plain URL but am unsure how to do. Any help would be appreciated.

You can dump $content['field_primary_section_link'] using var_dump() or if you have devel module installed in your project you can use dpm() and you'll see a bunch of arrays there and check the raw url that you need.

Use file_create_url(). It gives you the absolute path if you feed it the file's FID.


Add script on head section without module I have a google add script Which I want to integrate on the head section. How can I add the script to the head section on drupal 7 without any module and info file? Script is below:

 (function () {

        var _onload = function(){

            if (document.readyState && !/loaded|complete/.test(document.readyState)){setTimeout(_onload, 10);return}

            if (!window.__adroll_loaded){__adroll_loaded=true;setTimeout(_onload, 50);return}

            var scr = document.createElement("script");

        };
});

Add it your theme instead.

html.tpl.php would be the correct template to use.

I would place this script in external js file and insert it with "drupal_add_js" function in template file.

drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/file.js', array('type' => 'external','scope' => 'header','group' => JS_THEME,'every_page' => TRUE,'weight' => -1,));


Help learning OpenLayers for D7 I need to learn more about OpenLayers for Drupal 7. There is a ton of documentation for D6, some of which is helpful and some which isn't.

I'd like advice or suggestions for tutorials for a few different pieces..

When creating content, I want users to add a point or an area using a map. I know this is GeoField with the OpenLayers Map widget (so they don't type anything, but select visually), but I'm not sure how to then use this data in views.

In views, I need to create a map that displays the content. I want to set the default area based on the users' location.

Thanks.

This is the best tutorial I'm aware of: http://www.istos.it/blog/mapping/openlayers-and-addressfieldis

this is very good: http://www.syntux.nl/blog/basic-setup-drupal-7-openlayers-geofield-views-3.html


File save upload doesn't replace existing file despite FILE_EXISTS_REPLACE I'm trying to force replacement of existing file with same name, if a new version is uploaded by user. I've seen a lot of posts about this topic but none that I could find addresses how to force the replacement.

I'm using a custom form, and here's the code I've been trying to make work during the form validation:

  $file = file_save_upload(
      'file',
      array(
        'file_validate_is_document' => array(), // Validates file is really a document.
        'file_validate_extensions' => array('pdf doc ppt pps avi mpg mov wmv'), // Validate extensions.
      ),
      'public://',
      FILE_EXISTS_REPLACE
  );

The revised file (let's say "file.jpg") is uploaded, but inevitably Drupal creates a new copy and renames it file_0.jpg, file_1.jpg, etc for each new version.

I even tried to programmatically delete the original file using "file_delete" prior to committing the upload but I still get the copy!

Any help would be appreciated.

This is drupal's default behaviour and a known issue. It has been addressed a couple of ways.

The Upload File Replace module addresses this issue by swapping the filenames so the new file retains the original name.

The Media Update module allows in situ replacement of media files (part of the Media project).

You could either make use of one of these modules, or use them as a model for your own function.

$file_temp = file_save_data($attachment->data, 'public://<my_files_locatioin>/<my-filename.pdf>' , FILE_EXISTS_REPLACE);


form rendering through tpl file I want to render drupal 6 form through tpl file.
for that
1. I have written mytheme_theme in template.php file and there I have define my template forms arguments and path for tpl file.

I have written tpl file
in form function at the end I have called theme by '#theme' => 'my_template'

doing all these thing my from is rendering through tpl but now its not going into submit_hander() and validation.

can any one help me these? I am not getting what's wrong in these.

see in my template.php contain:

function cs_theme(&$existing, $type, $theme, $path) {
  $hooks = zen_theme($existing, $type, $theme, $path);
  // Add your theme hooks like this:
  /*
  $hooks['hook_name_here'] = array( // Details go here );
  */

  // @TODO: Needs detailed comments. Patches welcome!

  $hooks['my_theme_example'] = array(
                  'arguments' => array(
                  'order' => null,
                  ),
                  'render element' => 'form',
                 'template' => 'mymodule_template',
                 'path' => drupal_get_path('theme', 'theme_name') . '/templates',
              );

  return $hooks;
}

In these way I have printed all the form fields
in my .tpl file is:

   <?php print drupal_render($variables['order']['logo']);?>

You need rewrite 'form' like this:

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $form_registry = &$theme_registry['form'];
  $form_registry['function'] = 'mymodule_form_theme';
}
function mymodule_form_theme($element) {
  // I'm not sure that $element has 'from_id' but you could pass it if you need.
  if ($element['form_id'] == 'yours_form_id') {
    return theme_form($element);
  }
  // Else return what you need I guess that better to use hook_theme()
  // and then call theme() function.
}

Look at theme_form() to understand what variables need to pass in form tag.
I don't understand why do you need this. What is the reason to use template file?


Get the submitted values of a multistep webform I need to get the submitted values of a multistep webform. It looks like webform doesn't save values from earlier steps in the usual place: $form_state['values']['submitted'] or $form_state['input']['submitted']. I just need the submitted values of every form component at the last page.

I actually made a custom submit handler to store the values from each form in my own location in $form_state, but I was wondering if there was a better way.

You will find the multi-page values stored in

$form_state['storage']['submitted']

Note that this array does not contain values from the current page and will be empty if the current page is 1.

And incidentally you can find out which page was just submitted by checking

$form_state['storage']['page_num']

I doubt that this is the correct way to do it but...
I was able to pull values from the previous page using the following,

$_POST['submitted']['FIELD_ID']

where FIELD_ID is the ID of the desired form field.

This seems rather sloppy and I would like to find a better solution.

EDIT: Coleman's solution is the correct solution and should be used instead of this.


How can I replace "English" with "EN"? I have 3 languages in my Drupal 8 site. All works fine, without the language switcher.
Replacing German with DE worked, but replacing English with EN didn't work.

How can I replace English with EN in Drupal 8?

I use this, it's a little bit more dynamic then if you would hardcode the language code yourself. Hope it helps. This example works with the language switcher block.

function theme_preprocess_links__language_block(&$variables) {
    foreach(array_keys($variables['links']) as &$code){
        $variables['links'][$code]['link']['#title'] = $code;
    }
}

If you want that "EN" preffix appear in your URL, go to Administration > Configuration  Regional and language > Languages > Detection and selection , and click "configure" in URL. There, you have to add "EN" preffix to english path.

If you want that "EN" preffix appear in your language switcher block, you can use Language Switcher Dropdown module with has an option to change long names as "English" for its internacional code ("EN"). I've only used D7 version.


How can I use tokens in my content I want to use tokens in my content but it seems like it doesn't let me. I've found an article about using the Token Filter module but I have not been able to configure it so that it would print. In the README.TXT it says,

  Go to /admin/settings/filters and enable the token_filter for any of
  your existing filter type    or if you wish, create a new one.

but my problem is, when I go to http://127.0.0.1/drupal-7.34/#overlay=%3Fq%3Dadmin%252Fsettings%252Ffilters (on my installation, I just get to see  and I'm not sure how I can "enable the token_filter for any of your existing filter type" - may anyone help me?

Thank you!

Actually in order for this to work you need the token filter module:

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

Otherwise there is no option in text format config.

On Drupal 7, you set the text formats at admin/config/content/formats; so, on your site it should be http://127.0.0.1/drupal-7.34/admin/config/content/formats. Click on configure for the format you want to change.


Custom tokens in custom module The story :
I create lets say a simple module to store input data and sent a mail when you click save.
Now i done the part of store data, send mail and retrieve data, but i would like to add tokens to the mail part.

So for now i have something like this.

 function mymodule_form (){
         $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#size' => 60,
        '#maxlength' => 100,
        '#description' => t('Input your first and last name.'),

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

    return $form;

}

Now you have mymodule_submit that saves the data and sends mail.

function mymodule_submit(){

 here goes the part for saving data into table(not going to write it)....

/*mail send*/
    $text=array();
    $subject=array();
    $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");
    foreach ($mail as $data){
        $text = $data -> text;
        $subject = $data -> subject;
    }

    $params = array(
    'subject' => $subject,
    'body' => $text,
            );
     $to =$emailto; //db_query that selects from table
     $from =$emailfrom; //db_query that selects from table
    drupal_mail('person', 'my_module', $to, language_default(), $params, $from, $send = TRUE);

    /*end mail send */

}

function mymodule_mail($key,&$message,$params)
{

  switch ($key) {
    case "my_module":
        $message['subject'] = $params['subject'];
        $message['body'][] = $params['body'];
      break;

  }
 }

Now I made a form for inserting subject and body of mail hence $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");

My question is how can i allow user to use tokens or something else to add tokens like in drupal account mail settings(like: account activation, account blocked etc...), where you can add tokens to text so that you get :

[user:name],

A site administrator at [site:name] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:

[user:one-time-login-url]

So to clarify ... I have a form that user uses to input mail data but for now he can only input text , i want to make it possible for him to use tokens(or something else like drupal_set_message(t('Saved input @var!', array('@var'=>$temp)));) when he inputs data...

Its a form like mymodule_form.

You would have to add them to a global token piece like [site] for them to be able to be used anywhere tokens are used.

But to use in a custom module you can use the following hooks:

Generate token info:

/**
 * Implements hook_token_info().
 */
function module_name_token_info() {
  $info = array();
  // Define a new token type.
  $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
  );
  // Define any new tokens.
  $info['tokens']['my_custom_tokens']['my_token'] = array(
    'name' => t('My token'),
    'description' => t('A token I use in my module.'),
  );
  return $info;
}

Give values to token:

/**
 * Implements hook_tokens().
 */
function module_name_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'my_custom_tokens') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'my_token':
          // Work out the value of our token.
          $value = 'Value of token';
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

That should get you started with custom tokens. I've used this a few different times with different situations and it works very well.

Thanks for the help i did it this way:

  function mymodule_submit(){

 here goes the part for saving data into table(not going to write it)....

/*mail send*/
    $text=array();
    $subject=array();
    $mail = db_query("SELECT * FROM {mail_data} WHERE mail_id=2");
    foreach ($mail as $data){
        $text = $data -> text;
        $subject = $data -> subject;
    }

   $params = array(
'subject' => $subject,
'body' => $message,
'!buyer_name'=> $name,
'!buyer_lastname'=> $lastname,
etc...

        );

     $to =$emailto; //db_query that selects from table
     $from =$emailfrom; //db_query that selects from table
    drupal_mail('person', 'my_module', $to, language_default(), $params, $from, $send = TRUE);

    /*end mail send */

}

function mymodule_mail($key,&$message,$params)
{

  switch ($key) {
    case "my_module":
        $message['subject'] = $params['subject'];
        $message['body'][] = $params['body'];
      break;

  }
 }

Then i just call !buyer_name !buyer_lastname when writing a text in text box.


How to set Permission based on roles for Views Data Export Using views data export module, I set the permission for different roles in the Data Export in Views like:

But I can still see the Export button for all users in front page. However if the role doesn't have permission to export then after clicking it they are redirected to Access Denied Page

Is there any way I can hide the export button from all the user roles except the ones that have permission to export?

If it was a link defined in *.tpl.php then I could have done something like

<?php if (in_array('myRole', $user->roles)): ?>
// The export button
<?php endif; ?>

But I couldn't figure out how to do it with Views Data Export (without hacking the module)

This issue has been fixed in the 7.x-3.0-beta8 version. See the issue thread here.

Add a template for the view. Then by using css, hide the default export button coming with view. Then print the export link manually based on user role.


How can I pass variables from views template to node template? I have a view of contents of a content type. This content type has fields which references entities of another content type (and that in turn references another set of entities of yet another content type).

I am trying to iterate through this view with twig templates.

If I choose to show contents for my format, I can easily access the referenced entities and its fields. My quandary is however, I cannot track what row.content row/index I am in.

If I switch to show fields, I can use the global view results count and I have an effective counter.  However, I cannot seem to be able to access the referenced entities to get the values of the fields.

So far I have not found anything thru searching the net that actually addresses this particular problem.

I am using the views-view-unformatted template which in turn calls the node--view template. I am unable to 'pass' along the row index from the unformatted views template to node view template.

I already know that this is doable when using fields, but fields is out of the question because of the inability to access referenced entities.

Now there are two possible solutions to this issue:

Show content and somehow track the row.content index between twig templates.
Show fields and be able to actually access the fields of referenced entities.

Anyone have any suggestions?  Thank you.

Possibly use devel and kint modules.

Once both modules are enabled add {{ kint(fields) }} or {{ kint(content) }} to see what your options are for displaying your view's data. If the view wrks successfully then you should be able to display it using twig e.g. if you find field_name in kint and it output's the correct data then add <p>{{ fields.field_name }}</p> to your template


How do I update the configuration of a module? I'm building a custom module in Drupal 8. It includes some YAML config files.
As I develop I need to change and add to the config, e.g. to add another field onto my custom entity.
At present the only way I've found to get Drupal to notice the changes is to uninstall the module and re-install it.
Is there a way to get Drupal to check that the config files provided by modules is the same as the active config, and if not, update the active config? How are module updates handled? In D7 hook_update_N would be used to add fields using PHP, but it looks like this should be handled by the CM in D8?
Things I've tried after updating the yml files in the module:

drush cr, config sync.

manually copying all the updated config files into sites/default/files/config_XXX/staging/ - but this gives this error "The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.".

manually importing the files one by one using the config manager. This works, but obviously there must be a more automatic way.

[EDIT] manually use the config_update module to inspect changes and 'revert' to the module's config. Again, this is manual.

EDIT: From Managing configuration - do's and don'ts

DON'TS
Try to change the active configuration on your site by changing files in a module's config/install directory. This will NOT work because Drupal will only read from that directory when the module is installed.

...but changes there are going to happen, unless modules are bound to whatever config they needed in their first ever release, and may never ever update or add config.
Thanks in advance.

As mentioned in the original question, and follow-up comments, there are a variety of contrib modules and manual methods to accomplish this.

To do it automatically, or in a custom fashion, I think hook_update_N() is still probably the most viable option.

For instance, this is an example from the Head 2 Head to update system.site to set the default_langcode:

  $config_factory = \Drupal::configFactory();
  $langcode = $config_factory->get('system.site')->get('langcode');
  $config_factory->getEditable('system.site')->set('default_langcode', $langcode)->save();

You can also read in config (recommended only for adding new config, not necessarily updating or overriding config that may have been customized):

  $source = new FileStorage($path);
  /** @var \Drupal\Core\Config\StorageInterface $active_storage */
  $active_storage = \Drupal::service('config.storage');
  $active_storage->write($name, $source->read($name));

where $path is the absolute path to the my_config.foo.yml file.

I discovered this post after trying to add some new config to an existing custom module and drush cex wasn't picking it up. I tried the accepted answer using hook_update_N() but still no luck.

Turns out the project has https://www.drupal.org/project/config_ignore enabled, with the relevant *.settings.yml ignored at /admin/config/development/configuration/ignore


Quick Uninstall/Reinstall of a Custom Module I'm working on creating a module and I'm slowly getting familiar with the Field API and what all settings work on various fields and what don't. While I'm doing this, it seems that the only way to update a custom content type is to disable the module, uninstall it, then re-enable it.

Is there an easy way to do this? Right now, it's a somewhat laborious process that requires a handful of clicks to do the same thing over and over. I'm looking for a script or module to handling this very quickly with (ideally) a single click.

Solution 1. Devel + Drush:

You can use devel drush command for module re-installation with all the module dependencies:

drush devel-reinstall modulename

There is also alias for this command

drush dre modulename

Solution 2. Drush:

This is something that I would typically use drush for

drush pm-disable mymodule
drush pm-uninstall mymodule
drush pm-enable mymodule

You could also use it to define your own custom commands to combine these into a single command.

For those of you that want a script that does the devel command without the devel:
https://github.com/nategd/drupal_module_restart


How can I count a multivalue field's values in twig? I want to count the number of values of unlimited field in twig tempalate I tried

{{ node.field_mytext.count }}  => faced with error

and  in another try

{{ content.field_mytext.count }} => nothing returned

(in this method I checked my field is not in disabled field is display manager).

My question is how can I count the number of items of a field in Twig?

I hope I face with the solutions expect these solutions :D

add it in preprocess_node
use Twig Tweak

{{ node.field_mytext.count }} => faced with error

This does not work, because the method count is not allowed in twig policies:

  core/lib/Drupal/Core/Template/TwigSandboxPolicy.php

{{ content.field_mytext | length }}?

This does not work, because content is a render array with a lot of additional keys.

This works: Convert field to array and count

{{ node.field_mytext.getvalue | length }}

Use length filter

{{ content.field_mytext | length }}


How do I hide the default page /node? Drupal out of the box comes with a page (which is the default homepage) that is assigned to the node path.

How do I avoid users reach it, and redirect them to the actual homepage of the site?

There is no easy way to hide that page. If you don't use it, you can implement hook_menu_alter(), and either remove it completely, or set its access callback to FALSE.

the best way is to hide nodes from template_preprocess_page function

function template_preprocess_page(&$variables) {
    if ($variables['is_front'] == 1) {
        if (isset($variables['page']['content']['system_main'])) {
            unset($variables['page']['content']['system_main']);
        }
    }
}


WYSIWYG and TinyMCE stripping out float: left I've got the WYSIWYG module installed and the TinyMCE javascript library as well. I've created a text format "Rich Text" which is similar to Filtered HTML but I've added more allowed tags.

I insert an image into my text and I set it to align left which adds float: left to the markup. However, when I save and view the page, the float: left has been stripped out.

I can't find any options in the WYSIWYG configuration or my "Rich Text" format that allows me to control this. Am I missing it somewhere?

Why is my float: left getting stripped out?

My solution:

I downloaded a new module called WYSWIWYG Filter. On my Text Format, I turned off the Limit allowed HTML tags option and instead enabled the WYSIWYG Filter option. Then below in the WYSIWYG Filter settings, I configured the allowed HTML elements like so:

a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd,
img[!src|alt|title|style|width|height|typeof],
@[style|title]

And I checked all the boxes to allow margins, padding, floating, etc.

This does not help your exact question, but it is best to avoid WYSIWYG editors, it can often end up messing up the code or at least putting it in a way you cannot understand or draw sense from.


Can I Search an entity reference with search api db? I am using the search api database backend together with a views (with exposed fulltext search field). I want to show a 'related field' that is related to a content type that is being indexed. When the entity reference field only holds 1 value, all is fine.

But when it holds unlimited values (in the field settings) it no longer works in the view :-(

Does search api db have a limitation on indexing multivalued fields?

UPDATE

My content types are as follows:

Content type a

Field_a = text
Field_b = entity ref to content type b (allowed values unlimited!)

Content type b

Field 1 = text
Field 2 = text

I have indexed all fields above and added the related fields 1 and 2 to my search index as related fields.

Then when i create a view that shows the indexed nodes for content type a, and want to show field 2's information of the node that is referenced it only works when field b is set to allowed values: 1

SearchAPI does have this limitation: Note: This is a multi-valued relationship, which is currently not supported. Only the first related entity will be shown.

Here is the issue about this. https://www.drupal.org/node/1378656

Does search api db have a limitation on indexing multivalued fields?

NO

Search Api DB & Solr allows you to indexing multivalued fields. You probably did not see the changes because you did not re-index your index.

Edit: To answer your question base on the comment below. My answer still NO does not have limitation on indexing entity reference.

  Can I Search an entity reference with search api db?

Yes

And here is an article that wunderkraut posted based on Entity Reference.

  Benefits of Entity Reference: Can reference any type of entity. Easy
  to implement – follows same patterns as Node/User reference. Has Views
  integration, even for reverse relationships. Has Entity API
  integration, so it works well with Search API and Rules.


Access denied on image styles files on Drupal 7.34 As you can see in the screenshot below, images that are processed through image styles aren't showing up and when trying to display them through their urls, we get a 403 access denied.

It's a fresh drupal install on a Debian 7 with no additional modules

Any ideas are welcome to overcome this problem

Thanks

It's common to have incorrect permissions on that folder. You'll need to fix the permissions for /site/default/files directory. For a complete answer, see the recommended directory permissions or just run the following from the website root (per @David's comment below).

find sites/default/files -type d -exec chmod 755 {} +
find sites/default/files -type f -exec chmod 644 {} +
chown -R www-data:www-data sites/default/files

For additional issues, check Status Reports on yourWebsiteName.com/admin/reports/status.

Update:

I think I found the issue.

There was a similar question asked on Drupal.

It seems that the issue is that certain hosts, such as BlueHost, HostMonster and Virtualmin forbid +FollowSymLinks. You will need to change +FollowSymLinks into +SymLinksIfOwnerMatch in your .htaccess file. See an entire discussion on Drupal.

Go to Terminal by pressing Ctrl+T
Type :
cd /var/www/drupal ( assuming it to be the drupal root for your site )

sudo chmod 777 -R sites/default/files

Now clear cache and try to update the previously created image style


How do I include jQuery scripts at the bottom of the  tag? I want to include a JavaScript file at the bottom of the <body> tag, and I only want to  include it for a specific node type, but my node.tpl.php file's content is only wrapped by <article> tag; there is no ` tag in this file. If I do this in the root template.tpl.php file, it will effect all pages, which is not what I want.

Can I do this via theme preprocess functions?

The example on the documentation for drupal_add_js() can explain this.

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

If you want to add jQuery files, just change 'type' to 'file'.

Drupal 7 has introduced several new techniques that allow you far greater flexibility and control in the scripts you can have on your Drupal site's pages.

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.

(function ($) {
  // All your code here
})(jQuery);

If you don't, you may see the error Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function or similar.

Basic module code should go from something like this in Drupal 7:

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery);

These behaviors are instigated as you declare them in JavaScript so to clarify, there is no need for defining behaviors within a theme's or module's PHP file.

When applying certain behaviors to elements through JavaScript, we apply a class to the element to depict whether or not the effect has been applied.

Using jQuery Once (integrated into D7 core), the developer experience of applying these effects is improved. Note that there is also the removeOnce method that will only take effect on elements that have already applied the behaviors.

Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('input.mybehavior', context).once('mybehavior', function () {
      // Apply the MyBehaviour effect to the elements only once.
    });
  }
};

For best-practice examples, it's helpful to look at (comparatively) simple examples such as misc/collapse.js to see how it's done.

Thank you.


How to set a default theme programmatically I am trying to build an install profile and I want to have my custom theme enabled and set by default after the installation.

Adding in MYPROFILE.info.yml...

theme:
  - my_theme

...is not enough. This only installs it, but it is not set as the default theme.

I guess I have to do something else in the MYPROFILE.install file in

function MYPROFILE_install() {
  // how to set as default my custom theme
}

Thank you

Looking at ThemeController::setDefaultTheme (the request handler for the /admin/appearance/default route), this should do the trick:

\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', 'machine_name')
  ->save();

You can create a site that has the correct default theme, and copy over the theme related config files into your profile's config directory (or all the files if it makes sense for your profile).

See https://www.drupal.org/node/2210443#config for more.


Views RSS channel properties added with hook_views_query_alter() disappear I have applied this patch to the Views module so that it will add the channel properties of pubDate and lastBuildDate.

Then I ran Drupal "Clear all caches" within /admin/config/development/performance.

The added channel properties are only available for the first page requested each time after running another Drupal "Clear all caches".

For Drupal 7 how can I ensure that views RSS channel properties that are added with hook_views_query_alter() remain?

=================================================================================

I have already tried the “Views RSS” module and after downloading and enabling this module along with its associated “views_rss_core” the “RSS Feed – Fields” radio button does not display and only the “RSS Feed” option is present which comes from the “Views” module.

You can do this with Views RSS 2 and hook_views_rss_item_elements().

As we can see in the documentation for Views RSS API views_rss_get it can :

  Fetch item elements provided by other modules.

So to create your own item element do the following :

First thing, revert your hack, it won't be needed.
Download and install the module Views RSS (and Core Elements, DC Elements)
Create a default view for content and fields
Add a feed to it
Style it as RSS Feed - Fields
In the settings pubDate is avaible alerady so we don't have to worry about that.

Create a tiny module and enter the following

/**
 * Implements hook_views_rss_namespaces().
 */
function MY_MODULE_views_rss_item_elements() {
  $elements['dc:lastBuildDate'] = array(
    'description' => t('My custom lastBuildDate field.'),
    'help' => '',
  );
  return $elements;
}

Then install it and clear your cache.

Now, in the Views RSS field settings there should be a new field for your custom field (see image)

And when you view your feed it should be included (see image - last line)

Note: if you look at the snippet, it adds the field to the dc namespace. If you want to use another or provide your own namespaces have a look at the API and hooks.

It appears to me that you have custom patched the Views modules with an extra function which calls hook_views_query_alter.  There are at least two problems with doing it this way:

Altering a module with a patch that is not being considered for commit by the maintainers will lead to trouble when the module is updated - in a few years when somebody else is maintaining the site, will they remember to apply the same or an updated patch each time?  Will you?
The views module may already have a hook_views_query_alter call and you can't call a hook more than once in any one module.  If it doesn't, maybe it will have one in later versions.

I suggest moving your code to a custom module.


Select list of node titles for a view exposed filter I want to create an exposed filter based on the title of a node. How do I do this? I would prefer this filter be a select list - that is, all of the node names are listed based on the criteria I list.

So let's say you have three titles for events:

A Trip to the Woods

Go to the Beach

Off to the Farm

I would like the exposed filter to be a select list of these three nodes.

Look into the Finder module in addition to creating a View Page.

From the Finder module project description:

  Typically Finder is used for these purposes:

  As a search tool to find a group of nodes or users.
  As a way to navigate to a specific node or user page that matches criteria.
  As an alternative to exposed filters for a Views module display.

  Specific example uses of Finder:

  An autocomplete search on node titles in order to find a node.
  A select list of all the possible values for a particular content field
  in order to get a list of corresponding nodes.
  Multiple groups of radio buttons and checkboxes with taxonomy terms to find nodes that match all the selected terms.
  An autocomplete search on usernames in order to go to a user profile.
  A multi-step wizard form to whittle down a pool of potential results by asking questions on one step that will reduce the possible answers on the next step.

Finder should be able to pick and choice, or filter, what shows up in the that Select list.

Views Autocomplete Filters

  It works for node titles or cck text fields.
  The autocomplete results are actually the view results, so they are view related.


How do I simply make the whole site use a secure connection? In Drupal 7, I used the Secure login module to run the site on a secure connection, but it seems it doesn't revert back to http on logout. I would like to just run the whole site as https:// as a simplification.

Is there a simple way to do this without the use of module?

If you want to redirect all of your pages to be forced to use SSL then add this to your .htaccess file.

# Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This should be placed directly after RewriteEngine on if you have no previous rewrites.

There's another solution, which is to simply add $_SERVER['HTTPS'] = 'On'; in the settings.php file

See more at https://www.drupal.org/https-information#comment-9901783

It appears however the htaccess method redirects irrespective, whereas the settings.php file requires browser cache to be cleared.


How do I create a TEXT column? I am trying to create a TEXT column.

function _mymodule_installed_fields() {
  return array(
    'mymodule_summary' => array(
      'field_name' => 'mymodule_summary',
      'label' => $t('Summary'),
      'type' => 'varchar',
      'not_null' => TRUE,
      'length' => '400',
    );
  );
}

I get a VARCHAR column. How do I get a TEXT column?

Given the code you are showing, which is similar to the code shown in Fields API, create new content type I take you are adding a new field to a content type, not simply creating a new table field for a database table. This explains why the code is using properties like field_name or label that implementations of hook_schema() would not use.

The values you can use for the type property are the ones described from the hook_field_info() implementations. In particular, if you look at the code of text_field_info(), you will see the following descriptions.

text: The field stores varchar text in the database
text_long: The field stores long text in the database

The confirm of what database field type is used for each entity field type comes from the implementations of hook_field_schema(), in particular from text_field_schema().

case 'text':
  $columns = array(
    'value' => array(
      'type' => 'varchar',
      'length' => $field['settings']['max_length'],
      'not null' => FALSE,
    ),
  );
  break;
case 'text_long':
  $columns = array(
    'value' => array(
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
    ),
  );
  break;

So, if you effectively need to use a TEXT database column  type, you need to use the following definition for the field.

array(
  'mymodule_summary' => array(
    'field_name' => 'mymodule_summary',
    'label' => $t('Summary'),
    'type' => 'text_long',
  );
);

Data type of 'text' is supported in Drupal in the Drupal Schema API as well as other MySQL data types that are not part of the official Drupal data types. Refer the Drupal Schema API documentation and to hook_schema() on how to set up the tables in your custom code. You did say where you code existed. The text data type is hardly ever used in Drupal. It is either VARCHAR or BLOB. VARCHAR can be 65,535 in size - maximum.

Also, note that TEXT data type size is determined by the TEXT type. See the MySQL documentation on BLOB and TEXT types.


Using blocks in multiple regions In one demo projects I have found that I need to place same block in two different regions.
I have the knowledge that one block can be placed to one region only.
Can anyone help me with this ?

Using the Context module you can achieve your required feature.

This module will help you to place all your blocks in multiple regions on same or multiple page.

You can also use the multiblock module (http://dgo.to/multiblock) - D7


How to add link internal or external to an image in a view for a slideshow? I need a slideshow and sometime the images need to have a link. This link might be external or internal and it is posted by users. I use rewrite results in my view. However, sometimes the picture does not have a link. So this does not work for me.

I am using Drupal 7, Views, link and slideshow, picture module. My content type has the following fields:

field_slideshow_image
field_link_in_picture
text_slideshow

I try used another modules but I need to use the picture module to make my pictures responsiveness.  Other modules require that use the Formatter in views and picture module uses its own format.

I solved using theming in the view. I use the template in the image field. I ended up with a template like views-view-field--field-slideshow-image.tpl.php.

  <?php
//dpm($row); only work if devel module enabled

$url='';

if (!empty($row->field_field_link_in_picture_)){

    $url=($row->field_field_link_in_picture_[0]['raw']['url']);

}

if (!empty($url)) {
     echo "" .$output .""; //print image with link
}
else {
    print $output; //print image
}

?>

If someone knows a better way to do this please feel post it here. If I am not doing something in the Drupal way please let me know or you have another way to accomplish this. I would love to hear it :)

If you know little  about theming views you can check this video to understand better
Theming Views

I would also use

//dpm($row); only work if devel module enabled
$url='';
if (!empty($row->field_field_link_in_picture_)){
  $url=($row->field_field_link_in_picture_[0]['raw']['url']);
}
if (!empty($url)) {
  echo "" .$output .""; //print image with link
}
else {
  print $output; //print image
}


Memcache Admin not showing up in Modules I am updating a Drupal 6 installation to support memcached. After installing the memcache plugin, and configuring it with the following in settings.php, I cannot seem to access the Memcache admin page like I can on Drupal 7.

$conf['cache_inc'] ='sites/all/modules/memcache/memcache.inc';
$conf['memcache_servers'] = array(
  'ELASTICCACHE URL (Left out Intentionally)' => 'default'
  );
$conf['memcache_bins'] = array(
  'cache_page' => 'pages'
  );

I checked in modules to see if it was enabled but I do not see it there at all. All I can see is the memcache module without memcache admin.

Any suggestions?

The Drupal 6 version of memcache requires enabling the Memcache Admin module:

Once this module is enabled, there is an option at admin/settings/memcache to display memcache statistics on a page-by-page basis:

It looks like it had something to do with the version of Memcache I was using. The Development version reintroduced Memcache Admin (from Keithm's post).


Converting static site to Drupal 7 - How to set-up department sites? I am new to Drupal.  We have a corporate site that is static html, has 13 departments.  The template for the department sites are very similar to the main corporate site.  The departments will not have a different DNS assigned to it, that is, the structure will be as so:

main site URL:  www.mycorp.com
department Site:  www.mycorp.com/hr

We would want the departments to update their own content. Each department has about 10 pages to maintain, but can grow. It is also important that all of the departments' content is  shared/accessed/searched by the main corporate site. Would Drupal 7 multisite set-up be recommended for this?

I think multisite is not the optimal solution for you. With a multisite installation, you will end up with completely separate sites that have their own content, categories, users, settings, user files etc. etc. In my experience, that is often too much separation for a site like yours.

For instance: With multisite, if one person needs to get access to two or more departments, you need to create a user account for him in each site. He will also need to login in every site. Another example: With multisite, it's not easy to take content from a department site and promote it to the main home page.

In your case, I would look into a solution built with Workbench and Workbench Access, or perhaps Domain Access. With those modules, you will end up with a system that is technically a single site, but where Drupal is configured to split the site into sections and control user permissions on a per-section basis.

There are a number of ways to do this and other answers may expand upon your options.

I would suggest enabling Views module to select the content for each department's path.  You can also attach a field (using a taxonomy vocabulary) to each user to identify the department's they have access to.  The view will then allow you to limit who can see the contents on each departments view definition.

There is a quirk in the current Views filters that requires you to set up a relationship to content author before you can see users in the filters section.  If you have a problem seeing the users, ask a question on this site, and someone can guide you through the setup.


How to retrieve datetime from database in Drupal? How do I retrieve a DateTime column from my MySQL database using Drupal Database API + PHP. The DateTime format is in YYYY-MM-DD HH:MM:SS(2013-02-20 23:59:59). I want to retrieve all the rows in the database that match a specific date, and then store the hour inside an array.

For example, I want to grab all the data from January 1, 2013. I then only want to store hours 00:00 to 23:59 inside my array, not the entire date.

I do not want to use any modules to accomplish this.. because I need to code it inside my custom module.

Thanks for your help!

Current Code:

$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);
$results = $query->execute()->fetchAll();
foreach($results as $r) {
    $rows[] = array(strtotime(date("H:i:s", $r->date_time))*1000, $r->submissions);
}

I plan to display the data on my Flot line graph.

If you want the benefits of a SelectQuery, but with the more fine-grained control over the SQL, you can always use the where() method to inject (sanitised) raw SQL into the WHERE clause. e.g

$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);

// Fetch only records where date_time is greater than 30 days ago
$query->where('date_time > DATE_ADD(NOW(), INTERVAL -30 DAY)');

$results = $query->execute()->fetchAll();
foreach($results as $r) {
  $rows[] = array(strtotime(date("Y-m-d", $r->date_time))*1000, $r->numberOfPackages);
}

I don't know of any 'structured' way to get those sort of advanced conditions into a SelectQuery object so resorting to plain ol' SQL is necessary sometimes.

The code below works for me for fetching a group, so you can quickly adapt it for your own purpose.

$query = db_select('og')
    ->fields('og', array('etid'))
    ->condition('gid', $gid,'=');
$results = $query->execute();

$result = $results->fetchAssoc();


How can I ensure automatically that a module is disabled on my live site? I'm using a development -> staging -> live server workflow, and all three sites run off the same Git repository. The repository contains a few modules (a custom module for Selenium testing, etc.) that I never want to run on the live site.

Is there a way (in settings.php, perhaps?) to block a module from ever being enabled? I suppose I could also remove it from the repository, but my workflow is easier if I keep everything together.

You can hide modules from the admin UI by using the hidden property in the module's .info file:

hidden = TRUE

This method might be useful if you want to make sure the module is never enabled via the UI.

In case you're interested in how to do the opposite (stop a module from being disabled), it's also done in the .info file by setting the required parameter:

required = TRUE

Once you've done that Drupal will see the module as a 'core' module and stop it from being disabled through the admin UI.

You can check it with module_exists

if (module_exists('mymodule', 1.2) {
  if($myliveip == 'myliveip')
   drupal_uninstall_module('mymodule');
}

And call this in your modules hook_init
API


Nothing returned from taxonomy_term_load function The --very normal-- taxonomy_term_load() doesn't seem to be able to load entities within a custom menu callback. Yet I can access a profile entity, load fields, and get the field tids, but I get nothing from the taxonomy load function!

function mymodule_menu() {
  $items = array();
  $items['user/account-convert'] = array(
    'title' => 'My Page',
    'page callback' => 'mymodule_page',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mymodule_page() {
  global $user;
  $profile = profile2_load_by_user($user, 'my_profile_type');
  // Sanity check tid return. Success.
  echo $profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'];
  // Term name returns nothing. The object just won't load.
  echo taxonomy_term_load($profile->field_profile_myfield[LANGUAGE_NONE][0]['tid'])->name;
}

This makes absolutely no sense.

I have even sanity checked outputting hard coded tid's like echo taxonomy_term_load(1708) after 100% confirming it's a valid tid value.

Additionally I followed the function tree up and tried calling taxonomy_term_load_multiple
 directly, and entity_load directly. All give me nothing.

Furthermore I can confirm the function is valid and available at that point with function_exists, and the lack of undefined function errors.

Probably, this is a Taxonomy Access issue.

See taxonomy_access_query_term_access_alter().

(For the rest of the Internet, I only know this is the issue because Josh and I are working on the same codebase and I ran into the exact same issue in a completely different context.)

Try this one:

function get_tag_name($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query
            ->condition('t.tid', $tid, '=')
            ->fields('t', array('tid', 'name'));
    $result = $query->execute();

    foreach ($result as $row) {
        return $row->name;
    }
}


Load nodes from specific content type Thanks to kiamlaluno♦ I can load recent nodes using node_load() but how can I load recent nodes from a specific content type?

You should always enclose the table names with curly brackets. That way table prefix (if any) will be added automatically. It's better to use that way all the time.

This is how your query should look like:

SELECT nid FROM {node} WHERE type = 'page' ORDER BY created DESC.

I found the solution:

SELECT nid FROM node WHERE type = 'page' ORDER BY created DESC