How to replace internal links with a view (similar like the Open Graph feature)? I would like to have the feature, that if users on my site post internal links within a text, this links are replaced by a thumbnail, node title etc. For choosing what to show instead of the link I would like to use Views.
What would be the best method to do so?

I think, a simple replacement with hook_node_submit() or
something, is not a good solution: If the user edits his content, I
want him to see only what he added himself.
I could do it within the template, but this is not very elegant, I guess.
What is about hook_url_outbound_alter(), would that be the best way?

Please give me a hint.

The correct way to do this is to write text filter and add it to input formats your users will be using. Here you have Basic description of filters and formats - for Drupal 5 and 6, but concept is still valid. They are applied on display - Drupal agrees with you that you should save just what user wrote.

You need to use hook_filter_info(). Read about it, and then about rest of filter hooks family and you will have an idea.

To provide proper content for filter, well, there is no definitive solution. If users will only input node id, simple node_load is enough. Every set of scenarios and every use case calls for it own methods. Views are elastic tools, I guess for pretty big part of use cases they can be the tool.


Migrate paragraph fields I have migrated Drupal 7 website to Drupal 8 version using the core migrate_drupal_ui module successfully but the paragraph module was broken upgrade path which results in final that the paragraph bundles not migrated and I have created in the new site like the old.

Now I need to migrate content for the paragraph fields only and update the nodes, I did some research and found possible solutions as follows:

1- Custom migrate plugin But I don't know how to edit existing.

2- custom script to read the nodes from other site by creating feeds and update.

//$nid get from feeds.
$entity = entity_load('node', $nid);

$entity->set('field_audit',
['field_number' => [0 => ['value' => 4]],
'field_regular_materials' => [0 => ['value' => '44']],
'field_verification' => [0 => ['value' => '444']]], FALSE);

$entity->save();

  That code gives error Fatal error: Maximum function nesting level of '256' reached, aborting!

what is the best practice to achieve.

I would approach this differently. Using PHPMyAdmin or a Database viewer program, I would look at the Database for the paragraph fields table. Then just export table from D7 as a CSV file.

In D8, fill out 1 node paragraph values, just so you get the table structure, and export table as CSV.

Then with excel (or Libre office Calc) copy and paste values from one CSV to another.

Import CSV to D8 Database.

Clear the cache to see changes.


drupal multilingual frontpages different templates I am building multilingual site using 3 languages.
English is default and 2 other used wit prefixes. www.example.com/fr/.../cs/

I would like to create custom landing page on www.example.com using different template than other landing pages with prefixes.

So www.example.com (which is English language) would only be plain page (custom template) with links to www.example.om/fr (with default template page) and to www.example.com/cs (default template)

Would be something like this possible?

Thank you

Create a custom template file for the English landing page first (for example: page-customfront.tpl.php) then add the following code into your theme template.php file:

function mytheme_preprocess_page(&$variables) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'en') {
    $variables['template_file'] = 'page-customfront';
  }
}

This should do the trick (assuming English will remain the default language with no prefix). Don't forget to switch out mytheme in the function name with your actual theme name.

As for the language links you could use the following code:

<?php
$langs = language_list();
foreach ($langs as $lang) {
  if ($lang->enabled) {
    if ($lang->language == 'en') continue;
    print l($lang->native, '<front>', array('language' => $lang));
  }
}
?>

This should go into page-customfront.tpl.php in the place where you want the links to appear. If you are familiar with creating custom modules or don't mind learning it would probably be preferable to turn this code into a function, add it your module file, enable the module and then just call the function from page-customfront.tpl.php.


How to track the published/unpublished status for node revisions? I am ultimately looking for a way to create a report in Views showing what nodes were active on the site at what times but thus far have been unable to accomplish this. I've done a fair bit of research and experimentation but it seems the main obstacle is that node revisions in Drupal don't capture whether the node was published or not at the time of the revision. Can anyone offer some guidance on how to do such a thing in Drupal 7?

As an example for clarification - though not my exact situation - imagine a classifieds site where the managers need to know how many listings (i.e nodes) were currently published (not published on a particular date, but "live" on the site) for the month of January. Or, perhaps to see what listings were active the week of January 1st-7th, who posted them, and what the headlines were.

Any pointers in the right direction? Or is this something reasonably achievable with custom development (I am just a site builder not a developer!).

Try this hope it helps.

First create a Views page

Second add the fields you want to display based on your node. Add relationship 'author' so that you can add a user:name which is related to the author of the node.

Third change your use pager to 'page by date'. Next add a contextual filter Date: date(node). After adding do this.

And your output should be like this.

Additional, you can add exposed filter date so that you can filter on what month you want to check.

Hope this helps you in your problem.


Memory error when updating user field with Rules I'm using the Rules module to update my user email signatures.
The rule get's triggered whenever an account is updated and performs a simple custom action.
This is the action, all it does is save a new value to the signature field (textfield, full_html).
<?php

namespace Drupal\frontview_general\Plugin\RulesAction;

use Drupal\rules\Core\RulesActionBase;
use Drupal\user\Entity\User;

/**
 * Change event date status to ( selected, open, closed )
 *
 * @RulesAction(
 *   id = "rules_update_signature",
 *   label = @Translation("Update User Signature"),
 *   category = @Translation("Custom"),
 *   context_definitions = {
 *     "uid" = @ContextDefinition("integer",
 *       label = @Translation("User id"),
 *       description = @Translation("Specifies the id of the user that needs to be updated.")
 *     )
 *   }
 * )
 */
class UpdateSignature extends RulesActionBase {

  /**
   * {@inheritdoc}
   */
  public function doExecute($uid) {

    $user = User::load($uid);

    $first_name = $user->get("field_first_name")->value;
    $last_name = $user->get("field_last_name")->value;

    $name = $first_name . " " . $last_name;

    $user->set("field_signature", $name);
    $user->field_signature->format = "full_html";

    $user->save();

  }
}

This all works fine until it hits the  $user->save(); part. That's where something goes wrong and I end up with this error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /Users/lennertslabbinck/Sites/Frontview/web/core/lib/Drupal/Core/Cache/DatabaseBackend.php on line 167

This works great in other actions with other content so it probably has something to do with this being users but I can't figure out what.

Your problem is loop update user infinity. When user update, hook_entity_update will be call:
/**
 * Implements hook_entity_update().
 */
function rules_entity_update(EntityInterface $entity) {
  // Only handle content entities and ignore config entities.
  if ($entity instanceof ContentEntityInterface) {
    $entity_type_id = $entity->getEntityTypeId();
    $event = new EntityEvent($entity, [
      $entity_type_id => $entity,
      $entity_type_id . '_unchanged' => $entity->original,
    ]);
    $event_dispatcher = \Drupal::service('event_dispatcher');
    $event_dispatcher->dispatch("rules_entity_update:$entity_type_id", $event);
  }
}

soure
This event will be call your rule action. So when you call $user->save(), the hook_entity_update will call again... That's your problem. To be resolve, you can follow example.

Edit your annotation. "user" = @ContextDefinition("entity:user",
Update logic method doExecute
Update your rule.

Remember don't call $user->save() again.


How to trim view field to height or number of lines? I have a div with a fixed height and want to display a view field.  When the content overflows the div, I'd like an elipsis to click for more.

CSS can handle overflow and hide it (and overflow-text can handle a single line) but I have to estimate everyting for number of lines since words can be an arbitrary length.  Sure views with or without the smart trim module can handle words or characters, but I need to estimate the number of lines or, ideally, I'd like the trim based on the max-height of a div.

The Smart Trim maintainer suggested a CSS library which may help but does not solve the problem.

I imagine that views text overflow based on height is a common problem.

There is no way to handle this with Drupal modules, I suggest you use  Ellipsis in your Style( style the result rows items with Ellipsis .

You can read below help content :

link1

link2


How to bulk delete translation strings I imported some translations using the locale update module but the translations are horrible and it would be better to revert to English.

How do I bulk delete all the imported translations in Drupal 8?

I found an issue on adding back the D7 translation string deletion option to the UI, but I want to mass delete all strings, not individual strings.

Drupal 7 version of this question

EDIT: Deleting the language is one approach, but I can't do that because I already have a lot of content translated into the language.  I want to keep the content that I have translated into the language, but delete all the user interface strings that were imported through localization update.

If you intend to remove ALL strings imported through interface translation, you could execute something like this:

// Replace the empty string with your target language code.
$langcode = '';
\Drupal::database()
  ->delete('locales_target');
  ->condition('language', $langcode)
  ->condition('customized', 0)
  ->execute();

You may also want to reset the source file history information, so - if you change your mind afterwards - you can re-import the very same translations:

\Drupal::database()
  ->delete('locale_file')
  ->condition('language', $langcode)
  ->execute();

or

locale_translation_file_history_delete([], [$langcode]);

As the locale module is making heavy use of static caches, you may run above commands in a dedicated process as, e.g. Drush PHP CLI (drush php:cli).


How to print custom date format in Twig? How can I print a custom date format in Twig?  First of all my I am trying to edit the field.html.twig of the field called field_publication_date, in that file I find this variable {{ item.content }} which prints   Jun, 12/06/2016 - 12:29.

This is what I have tried: {{ item.content.field_publication_date|format_date('M') }}

Try to use this -

{{ item.content.field_publication_date|date("M") }}

But, I think you will get your solution in

{{ item.content|date("M") }}

Where item.content contains the date string inside field--node--field-publication-date.html.twig.


No "body" when creating a node programatically, with Internationalization I am trying to create event type nodes in Drupal 7, using data from an external database.
It's reading correctly, and creating a node almost perfectly.
But, it doesn't seem to save the "body" part of the node.

db_set_active('default');

foreach ($results as $record) { // Results gained from an ext DB
  echo 'Creating event: ' . $record->name;

  $node = new stdClass();
  $node->type = 'event';
  node_object_prepare($node);

  $node->title    = $record->name;
  $node->language = "en";;

  $node->body[$node->language][0]['value']   = $record->bodytext;  /* This line ?? */

  $path = 'content/programmatically_created_node_' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);
}

This is early stages, and I have a number of fields to put into events type nodes, including some custom fields.

I am unsure how to map the fields in the external database to node fields.  The line above might be completely wrong at this stage, but it's gone though many many failing iterations.

As requested: DPM output of the node (after save)

... (Object) stdClass
type (String, 5 characters ) event
uid (String, 2 characters ) 10
status (Integer) 1
promote (Integer) 0
sticky (Integer) 0
created (Integer) 1357635638
revision (Boolean) FALSE
comment (String, 1 characters ) 1
language (String, 3 characters ) und
menu (Array, 13 elements)
title (String, 42 characters ) Starter Course
field_pakp_p1_id (String, 36 characters ) 78ee9b05-9225-fb5b-9bbb-508eada6ba81
body (Array, 1 element)
  en (Array, 1 element)
    0 (Array, 3 elements)
      value (String, 19 characters ) This is a body text
      summary (String, 19 characters ) Here goes a summary
      format (String, 13 characters ) filtered_html
path (Array, 1 element)
validated (Boolean) TRUE
changed (Integer) 1357635638
timestamp (Integer) 1357635638
publish_on (Integer) 0
unpublish_on (Integer) 0
log (String, 0 characters )
nid (String, 3 characters ) 423
tnid (Integer) 0
translate (Integer) 0
vid (String, 3 characters ) 423
field_event_status (Array, 1 element)
xmlsitemap (Array, 15 elements)

...

I also tried using the drupal_form_submit method..

foreach ($results as $record) { // Results gained from an ext DB
    echo 'Creating event: ' . $record->name;
    $node = (object) array(
      'type' => 'event',
      'language' => LANGUAGE_NONE
    );
    node_object_prepare($node);

    $form_state = array();
    $form_state['values']['language'] = "en";
    $form_state['values']['title'] = $record->name;
    $form_state['values']['description']['value'] = "description....";
    $form_state['values']['body']['value'] = "body....";
    $form_state['values']['body']['format'] = filter_default_format();
    $form_state['values']['body']['LANGUAGE'] = "en";
    $form_state['values']['name'] = $user->name;
    $form_state['values']['op'] = t('Save');

    drupal_form_submit("{$node->type}_node_form", $form_state, $node);

}

But again, try as I might, using this method I could not get the "body" to be saved.  (I know there is some junk in this code, it's my experimentation.)

Questions.

Which is the best method to use for my application.  node_save or drupal_form_submit
For the correct method, which is the best way to store the body text?
How do I know what are valid $form_state array keys, or $node elements, so I can find the correct place for further field mapping?

If your site is multi-lingual then 'en' would contain the English-language translations of your original node (I think that's right).

Going out on a limb, I'd say you're not running a multilingual site and instead want to use the LANGUAGE_NONE constant, e.g.

$node->language = LANGUAGE_NONE;

If your site isn't multi-lingual, using 'en' would probably explain why you're not seeing the body value saved. It might even be there in the database, but because the field system is looking for fields with a LANGUAGE_NONE when it's attaching data to a language-neutral node, nothing gets found.

That might be a load of nonsense though ;)


Get node ID for all results for current view including its filters, disregarding the pager I have a view that produces say 70 results with certain exposed filters applied (this is a view that uses Apache Solr indexed content) and I want to get the NID of every result, so I can then send it through to another page in a simple array of NID's.

I've found that all the results NIDS are within the $results array produced by views, but this only has the results that are shown on the current page, is there a way to get all the results disregarding the pager, without removing it entirely. Is this impossible to do without generating a new query based on the active filters? this is what I'm trying to avoid because there are quite a few filters.

I ran into this problem on a recent project.  I decided against a EntityFieldQuery or db_query()/db_select() solution for four reasons.

Views can do some really weird things when it builds a query.  For example, in some instances when you add a sort, the sort key will be added to the returned field list.  This can alter what gets returned when you enable aggregation, reduce duplicates, etc.
Views tends to use LEFT JOIN instead of INNER JOIN.  You can do this with db_query() and db_select(), but not EntityFieldQuery.
SQL can be unpredictable with the undefined ordering between having a LIMIT or not.  For example, if you are sorting by titles and have duplicates, I have seen different results orders.  This mans you may need to be really explicit with sorts, if order is important (I was implementing prev/next through a result set, so it was).
I really don't like implementing things in code when I know a non-coder may want to adjust the View.

So, I ended up using this:

$all = views_get_view('my_view');

$all->display['default']->display_options['pager'] = array(
  'type' => 'none',
  'options' => array(
    'offset' => 0,
  ),
);

$all->set_display('my_display');

$all->display[$all->current_display]->display_options['pager'] = array(
  'type' => 'none',
  'options' => array(
    'offset' => 0,
  ),
);

$all->pre_execute();
$all->execute();

$nids = array();

foreach ($all->result as $result) {
  $nids[] = (int) $result->nid;
}

This will

Manually instantiate the view.
Reset the pager on the master to show all results starting from 0.
Set the display to whatever I am using.
Reset that pager, too.
Execute the view
Loop through the results for what I need.


view_get_views returns null I have a module function which needs to get the raw results of a view, so I use this bit of code:

$view = views_get_view('sluitingsuren_bakker');
  $view->preview();

  return $view->result;

The views machine name is sluitingsuren_bakker. I also tried some other views, but it seems the module can't find any of the views.

Also I set my permissions on this view to none, because I thought that was the problem.

You are missing the display name, which is the machine name of the block/page.

You can find the machine name under Advanced settings in the right side of the view.

try:

   <?php
    $view = views_get_view(view_name);
    $view->set_display(machine_name);
    $view->preview();
    return $view->result
    ?>


Source of Zen theme variables This relates perhaps more to Sass then Drupal per se. But, it does come from a Drupal contrib theme; so- I'm hoping someone has encountered this or simply knows the answer.

Question is: where are some of the Sass variable set. For example $nav-height

In the sass file _responsive.scss the following code

/* Navigation bar */
@media all and (min-width: 480px) {
  #main {
    /* Move all the children of #main down to make room. */
    padding-top: $nav-height;
    position: relative;
  }
  #navigation {
    /* Move the navbar up inside #main's padding. */
    position: absolute;
    top: 0;
    height: $nav-height;
    width: $zen-grid-width;
  }
}

No where can I fine where $nav-height was initialized or set. Yet, when sass is compiled, magically - somehow, the value is there.

Same question holds for the next variable "zen-grid-width".

$nav-height is specified in the file _init.scss (in the sass directory of your sub-theme) and the $zen-grid-width is set by the Zen Grids extension in the _grids.scss file (and if you're developing a non-responsive theme it is set in the _fixed.scss in the layouts directory of your sub-theme).


How to change "New content" text in entity connect autocomplete edit/add buttons? using entityreference autocomplete widget (field-widget-entityreference-autocomplete) with entity connect I have the buttons "New content" and "Edit content".

How can I just rename them in "New" and "Edit" respectively ?
These are coded in the value field of the input, hence I can't change them just with CSS..

I think I could do it on a form specific way using hook_form_alter, but I would like to apply it to any form where the widget appear.

I tried already hook_field_widget_form_alter(&$element, &$form_state, $context) but then I got lost, I am not sure it's the right place..

In a form alter you can access those two buttons with something like:

$field_name = "field_test";
$form[$field_name][LANGUAGE_NONE][0]["add_entityconnect__".$field_name."_0_"]["#value"] = t("New");
$form[$field_name][LANGUAGE_NONE][0]["edit_entityconnect__".$field_name."_0_"]["#value"] = t("Edit");

Adapt the name, language and cardinality of the field accordingly.

You can use a basic hook_form_alter to affect all forms. The widget creation code is in entityconnect.form.inc and it can't be altered (no hooks, no variables).


Entity Reference: User field not displaying unless user is referenced I have a field that references users: field_cc. When userA creates a node with this field populated with userB, userA cannot see the field when the node is displayed. If userA references himself, then userA will be able to see the field when the node is displayed.

This was on a clean install, no other permission-type module installed. Also tried fixing this with the Field Permissions module but this is did not help. I went through all possible permissions and settings but nothing seemed to work.

Am I misunderstanding how this module works out of the box?

Thanks in advance!

Does that field display a link to the user profile? I think it does, and your users do not have the 'View user profiles' permission, so they cannot see the link to a page they don't have access to.


views_get_view_result() how to retrieve a specific pager (pagination) page? views_get_view_result() returns the results of the first pagination page (views pager). Is there a way to retrieve a specific page pagination results?

I have tried views_get_view_result('MYVIEW', 'MYDISPLAY', array('page' => 3)); but no juice.

If this function specifically does not do this trick, is there any that does?

I think I have it figured out:

$myview = views_get_view('MYVIEW');
$myview->set_display('MYDISPLAY');
$myview->set_current_page(3); // Get the pagination page 3
$myview->pre_execute();
$myview->execute();

dpm($myview->result); // You need Devel module for using dpm()


Personal contact form button if available How can I add a button to the user twig template that links to their personal contact form, but only shows if that user has the form available, and the person viewing the page has permissions to use it?

This was the solution I came up with:

/**
 * Implements hook_preprocess_user().
 */
function MYTHEME_preprocess_user(&$variables)
{
    $account = $variables['elements']['#user'];
    if ($account->getEmail() != '') {
        $contactUrl = Url::fromRoute('entity.user.contact_form', ['user' => $account->id()]);
        if ($contactUrl->access()) {
            $contactLink = Link::fromTextAndUrl('Contact', $contactUrl);
            $variables['contact_btn'] = $contactLink->toRenderable();
            $variables['contact_btn']['#attributes'] = array('class' => array('btn', 'btn-primary', 'btn-contact-user'));
        }
    }
}


WordPress Migrate 502 Bad Gateway nginx I did a fresh Drupal(v7.39) installation on Nginx server. Everything seem fine until the WordPress Migration process with "Migrate", "WordPress Migrate", and "Migrate Extras" modules. The error message I got is
 An AJAX HTTP error occurred. HTTP Result Code: 502 Debugging information follows. Path: /batch?id=83&op=do StatusText: Bad Gateway ResponseText: 502 Bad Gateway 502 Bad Gateway nginx.

Even I got an error, all the content did migrate correctly except the url alias. The URL was set for "Set path aliases to their original WordPress values" during the process, but they came out like node/101, node/103....

What may causing the error and how can I fix this?

A 502 Bad Gateway error can mean a lot of things, however, if you had the site working OK and then it stopped after changing things in the database, then it basically points to a problem with the way PHP is interpreting things in the database.

You'll need to look at your PHP configuration to find where the PHP error log is on the server and then look into that error log to understand what the problem is.
There is a chance that the error is being recorded into Drupal's watchdog, usually available at admin/reports/dblog - if you can't view that inside the website you could use drush with the drush ws command to see items in watchdog, or just use SELECT * FROM watchdog ORDER BY wid DESC LIMIT 20; at a sql client to see the contents of the watchdog table.

The 502 error indicates there is a problem, but doesn't indicate the specific problem. If you post more details from your PHP error log it will be easier to help you fix it.


How can I check if the cart has shippable products? How can I check if the cart has any shippable product in Ubercart 3 for Drupal 8? Previous version had uc_cart_is_shippable() method which Drupal 8 module does not seem to have by default.

Is there a separate/additional module to get this function working? Or how else can I check if the cart has a shippable product?

The function is now a part of the CartInterface and implemented in the Cart::isShippable() method. You can use the CartManager service to retrieve the Cart object and call the method:

\Drupal::service('uc_cart.manager')->get()->isShippable()


Can the Views Module assign a value to the Can the Views Module assign a value to the  and/or $title variable?

More specifically, I would like the Views Field: "Content Title" to be the $title.

I found a place in the Contextual Filter that lets me set the page title based on the Node ID's URL parameter.

I set options that met my needs in "Context Filters > Content: Nid." Within the Nid options, there are several options for providing a filter value and for overriding the title.


Node delete doesn't delete from DB I'm trying to delete a node knowing it's nid.

I've implemented hook_cron in order to do this:

function my_module_cron() {
  node_delete(5446);
  print "deleting node 5446";
}

The print message it's shown when executing the hook_cron, so I assume it also executes node_delete.

But the node it's still there in the website and also in the DB.

Other alternative would be manually deleting the node from the DB using the queries that appear in the node_delete code

Would this be enough?

Could it broke something doing this manually instead of using node_delete?

I call the hook_cron using drush:

drush --uri="www.myurl.com" php-eval 'my_module_cron();'

How is cron being called? (drush, wget, manually run).

node_delete requires the permission delete to actually execute the delete queries.

Depending on how you run cron will depend on the result, for example if cron is run from wget then it's run as an anonymous user therefore nothing will happen as hopefully anonymous user can't delete content.

If you try calling cron from status report while logged in as uid 1 then it should delete fine.


Error when translatable When I save my Custom Entity Type I get an error. I tried several different things. The code looks valid to me.

  Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues() (line 367 of core/lib/Drupal/Core/Field/WidgetBase.php).

This is my annotation.

/**
 * @ContentEntityType(
 *   id = "email_confirm_redirect",
 *   label = @Translation("Redirect entity"),
 *   admin_permission = "administer email confirm redirect entity",
 *   base_table = "email_confirm_redirect",
 *   translatable = TRUE,
 *   handlers = {
 *     "list_builder" = "Drupal\email_confirm_redirect\Entity\Controller\RedirectListBuilder",
 *     "form" = {
 *       "add" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "edit" = "Drupal\email_confirm_redirect\Form\RedirectForm",
 *       "delete" = "Drupal\email_confirm_redirect\Form\RedirectDeleteForm",
 *     },
 *     "access" = "Drupal\email_confirm_redirect\RedirectAccessControlHandler",
 *   },
 *   list_cache_contexts = { "user" },
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "title",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode",
 *     "admin_name" = "admin_name",
 *   },
 *   links = {
 *     "edit-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/edit",
 *     "delete-form" = "/admin/email_confirm_redirect/{email_confirm_redirect_entity}/delete",
 *     "collection" = "/admin/structure/email_confirm_redirect/list"
 *   },
 * )
 */

This is the code I am using.

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

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

  $fields['langcode'] = BaseFieldDefinition::create('language')
    ->setLabel(t('Language'))
    ->setTranslatable(true)
    ->setDescription(t('The redirect language code.'))
    ->setDisplayOptions('form', array('type' => 'language_select', 'weight' => 2));

  $fields['admin_name'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Administrative Name'))
    ->setDescription(t('The name for the redirect (shown just in admin)'))
    ->setRequired(TRUE)
    ->setSettings(['max_length' => 255, 'text_processing' => 0])
    ->setDefaultValue(NULL)
    ->setDisplayOptions('form', ['type' => 'string_textfield', 'weight' => -5])
    ->setDisplayConfigurable('form', FALSE)
    ->setDisplayConfigurable('view', FALSE);
}

I also don't see the language selector on the edit/add form.

I had to set the fieldWidget to hidden.

 //langcode
        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language'))
            ->setTranslatable(true)
            ->setDescription(t('The redirect language code.'))
            ->setDisplayOptions('form', array(
                'type' => 'language_select',
                'weight' => 2,
            ));

Also I used Drupal's language configuration settings to enable the multilanguage feature for the entity.

The only missing bit is the language translation interface that you can use with nodes.


Disqus not showing on panel page only (panel set as homepage) Version Disqus 7.x-1.12
Drupal 7.38
Disqus is only not showing on my panel page. On all the other pages, Disqus is shown. It has shown before on the same panel. I wish I knew all the things I did between the last time it appeared and when I noticed, but I don't.

Things I tried to no avail:

in the configuration settings (admin/config/services/disqus)

I tried adding the block into a region
* Visiblity-    All node types selected; Location: Block
* Default options- All node types selected
* Behaviour- Localisation support: unchecked; Inherit User Credentials: checked
* Advanced- User Access Token: correct value; Public Key: correct value: Secret Key: correct value;
Visibility also set it to content area and weight tried 0, 50, 100, -100

Drupal Issue 1159690:

Doesn't correlate entirely to my issue because the HTML seems to be there (and not with me), but I suppose it was worth trying some ideas still.

Comment #9 insert <?php
print render($content['disqus']);
?> into template

Comment #60 suggest to simply hit save again on said configuration page and somehow that would be all it took.

Drupal issue 928354

About panels integration. Patch at comment #17 no worky.

panel config:

Tried inserting the disQus block in every possible region of my Panel to no avail.

I also tried this (as mentioned in above issue  )

  #
  in /admin/settings/disqus underneath the Visibility section, choose the Block option in the Location dropdown menu.

  Then you just select the "Disqus Comments" block from within the panels interface under the Miscellaneous tab.

On my panel page, when I do a dpm() of $node inside of the node.tpl.php file, there are 2 node objects in my Krumo. In each object there actually is an array for Diqus. This makes sense, because it is Disqus applied to the nodes inside of the panel. These comments don't show either though, but I don't want them to of course. I want 1 Disqus applied to my panel obviously instead.

Blocks configuration

I put the Disqus comments block in different regions of my theme, still same problem: showing up in other regions

Tried activating a different theme, same problem: Disqus shows on every page except the panel.

Updated the module to 7.x-1.12+5-dev, flushed cashes. Nothing changed.

A workaround I found in this comment #5 out of the Disqus issuequeue adding disqus on the frontend.

    function HOOK_preprocess_page(&$vars) {
  if (module_exists('disqus')) {
    $identifier = $_GET['q'];
    if (strstr($identifier, 'path/to/add/comments/to')) {
      $domain = variable_get('disqus_domain', ''); // A.K.A. short name
      $url = url($_GET['q'], array('absolute' => true));
      $title = drupal_get_title();
      drupal_add_js(drupal_get_path('module', 'disqus') . '/disqus.js');
      drupal_add_js(array('disqus' => array('domain' => $domain, 'url' => $url, 'title' => $title, 'identifier' => $identifier)), 'setting'); // Add to the Drupal.settings for the script above to be able to pick it up.
      // Add the div to the page for the Disqus embed script to be able to drop in the comments code dynamically.
      $vars['page']['content']['system_main']['main']['#markup'] .= '

';
    }
  }
}

Still curious about what it is in the backend that made the comment box disappear below the Panel though. I also disabled all the modules apart from the Disqus, panel en core, but still nothing.


How to override content_type "Article"? I want to add some fields (programmatically from my module) to the content_type "Article".

Is that possible ?

Use hook_entity_bundle_field_info()

Copying from the api docs

function mymodule_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = array();
    $fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    return $fields;
  }
}


Views exposed filter and non latin characters I have a combined text box exposed filter of a view. Is there any way that I can alter the keywords used by the user to convert non-latin characters to latin using hook_views_query_alter?

Transliteration module has some useful functions to convert unicode strings into latin strings. You may give it a try and use some of those functions in your alter hooks. I cannot give you a specific function name but I'm sure that I've used this module for a similar purpose.

Anyway, if you work with non-latin languages, you'll probably need to install this module for other purposes, like fixing the filenames and url parts generated by user input etc.

A quick look-up into the source code of Transliteration module, I can say that you can use transliteration_get() function to transliterate a give string. A sample implementation for your case would be:

function YOUR_MODULE_views_query_alter(&$view, &$query) {
  // To debug comment out the following line (Devel module is required).
  //dpm($query);

  if ($view->name = 'YOUR_VIEW' && !empty($view->exposed_raw_input['YOUR_FIELD']) {
    $transliterated = transliteration_get($view->exposed_raw_input['YOUR_FIELD']);
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on your field, change the
        // condition value to the transliterated string.
        if ($condition['field'] == 'YOUR FIELD') {
          $condition['value'] = $transliterated;
        }
      }
    }
  }
}


Should I create a reference field or a third content type to represent a many-to-many relationship? I have a student table and a course table that have a many-to-many relationship (a student can take many courses, and a course can be taken by many students).

If I am implementing the above data model as a database, I would create a third table to represent the many-to-many relationship.

But I want to implement the above data model in Drupal 8. I think that in Drupal 8 there are two ways to implement the above data model:

I can create a reference field in one of the two content types
(student or course) that points to the other content type.
I can create a third content type that have two reference fields
that points to the student and course content types.

Am I correct that these two ways are valid? And if I am correct, which one should I choose?

I know you won't like this answer but in general it depends:

What are your use cases when adding a new relationship? Is it more likely to add classes via students or the other way around? Or is it a migration process?

If UI is heavily used by both of the entites, I would give reference fields to both content types, and always update the other type reference field upon saving one type.

If this is more like for listing stuff (without editing on the UI these properties) and the information is coming from a big relationship list, then I would store it in a key-value table or a custom table.


"Add another item" button before field I'm trying to place "Add new item" button before the unlimited values field. Also two buttons un top and below field will work. In custom module added new button but it brakes AJAX call for both buttons. This is needed for Field collection field but I doubt it matters. This is how I've tried to build second button:

    $form['field_fieldname']['add_more2'] = array(
    '#type' => 'submit',
    '#name' => 'field_fieldname_add_more',
    '#value' => t('Add another item'),
    '#submit' => array('field_add_more_submit'),
    '#ajax' => array('callback'=>'field_add_more_js','wrapper'=>'field-fieldname-add-more-wrapper','effect'=>'fade',),
    '#limit_validation_errors' => array(array('field_fieldname','und')),
    '#attributes' => array('class'=>array('field-add-more-submit'))
  );

The function theme_field_multiple_value_form($variables) is used (by default) to generate the HTML for the multi-value field. In this function the 'Add another item' button is hardcoded after the table:

$output = '
';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
$output .= '
' . drupal_render($add_more_button) . '
';
$output .= '
';

So, what you could do is override the theme function, and print the rendering of '$add_more_button' before the rendering of the table.

As a side note: if you want to override the theme function using a custom module, you could use hook_theme_registry_alter(&$theme_registry) and set $theme_registry['field_multiple_value_form']['function'] to your customized "theme" function.


Variable created in hook_preprocess_node is not available to template I have this preprocess function in my theme:

function hotness_preprocess_node(&$vars) {
  $node = empty($vars['node']) ? FALSE : $vars['node'];
  $vars['hotness_is_article_page'] = ($node && node_is_page($node) && $node->type == 'spot') ? TRUE : FALSE;
}

The other stuff I do here (not shown) works fine. However, I get an undefined error when I try to use $hotness_is_article_page in my theme tpl files (specifically region--branding.tpl.php). I am using Omega, if that matters.

For some reason I only seem to be able to create variables accessible in tpl files in my hotness_preprocess() function, but not page or node hooks. This is not ideal, as hotness_preprocess() runs several times per page load.

What am I doing wrong?

The variables added from hook_preprocess_node() are only available in node.tpl.php, or any other node template that Drupal will pick up because any suggestion contained in $variables['theme_hook_suggestions'] (Drupal 7), or $variables['template_files'] (Drupal 6).

To add a variable used by a region template file, you need to use a different preprocess function: hook_preprocess_region(), or hook_preprocess(). The latter is a generic preprocess function; the second parameter passed to that preprocess function tells it which theme hook is going to be preprocessed.

This means that, by default, the region preprocess function doesn't have access to $variables['node']; if you want to access the node object associated with the page being viewed, if there is one, you need to use similar code used in template_preprocess_page() and add the following line to your preprocess function:

if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

The function returns FALSE if the page is not associated with a node; this could happen, for example, if the user is visiting example.com/user/1.


How to expose votings (such as in rate or voting api) to views? To avoid the obvious misunderstandings: I know how to display the rate widget in a view, including the vote cast by the user, the average, sum etc. This is not what I'm looking for.

I want a view whose rows are the individual votes cast, with fields containing the information who cast the vote and what it was cast on and how much the rating was. When I create a new view, I can't select this kind of entity.
How can it be done, preferably without code? (If at all)

Alright, I found a workaround by accident.
Just add a new view that queries for the node bundle that the vote is attached to. No go to "Advanced" and add a relationship to "Rate" such that the relationship is required and not restricted to the current user. Don't apply any averaging or summing. Like that, it will spit out every node several times, once for every vote cast.


How to set Navbar to be a sidebar by default? Drupal 7's Navbar module is:

In wide windows, a bar across the top, with no dropdowns, just links to main sections like Content, Structure etc
In medium-width and narrow windows, a sidebar or dropdown menu, with accordion-style dropdowns allowing primary menu items to be expanded and secondary menu items shown without leaving the page.

I want to give users the sidebar view, even on wide screen devices, so they can use the secondary menu dropdowns it offers.

I want it to look like this when the menu is chosen, even in wide devices, similar to the old Admin module:

I can't find any way to do this within Navbar. What's the simplest way to do this, with minimal hacking to the Navbar module or hard-coded overrides?

I found a way to do this in a very simple custom module without any hacking or patching to Navbar code.

Just create and enable a custom module that contains (assuming your module is called custom):

/**
 * Implements hook_navbar_breakpoints_alter().
 *
 * Nullifies the breakpoint that switches the navbar to horizontal orientation
 */

function custom_navbar_breakpoints_alter( &$data ) {
    $data["wide"] = "not all";
}

The navbar module defines a hook, hook_navbar_breakpoints_alter, using drupal_alter, that allows its hard-coded breakpoints to be overwritten.

not all seems to me the cleanest and most intuitive way to implement an impossible media query condition (related: How to set a media query condition that is never met?).

This makes the switchable horizontal masthead view of the navbar menu, quite literally, the default on not any device.


Adding a new token to a product I'm trying to add a token to Product using the below code. The problem is that, although this adds the token I'm after, it also removes a number of standard tokens that are needed (e.g., the title).

/**
 * Implements hook_token_info().
 */
function fw_product_token_info() {

  $type = [
    'name' => 'Product',
    'description' => t('Useful additional tokens for products'),
    'needs-data' => 'commerce_product',
  ];

  $tokens['fw_product_parent_url'] = [
      'name' => t('Parent URL'),
      'description' => t('The full path to this product\'s parent'),
  ];

  return [
    'types' => ['commerce_product' => $type],
    'tokens' => ['commerce_product' => $tokens],
  ];

}

/**
 * Implements hook_tokens().
 */
function fw_product_tokens($type, $tokens, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'commerce_product' && !empty($data['commerce_product'])) {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'fw_product_parent_url':
          $entity = $data['commerce_product'];
          if ($parent_entity = \Drupal::service('fw_product.parent')->getEntity($entity)) {
            $replacements[$original] = $parent_entity->url('canonical');
          }
          else {
            $replacements[$original] = '';
          }
          break;
      }
    }
  }
  return $replacements;
}

Return 'tokens' if you want to add new/custom to the existing list.

return [
  'tokens' => ['commerce_product' => $tokens],
];


What is hook_menu_alter used for? In simple terms, what is hook_menu_alter for? I understand callbacks in general, but I'm not quite sure if this method is misnamed in a sense, as I see it used in the context of permissions rather than menus. I'm probably just confused.

I think that your confusion comes from the fact that Drupal 6 and 7 mixes menu and routing. One set of hooks for both purposes, and here you have problems. If this hook was named hook_route_alter(), using it to alter permissions to some routes would be obvious, right? So that's what modules do, using the name they got. Personally I agree it's not most lucky naming, but once you remember that in this context, basically, menu == routing, it all becomes much more intuitive.


Views and Filtering Data not getting results I have created a view to grab all of the invoices in a system, which it does. I have two types of invoices either payable or receivable. I have two filters to start with Published Content = Yes and Content Type = Invoice. I want to be able to filter this on the invoice type so only receivable invoices show up on the view.

I have added another filter that says content type = invoice type but when I do that I get no results at all.

If I leave off the content = invoice type I get all of the invoices. How can I create a filter that will pass the invoice type to the view so I only get the receivable invoice for this particular view.

Create a relationship to the invoice type content type in the view and then add filter for the status field of invoice type taking relation ship when adding the field in the filter.

Relationship can be found under the Advanced section of the view. Pick the suitable Entity Reference for the relationship to invoice type here and add the relationship.

After that if you add the status field to the filter options you have the option to use the relationship for that field.


Can I safely delete the migrate tables after migration? I passed a site from d7 to d8
I wanted to know if I can delete tables db migrate map d7 and migrate messages d7
they are more than a hundred
I can delete db tables migrate map d7 and migrate d7 messages of types of content that no longer exist on d8?

http://fortecad.altervista.org/ottomigratemapImmagine.jpg

http://fortecad.altervista.org/ottomigratemessaggeImmagine.jpg

regards

Yes. If you're doing a "one-and-done" migration you can remove the tables. Just make sure to:

uninstall the migration modules
remove your relevant migration config
then remove your DB tables once you have no code/config dependant on these tables.

Note, the caveat is you're wiping out your migration history.

The migration framework has an ongoing issue about this topic. These tables are persisted since these they capture migration source/destination metadata. The metadata is important if you have a phased, or ongoing, migration. If your migration project is over, the metadata has no relevance.


Removing /Drupal from the URL-path I know this question has been asked many times for the past versions of Drupal, but none of the solutions I've found works for Drupal 7.12.

I used to have an .htaccess file placed inside the document folder alongside with Drupal, and it partially worked on older versions when entering the front- and live-page of my website (which you can now only enter via "default-URL").
For reference, you were able to to enter the live page with http://pavescorner.com/live,
but after the patch and some other maintenances on my website, the link has to be like this http://pavescorner.com/drupal/live.

During those tests, when I tried to make another working .htaccess file, I accidentally destroyed the version working for me, and now you can only enter my homepage with the /drupal subdirectory.

What should I put in my .htaccess file so that /drupal doesn't appear in the URLs for my site?

Using mod_rewrite within .htaccess, in your server's document root. Untested, but something like this should work.

# Enable from .htaccess
RewriteEngine On
Options +FollowSymLinks
# For all URLs not starting with drupal
RewriteCond %{REQUEST_URI} !^/drupal
# Serve the same content from the /drupal directory instead
RewriteRule ^/(.*) http://pavescorner.com/drupal/$1


Up to how many nodes Drupal can handle without affecting performance? Is there a kind of known number of nodes Drupal can handle without visible performance down?

I suppose the more nodes we have on a site the slower it will load pages. However does it matter if the number of the nodes is like a couple of thousands?

It very much depends on your hosting and server configuration.

For example one of the projects I worked on handled without performance issues about 10 millions of nodes. But it lived on a cluster of 4 dual-core servers with lots of memory on each, and the cluster was behind load balancer and reverse proxy caching (Varnish).

On another project I had performance issues after something like 1000 of nodes, that was a shared hosting.


How to keep showing Administration menu when changing user? I'm using the Administration menu, like thousands of others. I recently discovered that one can change from user by hoovering over the red "hello user" button at the right. It's a nice feature, but I was wondering if it's possible to keep showing the toolbar when one changes from user (even when that user doesn't have permission to use it) in order to be able to switch back to administrator quickly. When I, as an administrator, would like to see how the page looks like for another user, I now always have to log in again as administrator - quite time consuming.

Any suggestions?

There is the Masquerade module for seeing how a page looks like for another user https://drupal.org/project/masquerade.

Another way is to duplicate your tab in incoqnito tab or in another browser and become another user there.

Third way is to make sure (if possible) your browser remembers user names and passwords on login forms. Then logging in as administrator is as easy as typing the first letter to the username field and pressing enter. This is less cool of course...


Drupal field that get db content How can I make a drupal field that gets a value from a specific database/table, it should be a select list. What I need is to have a drop down select where I can see all entries from a specific content on the drupal system. So I have content type A, and content type B. When I want to create a new content of type B I want a select box where all entries from content A are listed.

This sounds like something you can handle pretty easily with a couple of contrib modules:

If you don't already have them install Views and Entity Reference.
Add a View of type "Content", filtered by content type B. Call it something like "All type B content".
Add an "Entity Reference" display to the new View.
Add any sorting/filtering options and change the display field if required.
Repeat steps 2-4 for a new view called "All type A content", and filter by content type A instead.
Add a new field to content type A of type "Entity Reference".
On the field settings page under "Entity Selection" choose Views: filter by an entity reference view for the mode, choose the "All type B content" View, and save the rest of the field config as normal.
Repeat steps 6-8 for content type B, choosing the "All type A content" View instead.

That should get you exactly what you're looking for, with the added benefit of being able to customise the results easily with Views.


Showing list of nodes related to logged in user using views I have some content of content-type "mockup". The "mockup" content-type has a field that references a user (so when I create a mockup, I can select a user for it to "belong" to).

For some reason, I can't figure out how to use views to get all "mockups" that belong to the logged in user. I thought it would be in "contextual" but I don't see anything like that.

I don't want anyone to be able to view the node unless they are the "related user", is this a "views" thing or a "permissions" thing?

I'm not sure about the details of your use case, but it might be easier to set the author of the node to the user rather than setting up a field with a reference.

You can set the author manually if you have administrator permissions.  You could also use the Rules module (via the "Set a data value" action) to do so automatically.

If you use this method, you can simply set the permissions for "View own content of type ABC" and "View all content of type ABC" that are provided by default to limit access.

For your view, you can add a "Contextual filter" of "Author".


TinyIMCE not working: looking for image files TinyIMCE is not working: At Hostgator, I cannot access the images that I know are in there (at sites/default/files/field/image and at sites/default/files/pictures). In the text editor, I select the image-add icon (the tree). I select image url icon. The dialog box is limited to showing sites/default/files. It does not allow access to /field/image or /pictures/ The "insert image button at top right is missing (but it exists on my local server.)

I have uninstalled and reinstalled the wysiwyg and imce modules. I have checked permissions. I have made certain the files are in the places noted.

I believe the image component of TinyMCE is a licensed product you have to buy, see http://www.tinymce.com/download/download.php at bottom. You might want to try IMCE module http://drupal.org/project/imce which is free and integrates nicely with the WYSIWIG interface. If you do decide to go that route, afteryou install IMCE make sure you turn on the check box for IMCE in the TinyMCE options inside the WYSIWIG Admin Tab in Admin -> Configuration. Works like a charm for me.


share users or nodes across multiple sites without sharing database I have one master drupal site that offers basic functionality for users.(it's a shop); and we have some other sites, for example one news site, one marketplace, one job finding service etc. I want every "spin off" site be a separate site, but users sign up once, then login on each subsite without needing to sign up again. and I want to show nodes of subsites at master site in the user profile. which is the best way of sharing users and contents, since domain access module is not a good option, because we are going to produce lots of data and keeping all data in one database is hard. we want to be able to separate any high traffic spin off in the future, but with domain access, all should be at one database.
what options do I have for sharing users and contents without sharing database?

what I mean is someting like stackexchange that there is no need to sign up anytime. is it possible to do that with OpenID or OAUTH etc?

I tried almost every possible scenarios,

The best thing for me was use of Oauth2 server module for master site to act as authentication server and OpenID Connect module for other sites which use out-of-box authentication.

This solution can be done without needing to merge databases, or host sites on same server, or periodic synchronization. the only challenge I have is that authentication server must use https, and I'm going to buy certificate for my host.


Programmatically update a field's value I want to update a node field's value when a node is updated.

Tried using the code mentioned here Programmatically updating a node Drupal 8

use Drupal\node\Entity\Node;

    function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

      $check = \Drupal::routeMatch()->getParameter('node');

      if ($check) {
      $node = Node::load($check->nid->value);
      $node->title->value = 'testing';     //set value for field
      $node->save();
      }
    }

but it did not work. I get a 500 error after saving the node. I also tried taking out the if statement and specifying a node id $node = Node::load(1);

I also tried using Update a node / Entity programmatically in Drupal 8

use Drupal\node\Entity\Node;

function hello_world_node_update(Drupal\node\NodeInterface $node) {

$node = Node::load(1);
$node->set("title", 'New value'); // also tried $node->setTitle('The new Title');
$node->save();

}

but no luck either.

In addition, I tried using different hooks entity_presave, entity_update, node_update, but did not make any difference.

You can try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('new Title');
  $node->set('body', 'this is body');
}


don't allow multiple users with same email I've got a site using Commerce. On checkout a user is created to allow access to files, order history etc.

I just had a customer that couldn't find his files and discovered that he had two accounts registered to the same email address. So it seems my system isn't checking for accounts already registered to the same email address.

How can I make sure that

There's only registered an account in the event that the email used
for the order haven't been used on the site before?
If the email has been used before the new order is attributed to the
existing user?

Edit

After reading @Neograph734's answer below I checked my rules. And they look right to my eyes, so I'm a bit confused as to what can cause this:

Weight 1: Assign an anonymous order to a pre-existing user

Weight 2: Create a new account for an anonymous order

Drupal by default does not allow multiple users with the same email if you try to create them through Drupal forms. If users are created by code this check is not performed.

My best guess it, that this caused by one of the rules Drupal commerce ships with. Specifically the "Create a new account for an anonymous order" rule. This rule fires when a user who is not logged-in completes checkout. It should check if the email is already registered, but might have been altered.
Alternatively you might have a similar rule created yourself or by a module that does not check if the e-mail is already existing.

Most of Drupal commerce's behavior is controllable by rules, so I'd start looking there for rules that create users.


Once function not preventing behavior executing on AJAX update I am attempting to disable 2 inputs within the Views exposed filter form upon initial page load.  However I don't want this to happen after the filter form is autosubmitted.  I have the following code, but it runs every time the filters are autosubmitted.

(function ($){

Drupal.behaviors.ios2 = {
    attach: function (context, settings) {

        $('#edit-arrival-date-datepicker-popup-1, #edit-departure-date-datepicker-popup-1', context).once('disable-dates', function(){
            console.info('Disable em once');
            $(this).attr('disabled', true);
        });
    }
};

})(jQuery);

After the initial page load I can see the disable-dates-processed class on the input in question, but the filter autosubmit causes the attribute change to run again.

What is it that I'm getting wrong ?

The once method is a simple beast - it checks for a class of NAME-processed on the element (NAME being the string arg you pass it). If it doesn't find that class, it assumes this is the first execution; it runs the function, and adds the class to the element. When the code executes again, the class is there, so it doesn't run the function.

When your behaviour executes first time, there's no -processed class on the elements, so it gets added and your function executes. Everything's happy...

Then an AJAX call happens, and the textfields get replaced; they no longer have the -processed class on them, since they're new elements received from the from builder function, and once has no option but to start from scratch again, running the function and adding the class to the new elements.

2 ways you could solve this:

Keep using behaviours, and use your own flag:

(function ($) {
  var processed = false;

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      if (!processed) {
        $('#edit-arrival-date-datepicker-popup-1, #edit-departure-date-datepicker-popup-1', context).attr('disabled', true);
        processed = true;
    }
  };

})(jQuery);

Conclude that behaviours aren't appropriate for this particular op, and stick with jQuery.ready


How to load a file during the load of drupal 8 bootstrap (hook_init) I want to make something that in Drupal 7 can easily be done with hook_init, but this hook doesn't exists in Drupal 8.

I want to load an .env file and at the same time load the dotenv file from vendor.

I'm trying with EventSubscriber as it's plain here: https://www.drupal.org/node/2013014, but I'm not sure if this the good way.

I think that you actually already har answered your own question.
EventSubscribers is the way we do it in Drupal 8, so it might be right what you are trying to do.


Display views result from a certain entry on I have a ranking list on my Drupal site (Database output sorted by points, and I assign a rank via the field "Global: View result counter"). Now, displaying the entire ranking list is no problem. But I would also like to add a view where a user can find himself in this ranking list and see the list from his position on (i.e. himself and then all users with lower points). Any idea how I could do this? Filters are not suitable, as they retrieve only a selection of the original ranking list from the database, hence the rank does not match anymore...

Thanks for your help!

Tobias

As far as I can tell, you have no choice right now but to write a simple custom module which would use the current user name and output themed results of a corresponding query.

Though of course it would be nice to be able to use the Views UI in this, so I understand that perhaps this is not the best solution for you.


Convert integer retrieved from node field to uid? I've created a rule that sends a push notification to a specific user when a certain content type node is published. That said, in order to specify which user receives the notification, the 'Send Push Notification to Specific User' rule requires that I type in an existing uid.

That said, I've pulled an integer from a content type field, and I want to set that integer as the uid to send the notification to (as the user receiving a notification changes often). Naturally, Drupal won't let me do that, even after I convert the retrieved string (numeral, e.g. 7) to an integer.

Is it possible to achieve this? I'm stumped.

You have to fetch the User entity by ID using the value from the content type field without any conversion.
Then in the "Send Push Notification to Specific User" rule, you can use the ID from the fetched entity.
Not sure why you can't use the variable directly, but this is the case.


How to delete a file attachment from the apachesolr index My file attachments are indexed using apachesolr attachments 7.x-1.x-dev. I have a custom module that physically deletes a file using file_delete(), but file still remains in Apachesolr index even after re-indexing. The only way to remove from search results is to delete the index then reindex.

I tried this to no avail:

// Remove file from apachesolr index
$env_id = apachesolr_default_environment();
$entity_type = 'file';
$entity_id = apachesolr_document_id($file->fid, 'file');
apachesolr_remove_entity($env_id, $entity_type, $entity_id);
drupal_set_message('Deleting '.$file->uri.' from private attachments.');
file_delete($file);

The file is physically removed, but not removed from index.

Any suggestions on how to remove file from apachesolr attachments index/search results after it is deleted?

From Dileno blog:

If you simply want to delete documents from your Solr index by using the web interface, here's a code snippet that lets you do so:

http://localhost:8983/solr/update?stream.body=
<delete><query>id:298253</query></delete>&commit=true

This lets you delete documents where the id field matches 298253.

If you want to delete items that matches more than one field, just add another query:

http://localhost:8983/solr/update?stream.body=
<delete><query>id:298253</query>
<query>entitytype:BlogEntry</query></delete>&commit=true


Limit Migrate explode process plugin to 1 takes whole string I have a csv places column with values like that:

Madrid|Spain
Barcelona|Spain

I want to migrate this places to a custom taxonomy and 3 terms (Madrid, Spain, Barcelona) get generated doing it like that:

  field_taxonomy_places:
    -
      plugin: explode
      source: places
      delimiter: '|'
    -
      plugin: entity_generate

But actually I only want to create cities (Madrid, Barcelona), but not countries. So I try to take the first value till the delimiter like that:

field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 1
      delimiter: '|'
    -
      plugin: entity_generate

The problem is that now 2 terms get generated (Madrid|Spain, Barcelona|Spain).

Just found the solution after rereading the PHP explode docs:

  If limit is set and positive, the returned array will contain a
  maximum of limit elements with the last element containing the rest of
  string.

So setting the limit to 1 has the effect that the returned array element contains the rest of the string, which in my case is the whole string. So setting the limit to 2 fixes the problem and gives back the first part of the string:

field_taxonomy_places:
    -
      plugin: explode
      source: places
      limit: 2
      delimiter: '|'
    -
      plugin: entity_generate


Textarea not populating with previous value So I have been buildign a simple form used to populate a block on the sidebar of my drupal 7 site. However I have run into a problem, the textarea on this form does not seem to populate with the sidebars previous value.

What has me stumped is that a textfield with the same defaultvalue code populates correctly.

//a debug textfield that works
$form['debug'] = array(
    '#type'        => 'textfield'
       ,'#title'       => 'Debug'
       ,'#default_value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
       ,'#description' => t('Please enter a suitable heading for the left sidebar.')
     );

//the broken textarea
 $form['body'] = array(
        '#type' => 'textarea'
        ,'#title' => t('Body')
        ,'#rows' => 15
        ,'#description'   => t('Body text for sidebar')
        ,'#value' => $sidebar_content[$key] ? $sidebar_content[$key] : ''
    );

Edit: After disabling WYSIWYG the text area started populating again. More digging revealed the reason it wasn't populating as a rich text box was because when an editor is used it submits the value as an array with two items; value and format. Consequently, this meant that the text editor was being given an array to display rather than a string.

Altering the #default_value to $sidebar_content[$key]['value'] resolved this issue.


How to do incremental cron? I have to manage a rather large site which has problem with cron (white space of death on cron.php and 'segmentation fault' in drush). I could not fix the ong standing problem. Someone has suggested to do the cron job in several steps whcih can also hopefully pinpoint the problematic tables. I am wondering how to do the incremental cron and appreciate your help.

Have a look at Elysia cron.

That module allows you to configure each cron hook implementation separately and it allows provides you with information about how long each mean/max execution time of those hooks.


How to Give abilty to filter content by geography, separate from language? I'm not sure if this is feasible, or how to go about it. I want a dropdown (and use IP detection) to provide users with content based on Region - Not Language. Because we will Also be using the normal Language functionality in Drupal 8 to provide translated content, if they choose to read it in another language. Because languages and countries are not synonymous.

I want the same functionality that's in language filtering, where a user can select "Spain" from a dropdown field and they get page content and blocks that are related to the region. Then, if they desire, also an ability to filter by language.

Here's a scenario:

User, in the U.S., goes to Website.com
They see content that is related to the general global market, in English because they were auto-detected as a U.S. based IP.
User chooses Sweden from the dropdown. Page reloads as
Website.com/Sweden/English (or maybe just website.com/Sweden ?)
Now home page reloads the page, with content specific to Sweden. Similar to how language filters.. but filtered BY COUNTRY.
Now, the user DOES want to change the language. They choose Swedish from a second "language" dropdown on the page, and the home page reloads again with Sweden-related content, translated into Swedish, with this url.
website.com/Sweden/Swedish

Any thoughts on this? I know the language modules can do half of this, but how do I also provide a way for the user to view site content by region. I know views can do some of this, but I'm not sure Views is the appropriate way to present the Entire website.

Maybe someone can clear my head on this.

This is a really broad and quite opinion-based request. But what I'd suggest is you completely keep Drupal's core internationalization functionality and just add languages including their region subtag:

es-AR
es-ES
es-MX
...

You then can decide to use just the region as their label, which will then be displayed by the built-in language switcher.

A really positive side effect of this is you'd already have your content optimized for SEO pretty well (given that the region specific content actually are translations of each other).

Resources

https://www.w3.org/International/articles/language-tags/
http://www.lingoes.net/en/translator/langcode.htm

Another approach would be to just go for one Drupal language and instead introduce a new field "Region" or "Country" to the node type you need this filtering for and build your own View with filters to display nodes or teasers of nodes matching the selected country or region.


Add bulk products drupal commerce: Warning: Invalid argument supplied for foreach() en form_type_checkboxes_value() line 2337 form.inc I am workin on a commerce site and every product has many attributes and there are many combinations for each display. I am using Commerce Bulk Product Creation so I can add products quicly. The problem is that when I try to add many products in one shoot using this module I have a white screen and The warnng is:
Warning: Invalid argument supplied for foreach() in form_type_checkboxes_value() (lne 2337 de xxx/includes/form.inc).
Any help would be great.

The problem was because I am creating too many products at once. Not supported by the database or the hosting. It colapses and the foreach sends the warning. The result was a white screen.


How can I change the page title for user/login for unauthenticated users? In D7, we need to modify the page title for the user login page (shown when users have not yet authenticated).

The default value is 'User account', and it is set in 'user.module' line 1965:
    return user_is_logged_in() ? t('My account') : t('User account');

It appears as the page title for the paths:
  user/register
  user/password
  user/login

This is how it is eventually rendered:
    User Account

To override the value for an authenticated user, we can simply implement

function MODULE_username_alter(&$name, $account) {
 $name = 'New Name!';
}

But how to override that value for unauthenticated users?

It seems like it should be done in THEME_preprocess, but I can't seem to find the attribute to set.

I implemented page--user--login.tpl.php, and see there that it is somehow part of $page['content'], but can't find the attribute to set.

You have alot of good information there (seriously). What you want to do is probably use hook_form_FORM_ID_alter() on the user form.

You want to set the #title attribute of the form element for the name element of the login form.

Some example code:

function MYMODULE_user_login_form_alter(&$form, &$form_state) {
  $form['name']['#title'] = 'Your Nickname:';
}

You'll probably want to check that a user is not logged in yet with something like user_is_logged_in() or your own custom logic.


Using hook_entity_base_field_info for adding new field Is it fine to implement hook_entity_base_field_info to add a new field to the advanced group in each node?

If so, how is the storage handled by default for base fields? Should I need to create a schema to store the field value.

As said in the other answer, the entity storage internally handles the schema.

Here is an explanation for it, taken from the documentation

  If your field doesn't have any special requirements Entity Field API
  can take care of the database storage and update the database schemas
  accordingly. This is the default for fields that are not marked as
  being a computed field (setComputed(TRUE)), or has specifically
  indicated to provide its own field storage (setCustomStorage(TRUE)).

Say you want to add a new base field to all Node entities that contains a simple boolean value to indicate whether the content is "highlighted".

<?php
/**
 * Implements hook_entity_base_field_info().
 */
function MYMODULE_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();

  // Add a 'Highlight' base field to all node types.
  if ($entity_type->id() === 'node') {
    $fields['highlight'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Highlight'))
      ->setDescription(t('Whether or not the node is highlighted.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
      ))
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}
?>

Now all it takes is to visit update.php to run the database updates,
   and an additional 'highlight' column will be added to the tables
   holding the node data.

To run this database update automatically when your custom module is
   enabled or disabled, you can trigger it by executing the event
   listeners that are responsible for performing these updates in your
   hook_install() and hook_uninstall() implementations:

<?php
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create field storage for the 'Highlight' base field.
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionCreate($definition);
}

/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getLastInstalledFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionDelete($definition);
}
?>


Is multistep checkout supported? I am wondering if Drupal 7 commerce support the multistep checkout via hook or contrib modules, the target was I have products that is subscription based and once user select lets say product a before he can add to cart he needs to select how many months of subscription he wants after selecting that he can then press the select plan then move to another page to select attributes of the product items that is limited to 2 option or more then after he select and continue he will be on the page of customer info and last step was payment,

So basically it's a 4 page process.

Is this achievable? Can I setup the product types to accommodate subscriptions, with attributes?

going to post answers to help people that is having the same issue, I used one of this modules to help me fix the issue I am having :

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

hope this can help someone :)


How to add warning message before module is uninstalled The module in question has a content entity, entity1, that has another content entity, entity2, that depends on entity1. I would like to add a warning before uninstall of the module if there are currently entity2's that exist and that depend on entity1. The warning will suggest to delete the entity2 and then entity1 before the module can be uninstalled. How could I do this?

Before a module is uninstalled, Drupal invokes all the services implementing UninstallValidatorInterface and tagged with module_install.uninstall_validator. Their validate() method (see BookUninstallValidator::validate(), for example) returns an array of strings explaining why the module cannot be uninstalled, which are then shown in the user interface.

Notice that the validate() method receives the name of the module as parameter. While normally the module implementing the UninstallValidatorInterface service checks if itself can be uninstalled, a UninstallValidatorInterface service can avoid any module is uninstalled.

In Drupal 7, there isn't anything similar. The only way to achieve this is altering the page showing the list of the installed modules to show a message near a module.


"OR" condition in db_select() I am studying the new database layer, and I am glad it is changed to an OOP layer. I need to implement a query with db_select(). I found I can add a WHERE statement with $query->condition(), but by default the conditions are AND'ed together.

How can I OR the conditions together?

$query=db_select('users','u')->fields('u',array('uid','title','created','uid'));
$query->join('flag_content','fc' , 'u.uid = fc.content_id');
$query->condition('fc.fid', '5' , '=');
$query->condition('fc.uid', $uid , '=');
//…

That's not correct, the default is AND. To use or, you need to use:

$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

But the main conditions on the query are definitely joined with AND.


d8 preprocess commerce product entity Where can i alter commerce product twig template variables?
When i display commerce product mymodule_preprocess and mymodule_preprocess_entity never called.

Doesn't exist mymodule_preprocess_node(&variables) for commerce product entity?

Thanks
Fabio

You can use hook_preprocess_commerce_product like so:

function mymodule_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  ...
}


How to print fields value in views-view.html.twig in drupal 8 How to print fields value in views-view.html.twig
I have created a views-view.html.twig file for my view slider_3.
The template name is 'views-view--slider_3.html.twig'
The view formatting is done by this template, but I need a field is come at begging position of the view:

<div class="slider-3-main">{{ rows.required_field }}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if title %}
    {{ title }}
  {% endif %}
  {{ title_suffix }}

How can be the field will written to display at {{ rows.required_field }}

To get a field value of the first result row view.result[0] use the method EntityField::getValue of the view field:

{{ view.field.field_example.getvalue(view.result[0]) }}


Change Standard Title for Adding Content Into Something New? Also Redirect to the Page You Were On? What I have right now is an obituary page, with a listing of obituaries. Clicking on one of those listings takes you to that person's obituary page. There are links on that page for visitors to send their condolences to or make a memorial donation. The links look similar to http://shawnjacksonfuneralhome.simalam.ca/node/add/condolences?field_obit=131 and http://shawnjacksonfuneralhome.simalam.ca/node/add/memorial-donations?field_obit_donation=131. The text after the question mark is there to prepopulate a select list of entity references on the next page.

There are 2 things we are trying to do here. First, we want to change the title from the standard "Create Condolences/Memorial Donations" to something like "Send Condolences to the family of X" where X is the name of the deceased person. I've tried using the drupal set message function to find the value selected in the list.

drupal_set_message("Obit Name:" . print_r($node->field_obit, TRUE) . '');

According to those results, the value of the prepopulated select list should be like this:

$obit_name = $node->field_obit['und'][0]['entity']['title'];

However, it doesn't display anything (either with echo, print, or print render()).

The second thing we are trying to do is after the visitor submits their condolence/donation, we want them to be redirected back to the obituary page they were just on, along with a message thanking them for their actions. I've tried using the Rules Module to redirect and display a message, but it won't do both for some reason. It will not redirect to the previous page, either.

For the dynamic node titles you might want to take a look at Automatic Nodetitles module. It allows you to use tokens in the node title. These token can represent text from node fields.


Why can't I save a Send HTML Email action? I have a rule component set up that currently sends an HTML email. I need to change the body of the email to include a new field, but when I do and press Save, it doesn't return to the Rule page, it just goes to the top of the page and loses the changes I've made.
If I overwrite the HTML with a simple piece of text or a small piece of HTML, it works OK.
I'm wondering if there's some validation going on, but there are no error messages displayed or in the logs. I've validated the html through the W3C Validation Service and cleaned it up so there are only a couple of warnings.
My other thought is that maybe there's some limit that I've hit? The HTML is quite long, as it was generated by an online generator.
I can't include an export of the rule as it's too big for this message.
Any help?
I am using Drupal 7.59 and Rules v7.x-2.10; MimeMail v7.x-1.0. Have tried the latest dev version MimeMail too, but made no difference.

Thanks Pierre for your suggestion. I didn't need to try it, but it makes a lot of sense. Wish I'd have thought of it!

In the end (before I saw your suggestion), I rebuilt the email using a different generator tool, which seemed to produce much smaller and cleaner HTML.
This works OK. It looks like there was either a problem with the HTML or there is some kind of limit on length.


How to show a block on user profile edit page ? I am trying to display a block on an user edit page (example: user/123/edit/custom_url, but for some reason, I can't seem to get it working. Any help is appreciated.

I tried this, but this isn't working:

<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == 'edit' && arg(3) == 'custom_url' ){
  return TRUE;
}
else {
  return FALSE;
}
?>

Using the block ui, you can select the visibility of block using user/*/edit/custom_url. The star is a wild card and will give you the ability to place blocks on pages that have a variable in the path.


How can I modify body class based on non-taxonomy node data? I need to add a custom class to my html <body> tag when certain elements are present in content (namely, either a featured image or image gallery, both of which are added to content using Entity Reference fields in the site's main content types).

Currently I'm accomplishing this using the Context module and a taxonomy vocabulary.  (Condition: Taxonomy; Reaction: Theme HTML).  The workflow for content managers looks like this:

Add an image or gallery to a content item
Don't forget to attach the appropriate taxonomy term so the page lays out correctly.

Oddly enough, forgetting step 2 is a rampant problem.

Any suggestions on methods for eliminating step 2?  It seems like it ought to be possible to just test for the presence of a value in the appropriate fields and either automatically attach the taxonomy term, or skip the taxonomy term and trigger the theme HTML based on the data values themselves.

I should mention that the taxonomy vocabulary in question has NO purpose in my application other than applying the appropriate body class.

I'm open to using some other module to accomplish this.  (Rules?  Couldn't figure out how to make this work either).

(Drupal 7).

You could do this in your theme's template.php. Something like this:

function mytheme_preprocess_html(&$vars) {

  // Load node
  $node = menu_get_object();
  if ($node) {

    // Wrap to fetch field values easily
    $wrapper = entity_metadata_wrapper('node', $node);

    // Check image reference fields and add body class
    if (
      $wrapper->field_featured_image->raw() ||
      $wrapper->field_image_gallery->raw()
    ) {
      $vars['classes_array'][] = 'my-class';
    }
  }
}


How to find a field name/column name of a field in database where I have only the label of that field? I am working on an integration part with drupal framework. Here it's hard to  find the table names of the field which is present in the view as I know only the field label name.

Is there any way to sort this out?

You can derive the database table name by the host entity and the field name. The name schema is ENTITYTYPE__FIELDNAME

Views don't directly show the field name, but you can look at the entity's "Manage field" page to get the field name by label. (e.g. for nodes /admin/structure/types/manage/BUNDLENAME/fields)

Examples:

node__body
node__field_image
users__field_whatsapp
taxonomy_term__field_text

Exception:
Some special fields (like title or created) are stored as a column on the base table of an entity. Base tables follow the schema ENTITYTYPE_field_data, e.g.

node_field_data
users_field_data
taxonomy_term_field_data


Where do I find the "Security code" to test "Commerce PayPal WPP Credit Card" with my "sandbox buyer account" I am on Drupal 7.59 and using Commerce and Commerce PayPal modules.

I am at testing step, using my PayPal sandbox accounts (buyer and facilitator) to check if my PayPal classic and PayPal Credit Card payment methods work fine.

On PayPal classic I used WPS, and it works well
On PayPal Credit Card, I am using WPP, but something is missing somewhere.

About my PayPal WPP Credit Card (2)

All configuration is good, all the API credential that I have is correct. But one is missing : the Security code. In all tutorial I've watched, nobody talks about that field "Security Code". But it is a required field!. Whithout it I can not continue payment process which PayPal CB.

Can't anybody help ?

Just put in any number that matches the card type - e.g. 111 or Visa / Mastercard / Discover or 1111 for American Express. As far as I know, the PayPal API will accept any value. It should just be the card number and expiration date that have to match your sandbox test card details.


How to add an "apply for a job" button to a content type? I am trying to add an apply button to a content type, like job, so when the user visit the content he could click "apply button", and his resume will be send automatically to the author of the content.

I would prefer this be achieved with AJAX. How can I make something like this?

I would do that using Flag module, create a flag named 'Apply' and set it for job content types. You can then use Flag Actions or Rules to send emails.


Transform PDF to image place text on it I am hoping to find a drupal module that can transform a PDF to image and merge that image with another one.
Use case scenario is basically placing an endorsement stamp on an image.

Thanks

It sounds like you want PDF to ImageField.

  The PDF To ImageField module provides automatic conversion of uploaded
  PDF files to images. It can be used either to create a snapshot of the
  front page to use as a preview thumbnail, or to generate a gallery of
  images from each page in the document.

  The module is implemented as an additional widget for File Field where
  PDFs are uploaded to. It places generated images into a Image Field on
  the same content type.

That will get you half way there. As for the 2nd requirement of image merging, you'll likely have to implement your own solution via Drupal's node API/hooks to manipulate the converted PDF image with your stamp.


revert view option is missing I have exported my view, and I want to revert the same in other site environment; the revert view option is missing. Am I missing anything?

I am using Drupal 7 and Views 3.

It should be in "admin/structure/views", click the little arrow next to "edit" link under Operations column. If your view has changed from what's exported in code, it should display "revert" option there.


Views - show only items not in a given nodequeue Is there a way to filter on the value that is in nodequeue? I want to have a top 5 article list nodequeue, but I want a list of articles after that in terms of most recent is highest, except for those given nodequeue items. Is there a way to do this?

Alright the answer is this:

You have to create a relationship with the nodequeue(s) in question that you wish to filter against. You have to make it so that the checkbox, "relationship required" is unchecked - otherwise it will primarily filter all items that are not in the nodequeue.

At this point, this will provide a filter to you termed, "in queue" - set this queue to false.

At this point, all items that are NOT in the nodequeue will be listed.


enable secure site only on certain pages I am sending out user generation emails, but users can not access their one time login because of secure site  from this link i see something about "Bypass Login Filter Page" and an option to set secure site login exceptions on certain pages but I can not find that anywhere.

http://drupal.org/node/98514

I have two options, but there could be more (quotes included are from their project pages):

Secure Pages:

  A small process which will redirect the required pages to a SSL version of the page.

Context SSL:

  Allow site administrators to make sure certain sections of their sites are always accessed through SSL.

  This module adds a reaction plugin to the Context module and thus benefits from all the flexibility that the Context module provides.


How to Override CSS for a core module? I would like to make some changes to the core toolbar module across all my sites, and I don't want to modify the actual core's css.  It looks like I should be able to override the core css found in modules/toolbar/toolbar.css by simply copying this file into my sites directory at /sites/modules/toolbar/toolbar.css.  I tried doing this, cleared the Drupal cache, but nothing happened.  What am I missing?

Ben Your solution is not ideal, as you now have your own version of the toolbar module, and should there be any bug fixes and security fixes, you will not benefit from those, without upgrading your version of the toolbar module.

Solution 1.

CSS will by it's design overwrite itself, since the theme CSS files will be included last, any rule you make in your theme that is identical to what's in the toolbar will take presedence.

Solution 2.

Sometimes it can be a pain to revert styles to browser default, if that is the case, creating a css file with the same name as the one you want to remove and including it in your theme, will make Drupal skip the one in the module and use the one in your theme. In this case creating a toolbar.css file anywhere in your theme and adding it in your info file, will remove the toolbar.css file from the toolbar module and fix your problems.
Remember to clear cache

Solution 3.

If by some reason you have problems making solution 2 work, you can instead remove the css file using hook_css_alter, this only works in Drupal 7+


Selected date events in Calendar view I have a calendar of content type as a block. Currently clicking the date link opens the single day calendar view (from the Calendar template). Is it possible to display a view/list of events for the selected date on the same page? like this:

Thanks in advance!

One thing you can do is create a second block display view that's simply an html list of events (rather than a calendar display) and put that block on the same page as your current mini calendar.

The trick is that that event list can be set up to take a contextual filter that only displays it when you click on a day from your first calendar.

Here's how you can make it work

Customize your calendar-datebox.tpl.php file (except make sure you name it such that you're only customizing it for your specific calendar block, rather than globally) and place in your custom theme's templates folder.  It should have something like this, rather than the typical one line it comes with:

// Notice how I'm placing the current day's selection into a URL variable called selected_day.  You may need to customize this a little to fit your needs.
<?php
  if ($selected) {
       $output = '' . $day . '';
} else {
  $output = $day;
}
?>
<div class="<?php print $granularity ?> <?php print $class; ?>"> <?php print $output; ?>

Once you've done that, the links that are printed for your days that have events, will just add a parameter to your existing URL that is called 'selected_day', rather than replacing your calendar block.
Now just create a new block, which is an html list that prints out the event's name, time and description, like you have in your screenshot.  Place that block on the same page as your current calendar either via a context or your block's admin screen.
Create a contextual filter for your new block listing, which should be the event's start date.  Set the default value to be a php snippet, which just gets the url's 'selected_day' variable

  return $_GET['selected_day'] ;

If both of your blocks are present on the page, the second one -- the listing -- shouldn't display anything until you click on an event date, at which point the url's variable will be created and the second block should appear.  I just did a small test, and it works for me.

:-)


Drupal isn't picking up my custom action I wrote a couple of actions for my Drupal page, but for some reason, Drupal isn't picking them up... Nevertheless, it's a copy/paste of the Drupal.org website...

   function publicatie_omgeving_action_info() {
      return array(
        'publicatie_omgeving_publish_action' => array(
          'type' => 'node',
          'label' => t('A'),
          'configurable' => FALSE,
          'behavior' => array('changes_property'),
          'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
        ),
        '_mijn_organisatie' => array(
          'type' => 'user',
          'label' => t('AA'),
          'configurable' => TRUE,
          'behavior' => array('changes_property'),
          'triggers' => array('comment_presave', 'comment_insert', 'comment_update'),
        ),
        'publicatie_omgeving_menu' => array(
          'type' => 'comment',
          'label' => t('AAA'),
          'configurable' => FALSE,
          'triggers' => array('comment_insert', 'comment_update'),
        ),
      );
    }

I only get the first one, A. Is there something wrong with this code?

It's my understanding that, by convention, an action function should start with modulename_ (to prevent namespace collisions) followed by a short description of what it does, eg publish, but in order to be found at all, it needs to end in _action.

So try naming all of your functions:

publicatie_omgeving _ SOMETHING _ action

and see what happens.


How to export / import images uploaded using CKeditor Exporting and importing image fields is easy. How to export images uploaded using CKeditor in the body field of node? I have a view which exports the content from D6 (in XML format). In D7 i have feed importer which imports the content. I can add all fields in view and get all data exported. This works well for everything except images placed in body field. They don't get migrated as it is not part of node field.

You can get the uploaded files from the D6 files directory, and upload them to the default directory that CKEditor is set to use in D7. When you import those nodes, you can either change your XML source directly, or use the Feeds Tamper module find/replace plugin to rewrite the paths in the body field to the new location.


How to expose to users filter for changing views items limit for pagination? As in question, is this possible via UI or only custom form must be created?

I have done this manually.  I typically edit views-view.tpl.php file to build up a "items per page" list w/ links and tack on a perpage= GET argument.  You can do the same with a preprocess for the view, but I am spacing on what it is called.

I then implement a hook_views_pre_build:

function mymodule_views_pre_build (&$view)
{
  if ($_GET["perpage"]) {
    $perpage = check_plain($_GET["perpage"]);

    if (is_numeric($perpage) && (int) $perpage > 1) {
      $view->pager["items_per_page"] = (int) $perpage;
    } else if ($perpage == "all") {
      $view->pager["use_pager"] = false;
      $view->pager["items_per_page"] = 0;
    }
  }
}

The last time I remember doing this was with Drupal 6 and Views 2, so you may need to adjust the hook for Views 3.