No block available with a module I am using Facebook post module which display its "Fb Account connection" generated informations/options in an user/%uid/edit/fb-post page.

I want to display these outputs in a custom panels page, but the module doesn't provide blocks, views, forms, or nothing I see that I could handle inside panels.

Any way to achieve this?

It should be pretty easy to create a block in your own custom module that displays this info. Take a close look at the fb_post_page function in fb_post.admin.inc and you can see what the module uses to output that data on the user/%uid/edit/fb-post page.

I'm not super familiar but it looks like the info you want to display can be gotten by calling theme('fb_post_connect', array('connection_path' => fb_post_get_oauth_url($account, $app_id))); and displaying the result in a block (or even directly in a panel pane)


Entity Wrapper : how to delete multiple values field? I have a multiple values field on the user entity. This field is field_data.

There are several values in this field. I want to delete all of them.

I tried the following code:

for ($i = 0; $i < count($user->field_data->value()); $i++) {
    $user->field_data[$i]->delete();
}

But I get errors about ->delete() not being a method on this object. I also tried with ->clear() to no avail.

I've been looking for examples on Google for how to do this, but my Google-fu is not so strong today.

Well, I solved it. The answer is kind of tricky.

You can't delete a value in a multiple values field. However, you can set it to "empty". When it's empty, it's removed.

Here is the code to use:

// Also, note the ->count() method
for ($i = 0; $i < $user->field_data->count(); $i++) {
  $user->field_data[$i]->set();
}

This way, values are now empty and the multiple fields have no value left. It's well shown in the UI too and the deltas are correctly handled in the database.


How can I trace module dependencies in Features? I have a site with several module created with the Features module. I've just noticed that one of the modules created with Features (we'll call it module B), has a dependency on another module created with Features (module A). As far as I know, there should be no connection or dependency between the two modules at all.

Is there a way to track down which aspect of feature B is creating the dependency on feature A since I'm almost positive it is doing so in error?

Look through the info file of Feature B and look for anything known to be added or modified with Feature A.

My guess (with little information) would be that Feature A defines a field/cck field and Feature B either uses that in a content type or view.


User role weaker than authenticated user I am using LoginToboggan Module and I want to create to create a "pre-authenticated" user role that users get assigned to upon registration. After they have verified their email address they will be promoted to "authenticated" users. Obviously, pre-authenticated users should have restricted permissions.

  If "Set password" is selected, users will be able to login before their e-mail address has been authenticated. Therefore, you must choose a role for new non-authenticated users -- you may wish to add a new role for this purpose. Users will be removed from this role and assigned to the "authenticated user" role once they follow the link in their welcome e-mail.

I created a new role "pre-authenticated" and gave it weight 1 and "authenticated" weight 2 ("anonymous" has weight 0 and "administrator" has weight 4). However, whenever I give "authenticated" users the permission to do something, "pre-authenticated" users inherit this permission. It seems like Drupal treats all custom roles as being extra roles for users that already are authenticated. I already cleared my cache and ran cron.

This doesn't appear to be documented in the LoginToboggan interface anywhere but the default behaviour actually does what you want it to do.

You need to create new role like you mentioned, a pre-authenticated user.
After creating the new role go to LoginToboggan config page and select this new role as your Non-authenticated role and save.
Now when you go back to the permission config page you'll see this new role is excluded from the authenticated user permissions, just like the anonymous user.


How to enable click-sorting for views table display based on Search API index? I'm trying to create a view with table display based on Search API (database search) index, with column-sorting (column set as Sortable in the display settings). However, this option isn't available for my view fields, no matter if they are based on string or fulltext Search API fields. Is there anything I can do to enable this?

I'm using latest Drupal 8.7.x nad Search API 1.12

Edit:

It seems that availability of click-sorting is determined in \Drupal\search_api\Plugin\views\field\SearchApiFieldTrait::clickSortable method. The check inside that fails, because field definition array doesn't contain a search_api field key. So is there anything I can do to add it there?

BTW. th support for click-sorting was added in https://www.drupal.org/project/search_api/issues/2816979. There are some SOLR-related issues mentioned, but noting related to my use-case.

As it turned out, it was my stupid mistake - search index field can be added to views (as a views field) in 2 ways, with one of them having (Indexed field) appended to the field label.

When I added field with (Indexed field) appended, I can set that field a Sortable.


What happens to a render array after hook_form_alter() that does not happen after an AJAX callback? I have a multi-value field type in a content type. During hook_form_alter(), I add an #ajax property to the field.

Upon execution, the ajax callback loads a node's custom view mode and two form inputs from another content type into the div.

I am using field_default_form() to generate the form elements.

In order for these addons to persist through clicking the 'Add more' button, I use hook_form_alter() to call the same function that is called by the ajax callback, and I add them into the results/wrapper div.

My problem is that the form elements of the #ajax callback results are not rendered correctly. For example, they do not have a name or id for the <input> tag. One of the fields is an autocomplete field and autocomplete functionality does not get applied to the element.

However, the results of the 'add more' button, which calls hook_form_alter(), DOES render these elements correctly.

As far as I can tell, the render arrays are identical during generation. It seems to me like some additional processing happens after hook_form_alter() that does not happen after my #ajax callback.

I have tried adding #theme, #theme_wrapper, #after_build and #rebuild = TRUE keys to the resulting render array elements, but it does not appear to have any effect.

How can I get these elements to render correctly?

Since hook_form_alter() is returning the correct results, there is a way to use that to our advantage.

By calling drupal_rebuild_form() in our ajax callback, we can return the specific part of the resulting array that should fill in our wrapper div.

e.g.

function _send_item(&$form, &$form_state) {

    $delta   = $form_state['triggering_element']['#delta'];
    $lang    = $form_state['triggering_element']['#language'];

    $new_form = drupal_rebuild_form('mymodule_node_form', $form_state);

    return $new_form['mymodule_item_id'][$lang][$delta]['item_data'];
}


PHP Variables when writing rule I am writing some php code to update an external database with the shipping and billing information after the order is complete, so I am writing a rule on checkout complete that adds the customer information to the database.  I need to figure out what is contained in the variables that I want to use (eg. $commerce_order->???) how would I figure this out, and is there a reference list anywhere that I can use?

If you simply want to find out what is inside $commerce_order then you can use

<?php echo var_dump($commerce_order);?>

I have made a module in the past that did a simerler thing to what you are trying to do.
Using Ubercart I created a module that took advantage of the hook_order function.

<?php
function myFunction_uc_order($ops, &$arg1, $arg2){
    global $user;
    $userId = $user->uid;
    if ($ops = 'update' && $arg1->order_status == "payment_received" && $arg2 =="completed"){
        $order = uc_order_load($orderId);
        //$order now contains all order information for the current order
    }
}
?>

This code will be run every time an order is "updated", this includes being created. So inside the if you can add your code to export to your 'external' database.

Hope this helps


Gather arbitrary data in feeds xpathparser without mapping it to a field? I gather data with the feeds module and xpathparser.

Sample data 1:

<xml>
  <id>1234</id>
</xml>

Sample data 2:

<xml>
  <id>1235</id>
  <ref-id>1234</ref-id>
  <action>delete</action>
</xml>

In the incoming XML data, there are two fields, used to signify an old entry should be deleted. In my feeds Parser->parse(), I have

$this->config['sources']['refid'] = 'XML/ref-id';
$this->config['sources']['action'] = 'XML/action';

which makes the parser get these two data values even if I don't map them to a field. But I can find no way of making this information available to the Processor. I would like to find some way of sticking this data on to the $node, so that in entitySave() I can ignore saving id 1235 and instead delete 1234.

As per this issue: Map "Temporary target" to a property of an entity, Feeds tamper seems to be the way to do this.


Colorbox links not working on Ajax loaded content I am using latest stable version of the Colorbox module

I have an image gallery with small thumbnails and a big one.

When I click on a small thumbnail it loads via Ajax a big image:

$commands[] = ajax_command_html(
    '.big-image', l(theme('image_style', array('style_name' => 'node-image', 'path' => 'public://' . $get_src)), file_create_url('public://' . $get_src), array('attributes' => array('class' => 'colorbox'), 'html' => TRUE))
  );

As you see i have added class .colorbox to a link, but it works only on the images that were loaded during the page load and it's not working on AJAX loaded images.

How can I re-initialize colorbox on Ajax images?

You need to attach your js using Drupal behaviors.

Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
    // This code is run on page load and after every ajax request
    // attach colorbox functionality here...
    // the following line should do the job but I've not tested it
    // we are using context so it only applies to the newly added objects
    $('.colorbox', context).colorbox();
  }
};

I found this blog post on the subject really useful.


drupal migrate source csv I am trying to use 'migrate source csv' to migrate some content with taxonomy terms in drupal 8. If the field has only one term, I can use the following and it works out fineprocess:
  type:
    plugin: default_value
    default_value: adi
  title: title
  field_description: description
  body: note
  field_subject_terms:
    plugin: entity_generate
    source: subject_terms
destination:
  plugin: 'entity:node'

However, if it has more than one term, and I try with the following code, I get an error about th term is not an integer. I have also tried adding the iterator plugin to the code below, but still the same error.process:
  type:
    plugin: default_value
    default_value: adi
  title: title
  field_description: description
  body: note
  field_subject_terms:
    plugin: explode
    source: subject_terms
    delimiter: ','
    process:
      plugin: entity_generate
destination:
  plugin: 'entity:node'
migration_dependencies: null

Any help appreciated. Thanks

'process' is not recursive - you can't simply embed processing within another plugin in the general case (only iterator has that ability). Rather, plugins (generally) need to be executed in sequence:

field_subject_terms:
  # First step in the processing pipeline.
  -
    plugin: explode
    source: subject_terms
    delimiter: ','
  # Results of the first step are passed through to the second step.
  -
    plugin: entity_generate


jQuery Draggable plugin integration with Views 3 I want draggable and sortable contents by admin. So, installed jQuery UI and put this code in my main.js:

$(function() {
    $( ".panels-flexible-region" ).sortable({
      revert: true
    });
    $( "#makyaj .views-row" ).draggable({
      connectToSortable: ".panels-flexible-region",
      helper: "clone",
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  });

Yes, it works. But i want use this option only admin user. Whether View Sort Type: Jquery Draggable and qhat sets the admin users so they can see it.

Is it possible? Can i integration Views and jQuery UI Draggable?

I know this isn't exactly what you asked for, but have you considered using the draggable views module? It does what you aim to do without you having to code anything.


How do I get the database value of a text field with $content? I need to output a raw link from within a text field, without all the "field-" divs, in node.tpl. I've tried <?php print render($content['field_download_link']['LANGUAGE_NONE']['0']['value']); ?> but nothing displays.

The easiest way is to install and enable Devel module.

  A suite of modules containing fun for module developers and themers
  ...

After that add to your page.tpl.php file this:

<?php dpm($content); ?>

You need to be logged in as administrator and you will see debugger on the page. Find the value you want to print and double-click on it, you will see the exact "path" to the value and just print it as you wrote in your question.


How do I insert content fields above title in a content type template? While customizing node--mycontenttype.tpl.php full view, I wanted to insert a couple of fields above the main page title. Can this be done in node--mycontenttype.tpl.php? or should I step up into the page--whetever level of suggestions?

This if:

<?php if (!$page): ?>

seems to never be true for that full view I'm using. I'm afraid I don't understand this flag enough.
Any hints, please?

You will have to use the page template instead of node template so you can add fields before the node title.
page--content-type.tpl.php


hook_form_alter to create table field I created a form which takes user input for fields: title, link, date and description, however I have another field which is guid and it cannot be user created. This field needs to be created with hook_form_alter() which takes the user inputted link and concatenates a string to the front and then return it to the submit handler for db_insert. How can I go onto doing this? here is my submit handler

function rss_list_creator_form_submit($form, &$form_alter) {
//$GUID = returns GUID from hook_form_alter()
$query = db_merge('rss_table')
->key( array('GUID' => $GUID))
->fields( array(
'title' => $form_state['values']['title'],
'link' => $form_state['values']['url'],
//'GUID' => $GUID,
'date' => $form_state['values']['date'],
'description' => $form_state['values']['description'],
))
->execute();
}

**I solved my problem, since I have two forms available I needed to enclose the code in a switch statement. Here is the code block:

function rss_list_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
  case 'rss_list_creator_form':
  if(isset($form_state['values']['url'])){
    $guid = 'tag:news.google.com,2005:cluster=' . $form_state['values']['url'];
  }
  $form['guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '',
  );
  break;
 }
}

you can try with hidden field. You can make #guid field a hidden field. in your hook_form_alter() #guid initially will hold the default value to empty on submission, you can make #guid fields value to whatever you want to make.

funciton mymodule_form_alter(&$form, &$form_state, $form_id){
  if(isset($form_state['values']['url']){
    $guid = 'extra string' . $form_state['values']['url'];
  }
  $form['#guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '';
    );
}


Changing the order used to show the weekdays I have installed the event calendar module.

The problem that I have is that the calendar block outputs as follows:

  S M T W T F S

where I would like it to be outputted as follows:

  M T W T F S S

I've tried looking at other sources but I cannot seem to find a solution.

Can anyone offer a solution?

Thanks in advance.

Hopefully that module integrates with the rest of the system properly - if it does, you can go to /admin/config/regional/settings and change "First day of week" to Monday.


Need help Converting a jQuery event to a Drupal Behavior I have a Drupal 7 web site that is using jQuery animations to fadeIn div tags.  I need an event to capture a fadeIn when it is completed.  I have found a sample jQuery example that does what I need it to, but I have not been able to successfully convert it to a Drupal 7 behavior and I'm not quite sure what I might be missing.

Fiddle Example

Below is my Drupal JS file, fadeInEvent.js.

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

        var _old = jQuery.fn.fadeIn;

        jQuery.fn.fadeIn = function() {
            var self = this;
            _old.apply(this.arguments).promise().done(function(){
                self.trigger('fadeIn');
            });
        };

        jQuery('.tab-pane').bind('fadeIn', function() {
             alert('fadeIn Done.');
        });

    }
};

In the above JS code, I never get my alert that the fadeIn has finished on the item I have selected.

Alter don't show because in your code:

jQuery('.tab-pane').bind('fadeIn', function() {
             alert('fadeIn Done.');
        });

this function mean that when selecter .tab-pane fadeIn done, alert will show. But You don't call fadeIn => don't have event fadeIn. You need call that same:

jQuery('.tab-pane').fadeIn(2000);

And better function jQuery.fn.fadeIn need outside Drupal.behaviors.fadeInEvent

(function ($) {
    var _old = $.fn.fadeIn;
    $.fn.fadeIn = function(){
        var self = this;
        _old.apply(this,arguments).promise().done(function(){
            self.trigger("fadeIn");
        });
    };

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

            $('.tab-pane').bind('fadeIn', function() {
                alert('fadeIn Done.');
            });
            $('.tab-pane').hide();
            $('.tab-pane').fadeIn(2000);
        }
    };
})(jQuery);

then you call fadeIn() every where and have event fadeIn.


Custom template for custom block I'm tying to show all the taxonomy terms from a specific vocabulary linked to the current node being viewed. I'm doing this with a new block defined in my module.

In my hook_block_view i need to give a $block['content'] a value, i'm putting a 'foobar' in it because i won't use it, and i add a new key 'tags' which is a array with my tags to render. Then in my block.tpl.php i check the block name and change the rendering if my custom block is rendered.

I guess there must be a better way of doing this...

I would love to add a custom template file, that will be used on my specific block. Is this possible?

Thanks,
Jonathan

This is a good article on what trying to do...

http://www.pixelclever.com/how-theme-specific-blocks-drupal


How do I add the author's image in a view? I want to add the player's photo shown in the user profile, in a view that shows the following data.

The view shows a list of nodes. The "Player Name" field shows the author of the node.

How can I achieve this?

You can try using a relationship in your view.

Under advanced in your view -> Relationships -> add and choose Content: Author.
You should then have the option to add the user picture in your Fields section.


Entity reference view depending on other field I have a custom content type that contains an entity reference field (field_referencefield) and one more field as select box (field_triggerfield).

The values of field_referencefield should depend on the selection of field_triggerfield. This should happen in the create node form. I.e. If I change the selected item in field_triggerfield during node creation, different values for field_referencefield should be available. Maybe this can be achieved using views reference.

Step 1

On the field definition for the reference field that is dependent on another field you are going to change the reference method to views

Step 2

You'll need to create a reference view for this data.
Make sure to add a contextual field/relationships/etc on the reference view that takes the other value from your form that helps it pre-filter the autocomplete results.

Step 3

in a module or wherever hook into hook_form_alter and replace the reference field

/**
 * implements hook_form_alter
 *
 * @param array $form
 * @param array $form_state
 * @param string $form_id
 */
function my_module_form_alter(&$form, $form_state, $form_id) {

  if (in_array($form_id, ['node_mycontenttype_form', 'node_mycontenttype_edit_form'])) {
    // Add a wrapper around the reference field.
    $form['field_referencefield']['#prefix'] = '
';
    $form['field_referencefield']['#suffix'] = '
';

    // Add an ajax callback that replaces the contents of the wrapper.
    $form['field_triggerfield']['widget'][0]['target_id']['#ajax'] = [
      'callback' => 'mymodule_field_mycontenttype_trigger',
      'wrapper' => 'some-wrapper',
      'event' => 'autcompletechange autocompleteclose',
      'progress' => [
        'type' => 'throbber',
        'message' => t('Fetching filtered content...'),
      ],
    ];

    $field_triggerfield_value = $form_state->getValue('field_triggerfield');
    if (!empty($field_triggerfield_value)) {
      $contextual_filter_value = $field_triggerfield_value[0]['target_id'];
      $form['field_referencefield']['widget'][0]['target_id']['#selection_settings']['view']['arguments'][0] = $contextual_filter_value;
    }
  }
}

function mymodule_field_mycontenttype_trigger(array $form, $form_state) {
  return $form['field_referencefield'];
}

so what this is doing (I've assumed node edit form and node add form for a content type):

putting a wrapper around the reference field whose available values should change
adding an ajax callback to the trigger field that should cause the reference field to filter (the contextual field)
when the trigger field changes

add a new contextual value to the view reference field's view from the trigger field
replace the contents of the wrapper field in the form


How to disable the add to cart button if the shop owner does not have the premium role? I created a marketplace (several stores on the same site) and the merchant can create a paid subscription to have the "Premium" role. Here's what I want to do:

The owner of a store has the role "Premium" = the website visitors have access to the button "Add to cart" on the product pages of his store.
The owner of a store does not have the role "Premium" = the website visitors do not have access to the button "Add to cart" on the product pages of his store.

How to disable the add to cart button (FOR VISITORS) if the owner of the store does not have the "Premium" role? *

Can I do that with a TWIG? If yes, how ?

Read my question. Depending on the role of the owner of a store, all users must be impacted.

WHY :

On my markerplace, I want to set up a paid subscription for sellers.

If the owner of a shop is not subscribed, he can not sell his products ("Added to Cart" button disabled).
If the owner of a shop is subscribed, he can sell his products (button "Added to cart" activated).

Whether the owner of a store is subscribed or not, everyone needs to see the stores and products. Only the "Add to Cart" button is impacted.

Yes, you can do this in twig file. So you will have to create a commerce product twig file(you can copy it from commerce module template). In the preprocess hook you will have to pass a value whether that product can show cart button or not. In your twig file you can use value of that flag around {{ product.variation }}. Add to cart button is rendered by this variable.


How do I store the input value on form submission? I made a simple form in a module with a textfield and a submit button. Every time I type something into the textfield and submit, when the page loads, the default value is in the textfield. I followed the tutorial on http://www.badzilla.co.uk/Drupal-7-Tutorial--Form-Block-With-Template-File

Every #value property is set to whatever I type into the textfield under $form and $form_state except #default_value.

What am I missing?

Here is the code

<?php

function my_form_block_info() {
  $block = array();

  $block['my_form_block'] = array(
    'info' => t('My Form'),
    'weight' => 0
    );
    return $block;
}

function my_form_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'my_form_block':
      $block['title'] = t('Sample form in block');
      $block['content'] = drupal_get_form('my_form_form');
      break;
  }
  return $block;
}

function my_form_form($form, &$form_state) {
  $form['name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => 'some default value',

  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
    '#validate' => array('my_form_validate'),
    '#submit' => array('my_form_submit'),
  );

  $form['#theme'][] = 'my_form';
  return $form;
}

function my_form_validate($form, &$form_state) {

return TRUE;
}

function my_form_submit($form, &$form_state) {

    drupal_set_message(t('Hello :name - how are you?', array(':name' => $form_state['values']['name'])));

    $input = $form_state['input']['name'];
    $form_state['values']['name'] = $input;
}

function my_form_theme() {

    return array(
        'my_form_form' => array(
            'arguments' => array('form' => NULL),
            'render element' => 'form',
            'template' => 'my_form',
        ),
    );
}

I would have thought you would be able to do something like this in your form handler...

'#default_value' => $form_state['post']['name'] ? $form_state['post']['name'] : 'some default value',

...but perhaps since this is in a block, it is being called "fresh" each time the page is displayed.

So, quick and dirty (and possibly all hideously wrong) the following does work...

'#default_value' => $_SESSION['foo_bar_baz'] ? $_SESSION['foo_bar_baz'] : 'some default value',

...if you put...

 $_SESSION['foo_bar_baz'] = $form_state['values']['name'];

...in your submit handler.  At least for logged in users anyway, and will persist during his/her session.

Hopefully there is a "drupaler" way of doing this, but in the meantime, flame retardant suit on.


Would cache in files be an alternative? Once I worked in a company that had its own CMS and we used to cache data in files so basically the system would check if the cache file existed, if not it would go to the database, get the data, save it in a file and then show it to the users (basic cache thing). This resulted in less connections to the database.

I would like to know if this is a good option to Drupal or if there is any problems with this way of caching things.

As anschauung mentioned you can use Boost to create a static page cache. Boost will copy the entire HTML of a page and store that HTML as a static file on the disk in a specific directory. A set of rewrite rules will cause the webserver to first look for a static HTML file for each request and serve that file if it's found. If it isn't, a normal Drupal request occurs via PHP. Requests served through the static file will be really fast, but PHP and the database are completely bypassed.

Boost is not a replacement for the cache backend and that Drupal will still use the cache tables in the database when a miss occurs on the static HTML files created by Boost. If you want to completely replace the cache backend, you could look into memcache, which stores serialized objects in memory. Memcached runs as a daemon on the server and can be connected to via TCP. This can be both a good and bad thing, depending on number of servers in the environment and

Note that it is possible to have the database keep the cache tables in memory as well (at least with MySQL), although I'm not sure about the specifics of doing so.

You could all use the APC module if you're running Drupal 7. The APC modules integrates with the APC opcode cache and uses it as Drupal's cache backend. APC can be faster than memcached in certain scenarios because there is no TCP connection overhead. Each APC cache is tied to a specific server, while memcached and the database can be shared by multiple front end servers (again, this can be good or bad).


Drupal Webform Select 2 options instead of unlimited I have a list of 150 products on my select a sample list on my webform. Customers are supposed to select only 2 products, not 3, 4, etc....

I chose "Multiple" so how can I have them select only 2 products from the list instead of 3 or more?

Thanks!

You can do client-side checking for the number of items selected, and if greater than 2, you can add your desired behavior, such as clearing the selections and/or alerting the user.

Example with jQuery:

var selectID = '#your-select-ID'; // change this to your selector
$(selectID).change(function () {
  if ($(selectID + " option:selected").length > 2) {
      $(selectID).val([]); // clear the selections
      // do other stuff if you want, like alert('Can only select 2 options');
  }
});


Migration failed with source plugin exception I'm getting the following error:

Migration failed with source plugin exception Migration failed with source plugin exception: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'posmsoftllc' for column 'sourceid1' at row 1

I can't figure out why I'm getting this error.

It has something to do with my MigrateSQLMap - there's no real primary key on the source database, but I suppose username would probably work. I've got the MigrateSQLMap setup as follows:

$this->map = new MigrateSQLMap($this->machineName, array(
  'Username' => array('type' => 'varchar',
    'length' => 75,
    'unsigned' => FALSE,
    'not null' => FALSE,
  )
    ), MigrateDestinationEntityAPI::getKeySchema('commerce_line_item', 'recurring')
);

But I'm receiving this error - what could be causing this? Why is it expecting an integer value? Do I even need this map for a successful migration?

I find when I get these errors it is because initially I make an sqlmap using an integer key -- then see I don't have an integer key and try to change it. The migration still expects the initial configuration of an int key. You likely have to clear it out as seen in this issue comment.

  Everything looks OK to me. Is it possible that when you initially
  defined your migration, you had an integer key in the MigrateSQLMap
  call? Changing the key in the code will not automatically change the
  associated tables. What you can do is:

  Rollback the AttSubject migration, so the map and message tables are
  empty.
  Drop the migrate_map_attsubject and migrate_message_attsubject
  tables.
  Run "drush ms". This should call the ensureTables() method and
  recreate the map and message tables using your ca_varchar1 key schema.
  Check the structure of the map and message tables and make sure
  sourceid1 is a varchar in both.

Also see this issue which describes the same problem and solution with more examples/details.


Views random list with different css for result 1 I want to create a random list of pictures with views 3 in Drupal 7 where the first picture is larger than the other ones.

So each time I reload I have a random list and the first result is always bigger.

How do I do this?

You can get random results in Views by using the random sort filter.
Then there's quite a few ways to target CSS on the first result.  If your using a list style, the first list item will have a views-row-first class.

However, if you want the image to be larger you really want to use a different image style.  This means the field will be different from the rest, and the best way to do that would be to move it to an attachment display.  In there, override the fields and edit the image style.  Override the pager and limit it to 1.

The next problem would be how to exclude the random image from the attachment in the main view (so that you don't get duplicate results).

You can get a view to exclude a result by adding it is an contextual filter. And in the 'more' options, select 'exclude'.

However, I don't know of a way to pass the result from the attachment into the other display as an argument.  They will both inherit the same arguments.

You could generate a random id somehow, and pass this in to your view.

But the tricky bit is how you would generate this random id, it could even be done with another view!  And then also how do you pass this into the view.
I can't quite think of an elegant solution. If you're in a hurry, here's some quick and dirty php code you could put into a custom modules hook_menu callback.

$random_id = views_embed_view('your_view_name', 'display_that_outputs_random_id');
print views_embed_view('your_view_name', 'main_display_name', $random_id);

There's definitley a better way, if I can think of something I'll let you know.

Thanks
Leon


Using db_query() or db_select() to connect to multiple databases How can I execute a query that connects to different databases?

I have the following query, and I need to rewrite it for Drupal.

SELECT a.empid, b.empname FROM db1..empidmaster a, db2..emplist b
WHERE a.empid = b.empid

How can I rewrite the query using db_query(), or db_select()?

If the settings.php file defines the information to connect to the other database as $databases['extra']['default'], then you can use the following code, which is possible because SelectQuery::join() accepts also another SelectQuery object as $table argument.

$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$query->join($subquery, 'b', 'b.empid = a.empid');
$query->addField('a', 'empid');
$query->addField('b', 'empname');

A better code would be similar to the following one. In this case the alias used for the table used for the subquery is the one returned from SelectQuery::join().

$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$alias = $query->join($subquery, 'b', '%alias.empid = a.empid');
$query->addField('a', 'empid');
$query->addField($alias, 'empname');

SelectQuery::join(), and SelectQuery::addField() don't return the $query object; that is the reason you cannot the following code.

$query = db_select('empidmaster', 'a')
  ->join($subquery, 'b', 'b.empid = a.empid')
  ->addField('a', 'empid')
  ->addField('b', 'empname');

PHP would return an error about a method not being called on an object. In fact, SelectQuery::join() and SelectQuery::addField() return a string: the alias for the table, or the field.


View with empty filter result visible only to admin user So I am new to Drupal 7, just so you know.

Here is my problem:

I created a view displaying all registered users ("members"). Following a tutorial, I managed to display their user pic, name, date joined and amount of posts. The latter was done using aggregation and the relationship filter "User: content authored".

All works great in the preview and real view, but only for the Admin role. When I log out and try it as a fake member I created for testing, the members with 0 posts don't show up.

I have searched for an answer for hours now and have fiddled with filter settings until I am blue, but no luck.

ETA: I have found that some people have had luck using the Views Field View Module. I tried it, setting up a new view for the post counter and then adding it to the parent view, but now I am getting the same post count for all users. Don't know what I am doing wrong...

Please can anyone help?

So, in the end I followed some advice I found on another somewhat similar problem which said one can go onto the Advanced Settings on your view > Query Settings > check "Disable Query Rewriting"

This worked, but anyone following this advice should be aware of the security implications regarding visibility.


How to create a menu with background images for list items? How would you make a menu that have a different background image for each <li> element in the menu?

I would suggest:

Use the module http://drupal.org/project/menu_attributes (beta 1 is out for Drupal 7)
Give each menu item a CSS ID or class that needs an image
Use CSS to assign background images to the menu items

Using this method, no PHP coding is required, and the menu images become content editable by your authors (once the CSS images have been setup).


node_save JSON field formats I'm having an issue where node_save() (inserting new node) ignores some fields in my JSON node.  This happens with several content/widget types.
I've posted this to Drupal services with no response.

I followed Tyler's post here recommending to do a GET to observe and mimic the JSON format returned - unfortunately I'm finding the format returned in a GET is not always the same format as expected in a node_save() POST.
https://github.com/signalpoint/DrupalGap/issues/418

I also saved a node on our Drupal website and captured the format of the POST
body, trying to translate that format to analogous JSON.  No luck.

Date time field, with start and end date, using Date (Unix timestamp) field
type and pop-up calendar widget.
Formats recommended in the post below does not save, only default value (now)
is saved.  Example is field_when_available below.
Services module update date field
Integer field types with Text field widget will not save.
I've tried over 20 permutations of formats, posted here, no response.
htt ps://www.dru pal.org/node/2870095
field_scrap_weight is an example below.
Reference to another node will not save.
Same link above describes using target_id, tried that, no success.

What will save are are term reference and List(text) content types from
Radio button widgets.   field_surplus_type and field_unprepared_or_prepared
are examples.

I am posting to
http://127.0.0.1:8083/?q=drupalgap/node.json

Below is one example, but I've tried literally hundreds of permutations
with and without array brackets, with/without the "und" element,
with/without quotes in the data value, etc.

I'm beginning to think there's a more global/systematic issue like a content-type setting.

{
  "type": "donation",
  "form_id": "donation_node_form",
  "language":"und",
  "field_unprepared_or_prepared": {    // saves OK (List text, checkbox/radio)
    "und": {
      "value": "unprepared"
    }
  },
  "field_surplus_type": {        // saves OK (Term ref, checkbox/radio)
    "und": [ 1, 3  ]
  },
  "field_scrap_weight": {        // NOT saved (integer, text field)
    "und": {"value": "1"}
  },
  "field_when_available": {      // NOT saved (Unix timestamp), popup calendar
    "und":[
      {
        "value": {
            "date": "05/29/2017",
            "time":"09:00pm"
        },
        "value2": {
            "date": "05/29/2017",
            "time":"09:00pm"
        },
        "timezone": "America\/New_York",
        "timezone_db": "UTC",
        "date_type": "datestamp"
      }]
  },
  "field_surplus_location": {     // NOT saved - node reference
    "und": {"target_id":"256"}
  },
  "body": {           // NOT saved (long text w/summary, text area widget)
    "und": {
      "value": "dd"
    }
  }
}

It's important to understand that the Services module is closely tied to the Drupal Forms API, meaning that the JSON delivered via POST/PUT is sometimes dependent on the Widget that is selected for the field(s) in question, so it won't always match what is delivered via GET.

That being said, I can see some problems with your JSON. Try these instead:

integer, text field

"field_scrap_weight": {
  "und": [ { "value": "1" } ]
},

node reference

"field_surplus_location": {
  "und": [ { "target_id":"... (256)" } ]
},

long text w/summary, text area widget

"body": {
  "und": [ {
    "value": "dd"
  } ]
}

Often times it appears you are missing the wrapping [], this indicates the delta value for the field's item, i.e. it's an array so you can pile up extra values if your field is configured for more than 1 value.

The entity reference field can be any text, but the target id must be wrapped in the parenthesis.

The Date field is the trickiest and I would advise looking at the following answers:

https://drupal.stackexchange.com/a/78925/10645
https://drupal.stackexchange.com/a/180101/10645
https://www.drupal.org/node/1898072

If you're looking to POST/PUT exactly what is delivered via GET, then check out the Services Entity module and this extra configuration that can be added to jDrupal.


Simple order cancellation in Drupal Commerce, with 24 hour time limit? I want to create a way for customers to log in and edit their completed orders (the orders are registrations to classes). Compared to the standard order-edit page I want to remove all options except 'change order status to cancelled'. Preferably a simple page stating the content of the order, then some cancellation 'rules', and then a button saying 'cancel this order'.

Cancellation should then also check whether date/time of the booked class is less than 24 hours away from the moment of cancellation. If <24 hours, it should either refuse cancellation, or allow cancellation (nice for those on the waiting list), but not refund the cost of the class (paid for using a voucher - using the giftcard module)

Background: the site sells two products: one is a set of vouchers. These vouchers can then be used to buy product 2, which is a registration to a class at a specific date and time. When customers have booked a class, they now get an email with link to their order page. Their they find a button 'edit order', click that and you go to the standard order edit page which shows line-items, billing and shipping etc, and allows all existing changes to the order status. As this page is not made trough either a template or a view, I have no clue how to change what customers get to see and do with their completed order.

Also rules does not allow me to compare the time of the status change with the time/date field of the booked class, so I can't control the 24 hour limit either..

Suggestions are to build a custom module doing the above, but I have no idea how to kick that off..

All/any help massively appreciated

I haven't tested any of this, but you might some of the following useful:

Entity Operations allows you to take a Rule and turn it into a menu tab. This would be one way of getting that onto the order view page.

Something I've really been wanting to try is the Entity action links sandbox:

  Allows actions and rules components to be executed via AJAX links on entity view.

Just note the patches discuss in the Sandbox README.

If you wanted to do the Rules route, these would be probably your best option, because you can use conditions and components to provide some sort of response or action system based on the order status and time.

Otherwise, you'd need to create a custom module with a custom access callback that does the appropriate checks and then executes the action if allowed. (For a developer, I think this would actually be an easier route.) But the rules stuff is intriguing.


Drupal 7 drush - delete / edit views Drush for Drupal 6 had a plugin that allowed you to delete a view. That plugin's functionality was mostly rolled into drush for Drupal 7.

I have a view that can't be edited through the UI, and I was hoping the drush could solve the problem.

I don't know of a Drush command for this, but if you know your view's machine name or ID wiping it from the database isn't too hard.

SELECT vid FROM views_view WHERE name = 'your_views_machine_name';
DELETE FROM views_view WHERE vid = id_from_above;
DELETE FROM views_display WHERE vid = id_from_above;

That should be the last you ever hear from that view.


Expose table in Drupal View How can I expose a table with out primary key in Drupal view 3
I have table st as uid, gid, percentage.

attendance_views_data() {

$data['attendance_percentage']['table']['group'] = t('Attendance');

    $data['attendance_percentage']['percentage'] = array(
        'title' => t('Attendance percentage field'),
    'group' => t('Attendance'),
        'help' => t('Attendance percentage field.'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
            'click sortable' => TRUE,
            ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
            ),
        'sort' => array(
            'handler' => 'views_handler_sort',
            ),
    );
}

The above code does not work as I can not see percentage field in my view feild.

A problem in your code is that you are missing

return $data;

You also need to define the base for the table:

$data['attendance_percentage']['table']['base'] = array(
  'title' => t('Attendance'),
);

Should be enough.

Also remember you need to clear cache.


How do I change the default country on the billing address form in Commerce 2? I want to set the default country when customers check out in Commerce 2.  How do I do that?

You need to edit the form display for the Customer Profile Type.

You can find it in the Admin menu under "Users", or go directly there by this path:

/admin/config/people/profiles/manage/customer/form-display

Then, on the widget for the address field, click the gear to set the default country.


Tabular data representation I am building a demo site, trying to learn commerce kickstarter.
I figured out a lot of it but i wanted to add something more to the items.

If you click this link : http://www.sigmaphoto.com/product/sd15-digital-slr-camera
I don't own that or promote that site , i found it on drupale commerce kickstarter showcase.
My question is how can i create tabs that are like under the pictures.
OVERVIEW | TECH SPEC | ACCESSORIES

Do you need to create a view or is there a field that you can add so you can input the data in the content type ?

Yes, there is actually a few modules that will allow you to get tabs in your content easily. The one I use is Quicktabs, listed below along with some alternative modules.

Quicktabs (module) - https://drupal.org/project/quicktabs
Field Group (module) - https://drupal.org/project/field_group (has tabs support)
jQuery Tabs Field (module) - https://drupal.org/project/field_jquery_tabs


How to enable caching for ajax callbacks, especially for colorbox node? I am using colorbox node module on my site, and it looks like the ajax callbacks for rendering the node are not cached at all. Tested it with a simple snippet in the node template:

generated on <?php $dt=new DateTime();print $dt->format('d.m.Y H:i:s');?>

Colorbox is using a custom display, to have a custom node.tpl

function mytheme_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_content_type' && $vars['view_mode'] == 'colorbox') {
    $vars['theme_hook_suggestions'][] = 'node__my_content_type__colorbox';
  }
}

Caching for anonymous user is turned on and works for node pages.

is this issue related to colorbox node (e.g. missing caching implementation in colorbox node) or some other module?

I dived into the code of colorbox node and found out that the click on a colorbox link will be rewritten and rerouted through this menu:

/*
 * Implements hook_menu().
 */
function colorbox_node_menu() {
  $items['colorbox/%colorbox_node_url'] = array(
    'page callback' => 'colorbox_node_output',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'load arguments' => array('%map'),
    'delivery callback' => 'ajax_deliver',
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

is there a way to cache 'delivery callback' => 'ajax_deliver', without hacking the colorbox_node_output() function? Whats the best practice here to get this into caching? I think implementing a cache inside colorbox_node_output() might already be too late because it is running through the complete bootstrap process before executing that function.

This can be done. Will require 2 hooks hook_menu_alter() & hook_boot() and some non trivial code.

Top level overview of how to do this:
Use hook_menu_alter() to call a wrapper around colorbox_node_output() that will cache its output. Use hook_boot() to check the cache and deliver the cached content, routing the cached content though ajax_deliver().

An example of cache code flow can be seen in the 6.x-2.x ESI module. esi_get_page_cache() gets called from esi_boot. esi_set_page_cache() is what sets the cache; you can see it getting called at the bottom of these functions: esi__block_handler() & esi__panel_pane_handler(). Side note: A big reason the ESI module's cache code has a lot of complexity is it's compatible with D6 core and Pressflow; both have different code for the page cache.


Is it possible to have i18n without l10n? What I mean by this is: Is it possible to have translated content* without having a translated interface?  Can we make the interface always be in English, even if I am translating content into Spanish?

* I'm use Entity Translation, but I imagine that this question would apply equally to i18n module.

You can switch to the preferred interface language in your user profile.


How to programmatically create a custom panel pane I created a custom panel layout with Panels 3 (following this excellent link) and my layout is ready. Now I have my static markup ready for a node (I can use it on the article or a custom content type) and I want to find out how to create a custom panel pane programmatically. I don't won't to do it through the UI as I want to totally control the dynamic markup of a node.
to make things specific (but keeping a certain level of generality), imagine

       !!php dynamic day of the date!!
       !!php dynamic month of the date!!

     !!php dynamic title of the node!!

 !!php dynamic content(body) of the node!!

       !!php dynamic read more text!!

How can I achieve to manage the above dynamic node (and let's suppose I want to achieve an exact, specific markup)?

Ok my question maybe was not the best but at least I hope the following will help new themers get on track.

I created a custom content type called: seminar
I created this node--seminar.tpl.php and placed it inside /sites/all/themes/awesome (the name of my theme)
Inside this file I copy pasted the code found in /modules/system/node/node.tpl.php and I tweaked the code as follows.

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> post clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
  <?php if (!$page): ?>

         <?php print $date_day; ?>
         <?php print $date_month;?>

      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

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

Keep in mind that in order to achieve this

 <?php print $date_day; ?>
 <?php print $date_month;?>

so that $date_day and $date_month correspond to sth meaningful, I had to go through this. Othewise by default drupal outputs sth like  Apr 30  and we can't target Apr and 30 seperately for CSS styling.


How do I send a customized email to subscribed users? I have a post job content type. When an employer posts a job, all the registered users, basing on the job category (taxonomy), should receive an email about the posted job.

How should I implement this?

You'll have to write some code, essentially you need to hook in when Job node is created, find the users referencing to that taxonomy the Job has and then use the Mail service, something like (pseudo)

When a Job node is created

Get all user that has a reference to the created Node's taxonomy:

$job_tax_tid = $node->get('job_taxonomy')->target_id

Then find the users, perhaps by using a Entity Query:

$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('field_job_refs', $job_tax_tid)
  ->execute();
$users = User::loadMultiple($ids);

To send mail programmatically, you need to use the MailManager: http://valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8

Since there can be many users that needs to receive an email, you maybe want to use the Queue or Batch operations.

https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.2.x

https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.2.x


Displaying a Block on 2nd level pages but not 3rd level I have a block that I would like to only display on documents/* but not on /documents//.

I have set 'Show block on specific pages - only the listed pages' 'documents/*' but this displays the block on all children of documents.

How do I set it to only display on documents/company (etc) and not documents/company/board?

The drupal.org/project/context module can do this. In addition to the typical wildcard * operator ... its Path conditions support a Not operator ~.


Replace YouTube URL with player in nodes and comments? Is there a module or something similar I can use to replace a YouTube URL with the actual video in a node and also in comments?

I've found a few that work for the node, but what about in comments as well?

Use the Googtube module for this. It will provide you with an additional input format, which you can use wherever you want.

From the project page:

  Googtube allows users to embed Youtube, Vimeo and Google Videos in a simple way without tags. When users post a url to videos the link is automatically converted to a video witch is actually embed code.


Load The Drupal Database Schema in PostgreSQL I was following the tutorial in the link below to install Drupal 7 with PostgreSQL.
http://pgedit.com/install_drupal
I'm stuck with step 3.
3.Load the Drupal database schema

Your Drupal installation has a top level folder called 'database' where you will find an installation script called 'database.pgsql'. Simply run the script with psql:

psql -U test_drupal -f /path/to/drupal/database/database.pgsql

In my case I cant find database.pgsql. My database folder only contains files shown in the image below:

|Im using drupal7.34. Where am I possibly missing?

I am not sure this tutorial is up-to-date. You don't need to load database scheme, you can just choose to use PostgreSQL when running the installer at /path/to/drupal/install.php


Services 3 and Node Reference I am working with the module services 3 (D7) and I am calling the Drupal method from a Java client. I can login (and keep the session in the cookie) and I can create a simple node.

But I can't set a Node Reference Field.

To find the way to do it, I first looked to the node structure (with the reference field) in my drupal site:

 [field_presta_presta_suivi] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [nid] => 43
                    )

            )

    )

So, in my Java Client, I created a function to reproduce this structure:

public  static HashMap addReferenceField(String field, String language, String type_ref,Object value, HashMap node, int delta ){
        HashMap f = new HashMap();
        HashMap p = new HashMap();
        Object[] i = new Object[delta+1];
        HashMap val = new HashMap();

        val.put(type_ref, value);
        i[delta] = val;
        p.put(language, i);
        f.put(field, p);
        return f;
    }

This function is used to create a HashMap that will be add to the parameter of the service 'node.create'.

This function works with a User Refence Field (which has the same node struture), but when I used it for a node reference, the server returned "Not Acceptable".

I have already passed a lot of time on it and didn't find any example or similar case, so here my question:

How to you use services 3 (D7) to create a node with a node reference field ?

The default resources of Services are all fairly broken, because they rely on simulating an actual form submission (blah!). I recommend using those provided by Services Entity instead.


Add custom html to a facet api facet block How can i add custom html to a facet api facet block. Like a link to another page or some descriptive text and an image. It would be good for user experience.

You can create your own facet widget. Just extends from one of existing widgets. You can found examples in module facetapi.


Drush make SVN repository I want to add a checkout of an SVN project in the .make file. However, the checkout only concerns a specific folder (new profile added). Has anyone made this before ?

edit : Folder and not file. My bad.

The following will do a svn export (unless you provide the --working-copy flag to drush) into DRUPAL_ROOT/profiles/contrib/myprofile

Drush make old-style syntax:

projects[myprofile][type] = profile
projects[myprofile][download][type] = svn
projects[myprofile][download][url] = svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile
; This would place the checkout into /profiles/contrib/myprofile
projects[myprofile][subdir] = "contrib"

Drush make YAML syntax:

projects:
    myprofile:
        type: "profile"
        download:
            type: svn
            url: "svn+ssh://example.com/svn/path/to/subdirectory/of/myprofile"
        subdir: "contrib"

The drush make documentation is now located at http://www.drush.org/en/master/make.


How to unset fieldset in hook_form_alter? I want to unset a fieldset programmatically which is available in the content type. I tried to unset like this in hook_form_alter,

 unset($form['field_first_deposit']);

But it doesn't work, where as hiding individual fields works in the same format. I tried hide() too , but still it doesn't work.

Any help will be much appreciated and Thanks in advance.

The mentioned solution ['#access'] = false will be a possible solution, but if it's not working you may try:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_MODULE_form_FORM_ID_alter(&$form, &$form_state) {

  $form['#after_build'][] = 'YOUR_MODULE_form_FORM_ID_after_build';

}

/**Replace MACHINE_NAME with your fieldset group machine name.**/

function YOUR_MODULE_form_FORM_ID_after_build(&$form, &$form_state) {

  // Hide the B2B group.
  field_group_hide_field_groups($form, array('group_MACHINE_NAME'));

  return $form;
}


node_save causing duplicates I've seen a few other issues where people were causing this by calling node_submit followed by node_save, but I'm not - any ideas why this is creating a duplicate of every piece of content?

$art = node_load($node->nid);
$field_language = field_language('node', $art, 'field_intro');
$art->field['field_intro'][$field_language][0]['value'] = $record->intro;
node_submit($art);
print $art->title . ' saved <br />';

I've tried both node_save and node_submit, both with the same results

EDIT: sorry guys, it was a conflict with a bit of code from another custom module - nothing to see here!

If you want to update the content of existing entity than you may use field_attach_update($entity_type, $entity): this saves field data for an existing entity.

Example:

$art = node_load($node->nid);
$field_language = field_language('node', $art, 'field_intro');
$art->field_intro[$field_language][0]['value'] = $record->intro;
field_attach_presave('node', $art);
field_attach_update('node', $art);

Note: field_attach_update() always expects all fields (like we are [passing the complete node object as $art), but If you just pass it the fields you actually want to update it will drop others like image or file fields.


How do I get the translated title of a node? I have a content type available in FR and in EN.

In hook_node_presave(), I would like to concatenate the French title and the English title in another field. (This is an "helper field" which contains concatenate strings to be used by a filter in a view.)

This is my code.

function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_title1=$entity->getTitle(); //It is the French title if the saved node is the french node.
  $entity_title2= '?'; //HERE IS MY PROBLEM: how to get the title in the other language?
  $entity->my_helper_field->setValue("$entity_title1 $entity_title1");
}

How do I get the translated title of a node?

You should load the translated entity, and get the title from that.

$translated_entity = $entity->getTranslation('en');
$translated_title = $translated_entity->getTitle();

You can get the current entity language using $entity->get('langcode')->value;, and as @4k4 says, you should check that a translation exists using $entity->hasTranslation($langcode);.


How to change the day and month language? Working on multilingual site, I want to change the language of the month in dutch language. For that I have created a module.

<?php
function mymodule_format_date($timestamp, $type = 'custom', $format = 'd M', $timezone = NULL) {
  return format_date($timestamp, $type, $format, $timezone, 'nl');
}

and on the node file put the date format in t() function

<?php print t(format_date($created, 'custom', 'd M')); ?>

but no luck. Please help.

For multilingual you need to import .po file in your setup. Download .po file from this link just add language prefix at here language_prefix (/en, /hi, /de etc..).

https://localize.drupal.org/translate/languages/language_prefix

Now, add <?php print date('j F Y', $created) ?> simple php data function and add your data formate here.

After you will able to see day and month in your language.

If you wish to make a different format for both language just add this.

<?php if($language->language == "language_prefix") {
  print date('j F Y', $created);
}
else {
  print date('F j Y', $created);
}

Thank you.


Fatal error: Class 'Drupal\module_name\DOMDocument' not found Fatal error: Class 'Drupal\module_name\DOMDocument' not found in
  /var/www/drupal/modules/module_name/src/form_xml.php on line 359

Any idea why Drupal cannot find DOMDocument class?

I want to execute a code when a form is submitted

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Find out what was submitted.
    $form_field = $form_state->getValue('content_types');

    foreach ($form_field as $key => $value){
      if (!empty($value)){
        $return = File::generate();
      }
    }
  }

In case you are wondering, module_name is the name of my custom module.

File::generate() is a static method which contains the DOMDocument class

The code works fine when I use devel to execute it, so any idea why can't it find the DOMDocument class on form submit?

Seems to me as if the form blocks access to the DOMDocument class.

You need to rename the form class file CamelCase and make a namespace declaration at the top. The namespace will be Drupal\module_name\Form. Place the form class file in directory module_name/src/Form/.


Overriding hook_menu() { $items } For example, here's a snippet form the Comments Module (comment.module):

function comment_menu() {
  $items['comment/%'] = array(
    'title' => 'Comment permalink',
    'page callback' => 'comment_permalink',
    'page arguments' => array(1),
    'access arguments' => array('access comments'),
  );
  $items['comment/reply/%node'] = array(
    'title' => 'Add new comment',
    'page callback' => 'comment_reply',
    'page arguments' => array(2),
    'access callback' => 'node_access',
    'access arguments' => array('view', 2),
    'file' => 'comment.pages.inc',
  );

  return $items;
}

How can I override $items['comment/%'] with $items['comment/reply/%node'], without hacking core.

In other words, I need example.com/comment/[cid] to look exactly like example.com/comment/reply/[nid]/[cid]?

Yes, you should use hook_menu_alter
Create new module and add hook_menu_alter

function my_module_menu_alter(&$items) {
    // Unset core path
    unset($items['comment/%']);
    $items['your/pass/here/%node'] = array(
        'title' => 'Add new comment',
        ...
      );
}

But link "comment/reply/%nid/%cid" is used by Drupal for replies to other comments (where %nid - node id and %cid - comment id you are replying to). Use another path.


How affect for each user a subdomain ? with module domain-acces, we can  manage domains and subdomains,
example:

domain.com is my first domain.
user1.domain.com is affected to user1
user2.domain.com is affected to user2

but user1 can connect to user2.domain.com that is my problem.

Unfortunately, it looks like this isn't what Domain Access was intended to do, as its focus is "sharing information across subdomains" rather than restricting it:

https://www.drupal.org/project/domain/issues/480716

In the comments there is a link to a code library that can achieve what you want, however.


Add a "Save" action in local task to a node I would like to add a new action to local task on node.
This new action has to save the current node.

I have drupal 8.8.0

I know how to add a new action.

But my question is about how to save the current edit node from it if it's possible.

My goal is to replace the "save" button at the bottom of the node on edit mode

Local tasks are the wrong tool for the job. Local tasks are for providing context-sensitive action links (e.g. Edit, Delete, View) around an item (e.g. node/user). Trying to make a local task become a form submission button would involve all kinds of hacks that probably would be more trouble than its worth.

If the goal is to alter the save button's position for UI concerns, look at using hook_form_alter to alter the appearance/positioning of the node form's Save button. For example, look at a module like Floating Action Buttons that uses a form alter to place the action buttons in a fixed location.


Webform confirmation message on same reloaded page Webform has option to reload the page when submitting the form, but it just refresh the page and doesn't show any confirmation message that the message was sent etc. This might look misleading for simple home user when submitting the form.

Anyway to adding a confirm message on page refresh?

E.g. when submitting it as admin for more than once it actually reload the page and gives message that you already submitted this form. So basically I need the same when visitor submits the form and it would reload the page and show message like 'Thank you, your message was submitted'.

Cheers

Once you've set up  your webform you have the option to set up how the form responds after asubmission has been made. On the your Webform's Setting page...:

If you click the 'Customize Confirmation' checkbox you can - "Configure your website's actions when a user submits a response to this webform."

  Select from the following form submit options in the menu:

  Show standard confirmation page - Displays a confirmation page that contains the information you enter in the Page body field.
  Redirect to a different page - Redirects users to the page in the Path field. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.
  Stay on the same page - Users stay on the webform page. You can also display a confirmation message by selecting the Show a confirmation message check box, and then entering information in the Page body field.

You probably want to select the third option...


Erase custom translation I need to erase a custom translation I made for the Addresses Module. The problem is I changed

  Mexico

to

  México

(with accent) and now, logically, the module does not work correctly since it is looking for the previous value so it can autoselect the states.

Is there a way I can erase the translation? I have tried to search for it but so far, I have not found the right entry.

I am able to use PHPMyAdmin, in case this is feasable thru SQL.

Thanx.

I used a module called Localization Client which provides a user GUI for translations, enable it and go to the page with the translation you should be able to find it in the list then and alter it.


Export with default_content I have been able to export the commerce_store, commerce_product_variation and commerce_product entities with the default_content module and the drush dce (default-content-export) command, but when importing back, the products and the product variations are not linked together. What am I missing?

Has anybody managed to export products and import as default content in a drupal commerce 2.0 site?

Commerce currently does not work correctly with default_content. The commerce guys are looking into solutions for delivering default content.

AFAIK the next version of yaml_content is gonna be able to play nicely with commerce. However as of now, the module has no commands for exporting content, only for importing.

default_content - Question about architecture

yaml_content - Content Export Support


How can I display the values returned from an external API under a form? I have created a custom module that pulls in data from an external API. Users select a few values on a form; submitting the form makes a call to the external API. The module then displays the data, which has been filtered by the values entered from users.
I have been able to show the returned data with \Drupal::messenger()->addMessage(), but this doesn't seem the right method. I've found a few other suggestions, but I can't get any of them to work. They are for older Drupal versions.
I'd like to be able to display the formatted results under the form, on the same page.
How can I achieve this in Drupal 9?

It's not much different from what done with Drupal 7; the difference is the involved classes (which weren't implemented in Drupal 7) and the used methods.

The submission handler stores the values obtained from the external API and sets the form to be rebuilt
The form builder verifies the values set by the submission handler are set and shows them

In the case of a class extending the FormBase class this means:

submitForm() calls $form_state->setValue() to set the value obtained from the external API
submitForm() calls $form_state->setRebuild() to tell Drupal the form needs to be rebuilt
buildForm() uses $form_state->hasValue() to check the value has been set and $form_state->getValue() to get that value

As for showing the returned value, it's sufficient to use a form element similar to the following one.
$form['api_value'] = [
  '#type' => 'markup',
  '#markup' => $api_result,
];

As side note, the $key value passed to $form_state->setValue() should not be a value already used for a form element. Differently, $form_state->setValue() would set the value submitted for that form element.


How to not hide a taxonomy term if it has no content I have a view that shows content. The issue is that I needed to still show a taxonomy term even if it has no content under it. Is that possible?

Here's the screenshot

You can add output to be displayed even if the taxonomy term has no content related to it by adding a field under the settings "No results behavior".

Try adding "Global: Unfiltered text" and add the text that should display when there is no content assigned to the term.


Changing published revision I'm trying to published revision for a node, while saving.
Currently D8 manage revisions, but the last revision is always the "published" revision.

I'm using hook_entity_presave, but I can't find a method to do this.

Some suggestions?

The last revision is always the one that will be used throughout the site. So if it is published then it will be shown. You cannot have one revision published and working on another revision that is not published yet.

Although maybe you can edit an older revision(make sure you do not tick the "create new revision" option while editing) and then, via revision overview, make it the current revision.

If you want to change the status of node(not any entity, only node entity) programmatically than you can call the $node->setPublished(TRUE) or $node->setPublished(FALSE) methods.


Render entity reference field with link in node template I have a content type with an entity reference field to select a user.
Now I would like to render this field in the node template so that the field links to the user profile.
I set the format of the field to "Label" in Manage Display and clicked on the gear so the label is linked to the reference entity.

But because I am printing the field programmatically it doesn't seem to work.

Here's what I do in my node template:

$field_user = field_get_items('field_collection_item', $item, 'field_user');
$field_user_output = field_view_value('field_collection_item', $item, 'field_user', $field_user[0]);
print render($field_user_output);

Does anyone know how to do this?

If the field is configured to display and available on the node, in node.tpl.php, you should be able to use:

print render($content['field_user']);


What is the warning I get after moving to a new server? This is the warning that I've received:

Warning: file_put_contents(temporary://devel_themer/cs6782ec6bb66b8a6ebfd11530a1ce0d9d1ce55eba): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in devel_themer_store_krumo() (line 348 of /home/u894021300/public_html/sites/all/modules/devel_themer/devel_themer.module).

What is it?

Check for file permission where this module is trying to write , especially the temporary folder: admin/config/media/file-system


How to limit block management by role? In a Drupal 7 site, I want to give users with a certain role the permission to manage some (but not all) blocks. More specifically, only want to allow editing the blocks provided by the Nodeblock module.

I can probably do a lot with hook_form_alter, but maybe there is a cleaner way (or even a module) to specify edit permissions on the block level.

Part of your question is "... only want to allow editing the blocks provided by the Nodeblock module". Whereas the purpose of that module is like so (from its project page):

  This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

Together with "... I want to give users with a certain role the permission to manage some (but not all) blocks ..." (as in your question), it seems that a translation (summary) of your question is something like "How can I allow the content managers of my site to manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page".

Using the Bean module you can perfectly allow your content managers to ""manage some (but not all) blocks (eg: edit the block text and title) without having to access the block administration page"". Here is a quote about the Bean module (from its project page):

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require. The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case: for each Block type created with the BEAN module, you can use the typical Permissions page (at admin/people/permissions) to grant Add/Edit/View/Delete access to selected roles (Note: these are 4 separated permissions also). So if you'd create one such "block type" for the role "content managers", then all users with that role (and only those) could then Add/Edit/View/Delete such blocks.

Possible bonus: would you still need the Nodeblock module?

Some more background info about BEANs:

To define a Block type you use the admin UI (via admin/structure/block-types), which is similar to defining content types (via admin/structure/types).
The difference is that you don't create nodes (of a selected "content type", and by using node/add), but blocks instead (of a selected "block type", and by using block/add).

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

Remark: interesting detail on the Nodeblock project page:

  ... There are several other modules and approaches that allow nodes to be presented as a block. See a comparison at http://groups.drupal.org/node/93499 ...

And this last link states the following:

  The Bean module does not allow nodes to be presented as blocks, per se, but creates block entities instead. Since entities are the fundamental unit of Drupal 7 content, this is analogous and can accomplish many of the same ends.

This sounds like "Now that the BEAN module is available (it wasn't at the time this question was asked), you don't need blocks to be presented as nodes anymore to do more advanced things with blocks" ... no?

PS: The Bean module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. AND it has been integrated (already) in core in D8. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8.


How do I make drupal check for similar content? Im using drupal 7 and Im looking for a solution or a module that when a user goes to submit a piece of content they are presented with a "similar content already submitted" list after they enter a title or more specifically a link.
I want to reduce similar or duplicate nodes on my site. I currently use the link module and I allow users to submit links to my site. Occasionally a user will submit a link that has already been submitted by someone else and I want to help alleviate that. Thanks.

Use the Unique Field module and select your link field as the unique field.


How do I fix missing input fields in panels The site I am working on is Drupal7 site, built of panels and pages, panelizer.  Typical steps to edit, admin logs in, click on the "customize this page" button, various panels open up, click on the gear of the panel you want to edit, edit screen opens, make your updates, click finish then slick save, and all is right with the world.
Yesterday one of the editors, following the steps above, attempted to edit, but the panels input box, for some reason, the actual area where you would add the content is collapsed/gone.

It should look something like similar to this:

Anyone have any idea on what is causing this or where should I even start checking to see why all the fields are not displaying?
Any and all suggestions would be appreciated.
Thanks in advance.

Just a reference for those who come along after this.

Try to find out if anyone else has touched your code specifically .js or .CSS and CSS was the issue here.  ONe of the content editors added some css into a block: fieldset{display:none;} well that closed the fieldsets in that popup window and I am sure in other places on the site that we had not run into yet.


Metatag: How to programmaticaly set a node's canonical URL I am using the metatag module for defining several meta tags. As a default value, canonical tags use '[current-page:url:absolute]'.
Now I want to create a module that sets the value of the canonical tag to some other url.

Setting $node['metatags']['und']['canonical']['value'] to another string doesn't seem to work. Unfortunately, I also can't use an entity_wrapper, since metatag doesn't define information for its custom fields, which is needed by entity_wrapper.

Is there something else I could do?

look into the hook: metatag_metatags_view_alter().

/**
 * Implements metatag_metatags_view_alter()
 */
function mymodule_metatag_metatags_view_alter(&$output, $instance) {
  // Add Custom logic to overwrite the canonical tag here.
  $canonical = 'http://www.mysourceurl.com';

  // Alter canonical tag.
  $output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'] = $canonical;
}


How do I add a basic FlexSlider to the body? I only need a very simple slider on a single page and so I just want to use Flexslider's most basic HTML options. But I cannot get it to work!

My code is pasted from http://flexslider.woothemes.com/basic-slider-with-custom-direction-nav.html except that I'm using images from my test server. I have triple and quadrupal (pun intended) checked that my styles are correct.

Here is the first bit of HTML:

I have confirmed that FlexSlider is working by creating a View and adding it as a block.

One clue: My images all disappear on my test page when the flexslider block is active, which suggests to me that the flexslider JS is NOT being loaded normally (I presume it's loading its CSS dynamically).

Without hacking my theme files or adding JQuery code to my theme, is there a way to get FlexSlider to load in this scenario?

Just copying HTML-part won't work as the page needs FlexSlider java script. So add it either by calling drupal_add_js() or modifying the html.tpl.php file of your theme.


Javascript aggregation issue with new server I have a new VPS Host and have cloned my existing live site from my current VPS Host. On the new host, there is an issue with JS aggregation and I am hoping someone might recognize what this is and how to solve it.

Generally with JS aggregation set at /admin/config/development/performance, Javascript breaks sitewide, both front end and backend, logged in and non-logged in. I checked permissions and the JS directiory at /sites/default/files/js/ and it seems fine, files are writing to this directory (both the JS files and the GZipped ones).

When I view the raw code of any of these files, the code is fine (not corrupt). I have also tried switching this off, clearing cache, switching back on, clearing browser cache and even deleting the directory which Drupal did and then recreated without any issue. I checked my PHP info file (5.2.17) and it shows this under PHP Variables _SERVER["HTTP_ACCEPT_ENCODING"] - gzip,deflate,sdch so that seems ok. However my old server's PHP info file also had gzip,deflate,sdch under an additional heading called "HTTP Headers Information".

But here is the real tell-tale, I think, when I view the code of my webpage with Chrome web inspector and look in Console, I see as many JS errors as there are aggregated files. (5 or 6 I think). The error is: Uncaught SyntaxError: Unexpected token ILLEGAL If I then view the corresponding JS file, I see this:

So somehow, the aggregated JS files are turning into gibberish characters and the errors are thrown. I have spoken with my webhost and we tried some things but nothing worked. They had me put this code into .htaccess but it did not work:

[root@host ~]# httpd -L | grep deflate
DeflateFilterNote (mod_deflate.c)
DeflateWindowSize (mod_deflate.c)
DeflateBufferSize (mod_deflate.c)
DeflateMemLevel (mod_deflate.c)
DeflateCompressionLevel (mod_deflate.c)

Also I was not exactly sure where in .htaccess to put it. (under <IfModule mod_headers.c> perhaps?) At any rate this did nothing to help matters no matter where I tried that code. I feel like this is a bit of a needle in a haystack and might be tricky to fix but I am curious if anyone recognizes what might be going on so i can fix it.

** I should also note that litespeed Server is running on top of this so not sure if there are nay issues with that. I have not looked into this yet.

It's likely that your web server isn't sending the correct Content-Type or Content-Encoding header for compressed files.

Adding one of these to your httpd.conf file should solve the problem:

AddType application/x-gzip .gz .tgz

or

AddEncoding x-gzip .gz .tgz

There should be comments in your httpd.conf file that will help you determine which one's most appropriate for your situation (search for <IfModule mime_module> in that file if you're interested).


Reflection error on my first module development I'm using Drupal 8.0.1. Just I'm started to develop a custom module to simply show hello world text in /first path. Here is my code.

FirstController.php [It is in the path sites/all/modules/first_module/src/Controller]

namespace Drupal\first_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class FirstController extends ControllerBase {
  public function content() {
  return array(
      '#type' => 'markup',
      '#markup' => t('Hello world'),
    );
  }
}

first_module.routing.yml [It is in the path sites/all/modules/first_module]

first_module.content:
  path: '/first'
  defaults:
    _controller: 'Drupal\first_module\Controller\FirstController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'
    _permission: 'view first'

first_module.info.yml [It is in the path sites/all/modules/first_module]

name: First Module
description: An experimental module to build our first Drupal 8 module
package: Custom
type: module
version: 1.0
core: 8.x

I can able to see my custom module in http://localhost/admin/modules also I can able to install the module. But when I got to the path http://localhost/first it shows the error

ReflectionException: Class Drupal\\first_module\\Controller\\FirstController does not exist in
/home/aaa/Public/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityResolverManager.php on line 128, referer: http://d8.localhost/admin/modules

Where I would went wrong?? Any help!!!

a) in the route definition the path to the controller should start with backslash
b) in the route only one permission will work
c) you do not need to define type markup, just use #markup alone


How to change date field label? In my content I have one date field label, it is showing all uppercase letters automatically.

Example :I have given date field label as birthday(lower case) but it's automatically showing BIRTHDAY(UPPERCASE). How can I overcome this.

use Css if nothing is working to show the label in small letters.

text-transform: lowercase;


Drupal commerce get quantity per sku in hook_commerce_checkout_complete Inside this hook I need the total products per sku. For example, user #1 buy 2 products with the sku #7, user #2 buy 5 products with the sku #10. I need to know how to get:

sku #7 -> 2
sku #10 -> 5

I was trying something like:

foreach ( $order->commerce_line_items as $line_item ) {
   $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
   $line_item_wrapper->commerce_product->sku->value();
}

But it gives me just sku #7 and sku #10. Also, this function commerce_line_items_quantity($line_items) didn't help so much because it gave me just the total of all sku's, not individually.

This way I can award the user with some "user points" (I think is easier this way than using rules).

You need to wrap the $order object before looping over the line items. It also removes the need to wrap the line items explicitly.

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ( $order_wrapper->commerce_line_items as $line_item_wrapper ) {
  if ($line_item_wrapper->commerce_product->sku->value() == 'some-SKU') {
    // increment quantity counter, award points etc.
  }
}


Is there a way to implement drag and drop for image upload in drupal 7 I amn looking for a way to inplement drag and drop image upload for  the profile image field and serveral other image fields as well for drupal 7 is there a module that is easy to use or an easy way to implement uploading per drag and drop in template.php?

Thank you!

You can do this by using any of these modules :

Drag & Drop Upload.

  This module provides a Drag & Drop Upload element and widgets for a
  File and an Image fields.

Plup

  This module allows you to modify your content types with a plup field
  for drag and drop uploads.

Drag'n'Drop Uploads

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.


Drupal 7: When using the Features module and the database (e.g content type) is different than the matching Features component Drupal 7: When using the Features module and the database (e.g content type) is different than the matching Features component (e.g the same content type) what is used when viewing this component within the Drupal webapp?

If the Feature is overridden, then what you have stored in the database is what Drupal will be using until you revert either the whole feature, or the item in question (such as your View for example).

As an example, if you have an exported View and you make some changes, it will be read from the database. If you either update or revert your Feature, then it will go back to being read from code.


Views: Single Image Per Tag For examples purposes. Say I created a content type called ContentX with a image field and term reference field(Tag). I created 4 node(pages) of ContentX. All 4 nodes of ContentX have 1 Image to each node. Two of these nodes of ContentX have a Tag called TagA.  Two of these nodes of ContentX have a Tag called TagB.

I then create a view block stating that I want to view content from ContentX. In the view fields I make sure the images field is there. All 4 images of ContentX show.

THE ISSUE:
Say I want to show a single image from the 2 nodes with TagA. I go to filters,Content:TagA, check One Of: and bring up my tag which is TagA. HOWEVER instead of showing what I believe to be "One Of TagA", it shows both images of both nodes with TagA Tag.

THE OUTCOME I AM TRYING TO GET:
I am trying to get my View to show one image from 2 ContentX nodes with a Tag called TagA and one image from 2 ContentX  nodes with a Tag called TagB.

Any help?

In views pagerer you can limit "Items to display " section and give the option as 1 to limit ome image to display from that filter


Redirect beating out URL path and creating redirect loop Currently ran a bunch of updates on our site, and we're experiencing this issue:

Create nodea at /nodea
Change nodea's path to /nodeb

a redirect will be written added to nodeb: /nodea -> /nodeb

Create a new new node, and call it nodea, so the URL path then becomes /nodea for it
If you try to go to the new /nodea page, the redirect rule catches it first and sends you to /nodeb

I'm not sure what caused this, and it's a huge issue. (That example is, of course, just to show what's occurring; it's not the exact use case, but pretty close.)

Can anyone give me an idea on how to fix this? Or at least where to start looking?

This has since been corrected with an update to the redirect module.

There's now an "enabled" field on redirects, and when a conflict occurs (e.g. a new active alias is entered when that path is already a redirect), the redirect becomes disabled.


Easiest way to embed flash in a page? I am looking to embed flash in D7 on a simple page. How would I do this?

Or you can create a new text field for embed flash. Be sure that your WYSIWYG filter will allow the embed and object tags.


How do I modify a core field to use Ajax and add markup? I am still getting the hang of D8... I have some entity types with various reference fields. I need to ajax in other values from another node type when changing the value of the entity reference select field I have.

Node type form 1:

#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _______________________________  #
# |Node type 2 select reference |v| #
#                                   #
#####################################

Whenever I select a node from the Node type 2 select reference field I would like to Ajax in a specific view mode of the node as #suffix markup. After selecting a node the resulting form should look like this:

#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _________________________        #
# |Some node (node id: 2) |v|       #
#                                   #
#  * Node 2 value from field 'a'    #
#  * Node 2 value from field 'b'    #
#                                   #
#####################################

I have attempted using #ajax property in a hook_form_alter on the select field but am not getting it to work due to errors. What is the best approach here?

After much testing and finding a missing character in one line even I was able to come up with some working code:

<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

function fsed_entry_form_eform_submission_fsed_entry_submit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_faculty_member']['widget']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'fsed_entry_faculty_member_ajax_callback',
    'wrapper' => 'faculty-member-details-wrapper',
  );
  $form['field_faculty_member']['widget']['#prefix'] = '
';
  $form['field_faculty_member']['widget']['#suffix'] = '
';
}

function fsed_entry_faculty_member_ajax_callback($form, &$form_state) {
  $nid = $form_state->getValue(array('field_faculty_member', 0, 'target_id'));
  if ($nid) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $storage->load($nid);
    $build = $view_builder->view($node, 'eform_preview');
    $output = render($build);
  }
  else {
    $output = '';
  }

  $form['field_faculty_member']['widget']['#suffix'] = $output . '
';

  return $form['field_faculty_member']['widget'];
}


Add date field to drupal entity registration I created an event with a fieldset of dates. You're able to register to this event, but I would like to add an extra field with one of the dates of the event.

How can this be done (with the entity registrations module)?

Goto Strcuture->Registrations->YourRegistrationType and add a new field of type date.

You can use Field Validation Module to make sure that the entered field is between the selected date range of the content type on which you have the registrations enabled.

Note : You could also use the tokens module to make sure that this datefiled in registration type has default value of the starting date of the date field in parent content type.


Using the DB API to test against a trimmed value? I want to use the DB API (Drupal 7) to do a query like:

select my_field from table where trim(my_field) <> ''

where my_field is a text field.  My goal is to not get any values in the result that are made up of one or more spaces. (This is a greatly simplified example query, but you get the idea.) Is there any way to get that call to trim() in there? The only thing I could imagine trying was:

$query->condition('trim(my_field)', '', '<>');

which doesn't work at all.  Any thoughts?  Thanks!

You can use SelectQuery::where() for more complex requirements:

$query->where('trim(my_field) <> :val', ['val' => '']);


Display value from user input form I have this form which has 2 radio buttons. If I select the radio button labeled as one way, the return date and time will be invisible; if I select return, the return date and time will be visible. I just want to test if the data have been entered when oneway is selected. This is because when I select return, I can print out all the input values by user, but if I select oneway, I can't do so.

This is the code I am using.

echo "
Booking
";
$submit = $_POST['submit'];

if ($submit) {
  // Check the direction selected by user.
  if ($direction == "return") {
    if ($liner && $direction && $from && $f_date && $f_time && $destination && $t_date && $t_time && $txttotal) {
      echo "$liner/$direction/$from /$f_date/$f_time/ $destination/$t_date/$t_time/$txttotal  ";
    }
  }
}

In the Drupal Examples project you can find the ajax_example module with a similar form with dependent fields.

http://drupal.org/project/examples


Multilingual content and single language admin interface I want my site's content to be multi-lingual. I have a language switcher that can toggle between both the English and Spanish translations of a page. I want the administrative interface to always be in English, no matter whether you navigate to it from a Spanish or English translation of the page.

Here is my configuration at /admin/config/regional/language/detection:

Here is my configuration at user/1/edit:

My admin interface is always in English, but now my content is also always in English, no matter if I toggle the page to Spanish.

I have tried many settings, including the settings in Content language detection.

What is the correct configuration to achieve this?

/es/node/1

/admin/config/regional/language/detection/url

/admin/config/regional/language

On a fresh install, I could get it working that way:

In admin/config/regional/language/detection

put  Account administration pages on top of Interface text language detection an enable it of course.
enable URL method as second choice
enable Content language detection and put URL on top of detection methods.

In user/1/edit language settings :

set Administration pages language with your preferred language

There are various issues on D.O about that, maybe this is the most relevant  one : When content language detection is different from interface language detection, the detected language is not applied to the rendered content.

Apply these patches :

When content language detection is different ... (patch #24)
'Account administration pages' language negotiation causes 'access denied' in toolbar subtree caching (patch #10)
Admin toolbar should always be rendered in the admin language (if set) (patch #40)

Empty caches :

$ drush cache-rebuild

Language dropdown switcher and everything else seems now to be working fine !

An example of spanish content, strings passed through t() are translated, admin toolbar in english...

The same page edited: admin interface fully in english, but content shows  the correct translation....