What operators and functions can I use in a Views "Global: Math expression" field? When you create a "Global: Math expression" field in Views, the following help appears beneath the Expression field:

  Enter mathematical expressions such as 2 + 2 or sqrt(5). You my assign variables and create mathematical functions and evaluate them. Use the ; to separate these. For example: f(x) = x + 2; f(2)

I tried to use a modulo operator (%), but it didn't work, and the function specified in that help is obviously not vanilla PHP.

What syntax or language is allowable in this field?

Views Math expression fields use a custom expression parser in the Chaos Tool Suite (ctools) module. The code for this is contained in ctools/includes/math-expr.inc.

As of mid-July 2012, the built-in functions are:

'sin','sinh','arcsin','asin','arcsinh','asinh',
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'pow', 'exp',
'sqrt','abs','ln','log',
'time', 'ceil', 'floor', 'min', 'max', 'round'

Most of these are PHP's own math functions. The trigonometric functions beginning with "arc" are aliases to the ones beginning with "a". "ln" is an alias for "log".

The built-in operators are + - * / ^

The first four act just as they do in PHP. The fifth is the exponent operator; x ^ y is the same as pow(x,y).

You can create your own functions using this syntax, and such functions can use more than one variable. You can use this to create your own modulo function:

mod(x,y) = x - (floor(x/y) * y);

(Beware: The above function does not work with negative numbers.)


How to show upload date fore each file I have a content type called 'Documents' which has 2 fields: title and file.
There can be attached multiple files the file field.

But how can I show the upload date for every single file?
I have tried using Views, but could only get the upload date for the first file, not the rest of the files.

How can I do this?

I fixed it using this solution
https://www.drupal.org/node/1578484

function mytheme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'), t('Date'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
      format_date($item['timestamp'], $type = 'short'),
      );
  }
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}


Are tests built into contrib modules a reliable way of testing the success of a module upgrade? I have been updating some modules including Views and Feeds.  Given these modules are quite complex, I thought a good method of testing whether the update was successful or not was to run the tests which come as part of the module. This can be performed by using simpletest module which comes with Drupal core.

However the tests do not complete successfully (by this I mean that there was not a 100% pass rate).  I then rolled back to the previous version of Feeds, and low and behold it did not fully pass either.  This is a large site which has many visitors and I am certain that the Feeds functionality has been running fine, otherwise someone would have been complaining about it.

So it seems Feeds is working on the production site, but the built-in tests don't fully pass.

As follow up I did a clean install of Drupal 7.38 and then added latest versions of Feeds, Views, Features, ctools, Job scheduler and Feeds Tamper. Site is a standard install with no content.  After running the suite of feeds tests I get even more failures than on the existing site I mentioned previously. In fact almost all the tests fail.

This has got me wondering if in-built tests are a good measure of whether a contrib module is working correctly?  Or are they quite unreliable, as I now suspect?

No
Automated tests was created to test code, and to ensure quality of patches. They are meant to be executed in specific, clean environment (e.g. Testbot environment), which your live site certainly is not.
Second reason why it's no is what is tested. These tests only test code. But downloading and unpacking code is simple. Not many thing that can go wrong, and if it goes wrong, you will rather see. The hard and important part is database upgrade - and tests will not try to verify if your data was updated properly.


Drush Remote Alias Fails with No Drupal Site Found This is incredibly frustrating. Here's the deal. I have a drush alias defined for a server I'm working with. No matter what command it is, if it needs to bootstrap Drupal it fails with no drupal site found or some variant. Running drush with --debug gives me less than useful information although if you'd like to see it I'm happy to provide it.

I can run drush @alias sqlc and get the mysql command line on the remote server. I just cannot run things like drush @alias st or drush @alias cc all for example.

If I SSH to the server, change into the directory (i.e. /sites/default) and run the same commands they work fine. So this is only when going over a remote alias.

Here's the alias definition:

$aliases['alias'] = array(
     'uri' => 'site.com',
     'root' => '/usr/share/nginx/html/drupal/docroot',
     'remote-host' => 'us-west-2.compute.amazonaws.com',
     'remote-user' => 'ubuntu',
     'ssh-options' => '-i /Users/name/.ssh/id_rsa -q',
     'db-url' => 'mysql://dbuser:dbpassword@localhost/www',
     'path-aliases' => array(
       '%files' => 'sites/default/files',
       '%dump-dir' => '/tmp'
      ),
      'command-specific' => array (
        'sql-sync' => array (
          'no-cache' => TRUE,
        ),
     ),
);

Am I missing something here? I've done this a thousand times and for whatever reason this time it refuses to work.

Note: I have downgraded to Drush 6.x just in case it was a 7.x problem. Same result.

Well this is embarrassing.... The problem was my %root directive. I had an additional directory tacked on. It was usr/share/nginx/drupal/docroot. Not no html in the path.

Upvotes for @Queenvictoria though for commenting and getting me to realize my error by poking back in the alias file. Thanks!


Can't login to my Drupal website admin! I can't login My drupal website (D 7.23) now.
I have changed the password and tried to login back, but still the problem exists. After I reset the password by using the one time password and can log in, but when we log out and try again to login, it will be a failed one.

Please help me to solve it.

There is nice article on drupal.org on recovering administrator's password. Here is the link

Specifically, you would probably be using one of the two commands below:

Drush can generate a one-time login link.

drush uli

Reset password

drush upwd --password="givememypasswordback" admin


Upload multiple media entities at once Is there any solution yet which allows me to upload multiple media entities at once? At the moment I've to

Select a file
Upload it
Select the next file
Upload this

Especially for a gallery, where I've to upload a lot of images, this can be very annoying.

I really like to use the media entity module for this job because this way I can reuse all the images I've already uploaded in my gallery for other content.

Have you already checked the PlUPload module ?

It's still -dev, but should work ..

Another approach could be:
Using IMCE browser, that already allows multi-file uploads
in combination with filefield_sources, you should then be able to select the uploaded images for your gallery field and others.

  More sophisticated is the media(-entity)-suite, there's
  dropzoneJS in place.


Date Popup does not translate date format I am using date popup for a Italian site.
In edit/node when in my_data_field I select the date it shows in English format mm/dd/YY and not in dd/mm/YYYY.

Instead if I use the date popup in a exposed filter in the display view works as I expected.

The problem occour only in edit/node .

Can you help me to solve this?

Salve!
You only need to configure this in the field's settings, under MORE SETTINGS AND VALUES.

Here is a screenshot that shows that the option you are looking for is available in the drop down list:

Hope this helps.


How to assign a dynamically updating date to a user based on a related field on their profile I have a site where Users who can expect a delivery to their address every week depending on their delivery route. I also have a Content Type of "Delivery Route" and a Content Type of "Delivery" with a Date field and an entity reference field that adds related delivery routes for each delivery. With this I have a couple issues:

1: How to automatically assign a user a delivery route based on the ZIP code of their delivery address entered upon registration (Using the Address Field module).

2: How to display the next upcoming delivery date for a particular user on their profile based on deliveries collected for their delivery route.

You should be able to do those things without coding.

You can use the entity reference module to add a field to the user's profile that references the relevant delivery route node.

Then you can use the rules module, along with the rules conditional module to do the rest.

Have a rule that on user registration, uses the "Fetch entity by property" action to load the node that has the matching post code.

Then use the "Set a data value" action to set the value of the entity reference field for that user, based on the fetched entity.

Have another rule for when a user profile is viewed that uses the "Fetch entity by ID" action to load the delivery route node for that user.

Then add an if conditional that checks the entity type and content type, or use "Entity has field" and check that the date field is present. This step is required for you to be able to use all the fields on the fetched node in later actions.

Then you can use the "Show a message on the site" action to show a message to the user, in which you can use tokens to show the value of the date field attached to that delivery route node.


Problems with Media gallery I am using the media-gallery module to create dynamic galleries for a site.
I have a problem when I edit a node; I get the following error:

  Notice: Undefined index: media_gallery_format in locale_field_node_form_submit() (linea 405)

I have read Undefined indexes in locale_field_node_form_submit(), but I didn't resolve the problem. The issue report suggests that the error depends from a local language, and that I should change one line in media-gallery.module, but I don't understand where that line is, and how to change the code.

Can anybody help me?

The solution reported in the issue report is to replace every occurrence of unset($form[$id]) with $form[$id] = array('#language' => NULL) in all the module file; you just search for the first string, and you replace it with the second string. The module file is media_gallery.module.
Who suggests the fix doesn't report in which line you find unset($form[$id]) because you probably find more occurrences of that string, and the user doesn't want to make a list of all the lines containing that string. It is also useless to make such list, as an editor can easily make a search and replace for the strings listed in the issue report.


myform_validate() and myform_submit() functions not responding I have built a form from following examples on tutorials but neither the accompanying _validate() nor _submit() functions are responding when I submit this form. This is my codes:

/**
*implementing foodmenu form
*/
function my_magic_foodmenu_form($form, &$form_state){
    $form = array();
    $form['choice'] = array(
        '#type' => 'select',
        '#title' => t('Choose your meal'),
        '#options' => array(
            'ricestew' => t('Rice with Stew'),
            'ricejollof' => t('Jollof Rice'),
        ),
        '#required' => TRUE,

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

    );

    return $form;
}

/**
*Implement form validation: Foodmenu
*/
function my_magic_foodmenu_form_validate($form, &$form_state){
    krumo($form_state);
}

/**
*Implementing form submition: foodmenu
*/
function my_magic_foodmenu_form_submit($form, &$form_state){
   // krumo($form_state);
}

From the code above, I have implemented the 'choice' field to be '#required'. The _validate() function responds and prints the implemented krumo() when I submit this form without making a choice, so there is nothing wrong with the _validate() code then. Why does it not respond when I just submit the  form after making a choice??

EDIT:

I would really like to know why the default _validate() and _submit() do not work in my code, given that there is nothing apparently wrong with the code. I am not looking for alternatives. I just want to get the defaults above to work. Thanks

1 . You can add how many submit handler you want by using this

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

if you want to add a submit handler after default submit handler one callback the next callback to be called you can use this, This submit handler will be called after submit call back.

form['#submit'][1] = test_function;

To unset submit handler

submit handler

unset($form["actions"]['submit']);

$form['#validate'][] = 'test_validation_function';

function test_validation_function($form, $form_state) {}

this function will call before submitting the result.

Add these handlers and once clear your Drupal cache

Still you face issue look in to this url for example will help you out

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


Manage custom modules across multiple installations We have some custom modules which are used for multiple sites. Those can't be released as contributed modules, for example because they are client specific, make assumptions that don't work for contributed modules and so on.

I know about the following possibilities to deal with this:

copy & paste them around. Makes it obviously hard to keep the module up to date on all installations.
Have a single multi-site installation, but this isn't always possible.
Use git submodules, but they can be nasty, it's easy to forget to update them and aren't always supported (e.g. Pantheon)
Drush make scripts to check out from a common git repository. For this, you AFAIK need to use drush make for the whole site and we don't use it currently.
http://drupal.org/project/fserver. I haven't tried that out yet, does someone know if it is stable enough? The project description doesn't sound very promising and there is no 7.x version.

Anything else/better? What do you prefer and why?

The Drush make approach, as you've already mentioned, is the version my team is using.

Even though you are not currently using drush make for your sites, it should be relatively straightforward for you to move to this workflow if you want as drush also provides drush make-generate which will generate the make file from an existing site. Thus no need to feel like it's only worth it for new sites. :)


en/ language prefix remains after uninstalling internationalization module and dependencies I have cloned an existing internationalized Drupal website to create a new website. This new website does not need internationalization and translation. Therefore, I uninstalled all corresponding modules.

Unfortunately, the navigation through pages still use the default language prefix en/. Drupal complains that it does not find pages anymore. Yet, when I remove the prefix manually from the URL, the pages are reachable again.

How can I have Drupal stop using the en/ prefix in URLs?

the en/ prefix comes from core module Locale, you can change the configuration here: /admin/config/regional


How do I get my user picture back? Apparently if you take the "minimal" installation, it does not create the user picture field. I tried to manually create it, but now the Simple Facebook Connect module is not synching profile images, because it can't find the default user_picture field.

This is what the facebook module does:

// Try to download the profile picture and add it to user fields.
if (user_picture_enabled() && $picture_url) {
  if ($file = $this->downloadProfilePic($picture_url, $fbid)) {
    $fields['user_picture'] = $file->id();
  }
}
$new_user = User::create($fields);
$new_user->save();

I can confirm that it is able to get the $file, but the problem has something to do with the fields.

How do I correct recreate the "user_picture" field?

This is returning false:

function user_picture_enabled() {
      $field_definitions = \Drupal::entityManager()->getFieldDefinitions('user', 'user');
      return isset($field_definitions['user_picture']);
}

How do I add this field definition again?

I looked in the minimal.install file. I was hoping to find the code that enables user_picture, but all I could find was:

\Drupal::configFactory()->getEditable('system.theme.global')->set('features.node_user_picture', FALSE)->save(TRUE);

There is nothing in standard.install. I tried running the following, without any luck.

\Drupal::configFactory()->getEditable('system.theme.global')->set('features.node_user_picture', TRUE)->save(TRUE);

How do I get my user_picture field back without adding it manually, since I would end up with field_user_picture?

User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();


Search API Views only displaying one result I've just cloned a production site into a staging environment. I copied core and contribute, cloned the repo containing custom modules and themes, cloned the database and copied the solr configuration to a new core. Bringing up the database I configured a new search server pointing to the new core, repointed the index and reindexed the site.

All my old search API Views, and all new ones I create, only show one result. However the pager can tell that there are more. Jumping to other pages works. However no content is shown. If I do a search in solr admin I get many results.

I'm at a loss for where to start looking. As far as I can see all configuration is the same in the database and in the files. Google doesn't seem to think this is a thing.

Is this likely to be a Views issue, a solr issue or a search API issue?

EDIT: I've called the URL directly as @Eugene suggested. It looks to me like only one result is returned by Solr. However as you can see it things that a larger number has been found.

Query string:
http://example.com:8983/solr/core2/select?fl=item_id%2Cscore&start=0&rows=10&facet=true&facet.sort=count&facet.limit=10&facet.mincount=1&facet.missing=false&facet.field=sm_field_domains%24name&facet.field=im_field_regions&facet.field=im_field_topics&facet.field=im_field_sources&facet.field=im_field_domains&f.sm_field_domains%24name.facet.limit=50&f.im_field_regions.facet.limit=50&f.im_field_regions.facet.mincount=0&f.im_field_topics.facet.limit=50&f.im_field_sources.facet.limit=50&f.im_field_domains.facet.limit=50&f.im_field_domains.facet.mincount=0&group=true&group.main=true&group.field=ss_field_source_url%3Aurl&wt=json&json.nl=map&q.alt=%28ss_type%3A%22article%22%29%20%28bs_status%3A%22true%22%29%20%28index_id%3A%22solr_local%22%29%20%28hash%3Agpsxif%29

Response

  "response": {
    "numFound": 197180,
    "start": 0,
    "maxScore": 2.0000253,
    "docs": [
      {
        "item_id": "1646",
        "score": 2.0000253
      }
    ]
  },
...
}

Try to remove this from your url

&group=true&group.main=true&group.field=ss_field_source_url


Lock a Field Instance Is there a way to lock a field instance?

I want to prevent users from editing or deleting a given instance, but allow the field to be customizable elsewhere by the user.  If I lock the field, it will do the former, but prevent the latter.

According to this Field API documentation, fields can be locked by setting locked = TRUE in the field definition, but there is no corresponding locked key for the instance definition.

I experimented by adding locked = TRUE to my field instance definition, and while that removed the edit and delete links from the bundle types view, I can still edit and delete by visiting the appropriate url.

I was able to use a snippet from dropbucket to lock and unlock fields. I used the snippet in the devel execute php window but it could certainly be coded into a function instead:

/*
# You can use Devel Module to unlock/lock a existing field where you would otherwise get an error like "The field xxxx is locked and cannot be edited."
# Change the 'xxx' on line 1 with the machine readable name of your field.
*/
$field_name = 'xxx';
$field = field_read_field($field_name);
$field['locked'] = 1; //change this to 0 to unlock a field
field_update_field($field);


Change the bulk operations confirmation page How to change confirmation page in bulk operations?

Currently it is printing "You selected the following 4 items:".

I want to list titles of all items included in the bulk operation.

I assume that the entities are nodes, although the code can be easily adapted to any entity.

/**
 * Implements hook_form_alter.
 */
function my_module_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'views_form_ADMIN_VIEW_MACHINE_NAME_system_1' && $form_state['step']== 'views_bulk_operations_confirm_form') {
    $items = array();
    $entity_type = 'node';
    $ids = $form_state['selection'];
    $entities = entity_load($entity_type, $ids);
    foreach ($entities as $entity) {
    $data = 'Title: '. $entity->title . '
Created: ' . date('d/m/Y', $entity->created) . '';
    $items[] = array(
    'data' => $data,
    'class' => array('item-class'),
    );
  }
    $title = '
' . t('Nodes List:') . '
';
    $type = 'ul';
    $attributes = array('class' => 'list-class-one list-class-two');
    $list = theme_item_list(array('items' => $items, 'title' => $title, 'type' => $type, 'attributes' => $attributes)); // Create the list.
    $form['description']['#markup'] = $list;
  }
}


Get all registered Users into a Field Type List I would like to create a content/form where an authenticated user is able to choose another registered user from a list/dropdown. I've been searching for ways to get this done but am not able to find any working solution. Token can only display current-user, not all users. I can list all users using Views but not able to import them into the field of type list.

ie:
Nomination Form
Favorite Sport : [options](list from taxonomy)[/options]
Favorite Users : [options](list of all registered users)[/options]
etc

Appreciate if someone can point out what I am missing. Thank you

You can create form using Entity form.
It provides interface you to fetch content from the drupal fields taxonomy and other fields.
Term reference is inbuilt in drupal to add the Sports list.

For user reference list you can add the references module which will ask you to choose users from the registered users.

Hope it will help you


Unable to change theme that applies to view In a drupal page view under advanced=>Theme:Information=>Change Theme, I'm able to select a theme from the dropdown. Custom templates I've created go bold as expected. But when I save the view and check the theme information, it always reverts to the site default theme. I've tried this with a custom theme I created and a view themes that came with my installation.

To use a different theme for a specific page, try the ThemeKey module. It allows you to define rules for automatically selecting a theme. You can create a rule to switch theme for a particular path, which is probably the one you want. Another useful one is to select the theme based on the user's role. For example you can test theme modifications on a production site by showing one theme for anonymous users and your work-in-progress theme for the administrator role


Passing in URL parameters to menu callbacks I implemented hook_menu() to create a new path called 'user-login'. The page callback function receives url parameters like $_GET['parameter']; however, when I go to http://site.com/user-login?parameter=test, I get a 404 error. How should I implement hook_menu() to get this working?

This is the code I'm using

/**
 * Implementation of hook_menu()
 */
function login_menu() {
  //$items = array();

  $items['user-login'] = array(
    'title' => 'External login',
    'page callback' => 'user_login_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function user_login_callback() {

  // Get the URL params
  $uid = urldecode($_GET['uid']);
  $expiry = urldecode($_GET['expiry']);
  $provided_hash = urldecode($_GET['hash']);

}

Page would be called like http://site.com/user-login?uid=2?expiry=3?hash=sd7wdah

The drupal menu system does not care about $_GET arguments, you can do whatever you want with them, it doesn't affect the hook_menu() implementation **.

So, the error lies somewhere else. The result of hook_menu() is stored, it is not called on every page. If you change/add anything in that function, you need to rebuild the menus. The fastest way to do that is using the drush command "drush cc all" or "rebuild menus" in devel.module's Development links block. You can also submit the modules page, though.

** That said, it is much more common to pass arguments through the menu system as additional path arguments. Anything passed after the path will be passed as arguments to your page callback automatically. So calling user-login/2/3/sd7wdah will pass these three arguments to your function as user_login_callback(2, 3, 'sd7wdah'). You can also make these arguments required by specifying the path like this in hook_menu(): user-login/%/%/% and defining the path arguments like this: 'path arguments' => array(1, 2, 3),. This will make sure that your function can only be called with these three arguments and that they aren't optional.


get the content moderation value on node update The module content moderation has been activated and a custom workflow added to a content type.
On editing content, when selecting a content moderation state then clicking on save, I would like to programmatically save that value in a variable.

$mod in that code doesn't display the latest values for moderation state chosen on update.

I wonder if what I get is the default revision value (as configured for a state, Révision par défaut Quand le contenu atteint cet état il devrait devenir la révision par défaut; ceci est implicite pour les états publiés.)  but it is definitely not the latest revision value.

function my_hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'node') {
    return;
  }

  $content_id = $entity->id();
  $content = \Drupal\node\Entity\Node::load($content_id);

  $mod=$content->get('moderation_state')->getValue();
  var_dump($mod);
  die();
}

How do I get the latest value of content moderation on node update?

Getting the version of the entity meant getting the last revision and allow to get the correct value

function my_hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'node') {
    return;
  }

 $current_entity_lang = $entity->get('langcode')->value;
 $translated_entity = $entity->getTranslation($current_entity_lang);
 $mod = $translated_entity->get('moderation_state')->getValue());
}


How to add contents through block after enabling the blog module in drupal 7 Currently creating a single page responsive business website. Planning to add blog link to our site. For that we enabled the core blog module and added data.
But we want to add the contents through block!!! can anyone specify me with a solution?

Based on your comment above, you want to display blog entries in a block on your website.

I haven't used the Blog module in a long while (it's functionality can be duplicated easily without enabling it), but I think the easiest way for you to do this is to use Views.

Add a few blog entries
Create a new View that displays Content of type Blog Entry in a Block.
Views creates a new block, which you can place anywhere you'd like via the Block Admin page.

If you are unfamiliar with Views, you should watch or read some video tutorials. This one is recent and seems to be up your alley.


Trigger an action programmatically I have defined an action and want to trigger it from a hook.

We do not want to use the Rules module, because it is still buggy with Drupal 8. So, we cannot use rules_invoke_component().

What is the correct way to trigger an action? Do I need to construct a new Action object? Do I need a service? Is there documentation on that anywhere?

This works:
$action = \Drupal::entityTypeManager()
  ->getStorage('action')
  ->load('send_mail');
if ($action) {
  $action->execute($entity);
}


Data not returned / rendered in simple module I built a simple module to find the files in a folder and display them.  However no "content" is rendered and I get warnings from a core-include file.  Here is the module file:

<?php
function composer_example_menu() {
    $items = array();

    $items['composerExample/composer_example'] = array(
        'title' => 'Composer Demo',
        'page callback' => 'get_current_files', // 'call_back_function_name',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

/**
 * A utility function to return the array of current SplFileInfo objects
 */
function get_current_files()
{

  require __DIR__.'/../../../../../vendor/autoload.php';

    // the "files" directory
    $dir = drupal_realpath(file_default_scheme() . '://');

    $finder = new \Symfony\Component\Finder\Finder();
    $finder->in($dir)
        ->name('*.txt')
    ;
    $files = array();
    foreach ($finder as $file) {
        $files[] = $file->getFilename();
    }
  return $files;

The Warnings  I get:

  Warning: Invalid argument supplied for foreach() in element_children() (line 6583 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 6040 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 6050 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 6088 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).
  Warning: Illegal string offset '#printed' in drupal_render() (line 6095 of /Applications/MAMP/htdocs/drupal-7.51/includes/common.inc).

The value returned from the page callback will be passed into the function stated in delivery callback.

The default value of delivery callback is drupal_deliver_html_page().

  "delivery callback": The function to call to package the result of the page callback function and send it to the browser. Defaults to drupal_deliver_html_page() unless a value is inherited from a parent menu item. Note that this function is called even if the access checks fail, so any custom delivery callback function should take that into account. See drupal_deliver_html_page() for an example.

So you cannot output the $files directly. You have to return a render array if you want to keep using the default delivery callback.


Display event on click of Date with drupal fullcalendar module i have made a event calendar with fullcalendar module.

Now what i need is that when a user clicks on the date box for example 9-sept he should be send to a custom url with the full date in the URL.

And i need to highlight the date boxes with colors based on my event type.

Any clues ?

thanks

Have you done this with the Drupal Full Calendar Views module?

If yes, then its quite simple...

Add another field for "event date" and format the date in the format
you wish to use in the url , e.g., Y-M-D , then hide that field
using "exclude from display".
In the field you want to have as the
link, click re-write results.
Enter the path you wish to link to,
using the event date pattern rewrite pattern you created in step 1.
Your url should look like Link

As for highlighting the colour depending on event type, create another field for "node:type", and use that in the same rewrite results field as above, so your rewrite field is...

Link

Which will render out as...

Link

Then in CSS, declare classes for your node type, for example...

.event {background:red}


Entity relation field view I have a D8 entity reference field question. I have 3 content types: Student, Class, Book.

A student can have several classes and a class can have several books.
I have in student an entity reference field of type content connected to classes. I have in class an entity reference field connected to books.

In a view (block student class book) I want to show the student name, his/her classes and the books associated with each class.

I am able to create a view showing the student and it's classes (using the relationships option in a advance) but the books are not showing up!

Please can somebody help? Thanks

If you don't need to have filters or sorting or other view related things interacting with books or classes then I would set the view up to not display fields and use relationships, etc. Rather I'd configure it to display a view mode of the Student. Then do all display configuration for what should appear about the student in that view mode. I find using view modes, vs configuring fields directly in the view, to be an easier way to configure views in most scenarios. Plus if you need to display the same information somewhere else, it's much easier to re-use the view mode vs having to re-configure a view.

In your view, instead of showing fields, show Content and then choose a view mode of your Student. (You can create new view modes at /admin/structure/display-modes/view or Manage > Structure > Display Modes > View Modes in the admin menu.)

Then update your Student view mode via the manage display to show whatever student content plus the classes field. Configure your classes field to, again, show a particular view mode.

Then update your Classes view mode to show whatever content you want to display about the class plus the books field (not sure if you'd want to show just the label or again another view mode).


What tools do I need to automate my Drupal workflow? What tools do I need to automate the following tasks:

Project setup

Generate project wide password
Setup prod domain and dev and stage subdomain on server
Create user with access to /bin/bash/
Add public keys
Change open_basedir and increase memory limit
Delete files in document root
Initialize Git repo on Git hosting
Clone Drupal Repo Recursively
Add .gitignore (including Mac, Drupal and SASS specific paths)
Create Zen/Omega Subtheme
Create drushrc.php & aliases.drushrc.php
Commit changes
Create dev branch
Add Git remote and Push the branch master to it
Create databases for prod, stage and dev
Run site-install
Setup cron
sql-sync and rsync from prod to stage and dev
Fix file permissions

The quickstart project will handle almost all of these tasks.  It is basically a preconfigured drupal development environment that you run in a virtual machine.

If you wanted to install the tools locally, you can do almost everything in your lists with drush & make.


What's wrong in my code for setting up entity title in a Computed Field? I have written inside a Computed Field's Computed Code section the following code:

<?php
//work if the node is new and there is no value for the field yet
if (empty($entity_field[0]['value'])) {

  do {
    //calculate a promotion code
    $new_promotion_code = strtoupper(substr(md5(rand(999, time())), 0, 5));

    //check db for conflicts
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle','gift')
      ->fieldCondition('field_gift_code', 'value', $new_promotion_code)
      ->addMetaData('account', user_load(1));
    $result = $query->count()->execute();
  } while($result > 0);

  //assign the field value
  $entity_field[0]['value'] = $new_promotion_code;

  //option#1
  //$entity->title[0]['value'] = $new_promotion_code;
  //option#2
  //$entity->title[LANGUAGE_NONE][0]['value'] = $new_promotion_code;

  //presave the node with attached fields (not sure if this is working)
  field_attach_presave($entity_type, $entity);
}
?>

This code works except the commented out section which includes two options for setting up same node's title. I am also not sure if field_attach_presave() works but I have no means to debug it and it just doesn't fail like field_attach_update().

Using Auto Entity Label is also a solution but the token ([node:field-gift-code:rawvalue] or [node:field-gift-code]) for this field just prints Array.

Any suggestions?

You can't do it all in the first box.

Use the Computed Code box to create a value for the field in $entity_field[0]['value'].

Then use the Display code box to do something with this value.


hook_menu_local_tasks_alter for specific tab I've tried with my custom module to implement hook_menu_local_tasks_alter, but I'm not sure how can I edit specific tab.

Here's my example code:

<?php
    function my_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {

        $data['tabs']['0']['output']['0']['#access'] = FALSE;

        //krumo($data);

    }

With this code I can hide the first tab, but that does on all pages.

When I'm using hook_form_alter and with krumo(form_id) I can see what form is and I'm using switch statement to edit specific form.
Is it possible to do this or something similar with tabs?

I'm not using CSS in this case, because I like to change the name of the tabs on specific pages too.

You can use hook_menu_local_tasks_alter() in your template.php file for your theme or .module file in module like below:

function YOURTHEME_menu_local_tasks_alter(&$data, $router_item, $root_path) {

  foreach ($data['tabs'] as $key1 => $tabs) {
    foreach ($tabs['output'] as $key2 => $item) {

      if ($item['#link']['path'] == 'node/%/edit' || $item['#link']['path'] == 'user/%/edit') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';
      }
      else if ($item['#link']['path'] == 'node/%/delete') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($data['tabs'][$key1]['output'][$key2]['#link']['title'] == 'View') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($item['#link']['path'] == 'node/%/revisions') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }

    }
  }
}

Hope this will help.


How can I insert one bespoke item first and one last in a views grid? I have a set of views (in D7.57, views 7.x-3.18). Each view takes a selection of my (drupal commerce) product-displays and places them in a grid, in alphabetical order.

Now I want to add a bespoke item as first item (so in row 1, column 1), 'bumping up' all normal products one place (so product 1 goes to row 1 column 2, etc). Whatever I try (adding global header in views (obviously wrong), changing the views-grid-xx.tpl) 'breaks' the rows, displaying my bespoke item in perfect order, but breaking the row.

Option 1: adapt the views style or row output .tpl

Update after @AltaGrade answer: Thanks for your answer. That's what I tried, I amended both the 'style' and the 'row' templates for the view, but do not get the desired results with either.

The view does display my insert (which is a piece of fixed code, same lay-out etc as the normal grid items), but then treats the normal generated items as a full row, causing breaks where I don't want them, and also repeats my insert each row.

My rows (of three columns each) then look like:

insert - item 1 - item 2

item 3

insert - item 4 - item 5

and so on..

Code of the views.grid.xxx.tpl looks like this, where and how would I code my inserts (one to go before the first item in row one; one to go after all items have been listed)?

<?php

/**
* @file
* Default simple view template to display a rows in a grid.
*
* - $rows contains a nested array of rows. Each row contains an array    of columns.
*
* @ingroup views_templates
*/
// Match Column numbers to Bootsrap class
$columns_classes = array(1 => 12, 2 => 6, 3 => 4, 4 => 3, 6 => 2, 12 =>     1);
$bootsrap_class = isset($columns_classes[$view->style_plugin-   >options['columns']]) ? $columns_classes[$view->style_plugin-   >options['columns']] : 3;
$delay_attr = '';
?>
<?php foreach ($rows as $row_number => $columns): ?>
  <div class = "row<?php if ($row_classes[$row_number]) { print ' ' .  $row_classes[$row_number];  } ?>" >
    <?php foreach ($columns as $column_number => $item): ?>
      <?php
        if(isset($column_classes[$row_number][$column_number]) &&  strpos($column_classes[$row_number][$column_number], 'animation-delay') !==  FALSE) {
          $delay = isset($delay) ? $delay + 0.1 : 0.1;
          $delay_attr = ' data-wow-delay = "' . $delay . 's" ';
        }
      ?>
      <div class = "col-md-<?php print $bootsrap_class; ?><?php if   ($column_classes[$row_number][$column_number]) { print ' ' .  $column_classes[$row_number][$column_number];  } ?>" <?php print  $delay_attr; ?>>
        <?php print $item; ?>

    <?php endforeach; ?>

<?php endforeach; ?>

Option 2: Preprocess the view output using pre_render.

One suggestion I found is using hooks (hook_views_pre_render, hook_views_post_render?), is this the best way? If so, where would I put such a hook? Are these actually written into views.api.php? And how do I then write such a hook that it only applies to the view I want? All pointers / help very welcome, hooks 100% new area for me.

In the views.api.php I also found a whole section on views-handlers which looks similar to the hooks, are these an option too?.

Option 3: create extra content types

Create new content types (in this case product types) and let the view render first extra type, then the main products, then the second extra type. So I'd create a new content type for the bespoke items, and then add them to the view's filter. Any explanation how I would do that so it neatly merges into the row would be amazing.

Go to admin/structure/views/view/YOUR-VIEWS-NAME/edit/page, click on Theme:Information and you will see bunch of lines. Choose appropriate one depending what exactly you want to override. It can be the whole views display output, or style output, or specific field output.

Each line will have an active hyperlink, clicking which you can copy the content of the new file. Also each line will have file name suggestions.
When you identified the right output, you can choose pick any of the suggested file names on that line: the further to the right, the more specific output.

Create a new template file in your themes template directory, paste the copied content and start modifying the output per your desire.

For example, you could execute your checks just after foreach loop starts:

<?php foreach ($rows as $row_number => $columns):
  if ($row_number != 0) {
    // Here goes your custom modifications.
  }
<?php endforeach; ?>


Drupal Gardens Template builder: Can I have this feature on my site When you build a new site on Drupal gardens, you can select what features and blocks/regions you want on your new site.

Is there a module, which would let me choose my own set of features each time I create a new site on my own hosting (i.e. separate from Drupal gardens).

Fusion theme + Skinr module will get you part of the way there.  DG may have some customizations that are not available outside of their walled garden.


How do I print the {{messages}} variable? In Drupal 7 I was able to do something like this:

<?php echo $messages; ?>

It seems this variable is no more in Drupal 8.

{{messages}} // This returns NULL on {{dump(messages)}}.

I basically have a page--user--login.html.twig where I output the page.content and above that I want the messages to be displayed, in case there are errors on the page and not the entire header.

// Not desirable
{% if page.header %}
   {% block header %}
     <div class="col-sm-12" role="heading">
         {{ page.header }}
      </div>
   {% endblock %}
{% endif %}

What is the correct variable name for <?php echo $messages ?> in Drupal 8?

By default the messages are in the highlighted region, put this in your page twig:

{{ page.highlighted }}

If you changed the block layout, go to

admin/structure/block

and check in which region you placed the status message block. When it is disabled, move it back into a region.


How do I overwrite the controller for admin/content? On admin/content, I have created different views for articles and basic pages (the default content types created from Drupal). On admin/content, it shows Content | Article | Basic Page. When I already have Article and Basic page as separate.

On admin/content, I would like to show as Blank means no data instead of showing all data.

I tried the following code.

modules/custom/content/src/Routing/RouteSubscriber.php

namespace Drupal\content\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * Used to alter routes.
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setDefaults(array(
        '_controller' => '\Drupal\content\Controller\ContentOverviewController::overview',
      ));
    }
  }

}

I'm trying to override its default controller, so it show blank.

The code for the controller is the following one.

namespace Drupal\content\Controller;

use Drupal\system\Controller\SystemController;

/**
 * Class ContentOverviewController.
 */
class ContentOverviewController extends SystemController {

  /**
   * Content Overview.
   */
  public function overview($link_id) {

    $build = [
      '#markup' => $this->t('Hello World!'),
    ];
    return $build;
  }

}

The code doesn't seem to work.

I also tried to disable the content view, but that is not needed.

Check a namespace in your RouteSubscriber.php

You have

namespace Drupal\content\Routing

Should be

namespace Drupal\mcontent\Routing

Because your custom module is mcontent (not content)


Is it possible to get render a field for a paragraphs field in the parent twig template My use case requires that I get a fields values in the parent paragraph template file.

So to be more clear I have a paragraph type (wrapper) which itself has a field referencing to another paragraph type (nested).

I am trying to get the values of a field (like title) from the child paragraph (nested one) in the parent twig template.

Hope for some help with this.

in your node.html.twig file you can traverse up the element array like this

{{node.field_parent.entity.field_paragraph.entity.field_text.value}}

where

field_parent.entity is the parent paragraph
field_paragraph.entity is the child paragraph attached to parent
field_text is a text field attached to child paragraph

OR inside your paragraph.html.twig

{{paragraph.field_paragraph.entity.field_text.value}}

NOTE: its actually better to put this code in a paragraph--parent.html.twig file otherwise this template is going to be used also for the child text paragraph which does not have field_paragraph and its going to lead to error.


Do I use Content Type creator to create new modules? I read the Drupal 7 tutorial on creating modules.  I did fine from code and the example.  Got the basics.

Then I read about creating a new content type with fields.  I have ubercart and it had a product type, so I am kind of lost.  Other modules have their own content types with fields.

Say I wanted to track an inventory at the most basic level.  I want to know the item number and description, and on hand amount.  Nothing fancy.

Do I create a table to hold that data in the drupal database?  somewhere else?  Do I create a field with the content type additions?

Not sure what do to.  Thanks for help.

edit

After a quick google search I found this. Might be useful
-http://drupal.org/project/merci- (couldn't add more links)

I'm sure there is already a module you can download that does something similar to what you'd like to do, but if not then you should probably start like this.

Install the ctools and views module

Things that can be done without code (Drupal creates the tables in the database for you)

Create content type
Add necessary fields to it (sku, description, amount remaining)
Create some nodes of your content type with sample data in order to build/test your module as you go
Create a view to display nodes of your new content type

Now for the code

Get the node id of the product you are trying to alter
Load the node - http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_load/7
Your code that adds and subtracts inventory should updated the amount remaining field (you can use db_query or EntityFieldQuery for this) http://api.drupal.org/api/drupal/includes%21entity.inc/class/EntityFieldQuery/7 http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7

You also mentioned übercart, are you currently using it? If so you can just add fields to that content type and track those with your module and not have to deal with creating content types and views, because ubercart does all of that for you.


Exposed Filter Filtering on Unpublished Revision I have a content type with a massive number of fields. The primary way this data is seen is through a view with several exposed filters (looking at the fields) which provides a list of matching records. I have installed the revisioning module in order to provide drafts.

The issue I'm running into is that the filters are looking at the most recent (unpublished) revision which doesn't match the published data.

The exact problem I'm running into:

There is a published product which is marked as energy star compliant (field on a node). The new version of this product is not energy star compliant, but it has not been released yet (unpublished revision under moderation).

When users filter for only energy star compliant products (using the exposed filter) this product is not displayed. When they do not filter the product is displayed, and it is shown as energy star compliant.

What I've tried:

I haven't made much headway. I've discovered that drupal is saving the unpublished field data in the "field_data_field_..." tables, which is what I expect the filter works off of. The published data is in the "field_revision_field_..." tables.

The node table stores the vid of the most recent revision, not the published one.

I logged all of the SQL and saving the unpublished revision updates the field_data tables and saving the published revision does not.

Deleting and creating a new revision does not fix the issue.

Creating a new published and a new unpublished revision doesn't help.

The issue occurs on multiple nodes not just one.

I cannot find any settings in views, the view, revisions, or any other location that appear relevant.

What I suspect:

I'm guessing I have interference happening between modules. There are so many modules on this site that I do not have time to trace through the code and figure out what is actually happening, and there are over 60 modules enabled. My next step would be to start disabling modules but I did not build the site and I do not have the time-budget to figure out what all of these modules do and get the site working well enough without them to test if this behavior is the same.

My linux background says that this is a permissions issue (it's always a permissions issue).

My option at this point is to write a script outside of drupal (I'm not seasoned enough to know how to do this in drupal) that goes into the database and puts the correct data in there manually from the revision table. I don't want to do this, it's a bad idea and would be hell to maintain.

Any insight into what to try next would be very helpful.

After figuring out the magical combination of keywords (it's "views filter exposed content revision") I found someone with the same problem:

"Unpublished data belongs to the latest revision of a content type is accessible for querying by the Views module"

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

Drupal user fbrooks replied:

  lavms,

  I don't think modifications to the Revisioning module are necessary to address this.

  I was dealing with, what I believe is, a similar issue. I have a content type with a boolean field used in a filter in a view such that a node will appear if the field if set to true. When you create a node revision under moderation that has the boolean field set to false, the node would be filtered out of the view before the revision is published.

  I was able to address this by recreating the view and selecting "Content revisions" instead of "Content" from the "Shows" drop down list on the new view page. This results in node_revision instead of node being used as the base table, and automatically adds a join between the node_revision and node table on vid. When selecting fields for display or filtering I used the ones that begin "Content (historical data)", which results in the values from the field_revision_* instead of field_data_* tables being used. All these things combined resulted in the correct revision being used by the filter.

  Hope this helps.

  Frank

This is the "core view" of the site and is quite entrenched so recreating it will not be simple, but it has turned from an unknown problem to a known and solvable one.

Thanks sareed for your help.


Move Drupal to subdirectory - clean urls There is a requirement to move  site from www.test.com and make it available only under URL www.test.com/newsite.

When the clean URLs are enabled and after i click to login to the administration site, the URL changes to:    www.test.com/newsite/newsite/user.It duplicates the "newsite".

The page  www.test.com/newsite/user is visible...and only after the login attemp this happens.

I have set in .htacess

RewriteBase /newsite
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Clean URls are working normally in the rest of the site.

Perhaps setting the $base_url variable in the settings.php will help Drupal generate the correct urls.

/**
     * Base URL (optional).
     *
     * If Drupal is generating incorrect URLs on your site, which could
     * be in HTML headers (links to CSS and JS files) or visible links on pages
     * (such as in menus), uncomment the Base URL statement below (remove the
     * leading hash sign) and fill in the absolute URL to your Drupal installation.
     *
     * You might also want to force users to use a given domain.
     * See the .htaccess file for more information.
     *
     * Examples:
     *   $base_url = 'http://www.example.com';
     *   $base_url = 'http://www.example.com:8888';
     *   $base_url = 'http://www.example.com/drupal';
     *   $base_url = 'https://www.example.com:8888/drupal';
     *
     * It is not allowed to have a trailing slash; Drupal will add it
     * for you.
     */
    # $base_url = 'http://www.example.com';  // NO trailing slash!


How do I use hook_preprocess_page_title() on a Bootstrap subtheme? I've just discovered that Drupal 8 Bootstrap theme doesn't implement all existent hooks.
So, for example, hook_theme_suggestions_page_alter() works, but
hook_theme_suggestions_node_alter() doesn't work.

I'm interested on hook_preprocess_page_title(&$variables) and I wonder if it's possible to incorporate this hook into my custom Bootstrap sub-theme. I have created the page-title.html.twig template and cleared the cache.

I saw https://drupal-bootstrap.org/api/bootstrap/docs!plugins!Preprocess.md/group/plugins_preprocess/8.x-3.x but it seems this is for extending an already existent hook in Bootstrap theme, not for adding a new one.

How do I add hook_preprocess_page_title() in a Bootstrap theme?

How do I add hook_preprocess_page_title() in a Bootstrap theme?

In your sub-theme's .theme file you add:

/*
 * Implements hook_preprocess_page_title()
 */
SUB_THEME_NAME_preprocess_page_title(&$variables) {
  // your logic goes here
}


How do you programmatically include an entity type to a workflow? I have a workflow to which I want to include entity/content types programmatically since these content types will be included to the system by the installation of the module to which they reside. I'm not sure how to load the specific workflow object and attach the entity type to that via code.

You need the addEntityTypeAndBundle method from ContentModerationInterface

A static way to implement it looks like:

$workflow = \Drupal::entityManager()->getStorage('workflow')->load([workflow_id]);

$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'article');

$workflow->save();


How to create a Custom Drupal 8 Content Entitiy? - Baby steps edition There are already some resources describing how to write a custom content entity for Drupal 8. Perhaps the most useful one is the one included in the Examples module.

However I'd like a super-basic example that introduces Drupal 8 and PHP5 OOP concepts step-by-step,  without throwing me in the deep end.

Building a basic content entity type in Drupal 8.

In this case we create a Drupal 8 content entity to match a node from our Drupal 7 site, in preparation for migrating this data.

The entity does not implement the Field API so remains in code throughout. Nevertheless it can be a useful skeleton for building out Content Entities.

Background.

This stems from the need to build a basic custom drupal 8 content entity to hold data coming in from a migration.  Elsewhere we will explore writing tests to drive our field code and plugins for field constraints For the time being it is suffice to say:

Our new Drupal 8 advertiser content entity will have basetable fields:

UUID
ID
Advertiser Name

Defining a Content Entity in Drupal 8.

First all our custom entities now live at web/modules/custom.
Inside our custom entity the file structure that we will end up with looks like this:

web/modules/custom/advertiser$
├── advertiser.info.yml
└── src
    ├── Entity
    │   └── Advertiser.php

We start by defining our custom module in module_name.info.yml. This is self explanatory:

name: Advertiser
type: module
description: 'Barebones advertiser entity'
package: custom
core: 8.x

Meanwhile The basic Advertiser entity class and associated schema is defined in src/Entity/Advertiser.php.

We start with an annotation that describes the class that our file contains.

/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
 */

The next thing we do is define a namespace for our Advertiser Entity Class. This will come in handy whenever we want to use our classes.
namespace Drupal\advertiser\Entity;

Now it is time to define our entity, which we do in an annotation! - TIP: This is the  actual definition of the entity type it is read and cached so be sure to clear the cache after any changes.

/**
 * Defines the Advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("Advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

Because this is a barebones entity we only use a few properties and no handlers (like access). For a comprehensive list of available options for your entity see the docs here: https://www.drupal.org/node/2192175

At this point we have a functional module that defines our custom content entity, however if we go ahead and enable the module we will see that the 'advertiser' table has not been created in the database.

drush sqlc
SHOW TABLES;

This is because our class doesn't have any methods that explicitly interact with the database. Furthermore we need a description of the bare minimum of methods needed for an entity to interface satisfactorily with the Database.

Generally we can add classes by adding something like use Drupal\Core\Entity\ContentEntityBase; after our namespace defintiion at the top of our script. This makes these methods available to our own class, which can extend them or in the case of Interfaces, implement them.

We do two things, we extend an existing ContentEntityBase class that already has the necessary methods to interact with the DB, and implement an ContentEntityInterface to describe...

  the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works. - https://secure.php.net/manual/en/language.oop5.interfaces.php

All this means is that we end up with the following: Tip Remember to add any new classes through a use statement at the top of our script:

class Advertiser extends ContentEntityBase implements ContentEntityInterface {

But we still need use these new useful methods to put something in the database, we start with the basic fields for our entity.

The method baseFieldDefinitions comes from ContentEntityBase class that we are extending.
It takes two parameters:

  The entity type definition. Useful when a single class is used for multiple, possibly dynamic entity types.

And it returns

  An array of base field definitions for the entity type, keyed by field name.

So we implement it like this:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
  $fields['id'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('ID'))
    ->setDescription(t('The ID of the Contact entity.'))
    ->setReadOnly(TRUE);

  // Standard field, unique outside of the scope of the current project.
  $fields['uuid'] = BaseFieldDefinition::create('uuid')
    ->setLabel(t('UUID'))
    ->setDescription(t('The UUID of the Contact entity.'))
    ->setReadOnly(TRUE);

  return $fields;
}

So altogether we have this:

<?php
/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
*/

namespace Drupal\advertiser\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Defines the advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

class Advertiser extends ContentEntityBase implements ContentEntityInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Contact entity.'))
      ->setReadOnly(TRUE);
 // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Contact entity.'))
      ->setReadOnly(TRUE);
  return $fields;
  }
}

Now when we run drush en advertiser -y; drush sqlc we can see the advertiser basetable has been added to the database!


PowerPoint reader (.ppt) I searched for a PowerPoint player (ppt from Microsoft Office) but I couldn't find what i needed.
Is there a module that can display PowerPoint files on Drupal sites?

You can use the Embedded Google Docs Viewer module:

  The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.

There's a tutorial that details how to use it on the module page.


Advise a Drupal Image gallery module with an option to put text nearby the image (for medical atlas) Advise a Drupal Image gallery module with an option to put text nearby the image (for medical atlas). I could find a dozen of them, can`t choose before installing and setting them up. Thank you.

Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it.

Just to mention a few of them (mentioned on the linked page):

  Gallery formatter.
  Views Slideshow.
  Flexslider.
  Node Gallery.
  Multiupload Filefield Widget.
  Multiupload Imagefield Widget.
  Field Focus.
  pl upload.


Hide menu item in specific block/region I have two instances of main_menu on a page. One is in the header, using superfish. The other is in the sidebar, using menu_block.

I want to hide a menu item in the sidebar and show it in the header. Is this possible?

Could you use template.php to target a block/region?

For example:

function my_theme_preprocess_block(&$variables) {
  if ($variables['region'] == 'content' && $variables['block']->module == 'menu_block') {
    // What would go in here?
  }
}

Any help would be greatly appreciated.

Thanks,

Steve

If I were you, I'd rather do this in my module code to access the links data:

function mymodule_block_view_alter(&$data, $block) {
  if($block->title == 'myblocktitle') {
    $data['content']['#content'][idofthenodelink]['#access'] = false;
  }
}

And your link will no longer be accessible.

Here is the dpm($data['content']['#content']) after the operation:


Is there any way to alter the "field type" of a field? I need to change the field type "file" to "image" in drupal 7. I just hack the database and found a table named "field_config" and modified the "type" and "module" column, from "file" to "image". I found that it's works correctly.

My question is that, is this the correct way to change the "field type" of the field? Any better answer would be appreciated. Thanks in advance.

Drupal itself does not support changing the field type, only the widget. This is because different types have different database structure. On the other hand, it is possible to change some types with custom code (e.g. see http://www.up2technology.com/blog/converting-drupal-fields) but in general, you would need to write migration to do this.

So in general, it is not possible to change the field type without loosing the data stored in it, especially not things like text -> image etc.


Menu not showing on some content types I have an inherited website that uses panels, and the menu is not coming out on certain pages . how can I find out and fix it so that the menu comes out on all of the pages.

A couple places to start looking:

Block configuration

Is the menu placed as a block with specific logic that prevents it from appearing on certain pages. Go to 'Structure >> Blocks' and see if there is a block placed for your menu. Then under 'Visibility Settings'.
Context

Is the menu placed via Context? 'Structure >> Context', look for something that has to do with the menu.
Page Manager

Is the menu part of the page template or is it specifically placed in the content section of each page?  Check out a page that shows the menu and a page that doesn't in the page manager, go to 'content' of the applicable variant and see if you can spot any differences.

With out some more information it is hard to determine what method is being used to place the menu.


How to display Facebook friend count on your Drupal site I was hoping for some insight as to how I should go about getting my Fan Page friend count to display on my Drupal driven site.

Are there any good tuts out there?

Any help would do

Thanks!

Mind you I have the Drupal for Facebook module installed. So this is what I did:

function facebook_count($username) {
$url = "https://graph.facebook.com/".$username;
$fbData = json_decode( file_get_contents( $url, 0, null, null ), true );
return intval($fbData['likes']);
}

I then displayed it via:

<?php echo number_format(facebook_count('Fan_Page_ID') ); ?>

Hope this helps!


How can I add cache context to custom menu link? I have two routes that receive user as route parameter, and i need a menu link for every one in account menu. So I added in my *links.menu.yml

client_account_links:
  deriver: \Drupal\my_module\Plugin\Menu\CustomLinks\ClientMenuLinksDerivative
  class: \Drupal\my_module\Plugin\Menu\CustomMenuLink

And I created my CustomMenuLink class in my_module/src/Plugin/Menu with

<?php

namespace Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;

/**
* A menu link that cache by user context.
*/
class CustomMenuLink extends MenuLinkDefault {

    public function getCacheMaxAge() {
        return 0;
    }

    public function getCacheContexts() {
        return ['user'];
    }
}

And my ClientMenuLinksDerivative has:

<?php

namespace Drupal\my_module\Plugin\Menu\CustomLinks;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\user\Entity\User;
use Drupal\personas\PersonaUtility;

class ClientMenuLinksDerivative extends DeriverBase implements ContainerDeriverInterface {

    protected $account;

    protected $uid;

    public function __construct(AccountProxy $current_user) {
        $this->uid = $current_user->id();
        $this->account = User::load($current_user->id());
    }

    public static function create(ContainerInterface $container, $base_plugin_id) {
        return new static(
            $container->get('current_user')
        );
    }

    public function getDerivativeDefinitions($base_plugin_definition) {
        $links = array();
        if (PersonaUtility::hasPersona($this->account, 'cliente_konsey')) {
           $links['contratos_cliente'] = [
                'title' => 'Contratos',
                'description' => 'Mis Contratos',
                'menu_name' => 'account',
                'weight' => 3,
                'route_name' => 'page_manager.page_view_mis_contratos_mis_contratos-panels_variant-0',
                'route_parameters' => ['user' => $this->uid]
            ] + $base_plugin_definition;

        $links['solicitudes_cliente'] = [
                'title' => 'Solicitudes',
                'description' => 'Mis solicitudes',
                'menu_name' => 'account',
                'weight' => 4,
                'route_name' => 'page_manager.page_view_mis_solicitudes_mis_solicitudes-panels_variant-0',
                'route_parameters' => ['user' => $this->uid]
            ] + $base_plugin_definition;
    }

    return $links;
}

}

This create my menu links in the account menu but the route parameter always is the same, so if I change user, the links send me to another user page, the user that run the code before that cached.

My question is how I can create custom menu links, with route parameters (user in my case), and the links change by user? because this don't work. Also I tried with hook_menu_links_discovered_alter(), but without lucky.

As @4k4 says you don't need the derivates class in this case you need to do something like this example:

.links.menu.yml file:

client_account_links:
  class: Drupal\my_module\Plugin\Menu\UserProfile
  menu_name: account
  title: 'Edit Your Profile'
  route_name:  entity.user.edit_form

The class:

<?php

namespace Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Represents a menu link for a user profile edition.
 */
class UserProfile extends MenuLinkDefault {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, StaticMenuLinkOverridesInterface $static_override, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $static_override);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('menu_link.static.overrides'),
      $container->get('current_user'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters() {
    // If the user is not Anonymous.
    if (!$this->currentUser->isAnonymous()) {
      // Getting the uid.
      $uid = $this->currentUser->id();
      // Adding the link.
      return ['user' => $uid];
    }
    return [];
  }

}


How are SQL queries properly handled within a module? I would appreciate a little guidance on where to begin so I don't waste a ton of time looking in the wrong places.

I have a content type that has a number of associated entities appended to it; these all have date ranges on them. I need to create a module that upon hook_node_save() and hook_node_insert() checks other associated entities for various date conditions (do dates completely overlap, or partially overlap) and either adjusts the dates on those entities, or deletes the entity.

I know how I'd do this if it was purely SQL, but I want to do it the Drupal way.

How are SQL queries properly handled within a module?

Drupal essentially has three groups of functions to query the database:

Functions to make static queries
Functions to make dynamic queries
Functions to make queries about entity fields

db_query() and db_query_range() are part of the first group, while db_select() is part of the second group; finally the EntityFieldQuery class is what you use for queries involving the values of entity fields.

To make clear which functions you should use, keep in mind that dynamic queries are those queries that are dynamically built at run-time, such as in the following code.

$table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);

$query = db_select($table, 't')
  ->fields('t')
  ->condition('entity_type', $entity_type)
  ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
  ->condition('language', field_available_languages($entity_type, $field), 'IN')
  ->orderBy('delta');

Since the table name changes at runtime, using that code is preferable to concatenate strings to build the query.

Dynamic queries are also those that needs to be altered by other modules, such as the following one.

if ($nids) {
  $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
  $query->join('node', 'n', 'b.nid = n.nid');
  $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
  $query->addField('n', 'type', 'type');
  $query->addField('n', 'title', 'title');
  $query->fields('b');
  $query->fields('ml');
  $query->condition('n.nid', $nids, 'IN');
  $query->condition('n.status', 1);
  $query->orderBy('ml.weight');
  $query->orderBy('ml.link_title');
  $query->addTag('node_access');
  $result2 = $query->execute();
  foreach ($result2 as $link) {
    $link['href'] = $link['link_path'];
    $link['options'] = unserialize($link['options']);
    $all_books[$link['bid']] = $link;
  }
}

$query->addTag('node_access') allows other modules to alter the query to return only the nodes to which the currently logged-in user has access.

In the other cases, it is preferable to use a static query, which are faster. The only case you should not use static queries is when the query involves the value of entity fields; in which case, you should use the EntityFieldQuery class, which avoids you need to know any details about how entity fields are implemented (e.g. which database classes contain the field values).

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.


Is there a module that creates a jquery-like bar that displays system messages at the top of the page? Is there a module that creates a jquery-like bar that displays system messages at the top of the page. (exactly like the large, red bar on this site (stack exchange)?

You could have a look at the "Purr Messages" module - I haven't used this myself, so I don't know if it allows for the messages being displayed at the top - it says it creates a "jquery popup," which I suppose means an absolutely positioned div which either fades out or you can click away with your mouse.

I did something similar to this this on one site by simply editing page.tpl.php - but it sounds like you want a module, & not coding advice.


trigger colorbox on view page load What if I just want to trigger the first colorbox on a view page? maybe with js injector module.

  Drupal.behaviors.commerce_kickstart_theme_custom_mytest = {
    attach: function(context, settings) {
        $(document).ready(function() {
            $('.view-promoted-to-front-2 .views-row-1 > .views-field-rendered-entity .node-product-display .field-group-colorbox-trigger').trigger('click');
         });
    }
  }

You may not use the js injector module. Colorbox integrates seamlessly well with views. If you are displaying content as fields in the view (which I think you are) you can use the :

Fields -> Add

option to introduce a colorbox trigger.

For example, Lets consider the below fields :

The first item "Content : Gallery Image Upload"  has the following settings

The second item "Content : Gallery Image Upload"  has the following settings

and you set up your colorbox trigger like below :

The replacement pattern is all that matters here. If you are
confused what to put for popup, scroll all the way down
to Replacement Patterns and select appropriate field and paste
it in the popup box. Here the trigger field is the the first
"Content : Gallery Image Upload" field and when somebody clicks
it we are introducing a colorbox trigger to start the colorbox
slideshow configured for the second "Content : Gallery Image Upload"
field.

In short, we are setting up a Gallery here. :)


Adding a template to a specific page I want to have a template for a specific page, as I want to add multiple Javascript pulled games to it.

The nid is 34, so to create this page, I would have to create page--node--34.tpl.php, correct?

Yes, that's correct.

Once you've added the file, clear the caches and the new template will take effect.


How do I delete a Panopoly landing page? I was able to disable the page by going to admin/structure/pages then clicking Disable. However, I am not sure how to delete the landing page.

Note: I am running Panopoly on Pantheon.

Thank you @Patrick Kenny for the information. I prefer not to "hack" as it does cause difficulty updating.
My Solution
On admin/structure/pages/edit/mypagenameI clicked the Delete tab that appeared after disabling it.


Override user edit page title By default, the user form title is the user's username which looks a little ugly if you're using the email registration module. In Drupal 7 I used to solve this problem using the title override module which is not ported do Drupal 8.

I would like to change the user form title to "Login details". Is this possible using a hook? If so: how do I do this?

The title override module utilizes drupal_set_title() to do this in Drupal 7. This function is deprecated in Drupal 8. The D8 equivalent here is to alter the _title_callback for the entity.user.edit_form route.

This is done by using an event subscriber to alter the RoutingEvents::ALTER event. This can be done through a custom module that:

Registering a new service class in mymodule.services.yml that is tagged with event_subscriber (see d.o. documentation example).
Defining the new service class to extend RouteSubscriberBase (see d.o. documentation example).
Implementing the alterRoutes(RouteCollection $collection) method within the service class to alter the entity.user.edit_form route (see example below).
A class/method that defines the title callback (see UserController::userTitle() as an example).

Within your route subscriber class:

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Retrieve the user edit form route.
    if ($route = $collection->get('entity.user.edit_form')) {
      // Your module will need a controller class/method defined in
      // src/Controller/CustomUserController::userTitle
      // see core/modules/user/src/Controller/UserController.php to see how this
      // is implemented by default
      $route->setDefault('_title_callback','Drupal\mymodule\Controller\CustomUserController::userTitle');
    }
  }


Load all node titles with db_query() $title = db_result(db_query("SELECT title FROM {node} WHERE nid = %d", 1));

with this code i can get title from node with id == 1. But how can i load all node titles with specific content type?

$title = db_result(db_query('SELECT title FROM {node} WHERE type = %s', $content_type));

Please correct my code to get all node titles from specific content type and how to limit them by 20 items for example?

$result = db_query_range("SELECT title FROM {node} WHERE type = '%s'", $content_type, 0, 20);
$titles = array();
while ($row = db_fetch_object($result)) {
  $titles[] = $row->title;
}

http://api.drupal.org/api/drupal/includes--database.inc/group/database/6


Change / Increase the node title length I want to increase the node title length on Drupal 7, and as I guess I need to do just two things (theoretically).

Change the title column in the node table to acept more than 255 characters.
Alter the node creating/editing form to let the title field accept more than 255 characters.

I've done, #2 and trying to get #1 using this code:

/**
 * Implements hook_schema_alter().
 */
function my_module_schema_alter(&$schema){
    if(isset($schema['node'])){
        dsm($schema['node']);
        $schema['node']['fields']['title'] = array(
            'type' => 'varchar',
            'length' => 555,
            'not null' => TRUE,
            'default' => '',
        );
        dsm($schema['node']);
    }
}

If I check dsm() before and after, I can see a change, but I don't see the title column in the node table affected. Am I missing something or using the bad hook?

I also use this code to change the form on creating/editing nodes (this works well):

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id){
    if($form['#id'] == 'norma-node-form'){
        $form['title']['#type'] = 'textarea';
        $form['title']['#maxlength'] = 555;
    }
}

When you are implementing hook_schema_alter(), the table's schema is not changed.
You are informing the modules calling drupal_get_schema() (which is then called by functions such as drupal_write_record()) what the actual schema is. If you altered a database table without implementing hook_schema_alter(), the functions/modules using drupal_get_schema() would get the schema implemented by the module using that database table, which is not anymore the one describing the database table.

You need to first alter the existing database table using db_change_field(), taking in consideration the following note:

  IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.


CyberSource order gets stuck 'In Checkout', never completes I am using CyberSource, with ubercart 2.6. I am using the CS test server.
When I make a payment, everything goes through, but the order gets stuck in 'In checkout' when viewing the status at '/admin/store/orders/sort/all'.

In watchdog, I receive the following error:
Receiving invalid payment notification at URL for order ##

Does anyone know what might cause this issue?

Figured out the issue: In uc_cybersource.module there is a line in function uc_cybersource_hop_form($form_state, $order) that reads

$data['orderPage_version'] = '4';

It needs to be changed to the current orderPage version (as of this writing it is 7).

$data['orderPage_version'] = '7';

This should definitely be documented somewhere!


Master Detail page for taxonomy terms I'm essentially trying to recreate the results of this question, but using taxonomy terms instead of nodes.

I have my master view (a list of taxonomy terms from a vocab') item-view, which has the term ID (TID) and I've re-written it to link to the other view item-details/[tid].

On the detail view I have a contextual filter of Taxonomy term: Term ID (to match the field in the other view) and my Argument Input settings match those in the previous answer (namely: 'From Panel Argument' for the list box 'Taxonomy term: Term ID source', then 'First' from Panel argument.)

But on the page (item-page) that holds both views in separate columns, it just links through to the detail view, at item-details/[tid], opening the url in the browser rather than enacting that special drupal magic that makes it appear in the right hand column.

Does this not work with Terms and TIDs? Or have I missed something?

The Master page is at item-view and the links of there point to
  item-details/[tid], the detail view is at item-details/[tid] for each
  item.

In reality the links on the master page shouldn't link to the details view, but just to the current page with /[tid] appended.


Using ENTER key to submit default Drupal 7 Search doesn't not return results: Why? I have a design provided by the customer, where the search block form has no SUBMIT button. It is expected the user just hits the "enter" key.

Users can type keywords into the search box, and when they press "enter," the form is submitted. The problem is that the form is submitted always with "#default_value" and never with the keywords typed into the input box.

On the advanced search page/results the search does work.

Does anyone know why this might be?

We have hidden the submit button via a CSS call of display: none.

Are you using the <form>'s submit event rather than the <input>'s click event to respond to the form submission? Check out this working example on jsFiddle.

$("#form").bind('submit', function(e) {
    var $div = $("
Transmitting
").appendTo('body');
    $.ajax({
        url: '/ajax_html_echo/',
        data: {html: $("#html").val() },
        type: 'POST',
        success: function(data) {
            $div.html("Received: "+data);
        }
    });
    return false;
});


Entity "changed" timestamp is not incremented on $entity->save() only on a form submit; feature or bug? Anyone know why the changed timestamp is not updated when you save an entity programmatically (e.g. $entity->save()) but it is updated when you (for example) use the node form to edit the entity.

Is this intentional? If so, why?

If not, I'll open an issue on D.O.

Thoughts?

Pretty sure it is being updated, but it is updated to the REQUEST_TIME timestamp. If you have a long-running process or so, that will not work as expected.


Adding a taxonomy specific css file to certain pages Im building a web page with multiple sub-portals, which should all have slightly different css styles.
Is it possible to add a certain css file depending on the taxonomy of a node? With drupal_add_css maybe?
Im using Drupal 6.

Thanks,
Max

If you want to load certain CSS files based on taxonomy, maybe you could name your files according to taxonomy vocabularies. Just build the file name based on the vocabulary of a term.

$file = 'mymodule_taxonomy_' . $vocabulary . '.css';
drupal_add_css(drupal_get_path('module', 'mymodule') . '/' . $file);

If you have a node object you can use taxonomy_node_get_terms() to get the terms for a node and use this code to load a proper CSS file.
Then, with a vocabulary named cars you can name a CSS file mymodule_taxonomy_cars.css. That file can be loaded according to a vocabulary.


How to prevent a field with thousands of files from loading on Edit operation? I have a process running that renders a PDF to PNGs and attaches those PNGs to a file field.  There is one PDF's results per node, but  there we have a bunch of PDFs with 10,000+ pages.  We've found that this results in the operation of loading an edit form to eat quite a lot of memory (a node with 12,000 attached files ate up all 4GB of RAM on our server before Apache killed the process for taking up too much memory).

Does anyone have any ideas how we might prevent the field from loading?  It looks like I could hack file_field_load() to not perform its task given the user is on an edit page and the troubled field is expected but it would be cool if there was a solution that wasn't a hack.

The stack trace when the troubled field is set to not display is:

 1. {main}()  /index.php:0
 2. menu_execute_active_handler()  /index.php:18
 3. call_user_func_array()  /includes/menu.inc:348
 4. node_page_edit()  /includes/menu.inc:0
 5. drupal_get_form()  /modules/node/node.pages.inc:15
 6. drupal_process_form()  /includes/form.inc:121
 7. form_builder()  /includes/form.inc:406
 8. form_builder()  /includes/form.inc:930
 9. form_builder()  /includes/form.inc:930
10. _form_builder_handle_input_element()  /includes/form.inc:889
11. imagefield_widget_value()  /includes/form.inc:1020
12. filefield_widget_value()  /sites/all/modules/contrib/imagefield/imagefield_widget.inc:207
13. field_file_load()  /sites/all/modules/contrib/filefield/filefield_widget.inc:215
14. _field_file_cache()  /sites/all/modules/contrib/filefield/field_file.inc:51

And when the field is set to display:

1. {main}()    /index.php:0
2. menu_execute_active_handler()    /index.php:18
3. call_user_func_array()    /includes/menu.inc:348
4. node_page_edit()    /includes/menu.inc:0
5. drupal_get_form()    /modules/node/node.pages.inc:15
6. drupal_process_form()    /includes/form.inc:121
7. form_builder()    /includes/form.inc:406
8. form_builder()    /includes/form.inc:930
9. form_builder()    /includes/form.inc:930
10. form_builder()    /includes/form.inc:930
11. _form_builder_handle_input_element()    /includes/form.inc:889
12. process_weight()    /includes/form.inc:1063

Would it be enough to deny editing rights to that field using Content Permissions?


Views exposed Filter by date: month OR year If i make an exposed filter with a date-field, i can only select date and month together. Not on year or month. How can i make it by year OR month?

You should be able to add the same filter twice and set one to a Month granularity and the other to a Year granularity. Then you can rearrange the filters and setup an OR grouping and place the year in that one


Module and theme in one directory? For my project, I have a custom module, a features module and a custom theme. I want to keep all in a single Git-Repository.

The problem is: modules need to be in sites/all/modules, themes in sites/all/themes.

I know, I could bundle both in a profile. But I am already using a special profile. And as far as I know, there is no way to inherit a profile.

And yes, I know I could use symlinks. But they tend to create issues with path structures.

So is there another, maybe a "Drupal" way to bundle modules and themes in one directory?

Thanks to the suggestion of @kenorb, I have found a good way to solve this:

I init the git repository in drupal/, and I put  only the following line into .gitignore:

*

Then, I add (by force) my custom module and theme folders:

$ git add -f sites/all/modules/custom
$ git add -f sites/all/themes/custom

With this, my repo still contains only my code and no Drupal modules. And this allows me even to track also my .htaccess, with:

$ git add -f .htaccess


Can authenticaded users publish own content and see only own content? Besides the  module which has many interesting features, what's the best way to allow authenticated users publish content (based on a custom node type), but only allow such content to be seen only by an administrator (an specific role), or that same user only? Such content when published, will only be visible to a role type (administrator) and the user who published it.

For node access, you should set permissions based on role.

It is /admin/people/permissions on Drupal 7.

Yo can set who can view, edit , create any of your content type based on role.

For more grained field permission based on role, use Field Permission module


Content type with taxonomy in single exposed filter i want to a single exposed filter with content types and taxonomy for a single content type,
like i have 3 content types Parts,Tools,Equipments and have a taxonomy for parts with terms Hardware,Instruments and components, now i want a views exposed filter containing both of the them to filter.
Is there any method to do that ?

Finder module will filter both of the fields, You can select taxonomy term, node title, body, fields, ..etc to perform the search.

  There are many ways to put together finder's functionality to get the
  sort of search form you need. There are also many hooks and theme
  functions allowing full customization of finder's output.

It 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.


How do I know if a user has access to a private file in the node template I have a a content type with Title, Body, File (private), and Taxonomy. I want all users to be able to see the Title, Body and Taxonomy for marketing purposes, but they should only be able to download the file if they are an authenticated and their account is related to the same taxonomy term(s) the node is related to.

I have private files set up properly and have written a custom module implementing hook_file_download_access to check if the user should have access. If I go directly to the file URL, access is working as I think it should.

My problem is I'd like node page to say:

"Register Now" if the user is not logged in
"Contact Customer Support" if they are logged in but don't share the proper taxonomies
or "Download Now" if all checks out.

Just not sure how to get it done?

If your using the Pages Module then you can make different page 'variants' for different roles.


deleting nodes from a view I have created view which displays a list of nodes. I made a custom module with a function which calls db_query() to delete the specified node in the list. I made a Global:Custom Text  field in the view which I made into a link to point to that function. The link works perfectly, the node is deleted from the database table, but now the view still lists a blank line (where that node used to be) which still has the Global:Custom Text field there. How can I get rid of this line completely?

Why not use the Views Bulk Operations module? This is a great module for updating and deleting nodes from Views.


Broken image using custom View template I am trying to print each row with custom HTML. I need to display the image field wrapped inside the image link. I have this in the tow style output template:

        <a href="<?php print $fields['field_news_link']->content; ?>" target="_blank"><img src="<?php print $fields['field_news_image']->content; ?>" />

    <a href="<?php print $fields['field_news_link']->content; ?>"><?php print $fields['field_news_source']->content; ?> />

The link part is working, but the image does not display. In the HTML I get:

<img src="

On the front end, I see the broken image square and '/> directly after. What am I doing wrong?

You need to print image src like this:

<?php print file_create_url($uri); ?>

Just change $uri with uri of your image ($fields['field_news_image']...)

Take a look on function file_create_url as well.


How to share Drush code with the community? I created a simple Drush command. How can I share it with the community?
Do I need to create a module and add it to drupal.org ?

If it's a useful Drush command, and one that you could see being used on a daily basis, the I'd suggest heading to the Drush issue queue and posting a feature request.  Then answer the feature request with a patch that adds the command.  Whether to not it's suitable for Drush core will most likely then be discussed and further action will be taken by the maintainers.

Another option as you mentioned, is to create a module form your command and submit it via the standard module submission process.

The last thing I would suggest it hassling the module maintainers on social media channels or e-mail.

Greg Anderson does sometimes frequent this site though, so he might be able to provide a preferred approach :-)