Export content view to HTML As I'm not quite happy with the Simplenews module I want to use phplist instead. The newsletter should contain the teasers of the articles I want to send. Is there a way to export specific articles teasers to HTML (using a custom template), so that I don't have to copy and paste every single teaser to my newsletter?

If you want to make a View of node teasers, all you have to do is set the view format to Rendered Content, and select the teaser display mode.

From here, you can customize node--node-type--teaser.html.twig template to your exact specifications to satisfy phplist.

After this change, all the nodes that the View returns will be rendered in the teaser display mode using that template.

You can also create new modes under Admin > Structure > Display Modes if you want to create new ones for this purpose, especially if you are already using teaser display mode elsewhere on the site. You can still provide the markup and theme it with the pattern node--node-type--display-mode.html.twig.

If for some reason this is not enough, you may have to resort to creating a custom Views plugin to render your result rows. I think this should suffice based on what you asked, though.


Certain views for specific user I have a page that shows content to all the users in my database but I have an specific username (exchangeStudents) and I want to show in the same page another view that filters the information for that account.

For example... my main page is:
www.housing.com an when you login you can see www.housing.com/houses but I if you login as exchangeStudent you should be able to only see www.housing.com/exchange-houses

www.housing.com --> all users except exchangeStudent

www.housing.com/exchange-houses --> only for username: exchangeStudent

You can use login destination module, it is easy to use, you just need to create a rule where you can define after login specific role user can redirect to a specific page or you can use write php code too.

  The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.


Do I need to use a block or form to implement login box, or can I just post to a 'login' url the user details? I have static HTML for a login box which contains a form with username and password inputs and is part of the site header, which will be on every page ie. this is not a login 'page'.

To integrate this with the Drupal login system, can I point the form action at a certain url to post the login details and perform the login? Thereby, not requiring any Drupal backend form/block/theme coding?

Or do I need to implement my own form, or customise an existing form to achieve this? If so, why is that? What do I need from the Drupal back end to successfully login ie. hidden form fields that need to be passed with the login details etc?

I am trying to implement the site in the cleanest way possible, using my own HTML 5/ CSS 3 markup, so overriding most html so that the tonne of classes Drupal adds, and the extra unnecessary markup are scraped. So, ideally I would like to avoid having to make a login form/block as part of the back end.

You can print login block in the tpl file. No need to use username/password fields of HTML/CSS.

<?php print drupal_get_form('user_login_block'); ?>

For Registration :

<?php print drupal_get_form('user_register_form'); ?>


Searching a range by another range We are developing a Drupal website for displaying properties. Each property has a minimum and maximum size that is available.  The user can search with a minimum and maximum size also.

We need help trying to work out how to setup the View in Drupal 7. For example, a user might search for properties with min size 10,000 sq ft and max size 50,000 sq ft. The following properties would match:

Property 1 - min size 13,000 sq ft, max size 48,000 sq ft
Property 2 - min size 10,000 sq ft, max size 50,000 sq ft
Property 3 - min size 20,000 sq ft, max size 20,000 sq ft
Property 4 - min size 9,000 sq ft, max size 51,000 sq ft

How should we set this up in the Drupal View? The content type has a min_size and max_size already.

Set up two exposed filters (exposed filters show on the view itself, with the user able to set their own value) one for the min_size field and another for the max_size field.

When setting up the exposed filters you'll have a choice "expose operator." With that choice you can allow the user to choose the operator (e.g. less than, greater than, greater than or equal to, etc.). The end user can use either of the exposed filters or both.

You'll need to be pay attention to your label choices and the help text you create to make sure what you come up with is easy to use and returns the expected results.


How to show a image preview of the files in IMCE file browser? I'm using the the imce module with the ckeditor module.

When you open the imce file browser to select/upload a image you can see a list of the images you have in your server.

This list shows the name for every image.

Is there a way to make this list to show a image preview of the image (a thumbnail)?

Look my capture:

I have seen it work sometimes, but I can not tell does not always work. I will recommend you opening an issue on the IMCE module page in Drupal.org. See it working on the image below:


Is "system_settings_form" voodoo? A friend just showed me system_settings_form in action in a configuration file for a form.

The code in question looks like this (simplified).

function my_module_generateAdminForm($form){
  $form = array();
  $form['super_secret_password'] = array(
    '#type' => 'textfield',
    '#title' => t('Headline'),
    '#default_value' => variable_get('super_secret_password','password'),
  );
  system_settings_form($form);
}

system_settings_form adds in submit buttons and handles the form submission, saving the variables. It also adds a "Reset to default" button - that resets all the variable to the default.

I basically guessed what it does because there's not a whole lot of documentation out there and my friend doesn't know exactly what it does either. My question is how does it know the variables to save/reset? Aren't I just passing an array?

Also is there any other magic in system_settings_form that I should know about?

See system_settings_form and system_settings_form_submit for implementation details. In Drupal 7 Reset to Default button is removed from System Settings form .

function system_settings_form($form) {
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  if (!empty($_POST) && form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }
  $form['#submit'][] = 'system_settings_form_submit';
  // By default, render the form using theme_system_settings_form().
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}

System_settings_form :

Add's save configuration Submit button and submit callback to system_settings_form_submit function.

system_settings_form_submit:

function system_settings_form_submit($form, &$form_state) {
  // Exclude unnecessary elements.
  form_state_values_clean($form_state);

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

  drupal_set_message(t('The configuration options have been saved.'));
}

Iterates through all form elements and sets variables for each form element with key as form element key and value as user submitted form  element value read using $form_state['values']

So, it's just a form with submit handler that sets variables for all form values using variable_set function.


Feeds import by http always imports even after deleting the source I'm using Feeds to import an xml file. I'm using cron to do this every minute. I noticed that if I delete the source file, the import still succeds! It seems Feeds caches the data somewhere and there is no setting to disable this as far as I know.

This would not be a problem because I don't allow to have duplicate content but I need to have a different file with the same name to get different data but Feeds, recognizing a file with the same name, ignores it and imports the cached data.

Does anyone knows a good solution to prevent this from happening?

Thanks.

EDIT: I can't find any temp file in the system but in the db there is a 'cache_feeds_http' table that has in fact the data from the file. I tried truncate the table and delete the source file but the behaviour is still the same. What's going on here?!?! Where is the data being pulled?

I solved my problem changing FeedsHTTPFetcher to FeedsFileFetcher in my module and changing the importers to file also. In this case, each import gets the file even if there's already one with the same name.


Prevent caching of a node I'm working on facebook like button for drupal 8. It's about to be done, but I've faced a trouble. Whenever I change the configuration of my module, I still need to clear all caches manually for the changes to take effect.

I'm adding the like button like this:

function fblikebutton_node_view(&$build, $node, $display, $type, $lang) {
  $build['fblikebutton'] = [
    '#theme' => 'fblikebutton',
    '#weight' => 100,
  ];
}

Are there any ways to prevent all nodes from caching or to clear cache programmatically after configuration is updated? Or I should just change the way I add the button to the page?

It is not clear what exactly you are asking.

@Cottser's answer is correct for disabling the render cache during development but that is not something you want to do on a production site as the render caching critical for performance. Also, when disabling the render cache locally, make sure to always test changes on the same configuration as production to catch problems with it.

If the markup you are outputting is dynamic on something, then you can add that context to the cache key, see my answer in https://drupal.stackexchange.com/a/140777/31.

If it is about clearing the cache after the user changes settings, you can clear the node_view cache tag with Drupal::entityManager()->getViewBuilder('node')->resetCache(). If you want to clear the cache of a specific tag, you can pass the node ID to that method or you can use \Drupal\Core\Cache\Cache::invalidateTags($node->getCacheTags()).

Each thing that is rendered has one or multiple cache tags (inspect the X-Drupal-Cache-Tags header of a page response, I'm sure there will be development tools to better understand them in the future), by invalidating them, you can automatically clear all caches that contain them.


How to access parent site products in child site using drupal services ? I want to create shopping cart in child sites but using PARENT site database.
I don't want to install UberCart for each child site as i have several child sites.

For example : when i add a product (LAPTOP) it must be available on all child sites with complete detail (Title,Model,Price,sku,etc.....)

Can someone guide me to right path.
Using drupal 6.

What you can do is set up different codes connecting to same database.

So all sites might have different CSS but same database so same products and other Drupal configuration.

Essentially it is one Drupal site. Does this solve your problem?


How to pass Get parameter to url when url has "?" mark In my site clean urls is not working. As a result ?q is getting appended to the url.

My site url is http://abc.com/?q=user

I wrote a form in a page, and redirect to another view which is http://abc.com/?q=listings.

When I click on submit button in form page GET parameter are not getting appended correctly:
They are getting appended as http://abc.com/?field_list=3 which has to be like this http://abc.com/?q=listings&field_list=3.
I must use GET method in the form.

How should I redirect to URLs that contains "?q="?

How to do this.

If you are redirecting from the form submission handler, you need to use code similar to the following one.

$form_state['redirect'] = array(
  'listings',
   array(
     'query' => array(
     'field_list' => '3',
   ),
);

That code is equivalent to calling drupal_goto('listings, array('query' => array('field_list' => '3')) which should never be used inside a form submission handler. In both the cases, the function that is called to build the URL is url(), which works when clean URLs are enabled, or not.

  // With Clean URLs.
  if (!empty($GLOBALS['conf']['clean_url'])) {
    $path = drupal_encode_path($prefix . $path);
    if ($options['query']) {
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
    }
    else {
      return $base . $path . $options['fragment'];
    }
  }
  // Without Clean URLs.
  else {
    $path = $prefix . $path;
    $query = array();
    if (!empty($path)) {
      $query['q'] = $path;
    }
    if ($options['query']) {
      // We do not use array_merge() here to prevent overriding $path via query
      // parameters.
      $query += $options['query'];
    }
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
    $script = isset($options['script']) ? $options['script'] : '';
    return $base . $script . $query . $options['fragment'];
  }


Create a custom date format Our organization's style guide expects dates in this format:

  Oct. 31 2018 01:30 p.m.

I looked the date format drop-down in our views, and there were several options, including a custom one. However, I noticed that none of these are able render the post meridien with abbreviating periods.

There is option for a custom date format, but it seems to use the encoding for PHP date() function. Looking at the manual, there is a, which gives me pm, and A, which gives me PM, but I don't see anything specifying one with periods.

I looked in the code base for where date formatters are stored, and they all seem to be yaml files specifying date() formats:

$ cat core/modules/system/config/install/core.date_format.html_yearless_date.yml
...
pattern: m-d
...

So it seems that the built-in custom date formats are limited to what can be specified with PHP's date() function.

I googled for ways to create a custom date format, but only found explanations of where to specify a custom date format: https://www.ostraining.com/blog/drupal/d8-dates/

How can I create a date formatter where I can use PHP code to give myself a date format with properly abbreviated meridiens?

You are correct, the core date.formatter service uses the native PHP date formatting strings, none of which have 'a.m.' or 'p.m.' in them.

If you really need this, I suspect this would work.

Create a new module, with a class that extends DateFormatter.
In the format method, call the parent method, and then do string replacment to convert 'am' to 'a.m.' and 'pm' to 'p.m.'
Replace the date.formatter service with the one you created.

This may have side effects that I'm not thinking of right now.


how do i create a new link in node.tpl.php by preprocess function in drupal? I have content type in which I have two or three links .In node.tpl.php, all links are displaying from a single variable "$links" in node.tpl.php. i want to remove one particular link from the "$links" variable by preprocess function and assign that link to a new variables , so i can display it where ever I want.

I created a preprocess function  to implement it

function sample_preprocess_node(&$variables){
  if($variables['type']="product"){
    $node=$variables['node'];
    $create_review=array();
    $create_review=$node->links['review_field_product_review'];
    $variables['create_review']=$create_review;
    unset($node->links['shopping_review_field_shopping_product_review']);
  }
}

and I pasted the following code in node.tpl.php

print $create_review;

It displays "array" in product page and that particular link is not removed from the variable ($links) in node.tpl.php

Can you tell me how to remove the particular link from the "$link " variable in node.tpl.php and display it by another variable in node.tpl.php?

This line will always return true, since you are assigning a value with the '=' operator:

if($variables['type']="product"){

This should be a comparison, so use '==':

if($variables['type']=="product"){


Does Drupal modify folder permissions during runtime? Does Drupal modify the permissions on folder within the sites folder? Is there an edge case where this is possible outside of install?

I've been seeing an issue where a sites folder whether it be default or blah.com is getting it's write permissions removed after loading the site.

It's not specific to one codebase, it occurs across multiple codebases (no modifications to core) and across multiple versions 6/7.

This is problematic when using git with a specific site folder as git can no longer perform checkouts and merges without the write permissions.

Yes drupal modify default folder permission during runtime, and this folder is what exactly you should add it to your .gitignore because it contains user uploaded files which have not value to keeping in repository.


How to post to remote url on form submit We want to silently submit a Drupal6 form to a marketing partner, and redirect the user to page on our site.  Is this the correct syntax?

function my_form_submit($form, &$form_state) {
  $form_state['action'] = url('http://example.com/?method=cSurveyWebservice.submit&mode=test');
  $form_state['redirect'] = array('campaign/thank-you');
}

Certainly it processes and redirects, although I'm not sure how to independently validate if the form is actually posted to the specified URL.

You can try something like this

$request_url = 'http://your-url.com';
$request_headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$request_method = 'POST';
$request_retry = 2;
// form values you want to post
$form_values= array('apple' => 'red', 'banana' => 'yellow', 'pear' => 'green');
$data = http_build_query($fruits, '', '&');

// Send the request.
$response = drupal_http_request($request_url, $request_headers, $request_method, $data, $request_retry);

if ($response->code == 200) {
  $form_state['redirect'] = array('campaign/thank-you');
}
else {
drupal_set_message(t('There was a problem with your submission. Please try again later.'), 'error');
}

I haven't tried it but let me know if it works.


Is it always bad to pass a variable through t()? I have a little helper function for my hook_schema:

function _bbcmap_schema_asr_field($description) {
  return array(
    'type' => 'int',
    'unsigned' => TRUE,
    'size' => 'small', // Up to ~66k with MySQL (equivalent up to ~660.00 adjusted)
    'not null' => FALSE,
    'description' => t($description),
  );
}

And then I can use it something like:

/**
 * Implements hook_schema().
 */
function bbcmap_schema() {
  $schema['la_data'] = array(
    'fields' => array(
      ...
      'mort_asr_male' =>    _bbcmap_schema_asr_field('The age standardised mortality amongst men (fixed point with scale factor 1/100)'),
      'mort_asr_female' =>  _bbcmap_schema_asr_field('The age standardised mortality amongst women (fixed point with scale factor 1/100)'),
      'incid_asr_male' =>   _bbcmap_schema_asr_field('The age standardised incidence amongst men (fixed point with scale factor 1/100)'),
      'incid_asr_female' => _bbcmap_schema_asr_field('The age standardised incidence amongst women (fixed point with scale factor 1/100)'),
      ...
    ),
  );
}

I know that the guideline is not to pass variables through t() but this seems very similar to how the menu system passes the callback's title through t() (by default). Any comments on this being good or bad style?

The first argument of t() needs to be a literal string, which excludes:

variables, even the parameters of a function: t($description)
a concatenation of strings: t('If you want to add a link, click on' . 'this link.')
the value returned from a function:t(get_menu_description())
a constant: t(MYMODULE_MY_WIDGET_TITLE), t(MyClass::WIDGET_TITLE)

The reason is that, apart few specific hooks (e.g. hook_menu(), hook_perm(), hook_permission()), the string to translate are found from a script that scan the code of a module, looking for code such as t('This is an example.'); when it finds a value that depends from runtime, such as the value of a variable, the script is not able to understand which is the string that needs to be translated, as a variable could contain a different value each times the code gets executed.
In fact, http://localize.drupal.org reports a warning similar to the following one, in the case the argument for t() is not a literal string:

  The first parameter to t() should be a literal string. There should be no variables, concatenation, constants or other non-literal strings there. At t($filter['name']) in customfilter/customfilter.module on line 30.

If you are passing a dynamic value to t(), the script that extracts the strings to translate will not extract any value, in that case; the effect is the argument passed to t() will not be translated, which has the same effect of not using t() and using the dynamic output directly in the user interface. The only case for which the string will be translated is when the dynamic string is equal to the literal string a function passes to t(). Suppose, for example, that you have a library not thought for Drupal, which contains a function returning the name of the current month. With the following code, the value returned from that function would be translated.

function mymodule_calendar_page_title() {
  return t(Calendar::getCurrentMonth());
}

function mymodule_calendar_translations() {
  $translations = array(
    t('January'),
    t('February'),
    t('March'),
    t('April'),
    t('May'),
    t('June'),
    t('July'),
    t('August'),
    t('September'),
    t('October'),
    t('November'),
    t('December'),
  );
}

mymodule_calendar_translations() doesn't need to be called, nor to return any value. When the code of the module will be parsed, the call to t() will be found from the code that looks for literal strings passed to t().

Translating the description given for a database table and its fields is then not something that you should do, as none of the Drupal core modules do that; for example, node_schema() contains the following code:

function node_schema() {
  $schema['node'] = array(
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      // …
    );
    // …
  );

  // …

  return $schema;
}

The report that caused the removal of the calls to t() from any Drupal core implementations of hook_schema() is Remove t() from all schema descriptions, which has been open by webchick (Drupal 7 co-maintainer).

  In Szeged, we had a big long discussion about t() around the schema descriptions and it was the consensus of everyone at the table (who included Dries) that t()s should be removed from these descriptions. They mess up things because t() isn't available that early, and people discussed that no one is going to take the time to translate technical descriptions of stuff, and it doesn't really make sense since we also don't translate code comments, for example.

The article about converting a Drupal 6 module to Drupal 7, has a dedicated paragraph: Schema descriptions are no longer translated.


The development snapshot of Drupal causes error on my server After having terrible errors with Drupal commons, I decided to install the standard version Drupal developing snapshot (from January 12th).

The original .htaccess was not acceptable; in other words, with the original .htaccess file, it does not show a site at all. I could not see the installation-site at all.

I replaced the .htaccess file with a hacked one.

After the installation I got the following results:

the final site was blank (http://www.linux-board.com/install.php?profile=minimal&locale=en&op=start&id=1)
after accessing to basic-site - linux-board.com i see the following error messages:

  Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/simpletest/tests/themes/test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/field/modules/list/tests) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/update/tests/themes/update_test_subtheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/update/tests/themes/update_test_basetheme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).
  Warning: opendir(modules/block/tests/themes/block_test_theme) [function.opendir]: failed to open dir: Too many open files in file_scan_directory() (line 2034 of /home/vhost/WWW/linux-board.com/includes/file.inc).

Can I patch Drupal to go round the too many files open issue,  or do I have to upgrade the server, which is six years old?

PS: The information about the server are the following one:

Web server: Apache/1.3.41 (Unix) mod_gzip/1.3.26.1a mod_throttle/3.1.2 mod_ssl/2.8.31 OpenSSL/0.9.8a

PHP 5.3.8
PHP register global: disabled
PHP extensions: enabled
Database support: enabled
PHP memory limit: 64M

I guess that the file handlers of Apache could be set up to a higher limit.

Apache 1.3, is considered deprecated. The very first thing I would try, is upgrading to a 2.* version, preferably 2.2, and try installing again with the standard .htaccess file. Given the enormous amount of apache servers running Drupal, the standard file should work.
What is the output of "cat /proc/sys/fs/file-nr"? That's useful for tracking down the to many open files issue, which likely is a server wide issue, and not really Drupal related.
While all patches to the 7 branch of core should pass all tests, it could be that you have stumbled on a broken commit. Why do you install -dev? Install 7.10 instead.


node preview button not working The issue I am having is that when I try to preview the content of a node I have created by clicking the 'Preview' button the page just refreshes and the preview.

What I have tried

Looking into permissions to do with viewing unpublished content.

Your site local or not? Can you give a link?

You use standart theme or custom?

Try to edit node type configuration → http://somesite.ltd/admin/structure/types/manage/content_type_machine_name. Before open link you must change somesite.ltd & content_type_machine_neme


VBO Pass Argument to Custom Action Function I have a view that list entities. It has a VBO field on it for executing a few custom actions.

I can get the actions working, but I need to add a field to the operations form on the view which lets the user select a date field. I then need to pass that date value on the VBO form submit, to the custom action, so that I can use it to manipulate some entity data.

I am able to add the date field via this method:

function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo){
    $form['vbo_set_close_date'] = array (
        '#type' => 'date_popup',
        '#title' => t ('Set Close Date'),
        '#date_format' => 'm/d/Y',
        '#date_label_position' => 'within',
        '#weight' => 1000,
    );
}

Now I am stuck because that data doesn't get passed to my custom action, and I'm not sure what the correct method would be to accomplish that. I've though of adding a custom form submit handler, but still not sure if that's working because I can't seem to get it to trigger.

Awhile back I did come up with a work around for this. Basically you can create a custom submission handler for the VBO form, then have that custom handler perform the code you need.

/**
* Implements hook_views_bulk_operations_form_alter().
*
* This is the function that alters our VBO form
*
* @param $form
* @param $form_state
* @param $vbo
*/
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo){

  // Here I added a date popup to the form
  $form['vbo_set_close_date'] = array (
        '#type' => 'date_popup',
        '#title' => t ('Set Close Date'),
        '#date_format' => 'm/d/Y',
        '#date_label_position' => 'within',
        '#weight' => -10000,
  );

  // Here is where I added the custom submission handler. This calls the "mymodule_set_close_dates" method
  $form['select']['submit']['#submit'][] = "mymodule_set_close_dates";

}

/**
 * Callback function for VBO form
 *
 * @param $form
 * @param $form_state
 */
function mymodule_set_close_dates($form, &$form_state){

  $date = $form_state['values']['vbo_set_close_date'];
  $action = $form_state['operation']->operationId;
  if(!is_null($date) && $action == 'action::mymodule_close_job'){ // <------- custom action
      $value = strtotime($date);
      $relations = $form_state['build_info']['args'][0]->result;
      foreach ($relations as $relation){
        $rid = $relation->rid;
        $wrapper = entity_metadata_wrapper('relation', $rid);
        $wrapper->field_ended->set($value);
        $wrapper->save();
    }
}


How to log in users without credentials? We need to integrate a CRM into our Drupal site. Storing users in native database is forbidden, so we won't store users in our Drupal database, we will use CRM for that.

But we still need to be able to login/register users from drupal standard login/register forms. On a backend we need to login/register user programmatically so user would think he's logging in/registering on a site, instead he logs in/registers in CRM (which is a third party application).

You can do it like this:

global $user;
$user = user_load($uid);

Where the $uid is the User ID of the user you want to log in.

Note that this potentially opens you up to major security issues.


Conditionally override link path Have the following code

    $links = array_merge($links, array(
      l(t('Administration pages'), 'admin'),
      l(t('Front page'), '<front>'),
     ));
    }

    $output = theme('item_list', array('items' => $links, 'title' => t('Next steps')));

It does <ul> html list. My goal is to override, for example, "admin" path on given page from my custom module. Since it's themed output, I can use hook_theme_registry_alter() to override the theme function. But seems I can't do that dynamically (because of cache).

Is it wise solution to copy whole theme_item_list function, rename it to my_theme_item_list and write there my own path logic?

Another solution?

I think you can do anything you could do in my_theme_item_list in a preprocess function. You can do this in your template.php file with a function like:

function mythemename_preprocess_item_list(&$vars) {
  // Change things here
}


How can I conditionally alter search API relevance score? I must be missing some core concept of search API somehow, but I am stuck. The goal is to alter search API results depending on a flag, like Give flagged products in search API a higher search score? however this time without SOLR, but with database backend instead.

I can see all flagged fields properly indexed, so there is a line that associates the content entity id with the user who flagged, and now I want to increase the relevance score of the results, so that items flagged by the current user are always shown first.

I have hijacked the SearchApiDbService class and I did add the following line in postQuery (I also wonder why this hook does not exist, but that is not relevant for now):

drupal_alter('search_api_db_query_results', $results, $query);

This should allow me to alter the search results right before search_api_db hands them over to the search API right?

So now I use the alter hook as follows:

function mymodule_search_api_db_query_results_alter(&$results, SearchApiQueryInterface $query) {
  global $user;
  $uid = $user->uid;

  // Fetch a list of content entities that the user has flagged.
  $drupal_db_q = db_select('search_api_db_MY_FLAG_FIELD_TABLE', 'f')
    ->fields('f')
    ->condition('value', $uid);
  $items = $drupal_db_q->execute()->fetchCol();

  // Iterate over results and multiply score of flagged items.
  foreach ($results['results'] as $key => &$result) {
    if (in_array($key, $items)) {
      $result['score'] *= 10;
    }
  }

dpm($results);

}

In $results I can see that the scores have changed, but the order of the items on my views results page has not, even though I am sorting by relevance.

It has to be something simple, or I am completely misunderstanding how the score value works somehow?

p.s. Since this is conditionally I don't think altering the search api query directly makes sense because I found no way to boost any field scores there. Directions on how to achieve that are welcome too.

Since everyone was telling me to solve this during the query, I decided to have another look at this approach. My main issue was not being able to order by the flagged status, which was eventually solved with an expression.

In the end I managed to get what I wanted with an implementation of hook_search_api_db_query_alter.

function mymodule_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  global $user;
  $uid = $user->uid;

  // Left join indexed flag table into search index.
  $db_query->leftJoin('search_api_db_product_index_field_my_flag_field', 'flag', 'flag.item_id = t.item_id');
  // Set a value of 1 for entities flagged by the given uid, 0 otherwise.
  $alias = $db_query->addExpression('CASE WHEN flag.value = :uid THEN 1 ELSE 0 END', 'flagged', array(':uid' => $uid));
  // Order by the flagged value (1 or 0), highest first.
  $db_query->orderBy($alias, 'DESC');
}


Filter taxonomy term view by referenced taxonomy term Using two taxonomies.

Fruit:

Banana
Orange
Blueberry
Strawberry
Lemon

Fruit taxonomy has a term reference to the color taxonomy

Color:

Red
Orange
Yellow
Blue
Purple
Green

Created a view using the built in taxonomy term view in a content pane::

Fields
Taxonomy term: Fruit Color [this is excluded from display]

Taxonomy term: Name

Filter criteria
Taxonomy vocabulary: Machine name (= Fruit)

Relationships
Taxonomy term: Content using Fruit

[Configure Relationship: Taxonomy term: Content using Fruit
Relate each Content with a Fruit set to the term.
Require this relationship]

View Output::

Red
 Strawberry

Orange
 Orange

Yellow
 Banana
 Lemon

Blue
 Blueberry

I would like to add a contextual filter to this view that takes the Color taxonomy name from the url and only shows the fruit for that color.

color/red would only show:

Red
 Strawberry

color/yellow would only show:

Yellow
 Banana
 Lemon

I'm stuck on how to add the contextual filter. I've tried taxonomy term name with validation set to change the term name to id. I also tried the fruit_color field with validation set to change the term name to id.

Should the term name/fruit_color field be configured differently? Do I need to add another relationship?

  Additional info:
  The view displays taxonomy terms.
  The result set is empty when I try adding a contextual filter.
  The relationship field should only show Fruit terms that have been used at least once to tag content.

To answer you question: No, it shouldn't need to be configured differently; it should work the way you describe.
Here is a screenshot of my configuration (following your description) that works as you would expect (you can see the contextual filter in the background set to 'yellow'):

Perhaps you can spot some tiny deviation from your config here.
Good luck in any case!


Image Style Issue Doesn't Work Every Time I posted a previous post about this, but it kind of went a different path, so in the interest of exploring another avenue I wanted to start a new topic to try and troubleshoot this a different way.

ISSUE: The site runs about 99% perfection, however, there is one issue. One of the image styles doesn't always generate when an image is selected for thumbnail.

BACKGROUND/EXPERIENCE ON SITE: I have created a website where I am accepting submissions through Webform version 7.x-3.20 on an installation of Drupal 7.32. The reason for it not being updated is due to a specific need to use Hubspot Drupal Integration 7.x.2.0-rc5. Updating breaks the HubSpot integration, so I've come to terms with the issue of security.

SUBMISSION EXPERIENCE:
 - User fills out form and attaches an image they want to display.
 - I receive an email to review it as admin for approval. I click the link in the email to travel to the submission within Drupal for approval.
 - I click "select" on the image to generate a thumbnail image and adjust any copy content that may be inappropriate.
 - I publish the page and review to ensure main image on entry page and thumbnails on overview page have been made correctly.

PROBLEM: The problem happens in step 3 above. 99% of the time images work without issue and are made into the appropriate thumbnail and entry sizes and crops. However, on occasion the image styles don't work.

WHAT I KNOW:

The uploaded images do make it to the server. I can see the image no issues what so ever before I request it be processed into image styles.
I can recreate the image styles outside of the website and upload them into their specific folders where the images that do work are placed without issue.
I have recreated the image styles in different ways and applied them to my form approval process with similar results which makes me believe it's not directly related to the image style itself.
I've increased the memory limit and max_execution times for testing purposes to a very high allowability.
It is not size specific. Many larger files go through just fine, while the occasional small file size will have this issue with the image style being generated.
It's doesn't seem to be related to the server. I've tried multiple server setups and each has eventually replicated the issue with specific images.

Thanks in advance for helping me continue to trouble shoot this issue.

My gut is that this is a file permissions issue. Check to make sure that the webserver has the appropriate permissions for the directory in question, and the one above it.


Enabling a module leads to memory exhaution. Where to look for? I have developed my little module for Drupal 7 and it has been working fine.  But suddenly it started to cause a memory crush.  Now I can't even enable it (drush en ModuleName) with the error message of:

  Error: Allowed memory size of 536870912 bytes exhausted [...] in /MY/DRUPAL/ROOT/includes/module.inc, line 596

The line number, where it fails, varies sometimes.  I clear the cache (drush cc all) frequently or practically at every step, so I don't think it is cache-related. The allowed memory for PHP and SQL are both 512MB, and the website is mini-scale with no load-hungry module.  The memory should be a way more than enough.

The module is just a little language switcher with only a *.module file (and *.info), and has no major loop — One time loop for an enabled couple of languages is all it has.  No recursive call whatsoever.  So, I have no idea where to look for to pin down the problem…  Only the potential thing I could think of is I had deleted a (unnecessary) path-alias directly via SQL (a row in Table url_alias), immediately before this trouble started.  It being the language-switcher, it accesses to drupal_get_path_alias(), but does it matter?

In case you are interested, my little module is available in GitHub:
https://github.com/masasakano/lang_switcher_advanced

[Edit]
It seems the problem was tracked down and I posted it as the answer.  Everything one'd need is written in it, but just to note, the example codes before and after it was solved are tagged as 0.1.1 and 0.1.2 in the above GitHub repository.

A short answer for the question is to check the function names defined in the module.  If there is any conflict with the existing function names, that can give a trouble when enabling the module.  Also, it may be advisable to disable and enable the module, whenever you add a function to the module, maybe, to detect a potential trouble at the earliest opportunity.
--The following appended--
Another preventive ways: (1) Keep only hook_ functions in a *.module file, (2) for D7, name always your private functions with a little convention, for example, add the prefix of _: e.g., function _myfunction_theme().
--Appended up to here--

It turned out the function name My_Module_Name_theme() conflicts with hook_theme() in Drupal.  I was not using it as my intention, but the code of the function was left for the future development - that caused a trouble, as it was regarded as a valid hook by Drupal, whatever the programmer's intention was.  The arguments given to a call of another Drupal function in that function were not compatible with the Drupal function.  That may have lead to the memory exhaustion.

My guess is, since it is the name of the function (or maybe because it is a hook?), that caused a memory exhaustion while enabling the module rather than during run-time.  I added the function in the module when the module had been already enabled.  At that time (I mean, after I added the function), the module caused no trouble and kept functioning as I intended.  It is possibly because the function names were not registered to Drupal?  I don't know, but whichever, it would make (and indeed did make in my case) a programmer's job to track down the cause of the memory exhaustion difficult, as the error message might not help much to pin down which module, let alone which function, is causing a trouble.

Note even after I had added the "hook" function, I have once successfully disabled and enabled the module (after Drupal experienced a memory exhaustion), and the module worked fine for some time, before it eventually started to cause a memory exhaustion and then it became impossible to re-enable it.  I do not know why it was enabled successfully once and worked OK for some time.

The moral of this case is summarised at the beginning.  Added to that, to chop off all the unnecessary parts like debugging may help (as @rooby suggested in the comment of the question), because something in those unnecessary parts, or those that you think are unused, may be causing a trouble.  Frequent disabling/enabling cycles, as well as clearing the cache, can also help to identify the problem at the earliest opportunity.


Load Multiple Arguments to a View with PHP Code I have a view that I am setting up that will be the view used to select users from a user reference field. I want to build the view so that it only allows the user to reference users that are referenced by a node that this node is referring to.

To Illustrate:

Node Type A => References different users with separate user reference fields (not multi-value fields)

Node Type B => References Node Type A, AND will only reference users that are currently referenced in Node Type A

So I am trying to provide an array of default arguments using PHP in Views. Here's what I have so far:

$node = node_load(arg(1));

if($node) {
$users = array(
'am' => $node->field_am_reference[0]['uid'],
'realtor' => $node->field_realtor_reference[0]['uid'],
);
  foreach($users as $user) {
  return  $user;
   }

}
else {
return FALSE;
}

The Node Type B form is embedded into Node Type A's node view in the .tpl file, so I am loading Node Type A's nid from the url...this is working, but I am only getting the first user reference ('am') field to show up in the checkbox list that is used for the user reference options for Node Type B's  embedded form.

Okay...Here's the right way to do it. I was running into a problem with empty key values. I had to create the array out of the user reference fields I wanted, scrape any of the empty array keys

$node = node_load(arg(1));

if($node ) {
$user_args = array(
$node->uid,
$node->field_am_reference[0]['uid'],
$node->field_realtor_reference[0]['uid'],
$node->field_title_rep_reference[0]['uid']

);
//Remove empty array values and thier respective keys
  $clean_args = array_filter($user_args, 'strlen');

//Take all of the array values and put them into a single key
  $safe_args = implode(',' , $clean_args);

return $safe_args;
}

else  {

return FALSE;

}


Code for Social Button The social button module allows us to use tokens so the share button can target the node url instead of the page url, when we are using views to display content. However, I'm not sure how the code and tokens should be used to achieve this.
My code for the addthis button is as follows:

The code I'm currently using (as shown above) shares the entire page instead of the node which the button is attached to. Social buttons module allows the addition of a field to the content type so the button is tied to the particular content node and I'm trying to get the button to share the content in the node rather than the page, which is a view listing.

So my question is, how do I use tokens in the code for the share button?

I managed to target the individual content nodes using the following code. Hope this helps someone.


add fields to comments programmatically I know how add fields to entity, now what is XXX in below code when I want add this field to comment of articles?

$instance = array(
    'field_name' => 'field_image',
    'entity_type' => 'xxx',
    'bundle' => 'xxx',
    'label' => t('Images'),
    ....

if any other setting is required, then what is that?

I found my answer, see:

dsm(entity_get_info());
dsm(field_info_bundles());

so my code should be:

$instance = array(
    'field_name' => 'field_image',
    'entity_type' => 'comment',
    'bundle' => 'comment_node_article',
    'label' => t('Images'),
    ....


How can I use tokens for Addressfield values without using Addressfield_tokens? I would like to use the Town/ City field as a token for Pathauto. I thought the Addressfield_tokens module was perfect for this, but Entity Tokens breaks Pathauto's patterns control panel; the issue seems to be common and unresolved.

I'm wondering what other options I might have for extracting the Town/ City value from Addressfield and using it as a token in a Pathauto pattern?

If Pathauto uses the core Token system, then you can follow along in this issue where we'll be adding token support directly to Address Field asap.


How to create Facebook style user notifications? Using Heartbeat I have been able to effectively make streams of user activities through Rules triggers. However I would like to be able to have users notified of new activities, and keep a count of the number of new activities like in facebook, or even similar to new email counts in most email systems.

In Drupal 6 there were a few modules which could achieve this well, however how can this be done in Drupal 7?

I have done quite extensive research on this but am unable to find the right module at this point:
There's the User Notifications and Notifier modules, which would be the perfect solutions except only D6 versions exist. There's Notifications which cannot be integrated with any activity logging module since it lacks proper Rules support. Two interesting implementations are Appbar and Taskbar which provide dropdown trays with lists of activities, but don't count the number of new activities and no longer integrate with Rules. Finally DLike is great as a dynamic counter, even though at the moment it only counts Flags and provides a link to a list of the flagging users. Perhaps with some tweaking it could be used via Flags Rules integration to track recent (flagged) activities and link to a list of these recent activities.

Is it possible to achieve functionality similar to this in Drupal 7?

Approach 1: Menu Badges
Use the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal (from the module maintainer).
Drupal 7 Menu Badges Module.

Approach 2: Message stack
Use the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium.
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
And the Message Stack will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture). Even though there is no such a thing as 8.x-dev yet, the Message code repository already does contain something already (not yet for the 2 other modules though). I assume the wip part of the branch name stands for 'Work In Progress'.


ssl with boost and securepages module I have this doubt.
I have a website in drupal 7 currently live (Kickstart2) and use as cache management boost
I have to buy a ssl certificate on my domain and with this certificate I would like to cover only the path checkout/* and user/*

I would like to proceed in this steps:

buy ssl certificate for the main domain
install the module securepages
configure the module with the path checkout / * and user / *

by this configuration I expect something like that:
http://www.example.com/mypage but https://www.example.com/checkout
only /checkout will be in https. Is it right?

This is just as reasoning and how to configure the module? Is it the right way?

Last question:
I read that boost module does not work well with ssl, that it means that my checkout/* pages will not be under cache, but the rest of the pages? Rest of the path like /about or /news are all done under cache?
You can confirm this to me?

Ty guys

Should I use securepages?

No. The best practice these days is to just go with https for the whole site.

How do I go about caching my https content?

On a normal site, the https wouldn't matter, you can cache static content regardless of how encrypted it travels. BUT. The caching questions are legitimate because it is an eCommerce site and with that (by default), even anonymous users will have a session. Most default caching systems do not work with per-user sessions, unless you use something like authcache.


Problem by creating nodes in loop i am new to drupal and trying to migrate same pages to drupal. I am able to create one node via druapals API, but when trying to create more nodes in a loop it doesn't work...

This is the working code:

    define('DRUPAL_ROOT','/var/www');
    require '/var/www/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

    #construct the new node object
    $node = new stdClass();

    #specify node properties
    $node->uid = 1;
    $node->title = "new node";
    $node->log ="";
    $node->status = 1;
    $node->comment = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->type = 'veranstaltung';
    $node->language = 'und';
    $node->created = time();
    $node->changed = $node->created;
    $node->tnid=0;
    $node->translate=0;
    $node->body['und'][0]['value']="
content
";
    $node->body['und'][0]['format']="filtered_html";
    $node->body['und'][0]['safe_value']="
content
";

    #save node
    node_save($node)

If i put this in a for-loop and change the body and title each iteration it doesn't work.. The code is inside an external php script. Even copy the code and paste behind it again with other body and title does not work.

Thanks a lot

Objects are passed by reference in PHP; therefore $node->nid is being set after your first go around the for loop. If $node->nid is set, no new node is created, so, I'd unset($node->nid) after each node_save() and give it another try.


Want to delete some custom user data while delete any user in Drupal8 Is there any Hook available for user delete in Drupal8.
I have some custom data in a custom table and I want to delete those data while I delete any user in Drupal8. Can anybody help me out of this?

Use hook_entity_delete().

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

function mymodule_entity_delete(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType() == 'user') {
     ...
  }
}


Creating new entity with rules I want rules to create a new entity on a timed schedule in the middle of the night, when no when is on the .  My question is what do I use for "The author of the node"?

This depends on the purpose of the content. Provided that it is just administrative content, you could just use the admin user (UID = 1). If the content needs to relate to another user, then you should use them as the author.


Integrate forums with OG groups? i am using drupal 7.

I want to add forums in OG groups so that forums added in OG groups can only be accessible by members of the OG groups.

Is there any other option to grant access restriction on forms except using Form Access, because it will not integrate groups with forums?

Check the module called OG Forum D7. This module allow to make some forum and their topics owned by an Organic group, just like any other group content.


How can I create a custom user profile page without overlapping the registration and login pages? I'd like to create a custom user profile page, but if I use /user/% path then it will also overlap /user/registration, /user/login and so on...

Is there any ways to avoid it?

One approach is to create a custom template file for the user.

add a bit of code to your .theme file:

MYTHEME.theme:

function MYTHEME_theme_suggestions_user(&$suggestions, $variables, $hook) {

  // Define the view mode.
  $mode = $variables['elements']['#view_mode'];
  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;

}

The above tells Drupal to look for template files that fit the new naming conventions.

Then create a twig template file in MYTHEME/templates:

user--full.html.twig

    {% if content.user_picture | render %}
          {{ content.user_picture }}
    {% endif %}

    {% if content.field_name | render %}

{{ content.field_name }}

    {% endif %}

The above html is just an example.

Now you have unique markup for just the user profile page in Drupal. From there it's just a matter of choosing fields, and adding styling.

Make sure to clear cache so Drupal will register your new twig file!


How to create a link with l() function that jumps to specific part of page? Hoping to create a link that jumps to a specific part of another page. For example in a block I have this:

<?php print l(t('About Me'), 'node/55#FIRST', array('absolute' => TRUE));?>

But in the browser it outputs the "#" as "%23":

http://www.site.or/node/55%23FIRST

Anyway to do this?

The last parameter of l() accepts also the same options accepted from url(). This means you can use the following code since Drupal 6.

<?php print l(t('About Me'), 'node/55', array('absolute' => TRUE, 'fragment' => 'FIRST')); ?>

On my test site, the output is the following one.

About Me


Log into Drupal using drush uli via CURL on the command line I'm trying to execute a CURL request via command line which uses drush uli to log into my site as an administrative user.  Then it's redirected to another destination url.

It works if the redirected url is a non-admin path available to anonymous users, but admin paths return a 403 Forbidden, which is something my site does for anonymous users trying to access admin pages.

This works:

curl -vk -L $(drush uli admin_username /node/1)

This returns HTTP 403 forbidden:

curl -vk -L $(drush uli admin_username /admin/structure)

The optional path parameter is being redirected to after logging in, but it's like when CURL gets there... it's not logged in anymore and is seeing the response as if it were an anonymous user.

Anyone experience this?

Is your site redirecting from http to https when you access admin pages?  If so, try to set the --uri parameter you provide to Drush to an https instead of http protocol, and see if that works better.


How do I change a view pager submit from GET to POST? Currently when I have a view pager at my site and I want to click on another site the pager gives me a link similar to "base_url/?page=0"
How can I change that so that the link just shows me the "base_url"?
In my understanding thats because the pager submit handles requests via GET.

You can't POST a link, it's a link; by definition clicking it will send a GET for the target href. The best you could do is hijack the click to POST via JS, set something in the session, then reload the page. Or wrap the View in a form and convert the pager to use submit buttons (possibly styled like links)

But that's very awkward, and would be more than a trivial amount of effort to achieve. Plus you'll need to write a custom Views pager for either method, and you lose the ability to link directly to a certain page, destroying navigation and SEO.

I would just leave it as it is (ie the same as every pager you're likely to find), or install Views Load More or something, if it's the UI you're concerned about.


Circular dependency on base fields' module I have 3 custom modules that provide custom entities with all fields defined as base fields.
Contact module - provides a contact entity(it could be one of the type: a person or email or phone etc) that has a store entity reference field.
Store module - provides a store entity that has a region entity reference field.
Region module - provides geographical region entity that has a contact entity reference field.
So

Contact depends on Store
Store depends on Region
Region depends on Contact

Each definition would look like this:
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  ...
   $fields['store'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Store'))
    ->setDescription(t('Select the store the contact is part of.'))
    ...
    ->setSetting('target_type', 'custom_store')
    ...
}

As these modules provide more than just entity (and custom field API plugins),  We can't combine them together.
when trying to install the modules, getting an unknown entity target_type error.

Since the dependency is purely on the reference field, we could add the target_type later. For example, setting the target_type at the bundleFieldDefinition wouldn't throw the install's error and set the right target_type.
So the baseFieldDefinitions would be
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  ...
  $fields['store'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Store'))
    ->setDescription(t('Select the store the contact is part of.'))
    ...
}

And the bundleFieldDefinitions would be
public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  $fields = parent::bundleFieldDefinitions($entity_type, $bundle, $base_field_definitions);
  $fields['store'] = clone $base_field_definitions['store'];
  $fields['store']->setSetting('target_type', 'custom_store')
  ...
  return $fields;
}


Update node alias while retaining the old alias I want to update many of my node's aliases. I have seen many questions here at Drupal Answers, but nothing I can use, as far as I can see.

What I want to do: I want to update a big portion of URLs (mostly forum nodes) to a new alias and still keeping the old aliases. I can do this by using VBO. However, when I update the URL alias using VBO, all forum nodes as well as other nodes will get the "Has new content" marker saying "updated". I want to avoid the nodes getting this "updated" marker since I have around +10,000 nodes.

I have looked in Rules trying to figure if there is I way I can set the nodes to being marked as "read" when I update the URL alias, but I can't see a way to do this.

The reason I'm not just deleting all aliases and then bulk generate them again, is that it won't keep my current aliases thus giving me many 404 errors in the future.

Is there a way to update the node's alias and still keeping the old alias and not having all the nodes marked as "updated"?

Ultimately, a VBO action affecting a node is going to call node_save() which will change the changed node property that determines when the updated marker appears.

To get around this, you'll need to preserve the node changed timestamps following your bulk alias updating. You can do this by directly updating the node.changed column in the database.

Depending on your preferences, there's many ways to backup/restore database data. For example, executing a Drush snippet before node alias bulk updating could dump a JSON file with your nid/updated timestamps:

drush ev '$nodes = db_select("node", "n")
  ->fields("n", array("nid", "changed"))->execute();
$timestamps = array();
foreach ($nodes as $node) {
  $timestamps[$node->nid] = $node->changed;
}
echo json_encode($timestamps);' > my_node_timestamps.json

Following bulk alias updating, another snippet could restore it from the JSON:

cat my_node_timestamps.json | drush ev '
$timestamps = json_decode(file_get_contents("php://stdin"));
foreach ($timestamps as $nid => $timestamp) {
  db_update("node")
    ->fields(array("changed" => $timestamp))->condition("nid", $nid)->execute();
}
'

As the case with any operations directly touching your database directly, make sure to perform backups before performing any such bulk operation.


What does menu blocks "Block title as link" option do? The Menu block module has an option on each block titled "Block title as link". My interpretation of the description combined with some testing, is that if I leave the "Block title" setting out, the name of the menu will be used as the block title, and it should also be a link to the currently viewed menu item.

However, when I check the option and try it, I never get any links. I've been trying to follow the code, but I couldn't make any sense of it, so I believe my expectation on the functionality is wrong.

For me it doesn't show the menu name, but the link to the parent menu item of the block. IE with a menu hierarchy like this:

<Main Menu>
-- a
---- b
------ c
------ d
------ e
-- f
-- g

If the block looks like this:

Title
c
d
e

Then having the block title as link makes the title a link to menu item b.


What is  $form_state used for? What is $form_state typically used for in the context of the Form API if it is used as an argument?

Specifically, I'm looking for an example of when it is used.

$form_state is one of the arguments passed to a form submission handler, or a form validation handler; its main usage is to retrieve the values entered from the user in the form see the content of $form_state['values']), but it contains other values that can be used for other purposes.
The documentation for drupal_build_form() contains the list of other values contained in that array, which include the following ones:

  rebuild: Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and drupal_redirect_form() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect. This is used for multi-step forms, such as wizards and confirmation forms. Normally, $form_state['rebuild'] is set by a submit handler, since it is usually logic within a submit handler that determines whether a form is done or requires another step. However, a validation handler may already set $form_state['rebuild'] to cause the form processing to bypass submit handlers and rebuild the form instead, even if there are no validation errors.
  redirect: Used to redirect the form on submission. It may either be a string containing the destination URL, or an array of arguments compatible with drupal_goto(). See drupal_redirect_form() for complete information.
  cache: If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which ajax_process_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of $form and $form_state happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.
  storage: $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

Other functions that get $form_state as argument are hook_form_alter() and hook_form_FORM_ID_alter().

As example of code that use that argument you can look at comment_form_submit(), which contains the following code:

function comment_form_submit($form, &$form_state) {
  $node = node_load($form_state['values']['nid']);
  $comment = comment_form_submit_build_comment($form, $form_state);
  if (user_access('post comments') && (user_access('administer comments') || $node->comment == COMMENT_NODE_OPEN)) {
    // Save the anonymous user information to a cookie for reuse.
    if (user_is_anonymous()) {
      user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
    }

    comment_save($comment);
    $form_state['values']['cid'] = $comment->cid;

    // Add an entry to the watchdog log.
    watchdog('content', 'Comment posted: %subject.', array('%subject' => $comment->subject), WATCHDOG_NOTICE, l(t('view'), 'comment/' . $comment->cid, array('fragment' => 'comment-' . $comment->cid)));

    // Explain the approval queue if necessary.
    if ($comment->status == COMMENT_NOT_PUBLISHED) {
      if (!user_access('administer comments')) {
        drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
      }
    }
    else {
      drupal_set_message(t('Your comment has been posted.'));
    }
    $query = array();
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    if ($page > 0) {
      $query['page'] = $page;
    }
    // Redirect to the newly posted comment.
    $redirect = array('node/' . $node->nid, array(
        'query' => $query,
        'fragment' => 'comment-' . $comment->cid,
      ));
  }
  else {
    watchdog('content', 'Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject), WATCHDOG_WARNING);
    drupal_set_message(t('Comment: unauthorized comment submitted or comment submitted to a closed post %subject.', array('%subject' => $comment->subject)), 'error');
    // Redirect the user to the node they are commenting on.
    $redirect = 'node/' . $node->nid;
  }
  $form_state['redirect'] = $redirect;
  // Clear the block and page caches so that anonymous users see the comment
  // they have posted.
  cache_clear_all();
}

To understand what $form_state['values'] contains, you need to look at the values added to $form in comment_form(). For example, $form_state contains $form_state['values']['name'] because $form contains $form['author']['name']. Generally, if $form['field'] is a form field, then $form_state will contain $form_state['values']['field'].


Ajaxly login/signup in bootstrap modal This is sample modal sample of boostrap modal

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

Some text in the modal.

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

and this is a line trigger modal in header.html.twig,

 {{ 'SIGNUP'|t }}

goal: open login form in bootsrap modal.

I find the name of file I can customize user-login block , it's block--userlogin.html.twig
then my markup

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Login

                <form method="post" action="{{ path( "user.login" ) }}"   role="form" name="loginform">
                    {% if error %}

{{ "Could not login" }}

{{ "A valid username and password is required to login." }}

                    {% endif %}

                        <input type="email" value="{{username }}"   name="_username" tabindex="1" class="form-control" id="email" placeholder="{{ "username or email :"|t}}">

                        <input type="password" class="form-control" id="pwd" ame="_password" placeholder="{{ "Password"|t }}">

                        <input type="checkbox"> Remember me

                    <button type="submit" class="btn btn-default">{{ "Sign In"|t }}</button>
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

but with this action action="{{ path( "user.login" ) }}" it redirect me to user/login page.
I want to know how can I login/signup usuer ajaxly in modal without redirect to user/login page?

There are two questions:

1.) goal: open login form in bootsrap modal.

In your code by redirecting to a new path the page will reload, and not display a modal login.

But you don't need a new path, your form is already there. It is in the block content and you should be able to place {{ content }} in the bootstrap modal dialog like this.

block--userlogin.html.twig:

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

                {{ content }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

2.) ajaxifing the login (not reloading after submit)

For this there is some work to do, you can see this in the D7 module:

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

For D8 you need to code something similar.


Easist way to moderate an image via a php GET callback request? I want to add some code that allows me to use an image moderation service called Webpurify http://www.webpurify.com/image-moderation/documentation/callback/. I can send the url request using a rule (or using a hook via a custom module) and they send a callback GET request to a URL I specify, with the imageid and the moderation status directly in the url like this - http://www.yoururl.com/imgcallback.php?imgid=43534dfdfg3453sffsd&status=1. What's the best way to setup a call back page or url in Drupal? It's very simple it just publishes the node if accepted and deletes it if not.

You can specify a path with hook_menu and let the call back point to this path. The call back method of the menu entry handles the call from the service, does any processing needed and finaly does a drupal_goto to your node.

Have a look at the commerce adyen module. It provides two entries in hook_menu which handle call backs from the adyen payment gateway.


Add a custom carousel block with HTML, CSS, and JavaScript I'm new to drupal and not a coder but trying to add owl-carousel in the custom block following some online guides.

I found 2 links which had good owl carousel demos and both of them had 3 sections (HTML,CSS,JS) that need to integrate to make it work.

Links:

owl carousel

Flickity carousel

I was trying the owl carousel and the method I tried was to create a custom block with Full HTML support and used the following HTML code.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<link href="/en/libraries/OwlCarousel2-2.2.0/dist/assets/owl.carousel.min.css" rel="stylesheet" />
<link href="/en/libraries/OwlCarousel2-2.2.0/dist/assets/owl.theme.default.min.css" rel="stylesheet" />

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ultrices, elit sed faucibus pharetra, diam mauris bibendum orci, sit amet ullamcorper purus dui sit amet augue. Donec aliquet diam ut neque mattis, eu tristique sem rutrum.

&nbsp;

Don Know

Important person, some Company

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ultrices, elit sed faucibus pharetra, diam mauris bibendum orci, sit amet ullamcorper purus dui sit amet augue. Donec aliquet diam ut neque mattis, eu tristique sem rutrum.

&nbsp;

Pablo Napp

Important person, some Company

Sorry, the code was taken from some other sources and I've only limited knowledge on it.

Could anyone please guide me how to implement such carousel.

Thanks

I would not bother with copy pasting HTML/CSS/JS into a block (this is bad practice regardless).

Instead, you might want to try the Owl Carousel or Flickity module for Drupal. You didn't mention your version, Owl Carousel exists for Drupal 7, while Flickity only exists for Drupal 8.


Best module where you create a block and select a node from drop-down to render? It's been a short while since I played with Drupal 6 and now I'm getting my feet wet in Drupal 7.7.

I need to be able to create a simple block and in that block 'configure' area I want to be able to simply choose a node in the system from a drop-down list. When that block renders on XXXX page, it will then render the teaser for that node along with any other variables set.

I thought I could do this with Views 3.x by just creating a block view which only renders one result and takes a node title as an argument. The new Views 3.x interface has me a little confused though. Not quite sure how to set it so the node title argument is configured in the block admin area and that argument is then always passed with the block view renders.

I guess what I sort of was looking for was an exposed filter in the block admin edit page where the value is saved but that doesn't seem possible. Anyone have any module suggestions?

The Nodes In Block module seems to give you the desired outcome - albeit a different workflow to what you described. Here is an excerpt about it from the module's project page:

  ... makes it possible to add nodes into a block. A number of configurable blocks are generated which you can assign to a region. Visibility settings of this block are automatically set to 'Show on only the listed pages'. On the node content form, you define the weight and visibility per node thus making it easier for content administration as all your content is now in the same place. With this module, you don't have to explain your customers how blocks work but is still able to decide on which pages content must be rendered.


how throw a custom exception in JSONAPI? In D8 i'm trying to throw custom exceptions for extra validations that i need to do before the content is saved in my custom entity, but when i do the validations in the presave method and throw a normal Exception:
public function preSave(EntityStorageInterface $storage) {
  throw new \Exception("The content is duplicated", 409);
}

The response of JSONAPI is code 500 Internal Server Error and the response:
{
"jsonapi": {
    "version": "1.0",
    "meta": {
        "links": {
            "self": {
                "href": "http://jsonapi.org/format/1.0/"
            }
        }
    }
},
"errors": [
    {
        "title": "Internal Server Error",
        "status": "500",
        "detail": "The content is duplicated",
        "links": {
            "via": {
                "href": "http://site.docksal/jsonapi/content_entity/content_entity"
            },
            "info": {
                "href": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1"
            }
        }
    }
]

}
how can i control de error Code, title, status and detail.

thanks  @4k4, I solved it using customs constraints in my custom entity, JSONAPI mapping well the error and the admin UI works perfectly with that.
like @kiamlaluno said, i try to explain the solution using constraints:
I want to response in the JSONAPI Request that the content is already exists but with a different code, no 500. So when i use constraints i can validate if content already exist or not and response if is a valid request (TRUE / FALSE), this constraints works in the JSONAPI Responses and in the Drupal Admin UI.
So you need to define the constraint in the folder
"my_module/src/Plugin/Validation/Constraint" and create 2 files, for my example i need that the content is unique. so my files are:
UniqueProfileContentConstraint.php
<?php

namespace Drupal\my_module\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Plugin implementation of the 'unique_entry_constraint'.
 *
 * @Constraint(
 *   id = "unique_profile_content_constraint",
 *   label = @Translation("Unique entry constraint", context = "Validation"),
 * )
 */
class UniqueProfileContentConstraint extends Constraint
{

    // The message that will be shown if the value is not unique.
    public $notUnique = 'This content already exists';

}

And the validator:
UniqueProfileContentConstraintValidator.php
<?php

namespace Drupal\ztv_content\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the UniqueInteger constraint.
 */
class UniqueProfileContentConstraintValidator extends ConstraintValidator
{

    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint) {
      // Next check if the value is unique.
      if (!$this->isUnique($entity)) {
          $this->context->addViolation($constraint->notUnique);
      }
    }

    private function isUnique($entity)
    {
      if ($entity->isNew()) {
        $query = \Drupal::entityQuery('profile_content_entity')
          ->condition('profile_id', $entity->get('profile_id')->getString())
          ->condition('video_id', $entity->get('video_id')->value);
        $storageContent = $query->execute();
        if ($storageContent) {
          return FALSE;
        }
        return TRUE;
      }
    }

}

And finally in the Entity annotation you need to add the id of your constraint:
 *   constraints = {
 *      "unique_profile_content_constraint" = {}
 *   }
 * )
 */


How to delete "In code" views? Some Drupal views I have are "In code" (while some others are "In database"); I understand that some are hard-coded in some PHP files and some are coded in the SQL.

Generally, what are the PHP files in which the "In code" views are stored?

The file name convention for default views provided by a module uses the extension .views_default.inc.

Alternatively, if a module isn't using standard naming conventions, you can search the code base for hook_views_default_views_alter() implementations (e.g. grep -r '_views_default_views_alter' . ) to find these views.


Programmatically create a Custom Content type on saving a form We have explored it and found - how to create a content type by adding the YML files in the config/install directory of a custom module. The new content type will be created when we enable the module.

But we have a use case where we need to generate content types on saving a form.
For eg: We have a custom form with a field called "Content-Type Name". On submitting the form, we need to create a new content type with that name.

We are not able to find any proper documentation for this in Drupal 8.

A content type is a config entity, you can create one like any other config entity (*):

$content_type = \Drupal\node\Entity\NodeType::create([
  'type' => $machine_name,
  'label' => $label,
]);
$content_type->save();


How do I get the raw field value in a twig template? myfield is a plain text field. {{ content.field_myfield }} renders the field with HTML markup and the field label.

How do I render the raw value of the field? {{ content.field_myfield.value }} doesn't work.

{{ entity.field_name.value }} to get the true raw value, includes tags and encoding.

Example: {{ node.body.value }}
result:
Batman &amp; Robin

{{ content.field_name.0 }} to get the raw value minus tags and encoding.

Example: {{ content.body.0 }}
result: Batman & Robin

  raw

  This filter should be avoided whenever possible, particularly if
  you're outputting data that could be user-entered. See this page for
  more information on auto-escape in Drupal 8.

  source: Filters - Modifying Variables In Twig Templates

  The raw filter marks the value as being "safe", which means that in an
  environment with automatic escaping enabled this variable will not be
  escaped if raw is the last filter applied to it

  source: Twig's official docs

For example, you can use:

{{ node.body.value|striptags }}

{{ paragraph.field_text.value|striptags }}

  The problem with using twig's |striptags is double encoding of html entities,
  not markup, so & becomes &amp; and then &amp;amp; – Berdir


Using Migrate API to select items from within an Events JSON array I am using the migration import to pull in events from a calendar service json api. I can capture and map almost all the event details except the start date which is contained within an array. I tried to use the extract plugin but can't quite get it to work.

"events": [
   {
      "event": {
         "id": 920693,
         "title": "This is the event",
         "url": "http://woodowloriginaldesigns.com/what-lies-beneath/",
         "photo_id": 481020,
         "detail_views": 892,
         "event_instances": [
             {
                 "event_instance": {
                     "id": 2711527,
                     "ranking": 0,
                     "event_id": 920693,
                     "start": "2017-06-28T00:00:00-04:00",
                     "end": null,
                     "all_day": true
                 }
            }
    ],
    "address": "124 Main Street USA",
    }
  }

I am trying to get the "start" date out of there. The process section for my yaml file for the start date currently looks like this:

field_importdate:
  plugin: extract
  source: event_instances
  index:
    - 0
    - event_instance
    - start

When I omit this, I can successfully pull in/map all the other fields with a drush migrate-import jobnamehere  command.

How should my extract plugin be configured here to get the start
date?

Happy to provide more details and entirety of yaml file if needed.

Have you tried mapping directly rather than using extract?

field_importdate: event_instances/0/event_instance/start


How to convert text into long text? I have a text field on my site which is becoming a problem.  Users tend to input more text than I had expected.  I need to convert this text field into a long text field.  This is problematic because there is already content.  I'm looking for a way to do the conversion as painlessly as possible.  Here is my current plan:

Create the new long text field
Use a module (probably feeds) to duplicate the data (export, then re-import)
Delete the old text field.

Is this a good idea or is there a better faster one out there?

Though the question is pretty old, I would like to add my suggestion to it. I don't think changing the field type directly in the database is a good idea.

Create a new field (long text) with the necessary settings, and add it to the content type.
Then you can use the following script to copy all the old field values (text field) to new field (long text).

<?php
// Assign value from old_field to new_field
$nodes = node_load_multiple(array(), array("type" => "your_type"));
foreach ($nodes as $node) {
  $node->field_new = $node->field_old;
  field_attach_update('node', $node);
}

Finally delete the old field and use the new field for further use.


Posting to a Drupal Form via HTML page I have created a plain HTML page. I want that the when ever a submit button is clicked, It submits the values to a form that is present on a drupal Site. Its a simple form with only text field. Any idea ?

A form directly can not be posted to Drupal. But a general callback can receive post request data and can process it to store it somewhere.

For this, a hook_menu entry is required to register a callback with a newly created URL . This callback can access $_POST.

On the other hand post request to Drupal can be invoked with form data either by CURL or jQuery.ajax()

Your custom module:

function hook_menu(){
  return array(
     'path/to/submit/post/values' => array(
        'title' => 'Catch Post Data',
        'access arguments' => array('access content'),
        'page callback' => 'catch_post_data',
        'type' => MENU_CALLBACK,
     )
  );
}

function catch_post_data(){
   $values = $_POST;
   // Get post values and store where you like.
   // Do not break the system. Do it carefully using proper entity functions.
   if($success)
       drupal_json(array('status' => 'SUCCESS'));
   else
       drupal_json(array('status' => 'FAILURE'));
}

Form can be posted via jQuery.

$.post('path/to/submit/post/values', $('#form').serialize(), function(response){
    response = $.parseJSON(response);
    if(response.status == 'SUCCESS')
        alert('Congrats!');
    else
        alert('Something went wrong');
});


Retain revision author when editing revision I am using the Revisioning module and it has an option when saving nodes: 'Modify current revision, no moderation'.

When selecting that option I want to retain the node revision author.

So far I think I need to do this:

Create my own submit callback for node_form and replace the submit button with my own so that the default submit handler is not called.

Copy the code out of the default submit handler into my new hander. Then before node_save is called I must impersonate revision author if my condition is met.

Is this right, or is there a better way to achieve this?

You definitely don't need to copy, replace, override, etc.

Node revision information is handled here.  As you can see, the revision author is maintained, but most use-cases will call to show the original author.

Depending on your situation, there's many ways to show the revision author instead.  For example, I see that the revisioning module you're using provides a revision-author token in revisioning_tokens.inc.

Other possibilities: hook_node_view in a module, template_preprocess_node in a theme's template.php, node--NODE-TYPE.tpl.php, etc.

Edit: BTW, if you went about updating the author ID like you mentioned, you would effectively change the ownership of the node to another user, which probably isn't a good idea!


How do I add just one extra node to a view? Display OG contents plus OG group node I have created an ajax view that displays the contents of a group.  It shows one page at a time, with a nice jquery pageturn effect when you go to the next page.

I now want to insert the actual group node at the start of this view.  I can't put it in header or template files, as then it wont work with the ajax pagination.

I have worked out the SQL I need to get the results I want...

SELECT node.nid AS nid FROM d7_node node
LEFT JOIN d7_og_membership og_membership_node ON node.nid = og_membership_node.etid AND        og_membership_node.entity_type = 'node'
WHERE (( (node.status = '1') AND (og_membership_node.gid =   '42' ) )) OR (node.nid = '294')
ORDER ASC

The SQL my view is currently using is...

SELECT node.nid AS nid FROM d7_node node
LEFT JOIN d7_og_membership og_membership_node ON node.nid = og_membership_node.etid AND        og_membership_node.entity_type = 'node'
WHERE (( (node.status = '1') AND (og_membership_node.gid =   '42' ) ))
ORDER ASC

So basically I just need to tag on  'OR (node.nid = '294')' to the WHERE.

I'm trying to use this custom module

function hook_views_views_query_alter(&$view, &$query) {
if ($view->name == 'flipbook_ii') {
    $nid = $view->args['0'];
    $query->where[] = array(
      'conditions' => array(
        '0' => array(
          'field' => 'node.nid',
          'value' => $nid,
          'operator' => '=',
        ),
      ),
      'type' => 'OR',
    );
  }
}

But that is still setting the WHERE query

WHERE (( (node.status = '1') AND (og_membership_node.gid = '42' ) AND (node.nid = '294') ))

Can anyone explain a way that works?

Took me a while but eventually solved this....

Needed to add

$query->group_operator = 'OR';

into my hook_views_query_alter.


I want to change the layout of add/edit page I have one content type called Restaurant, and I want to change the layout of this content type in the administrative area. When the administrator user adds/edits a Restaurant node, the layout should be my custom layout.

How can I change the whole layout?

As shown in the comment at the beginning of theme_get_suggestions(), for a URL such as http://www.example.com/node/1/edit, the following default suggestions will be used.

page__node
page__node__%
page__node__1
page__node__edit

If you want to add page__node__edit__article as suggestion, you need to implement hook_preprocess_page() in a module. The following code works for any content type.

function mymodule_preprocess_page(&$variables) {
  if (!empty($variables['node']) && arg(2) == 'edit') {
    // (1)
    array_unshift($variables['theme_hook_suggestions'], 'page__node__edit__' . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type));
    // (1)
  }
}

If you want to be use not to apply the template file for, e.g., node/1/edit/revert, replace the code between // (1) with the following one.

$arg3 = arg(3);
if (empty($arg3)) {
  array_unshift($variables['theme_hook_suggestions'], 'page__node__edit__' . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type));
}


Attachment added through hook_mail_alter() is making no effect I'm trying to add one pdf attachment to the mail sent on webform submission. I'm using hook_mail_alter() to add attachments to the mail.
This is the code I am using.
function webfpdf_mail_alter(&$message) {
$attach = genpdf($message['params']['message']);
$message['params']['attachments'][] = $attach;
dpm($message);
return $message;
}
The output message shown by dpm() shows attachment, but the email doesn't contain attachments.
This is the output of dpm().
attachments (Array, 1 element)
0 (String, 568525 characters ) Content-Type: application/pdf; name="Webform-...
Content-Type: application/pdf;
 name="Webform-submission.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="Webform-submission.pdf"

cSA4NS4wNCAwIDAgMzMuNzMgMjguM......
..../****base64data*****/.....
..... ;
body (Array, 1 element)
headers (Array, 7 elements)
MIME-Version (String, 3 characters ) 1.0
Content-Type (String, 24 characters ) text/html; charset=UTF-8
Content-Transfer-Encoding (String, 4 characters ) 8Bit
X-Mailer (String, 27 characters ) Drupal Webform (PHP/5.3.29)
Return-Path (String, 35 characters ) enquires@xxxxxxx.org
Sender (String, 35 characters ) enquires@xxxxxxx.org
From (String, 28 characters ) "LESS" <support@xxxxxx.com>

Can anyone help me to fix this?

If you're not already using it, I think you need MIME Mail or something similar to handle attachments, and when you do, your attachment needs to be added as an array of arrays rather than an array.
This is what the README file says.

You can use the following optional parameters to build the e-mail:

'plain': Boolean, whether to send messages in plaintext-only (optional, default is FALSE).
'plaintext': Plaintext portion of a multipart e-mail (optional).
'attachments': Array of arrays with the path or content, name and MIME type of the file (optional).
'headers': A keyed array with headers (optional).


Open Atrium: How to change Task assignment from users to groups? I'm trying to change the Task content-type to be able to assign tasks to groups, and only show those tasks in Task List that are assigned to your group you are added. I've tried by adding a new field with Entity Reference to groups, to select multiple and this part is okay and working fine.

I'm blocked when I'm trying to set the filters in the Views to get the current user's group and show the task if it's assigned to that group.

Thanks a lot!

Edit the Task content-type, add a new Entity Reference field for oa_group_ref.
Edit the Task List view and set a contextual filter on the added field, and provide the default value for the filter with the OG groups of the current user, and allow multiple values in More options.
In query settings set the Distinct to make it work with multiple assignment.


How do I manage 404s for old paths? We moved to Drupal from another CMS about a year ago, and we still get 100s of "page not found" log entries each day for paths that were for our old site that don't exist on the new site. By checking IPs, I have concluded that most of these are from Google's indexer, but not all.

I add redirects when I can, but most of the links are to some meaningless tokenized path that our old CMS used. I feel like there is probably something I should be doing to flag bad paths for Google/SEO/whatever.

Is there a best practice for what to do with old broken links?

Is there a best practice for what to do with old broken links?

Redirect as much links as you can to existing pages using URL aliases.
Find out what pages are linking to your website on the old URLs, see if you can get them adjusted by contacting the webmaster (using a backlink indexing tool like Open Site Explorer or Majestic SEO).
For other links you have the HTTP 404 status code. Sometimes you just can't redirect the links...