Print just the value of Views field inside of views-view-fields template I cannot for the life of me figure out how to print the value of a field in the 'fields' template.  Currently, I'm doing this to strip the unnecessary html (don't laugh):

<?php $shortContent = $fields['field_short_name']->content; ?>
<?php $shortText = strip_tags($shortContent); ?>
<?php $strategy = $fields['title']->content; ?>
<?php $cleanStrategy = strip_tags($strategy); ?>
<?php $company = $fields['field_money_manager_company']->content; ?>
<?php $cleanCompany = strip_tags($company); ?>

<?php echo ''; ?>

    <?php echo '
' . $cleanCompany. '
'; ?>
    <?php echo '
' . $cleanStrategy . '
'; ?>

How can I just get the value of the fields without having to print the entire 'content' and then strip the unnecessary elements?

I guess you want to create a row header which contains some value from other fields. If it is your case, I will suggest you this solution.

Use fields in format

Add field Global: custom text

Then you can use the token, which is the value of field, with your custom HTML structure.

Please note that custom text field must be placed after the field you want to use. In my case, it is title. You need to exclude it from display, otherwise, there will be 2 titles.


Import external modules yaml config through own hook_update_N implementation I am trying to update a module on an old project of mine. In the meantime the module's devs added new configuration and schema yaml files but did't write the update functions for already existing sites.

How would you import all schema and config changes automatically?
Do I need to import the yaml files though Yaml::parse and then use \Drupal::configFactory() and \Drupal::entityDefinitionUpdateManager() in my hook_update_N function? Or is there an easier way?

If you have no data then reinstall the module.

If you want to keep the data then this depends what you have changed in the configuration. You can try how far you can get with the method you've described. If you only add fields, this will probably work. Also minor changes to a field can work. But if you change how a field is stored in the database this will not work.

The official way to do this is described here https://www.drupal.org/node/2554097.


Calendar add date programmatically I am having a bit of trouble figuring out a thing with Drupal Calendar.

I have created a custom content type , with a date field.
I display the dates as events in a Calendar style view.

I want to add custom "event" on the day(s) after this event,based on some PHP logic.
What would be a starting place to start modfitying it  ?

For example: I insert 26th of May as a date (in a node of my custom content type).
If the day is Saturday, I want the next day to be also marked in the calendar.

Since the event is a content type. You could use hook_cron to find expired events and add new event node.

Add node programmatically.

  $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

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

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

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

  node_save($node);

How to programmatically create node in drupal 7


How should I include  or  inside ? I'm trying to use a Google font, which requires adding either a <link> or <style> section inside the <head> per the below instructions. I am using a subtheme and can modify the  section directly in html.html.twig, if that's the right way to do it.

However, I noticed <head-placeholder>, <css-placeholder>, and <jss-placeholder> inside <head> and I am wondering if those are intended to be used to insert code from somewhere else.

What's the best practice for adding to <head>?

First, define a library in your theme that links to the font.

[THEME].libraries.yml:

fonts:
  css:
    theme:
      # Do not include http: or https.
      # Should start with a double slash.
      //fonts.googleapis.com/css?family=Source+Sans+Pro: { type: external }

This library is loaded by adding it to the theme's [THEME].info.yml file:

libraries:
  - [THEME]/fonts


Password may contain illegal characters Is it possible to change an option or overwrite the password validation so that a user can add characters like é to their password?

From the Login Toboggan config page:

  LoginToboggan automatically performs basic password validation for
  illegal characters. If you would additionally like to have a minimum
  password length requirement, select the length here, or set to 'None'
  for no password length validation.

If you check the logintoboggan_validate_pass you see:

  if (preg_match('/[\x{80}-\x{A0}'.          // Non-printable ISO-8859-1 + NBSP
                   '\x{A1}-\x{F7}'.          // Latin punctuations
                   '\x{AD}'.                 // Soft-hyphen
                   '\x{2000}-\x{200F}'.      // Various space characters
                   '\x{2028}-\x{202F}'.      // Bidirectional text overrides
                   '\x{205F}-\x{206F}'.      // Various text hinting characters
                   '\x{FEFF}'.               // Byte order mark
                   '\x{FF01}-\x{FF60}'.      // Full-width latin
                   '\x{FFF9}-\x{FFFD}]/u',   // Replacement characters
                   $pass)) {
    return t('The password contains an illegal character.');
  }

So your problem comes from Login Toboggan.

I think this automatic validation is only performed when user can set the password int he register process.


How to restrict previous date display in custom forms? I created a custom module for a form which accepts from date and to date as user input. I would like to restrict the user from selecting a date prior to current date.

Code snippet of my code

$form['oneway']['from_date'] = array (
  '#type' => 'date',
  '#title' => t('From Date'),
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
);

Can someone please help me out?

Approach to get today's date as Minimum date

Pass the JS options in '#datepicker_options'

$form['oneway']['from_date'] = array(
  '#title' => t('From Date'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

  minDate => 0 (Sets the min date to today's date)

  minDate => -1 (Sets the min date to yesterday's date)

More info: http://api.jqueryui.com/datepicker/#option-minDate


Create custom language not based on english I would like to add Canadian French as language, since there already is a French version of the site it would be very handy to just start from there.

When you create a new custom language it always copies the english language into the new one, you cannot select the language it should copy from. I also tried to set the default language to french and then create the new language but that doesn't change anything.

Anyone an idea how to do something like this? Or an easy way to switch the english for french after the language is copied?

Be sure to create the new custom language:

admin/config/regional/language
(use fr-CA language code)

Get the French po files from here:

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

Then import (choose Canadian French):

admin/config/regional/translate/import


How to store additional_settings value when adding a node? Since storing node type additional_settings is done without the need for calling any other hooks, I quite have a problem to store a simple string from additional_settings on node add form.

After the admin enables a feature on the node type form he/she is offered the following form when adding a node:

$form['MY_MODULE'] = array(
  '#type'         => 'fieldset',
  '#title'        => 'Custom String',
  '#collapsible'  => TRUE,
  '#collapsed'    => FALSE,
  '#weight'       => -99,
  '#group'        => 'additional_settings',
  '#attached'     => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.js',
    ),
  ),
);
$form['MY_MODULE']['MY_MODULE_string'] = array(
  '#type' => 'textfield',
  '#title' => t('Enter a string'),
  '#default_value' => '',
);

I've seen other modules, like comment.module or nodeapi_example.module where they then call hook_node_insert() and I tried that as well. I happily can see my string within dpm($node), but then I'll get a PDOException: SQLSTATE[42S02]: Base table or view not found. Do I have to follow any naming conventions on how to name the table? Or do I have to create it first (where)?:

db_insert('MY_MODULE_string')
->fields(array(
    'nid' => $node->nid,
    'vid' => $node->vid,
    'string' => $node->MY_MODULE_string,
))
->execute();

Turned out I simply had to look into nodeapi_example.install to find out about hook_schema() to create a new database table where I then can save my values to. So I created an install file and put the following code inside:

function MY_MODULE_schema() {
  $schema['MY_MODULE_string'] = array(
    'description' => 'Stores information of extended content.',
    'fields' => array(
      'nid'    => array(
        'description' => 'Node ID that the string is applied to.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'vid' => array(
        'description' => 'Revision ID, as we are tracking strings with node revisions',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'url' => array(
        'description' => 'MY MODULE string',
        'type' => 'varchar',
        'length' => 19,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('vid'),
    'indexes' => array(
      'nid'   => array('nid'),
    ),
  );
  return $schema;
}


Assigning (adding) an entity reference when an Order process is completed In Drupal 8, I am needing to know how to assign/add an entity reference of an e-book to an multivalue entity reference field of the user when an order with the e-book is placed. This will allow the user to then access only the e-books attached to his user account.

What hook do I use? how do I know if there is a product in the order that have field_ebook=true? Then how do add it to the list of entity references?

Not a hook but an event.

Orders have an attached workflow. You can listen to the event of an order being placed, see the state_machine module for documentation on this. Basically, you need to define an event subscriber service, subscribe to the event commerce_order.place.post_transition, then check if order is an ebook and if so act based on the order customer ID.

The subscriber method needs like this:

public function orderStateChange(WorkflowTransitionEvent $transition_event) {
  $entity = $transition_event->getEntity();
  // Check the transition id and whetever else you need on the order and then do your thing.
  if ($transition_event->getToState()->getId() == 'completed' && ...) {

  }
}


How to get a taxonomy custom image field URL value I've created an image 'field_term_preview' field on the taxonomy vocabulary and trying to get this URL in my custom module:

$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, null, true);

foreach ($terms as $term) {
    if ($term->getName = 'Term with preview')
    {
        foreach ($term->getFields(true) as $field)
        {
            if ($field->getName() == 'field_term_preview')
            {
                var_dump($field->getValue());
            }
        }
    }
}

This code shows only target_id, alt, height, etc.

How to get the URL to the preview image?

In Drupal images are File entities, the target_id is the File ID. So...

$fid = $field->getValue()[0]['target_id']; // File ID,

// Note the [0] in the array. We assume there is always going to be 1 image here.
// If your field allows more than 1 image, you will need to loop through each $field->getValue()

$file = \Drupal\file\Entity\File::load($fid); // load File entity object

$file_url = $file->url(); // get the URL.


Static form to print on TPL I have created a module i can use to create multiple blocks, now with one of those blocks, there is a requirement for a form (which the user needs to be able to see). However, this does not require any Drupal "Save" interactions.

Its a very simple static form that is manipulated with Ajax functionality. I have just coded this form simply within the TPL file.

<form name="formelement" method="post">
    <input name="data" type="hidden" value="" />

something here

something there

    <input required="" type="text" class="" name="blah1">
    <input required="" type="text" class="" name="blah">

        <button type="submit" class="btn" href="">submit</button>

</form>

Question - I need to be able to get the $_POST in a function - what would be the best method of creating this form with the .module file or the drupal 7 api and then print it within the tpl file

You can create form by develop custom module then you use developed form any where in node or block.

Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info
Create a file sites/all/modules/own/form_test/form_test.module

(start it with <?php tag, but don't add ending ?> tag)

function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

More details


product in cart but when clicking on cart it shows empty I really don't understand this one...
I have Drupal commerce on Drupal 7.

When I'm adding a product it shows in the cart summary just fine. but when I go on mysite/cart ...the cart is empty. It is not a browser issue I think. Any help on that odd problem would be more than just appreciate, please.

I tried clearing the cache on the server, browser ..none worked

If you do a quick search of the issue queue for "Views results empty", you should turn up the solution: you've probably customized your shopping cart View to include a product relationship, but your test user must not have access to view all products. When Views goes to render the results and performs the access check on the View results, it won't show anything as a result.

If this is the case, my recommended solution would be to edit the View, open the advanced settings fields, and edit your query settings to disable SQL rewriting for the View.


How do I find the user whose field is equal to the email address? I am trying to fetch a Username where a field equals the value of another field.

On my content type, I have an Entity Reference fields that creates a select list of email addresses.

In Rules, reacting on Creating/Updating nodes in this content type, I am trying to Fetch a User Entity where the value the select list field equals the user's email.

How can I do that?

What I have tried:

I first chose to "Fetch Entity by Property".

The Value is "User", the Property was set to "Name", and the Value was set to the title of the Entity Reference field in the first screenshot (The title of each node in the select list is an email address)

The Fetched Entities are called "fetched_user".

When trying to Add a Variable, it shows multiple values, so I assume I would need to make a loop first.

So I created a loop:

I am very lost on what to do next. Can anyone help me?

Thank you.

Your first mistake is in your fetch by property action. The property must be set to email for the users to be found.

After that, the fetch by property action will always return a list even if it's only one result. So you just need fetched-user:0:name. No loop required.

In php, 0 is the first item in a list.


What approach for showing custom user fields on a node? I've added a few custom user fields which users complete when registering.

What is the simplest approach to show these fields when viewing content that user has created?

For example, when viewing a blog entry I can see the 'submitted by..' and their name. I would like to use my custom user fields to expand that summary.

I've got no problem using views, or creating/modifying the theme etc, but I'd like some guidance on the easiest approach before I start out. (It's too easy to hack away on one approach in Drupal when there's a much easier solution!)

Ok, I'm only using drupal 6 but I think these answers can lead you to a solution:

With the core profile module there is a block "Author information"
You can use the Author Pane module but it doesn't have a stable release for D7 yet.
You can use views to build an author block:

If you're using profile from core:

  Create a user view
  Set the argument to User: uid
  Choose "Provides default argument" set to "User ID from URL" and check "Also look for a node and use the node author"
  Add your user profile fields.

If you use Content Profile

  Create a node view
  Set the argument to Node: Nid
  Choose "Provides default argument" set to "Node ID from URL"
  Create a relationships to retrieve the content profile
  Add your content profile fields.


Superfish themable hooks not getting called According to superfish.module these following theme hooks are available.

 function theme_superfish($variables) {

    function theme_superfish_build($variables) {

    function theme_superfish_menu_item($variables) {

    function theme_superfish_menu_item_link($variables) {

but for some reason using these in my template.php only theme_superfish is getting called.

function nph_superfish($variables){
 dpm("nph_superfish");

        dpm($variables);

  return "HTML";
}

works

function nph_superfish_menu_item_link($variables) {
dpm("theme_superfish_menu_item_link");
      $menu_item = $variables['menu_item'];
      $link_options = $variables['link_options'];
      return l($menu_item['link']['title'], $menu_item['link']['href'], $link_options);
    }

doesn't work

This post is probably the most comprehensive to answer the question for what I am trying to achieve (I want to add classes to menu items based on the title).  Any ideas what might be happening?

UPDATE:

I just noticed a setting on the settings page, not mentioned in any of the answers I found around the web....

UPDATE: I've  just noticed it says Default:enabled ..., so by checking it I'm disabling it...

As in my image

Make sure these are checked or the theme hooks wont work, and they need to be checked even though, it says default:enabled.


How to translate country names I need to translate the names of countries in drupal. I am using countries_get_list, looping through the array and saving it in another array but wrapping the country names in t(). I'm not so so sure but it seems this isn't working.
I was doing something like

$new_array = array();
foreach(countries_get_list() as $key => name) {
    $new_array[$key] = t($name);
}
return $new_array;

You should never use t() to translate variables, unless the text that the variable holds has been passed through t() elsewhere:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/73#sec_translating_vars

In this case country_get_list() calls _country_get_predefined_list(), and inside this function country names are passed through t():

https://api.drupal.org/api/drupal/includes%21iso.inc/function/_country_get_predefined_list/7

So, if you have country strings translated in your database (as Molot says) translation should work.


How do I prevent a Node from being deleted? I want to make some checks and, under certain circumstances, prevent a node from being deleted.

My module makes checks in HOOK_form_BASE_FORM_ID_alter() when the node is being created, but I cannot see where I can get control when the node is being deleted.

Using hook_node_access() is one option:

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

...

function MYMODULE_node_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'delete') {
    if (some_access_function($entity, $account)) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  return AccessResult::neutral();
}

This method has the advantage of preventing deletion through other methods (e.g. REST) at the same time, and will automatically remove the delete link and tab from the node form anyway.


Is memcache only for logged in users? I am trying to understand what the role of Memcache is. A few of my friends who have been working with Drupal for more than a year tell me that Memcache would only work for logged in users, and I would have to look to Varnish or Boost for caching the content shown to anonymous users.

While I understand that varnish acts as a reverse proxy, and caches a copy of the page, I wanted to know if anonymous users make a request, and if varnish does not have a cached copy of it, would the webserver route the request to Memcache, or would the request directly go to the database?

Architecture example: Varnish/Boost, web server, Memcache, database.

In short, yes memcached will benefit both anonymous and authenticated visitors (even if you also use Varnish).

Memcached and Varnish operate at different layers.  Varnish caches entire HTTP requests (and sometimes edge-side includes, but this is less common in the Drupal ecosystem). Memcached stores frequently used data within the application, and it is a replacement for the cache_* family of database tables.

Memcached will speed up anonymous requests when the Varnish cache misses or is bypassed.


$ is not a function in drupal 7 theme $(function(){
  $('.slider').mobilyslider({
    content: '.sliderContent',
    children: 'div',
    transition: 'horizontal',
    animationSpeed: 500,
    autoplay: true,
    autoplaySpeed: 9000,
    pauseOnHover: true,
    bullets: true,
    arrows: true,
    arrowsHide: true,
    prev: 'prev',
    next: 'next',
    animationStart: function(){},
    animationComplete: function(){}
  });
});

I am integrating the above JavaScript file in a Drupal theme, but it is giving me the "$ is not function" error. I googled it, and changed the code bro the below, but it doesn't work either.

(function($) {
  $('.slider').mobilyslider({
    content: '.sliderContent',
    children: 'div',
    transition: 'horizontal',
    animationSpeed: 500,
    autoplay: true,
    autoplaySpeed: 9000,
    pauseOnHover: true,
    bullets: true,
    arrows: true,
    arrowsHide: true,
    prev: 'prev',
    next: 'next',
    animationStart: function(){},
    animationComplete: function(){}
  });
})(jQuery);

The above code gives me following error:

  $('.slider').mobilyslider is not a function

The first error you were getting was because $ isn't defined as jQuery in Drupal 7, to avoid conflicts with other libraries. Adding the closure fixed that, as in your second code example.

As long as the mobilyslider library is definitely loaded into the page, the problem is probably that you're attaching the event before the DOM is ready...so the elements you're trying to attach to don't exist yet.

You could use the standard $(document).ready() method to solve this if you want to, or else use Drupal JS behaviours. For Drupal 7 that code would look like this:

(function($){
  Drupal.behaviors.mymodule = {
    attach: function(context, settings) {
      $('.slider', context).mobilyslider({
        content: '.sliderContent',
        children: 'div',
        transition: 'horizontal',
        animationSpeed: 500,
        autoplay: true,
        autoplaySpeed: 9000,
        pauseOnHover: true,
        bullets: true,
        arrows: true,
        arrowsHide: true,
        prev: 'prev',
        next: 'next',
        animationStart: function(){},
        animationComplete: function(){}
      });
    }
  };
})(jQuery);

Be sure to pass in context to your jQuery selector for reusability.

See Managing JavaScript in Drupal 7 for more info.


Display entity as options_select multi-select Below is my code for the view. I have tried multiple = true, multiple_values=true, multiple = multiple. None have worked.

->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [
        'match_operator' => 'CONTAINS',
        'size' => '60',
        'autocomplete_type' => 'tags',
        'placeholder' => '',
    ],
])

The options_select widget will automatically be multi-select if the cardinality of the field is multiple. Make sure your field is created as such, e.g.

use Drupal\Core\Field\FieldStorageDefinitionInterface;

...

$fields['foo'] = BaseFieldDefinition::create('entity_reference')
  ...
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [],
  ])
  ...

Incidentally, options_select has no settings, so you can provide an empty array instead of the autocomplete settings you're currently using.


My slider's images have larger file-size than their originals I have a slider in my homepage and this slider has 3 photos named a.jpg, b.jpg, and c.jpg.

The original file's sizes are (respectively), 42kb's, 20kb's, 52kb's. And yet when I download them from my slider (Flexslider) they whey much larger (c for example is 191 kb's).

Replace image style from the Slider's View (At Views module). I kept it without any style so the image won't be scaled to a larger style (You could scale it yourself with CSS in the relevant Div at the slider and it won't affect size).


What are the alternatives to the Calendar module? I have a requirement to add a calendar to my Drupal 7 website. Currently the Calendar module has an alpha version. This is a little subjective, but I was wondering if the Calendar module is stable enough for my needs. Are there alternatives?

Well, in my recent experience is not yet ready to production, but it depends on your needs. Maybe most of this is because the "partner" module, date, has lots of issues now.
I suggest you test both: Calendar and FullCalendar. The Calendar module is more powerful and flexible, but if you need a simple calendar, FullCalendar is ready to go now.


Best way to allow multiple users to edit a node but require approval? I am looking for a way to allow multiple "normal users" to suggest changes to existing nodes, but only once they are approved by admin, should they take effect. I am not sure how this would work in the case where multiple users make changes, but if stackoverflow and drupal stack exchange can do it, I'm sure it must be possible.

I had a look at Node Changes, but its not technically ready. Is that the only option available to me?

You can look into the revisioining module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You can set the role based permision for create , edit, view and delete revision of a content.


Can user UUID be null? I have a Drupal 7 site with a bunch of users. I want to migrate the users to Drupal 8 but not any of the content so I'm writing a crosswalk. Drupal 8 has uuid in the users table. Is there a way I can compute this or can I just set it to NULL? Thanks!

No, cannot be empty.
You can generate one with
$uuid_service = \Drupal::service('uuid');
$uuid = $uuid_service->generate();

If you use User::create it will automatically generate one for you.
Drupal\user\Entity\User::create([
  'uid' => $uid,
  'name' => '$user_name,
  'mail' => $email,
  'roles' => [],
  'pass' => [
    'value' => $hashed_drupal_7_password,
    'pre_hashed' => TRUE,
  ],
  'status' => 1,
])->save();

Rather than code it from scratch. The proper, Drupal way, to migrate is
using all of these:

core's migrate
migrate plus
migrate tools

I suggest your read this article A Quick Guide to Migrating Drupal Content from D7 to D8 which goes over how to migrate users and other scenarios.


Accessing Additional User Profile Fields I added a dozen or so new fields (in Drupal 7) to the user profiles using:

Configuration -> People -> Account Settings -> Manage Fields
(admin/config/people/accounts/fields)

How can I access these values?  They do not seem to be part of $user

Tried, without success:

global $user;
var_dump($user);

I think I found it. There is one additional step it seems.

global $user;
$user_full = user_load($user->uid); // user_load(uid) returns the complete array
var_dump($user_full);

I now have access to my custom profile fields through $user_full


Product image is not shown in View Mode Node:Product List I'm starting with Commerce Kickstart 2 together with demo store.

I added a product and upload one image, this product has one of the demo store variation types (Bags & Cases) and the product display type associated.

It seems simple since I didn't change nothing. But when I click in main menu the products already there are listed fine, with product image, only my new product don't show the image.

I see in variation types Bags & Cases that the Images field, Column Format, is defined as image delta, Image style: product_medium. And that is the point. In MySite/sites/default/files/styles directory are the styles of images. In that directory there is the product_medium directory where the images showed when in View Mode Node:Product list (the list of bags listed when click in To carry).

Well, the fact is when I create the product there is no option to load an image that will saved in MySite/sites/default/files/styles/product_medium directory. And that's the problem. Since when I manually copy the image to that directory, the image is showed up.

Where I define this product_medium image?

Could it be that your file folders are not setup correctly? Checkout drupal.org/node/15368 Also check your database log if there are any file related errors reported, more info at drupal.org/documentation/modules/dblog


How to get higher weight range for vocabulary I found the line in the taxonomy.admin.inc, but i didn`t want to change it in the core. So, How can I get it in my module to override the #delta of the vocabularies?

With the function I didn`t get a solution:

function <MYMODULE>_form_alter($form, $form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as $vocabulary) {
        if(isset($vocabulary['weight']['#delta'])) {
            $vocabulary['weight']['#delta'] = 20;
        };
    };
};

Remember to pass value by reference.

function <MYMODULE>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as &$vocabulary) {
      if (isset($vocabulary['weight']['#delta'])) {
        $vocabulary['weight']['#delta'] = 20;
      }
    }
  }
}


View users contributed content in profile I have users that have profiles using Profile2 module. I created a content type called Projects. A user can add a project, it has fields: title, description, and file. I would like to add a view to the users profile page that lists all of their Projects.

How can I connect the profile to the content author and use a contextual filter to get only that users content when viewing their profile?

Any help is greatly appreciated.

Edit: An example to clarify:
If user1 is logged in and views his profile he will see a list of his projects.

If user1 views user2's profile he will see a list of user2's projects.

In the views UI

Your view must be a view of nodes
Then, add a relationship with the node's author (the relation is: Content: Author)
Then, add an other relationship : select user and check profile. Then you can use the profile node in Contextual filters or Filter criteria. The technic part is that it is a relationship of relationship ;)


Filter content by group I use Drupal 7 with the Search API, and the Facet API modules.

I want to create a facet that shows all OG groups. When I click on an OG group all its content associated will be draw.

How can I achieve this?

Using the modules you described:

Create a index containing all the nodes that are group content
Edit the fields of this index and add a relationship to 'Groups' (at the bottom of the page)
You will get additional (group)fields available
Check the one named "Groups » title" and change the type to "string" (instead of default fulltext)
In the Facet tab, make the facet available, and place the block.

This should do the trick!


How to retrieve default Title in custom module block I have custom module that implements a block with our own template file to render:

function MODULE_NAME_block_view($delta = ''){
    $blocks = array();
    switch($delta){
        case 'twitter_feed':{
            $blocks['subject'] = t('');
            $blocks['content'] = theme_render_template(drupal_get_path('module', 'MODULE_NAME').'/inc/block--twitter-feed.tpl.php', twitter_feed_config());
            break;
        }
    }
    return $blocks;
}

I would like to pass the title value set in UI in blocks section to the template via the function twitter_feed_config specified above as following:

function twitter_feed_config(){
  return array(
       'title' => 'title set by user i am unable to retrieve'
   );
}

However, I don't seem to find a way to retrieve the value of title for this block configured via UI in the admin/block section. How to get this title value, so i can pass it to the template for rendering? Thank You

I think you should use hook_block_views_alter(&$data, $block).

Var $data['subject']; will have the title info of the block as per my knowledge.


Node post date in views exposed filter as a select list I want to add a node post date exposed filter to the views in the following format.

The date exposed filter will be a select list with the following options:

All
Today
Yesterday
Past Week
Past Month
Past Year

It it possible with views or I have to do some workaround?

No one has an answer for this question?

You can start with Views, dealing with Combined filters. Try it with option Grouped.


Elasticsearch-Connector: can't index with Search-API Im using latest Drupal 8.x with Search-API 8.x-1.5 und Elasticsearch_Connector 8.x-5.0alpha1.

I can add a cluster and via Search API I can also connect to the Elasticsearch Server. But when I try to add an Index via Search API the following error comes up:

{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [id]"}],"type":"mapper_parsing_exception","reason":"No handler for type [string] declared on field [id]"},"status":400}

Does anyone know of such an error and can help me with that?

Elasticsearch has deprecated the string type in 5.x versions, and is now using text or keyword. (see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/string.html)

In /admin/config/search/search-api/<CLUSTER>/<INDEX>/fields, you may change string by text in ID field. Considering this is an integer -id-, you may choose the type integer.


Only render translated nodes, prevent rendering of base language node Having an entity reference, Drupal 8 automatically renders the base language of a referenced entity if it isn't translated yet. Is there a way to globally prevent that? So if there is ContentType1 referencing ContentType2, both have a default language of en-gb. Translating ContentType1 to de-de will by default still show ContentType2's en-gb node unless I manually translate it or change a thing.

What I currently do is comparing the current page language \Drupal::languageManager()->getCurrentLanguage()->getId(); with the current node language $variables['node']->language()->getId(); and return an empty node.html.twig.

Is there a better solution? Especially when you have multiple node.twig.html

One way to think about it is to disable language fallback mechanism in Drupal. Although there are 3 different modules which handle language fallback priority, none of them provide such functionality.
However, the module Disable Language allows admin to disable an entire language entirely without deleting the content itself.
I think you can use its code to implement an EventSubscriber which checks whether the node has a translation for the current site language then return a NotFoundException in this case. This will cover direct node access.
I'm not entirely sure how to deal with nodes loaded via DB. I think you can use hook_entity_load for this case.


Getting the actual on/off value from a radio button instead of 1/0 I'm trying to store some data from an EntityForm to a txt-file.
This can be easily done with an entity wrapper, but when I get the value of the radiobutton (boolean) they selected I always get 1 instead of the value attached to that button (male/female).

This is my code:

$wrapper=entity_metadata_wrapper('entityform', $submission);
$wrapper->field_sex->value();  //this gives 1 instead of male

Try not to mix up the concept of an input's value and its label. They're two different things.

The value of a boolean field can only be, by definition, 1 or 0. It's a boolean after all. The label for the options can be anything.

To load the labels associated with those values, you'll need to load up the field definition:

$info = field_info_field('field_sex');
$allowed_values = $info['settings']['allowed_values'];
$label = $allowed_values[$wrapper->field_sex->value()];


Reindex Search API indexes for Behat testing I tried to use index the newly created contents to be able to test a page, but the problem is most of the times the tests fails, because the indexing process not finished yet until the contents starts checking. (i.e. if I stop before pageload with a breakpoint the testing, then the next steps always pass)

Method 1:

$search_api_index = search_api_index_load('SEARCH_API_INDEX_ID');
search_api_index_items($search_api_index);

Method 2:

search_api_cron();

The question, how can I call the indexing to wait until it's fully indexed before it goes forward?

The ultimate solution is $search_api_index->server()->commit() which needed because, there's a commit delay which you can set inside the solrconfig.xml and this delay cause the problem. (Or you can just sleep(1) your code, but that's not flexible at all and ugly...)


How to choose between Bean, Boxes and Fieldable Panels Panes? Bean, Boxes and Fieldable Panels Panes all provide similar functionality. I have trouble understanding what exactly the differences between them are.

What are their advantages/disadvantages compared to each other? Are they geared towards different use cases?

I want to use some kind of blocks in Panels to add custom content - content editors also need to be able to add content, in that sense the blocks I need are not pure configuration. But I also use Features...

Edit: I'll add what seem to be the main differences

Boxes

Largest userbase (~ 11500)
Treats blocks as configuration (i.e. the content ends up in your features)
Modules offering integration

Beans

Has recently become popular, ~1000 installs
Treats blocks as content, but allows exportability of their configuration via machine name (e.g. via Bean Panels)
Modules offering integration

Fieldable Panels Panes

Smallest userbase (~ 400)
From the author of Panels/Views/etc.
Panes cannot be used as regular blocks in theme regions like beans or boxes (I assume)
I wonder what the advantages over Bean mentioned here are ("offers additional features that makes it easier to empower content admins to lay out certain pages")

It's perfectly possible to make a D7 site without blocks if you can live without dashboard.
Our new - content driven - site is being built on panels with workbench as a suitable (for us) alternative to dashboard. Arjan appears to already understand this.

On to the alternatives.
Read Your site should be full of beans.
The problem with boxes is the danger regarding overwriting existing content when using features. But read Fabian Franz's comment in the same article. Beans has many options. I'm not comfortable regarding management, scalability and performance. Hardcore developers that are fluent with panels use Fieldable Panels Panes. Fieldable Panels Panes lack documentation and examples.
What should get everyones focus and effort for D8 is the wscci-initiative. It allows for REST-calls, including for example DELETE. This could permanently tackle the problem of overwriting site builder configuration on code rollouts.


D6 i18n slow due to huge locales_source table. How can I speed things up? I'm working on a site that slows down to an unbearable crawl when you view it in a different language (specifically "zh-hans"). When looking at the Devel query log, this appears to be because this query takes about 5 minutes:

SELECT s.source, t.translation, t.language
FROM locales_source s
LEFT JOIN locales_target t
  ON s.lid = t.lid
  AND t.language = 'zh-hans'
WHERE s.textgroup = 'default'
  AND s.version = '6.25'
  AND LENGTH(s.source) < 75

The reason it takes so long is that the locales_source table has almost 1 million rows, even though there are only 1 thousand nodes on the site. This seems like an extremely large amount to me. So my questions are:

Is this normal?
If not, how can I go about identifying which of the data in locales_source is not applicable or bad? I can't find the way to map it back to the original source (node body, title, menu item, etc.) so I'm not sure how to determine if the original source exists and is valid.

Re: #2 above, the locales_source table looks like this, if it helps.

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| lid       | int(11)      | NO   | PRI | NULL    | auto_increment |
| location  | varchar(255) | NO   |     |         |                |
| textgroup | varchar(255) | NO   | MUL | default |                |
| source    | blob         | NO   | MUL | NULL    |                |
| version   | varchar(20)  | NO   |     | none    |                |
+-----------+--------------+------+-----+---------+----------------+

Yes, 1 million is an extremely high amount. That's not normal.

The amount of nodes should have nothing to do with that table, because content translations happens by creating separate nodes for each language that are linked together.

What is added to that table are all strings which are passed through t(), and everything that is registered through the various i18n modules (menus, terms, ...).

t() must not be used for user generated content but this is often done and I suspect that might be responsible for your amount of rows in that table. The problem with something like t($term->name) is that the identifier is the term name. If you change your original term name, then your translations are lost and the source entry will stay there forever. See below on how to identify problems here.

The interesting column to check where something is coming from is the location, there are 3 different possible types of values in there:

When imported from a .po file (e.g. official translations from localize.drupal.org), the location is filename:line. These are most likely ok and should be much much less than 1 million.
Translations managed by i18n_string have some sort of context/identifier in there, that looks like this: taxonomy:term:1:name. That allows to look up a translation based on a unique identifier of something that won't change. There could be many of these, if you have many taxonomy terms/huge menus but again, not 1 million (except you have 1 million or close terms). You can also identify them by the text group, case 1 and 3 is both textgroup default, while this has a textgroup for each source type (taxonomy, menus, ...).
Every string passed to t() that is not yet in that table is automatically added. In that case, the location is the URL of the page where this string first occured. Those will probably be the most interesting ones for you.

What you need to find out is which pages are adding these dynamic translations and then track down the exact module/call and fix it. There two ways to start. First, look at the most recent additions to that table to see what URL's you have in there (last page on the translate overview, or you can look directly in the database). The second option is group by location and then sort by count(), which might forever on a table of that size. But it's likely that a large amount of sources have been added on the same page. Once you know the page, it's time to do some profiling there and track down who exactly is calling t() often.

Two contrib module examples that I recently identified while doing a performance review on a site:

The site had two hierarchy/relation select boxes using hierarchical select, which currently falls back to t($term->name) if i18n_taxonomy is not installed. That was a free tagging vocabulary with 10k terms and this resulted in 40k calls to t(), which obviously also makes it extremely slow. This issue is still there, I need to find the time to provide a patch.
The other case was the print module, which "translated" the node title on the print page.  I think this was recently fixed, but the already added sources will stay in that table.

Once you identified the problem, you need to fix it and then remove the existing strings from that table, e.g with a like 'taxonomy/term/edit/%' condition for the term edit pages. Just removing the strings can be useful to quickly check how it affects the site load time but they will get re-added as soon as the problematic code is executed again.

For the record, the site that I looked into had "only" 40k entries in that table but even that resulted in cache entry of the short translations of 10MB (in PHP, not serialized).


Dynamic colors for node bodies In Drupal 6, I have a CCK colorpicker field, and I would like to use the color for links, b/em tags, and headers in the body of the node.  In D7 i could use drupal_add_css to create inline CSS that is not aggregated, but that is not available in D6.  Is there a way of doing this that doesn't involve preprocessing the body and adding inline styles to the individual elements?

I haven't done it to make inline CSS, but you could try creating a new region in your .info, and using drupal_set_content to add structured content.  You can then parse / format it in a template_preprocess_page, and then print it in your page.tpl.php.  I've had to resort to similar tricks in the past to work around this.

I suspect your best place to call drupal_set_content from is a hook_nodeapi(&$node, "view")


Separate frontpage per domain? I have two sites, built in tanden but launched at completely separate points.

Both of them need access all content from both sites in some form, so that for example auto-completing references can be used across the two sites. For sake of brevity, I suggest exactly how that is done is kept out of this question.

The real difference between the sites, is that

One domain shows content types W and X, while the other domain shows Y and Z, they
Each domain has a completely separate front page.

How would you go about solving the above two problems?

In my mind, the big advantage of using Panels is so that you can extend/alter sites like this in the future, without needing a lot of rework.  In a lot of ways, Panels provides a framework for futureproofing sites.

While I am not sure if I have used Domain CTools,that is the first approach I would take.  I essentially use a similar approach using Mobile Tools in combination with Domain Access for providing split desktop/mobile sites that share some, but not all, content and features.

The access rules that Domain CTools provides will show up in the visibility and selection rules inside Panels.

For the node pages, I would enable the default node override page inside Panels, and then make variants for each of my content types.  I would then assign access rules to each, based on the domain.

For the home page, I would make a new custom page and set it as the home page.  I would then make two variants, and make a selection rule based on the domain for each.

The other thing to think about is how nodes get used in places other than the node view page.  For example, if you should double check your views and add access controls as needed.  Assuming the approach outline above, you could also use the Domain CTools access rules.  Depending on what other uses there are, you may need to investigate whether you need a custom hook_node_access() for your site.


How to get the paragraph information in a custom display suite code item I want to add a custom field for a paragraph item in display suite,
but I don't know the name of variable.

I try a print_r($entity) and nothing is returned. How can I find out what the object name is?

I'm using a view and want to display the first paragraph of text type
  and the first paragraph of data type . But only the first one .
  Currently they all come out in the view

In Views click on your paragraph field, mine is called "test".

Then in Multiple Field Settings, change Display to 1


Is there a way to share content between users? Drupal 7... I just want to be able to send some information via content type from one user to the next such as an event. One user will create this content and only wants it seen by a select few of other users. Is there a way to make this happen. What would be cool is a field on my content type that collects usernames or emails for a private message or invite to view the content...

You will find that the Organic Groups module is very useful for allowing users to protect content in this way.  You may configure og such that only certain users may create groups, or if you prefer, as in the use case you describe above, many users may be allowed to create new groups for diverse purposes. There are many options on inviting users to groups, allowing users to request memberships to groups, or just letting anyone join groups automatically. It looks to me as if the behaviour you want can be achieved with just the og module, but if that is not the case, there are also many additional contrib modules that can extend or modify og's behavior.


The Mobile theme module conflicts with the default cache I am using the Mobile theme module in order to load a specific theme in the mobile devices. when I enable caching, the module does not work properly.

More specific, when a page is first visited from a a mobile device for the first time, it will always come up with the mobile theme, even when it is not visited from a mobile device. When a page is visited from a desktop device for the first time, it will always come up with desktop theme even for mobile devices.

I don't think there's a straightforward solution to this in Drupal7 but there are some workarounds available:

Use JavaScript to detect and do the switch
This issue happens because D7 uses page URL as page's cache id (CID). To distinguish different devices for same page, you'll need to alter the CID somehow so it looks something like CID_phone, CID_tablet and CID_desktop. I used mobile_detect module before and know there are some patches on this. Do keep in mind there's a side effect that this approach will triple the amount of CIDs in you database table.
If you use Varnish you can try something like this


How do I set "has_title = false" for an existing node? I understand how to set the node attribute 'has title' via the hook_node_info() when creating a node programmatically. However, I struggle to edit this attribute for a node that has been created with the built in Drupal node designer. Can anyone please give me advice on how to modify this attribute, for example on a node such as "article"? Which hook do I use and when? Could I even modify this attribute directly in the database and therefore get this changed permanently?

There is good comment in source:

// title_label is required in core; has_title will always be true, unless a
// module alters the title field.
$type->has_title = ($type->title_label != '');

So, you can alter the form and customize it.
I have created a simple example, because I found it interesting.

/**
 * Implements hook_form_FORM_ID_alter().
 * Alter 'node_type_form'
 */
function nodetitle_off_form_node_type_form_alter(&$form, &$form_state) {

    $type = $form['#node_type'];
    $default_value = $type->has_title;
    // Create simple flag
    $form['submission']['nodetitle_off'] = array(
        '#type' => 'checkbox',
        '#title' => t('Has title'),
        '#default_value' => $default_value,
        '#weight' => -1,
    );

    $value = !empty($form_state['input']) ? isset($form_state['input']['nodetitle_off']) : $default_value;
    if (!$value) {
        // Make field not required and empty
        $form['submission']['title_label']['#required'] = FALSE;
        $form_state['values']['title_label'] = '';
    }

}


Image uploading not working in server In a content type have a field image upload.its image upload type is jpg,png,gif.
When we upload these image type of images an error is coming :

  The selected file Chrysanthemum.jpg could not be uploaded. The file is
  not a known image format.

But its running in local not in server. What is the problem ?
Please help me.
Thanks

Below are the two ways. I hope help you to solve your issue.

1.
Your files via FTP into the image_import directory aren't being given the correct permissions. You have to provide the permission i.e. chmod 660 * on them in the image_import directory the files were recognized correctly and the import worked.

OR

2.
In /includes/image.inc, change line 117 from:

  if (!is_file($file)) {

to:

if (!is_file($file) && !is_uploaded_file($file)) {

Then check is your issue is solved or not. If not then try once updating below with second way :

On the admin/settings/file-system, try changing C:\WINDOWS\Temp to sites/default/files/temp (also made sure it was writeable by the web server).


User profile page title is mistake I use login toboggan and profile2. Now I'm logged in as "user1". The I logout and login with "user2". When I then go to the user profile page of user2 I see "user1" in page title.

Clearing the browser cache isn't a solution.

Clearing DRUPAL cache works (but at the moment DRUPAL cache is disabled). Then I see the right username in page title. Is it possible to exclude the user profile page data from DRUPAL cache?

Caching in metatag coused the problem. Disabling the metatags for users solved it.


why am i getting a Drupal\Component\Plugin\Exception\PluginNotFoundException: when the plugin does exist? I wrote a custom source plugin and put it in migd8_node_blog/src/Plugin/migrate/source/Node.php
with
<?php

/**
 * @file
 * Contains \Drupal\migd8_node_blog\Plugin\migrate\source\Node.
 */

namespace Drupal\migd8_node_blog\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d7\Node as D7Node;

    /**
     * Custom node source including url aliases.
     *
     * @MigrateSource(
     *   id = "migd8_node_blog_node"
     * )
     */

    class Node extends D7Node {

but i keep getting this error when i run drush mim migd8_node_blog Drupal\Component\Plugin\Exception\PluginNotFoundException: The "migd8_node_blog_node" plugin does not exist.
even after flushing the cache and reinstalling the module.

after flushing the cache and reinstalling the module

Check that the module is indeed installed at /admin/modules, if it's not, it's due to a migrate tools bug. Perhaps you deleted the part
dependencies:
  enforced:
    module:
      - migd8_node_blog

that you have in your other question, which fixes the reinstall bug if you have it before you install the module.
But if you installed it without the above code, you'll have to run this code once/one time only, and it will allow you to install again as this code removes the stuck configuration.
  $module_path = DRUPAL_ROOT . base_path() . drupal_get_path('module', 'migd8_node_blog') . '/config/install';

  $configs = array();
  $files = file_scan_directory($module_path, '/migrate_plus/');
  if ($files) {
    foreach ($files as $file) {
      $configs[] = $file->name;
    }
    // Delete each config using configFactory.
    foreach ($configs as $config_name) {
     \Drupal::configFactory()->getEditable($config_name)->delete();
    }

    return TRUE;
  }

If the modue is indeed installed, then the issue is due to you trying to assign migd8_node_blog_node as a plugin under the wrong key.
Since this is a source plugin and should be used only be used under source: and not/never under process: or any other key. See my answer.


Correct way to render fields from query in tpl? I'm here again to ask for some help, I'm running a query in a custom module to get contents of a node type, with this:

$node_type = "mynodetype";
  $nids = db_query("SELECT * FROM {node} WHERE type = :type", array(':type' => $node_type))->fetchCol();
  $nodes = node_load_multiple($nids);

And returning $nodes to the template, I'm using a foreach for $nodes array and I get something like this when I print_r() an element of $nids array.

stdClass Object ( [vid] => 12658 [uid] => 1 [title] => Node title [log]
=> [status] => 1 [comment] => 0 [promote] => 0 [sticky] => 0 [nid] =>
12658 [type] => mynodetype [language] => es [created] => 2017
[changed] => 1502159375 [tnid] => 0 [translate] => 0
[revision_timestamp] => 1502159375 [revision_uid] => 1 [mp_idmod]
=> Array ( [und] => Array ( [0] => Array ( [value] => 1 ) ) )
[mp_nmod] => Array ( [und] => Array ( [0] => Array ( [value]
=> Myvalue [format] => [safe_value] => Myvalue ) ) ) [rdf_mapping]
=> Array ( [rdftype] => Array ( [0] => sioc:Item [1] => foaf:Document )
[title] => Array ( [predicates] => Array ( [0] => dc:title ) ) [created]
=> Array ( [predicates] => Array ( [0] => dc:date [1] => dc:created )
[datatype] => xsd:dateTime [callback] => date_iso8601 ) [changed] =>
Array ( [predicates] => Array ( [0] => dc:modified ) [datatype] =>
xsd:dateTime [callback] => date_iso8601 ) [body] => Array ( [predicates]
=> Array ( [0] => content:encoded ) ) [uid] => Array ( [predicates] =>
Array ( [0] => sioc:has_creator ) [type] => rel ) [name] => Array (
[predicates] => Array ( [0] => foaf:name ) ) [comment_count] => Array (
[predicates] => Array ( [0] => sioc:num_replies ) [datatype] =>
xsd:integer ) [last_activity] => Array ( [predicates] => Array ( [0] =>
sioc:last_activity_date ) [datatype] => xsd:dateTime [callback] =>
date_iso8601 ) ) [cid] => 0 [last_comment_timestamp] => 2017
[last_comment_name] => [last_comment_uid] => 1 [comment_count] => 0
[name] => admin [picture] => 0 [data] => b:0; )

And inside the foreach, to render the fields I do it this way:

<?php print $nid->mp_idmod[LANGUAGE_NONE][0]['value'];  ?>

My question is, this is the right way to render the fields value of each node content type loaded? Or I should do it other way?

Personally, I would create an Entity View Mode for the content type with the fields arranged and formatted how I want them, then you can simply do:

$node = node_load($nid);
$node_view = node_view($node);
print drupal_render($node_view);

In your case, you need multiple nodes, so:

$views = node_view_multiple($nids, "name of entity view mode");
print drupal_render($views);

Now that you are using an entity view mode, you can give the markup you want in the node--node_type--view_mode.tpl.php file, and it will use that.

As for the query and dynamic code, it should go in a preprocess hook, and not the tpl itself. You can return it as a $variable to the template being rendered, usually this is a page callback.

Again, I don't know much about your module or where this code is. You could enable Entity View Modes and just shift this code and get rid of it, and leverage Views instead for the same exact result.


How would I store a reference in a custom FieldType in Drupal 8? I am developing a module for Drupal 8 and want to make a field on one entity that references another along with some additional data. e.g. Library A has a copy of Book B (of Edition 2). There will be multiple values stored in the field for each source entity. In the above example Libraries will have multiple books.

I know how to implement a new FieldType and the widget and formatter for it, but I am wondering whether this is the best way for a reference. Would it be better to create a new entity to hold the relationship with the two endpoints and additional data (like I would create an xref table in MySQL)

If I do go with a FieldType, when it comes to implementing the storage of the new field, would I just store the id of the referenced entity and then have to wrap the access in a method to change id <-> entity?

Thanks in advance for your help!
Jamie

So you're actually asking two questions.

Should I use a field type or a relation?

Both works. Field type requires much less storage (everything is in the field table), but it's hardcoded to one specific use case. The alternative is basically https://www.drupal.org/project/relation or you could also use something like https://www.drupal.org/project/paragraphs, https://www.drupal.org/project/field_collection if you only have a source -> target reference (relation can to n-n references). For all, you'd create a relation/paragraph/collection type with your additional fields. More flexible, can be configured and doesn't require custom code, but each  reference is another entity that has to be stored and loaded.

You will have to decide what's better for your case, depends on performance vs. flexibility requirements, how many variations (you probably don't want to create 10 field types..) and so on.

If a field type, how do I create it.

That's actually fairly easy in Drupal 8. You just extend from the default entity reference field type (EntityReferenceItem), override methods like schema() and propertyDefinitions() to define what properties you have and how they are stored. Then you write a widget and formatter for it, extending from the widget/formatter that's closest to what you want (e.g. autocomplete or select for the reference selection).

The advantage is, all the actual reference things will just work through the parent classes, you just have to implement your additional properties.


form with ajax dosen't send values I have a custom form built that generates some fields based on a select box,
the form works ok on user side. it loads new rooms when select changes.
the problem is that the globallink_ui_search_hotels in form[values]['hotels']['rooms'] it will only show room_0 even if you select 2 or more rooms.

update:
 from what i can see the after number of rooms changes, the generated select boxes dose not have a name attribute

  function globallink_ui_search_form($form, &$form_submit){ // the form creation function
  //........
  $form['hotels']['nrrooms'] = array(
      '#multiple_toggle' => '1',
      '#type' => 'select',
      '#title'=>t('Number of rooms'),
      '#options' => array(
        1=>1,
        2=>2,
        3=>3,
        4=>4,
        5=>5,
        6=>6,
        ),
      '#default_value'=>1,
      '#ajax'=>array(
        'callback'=>'globallink_ui_rooms_change_callback',
        'wrapper'=>'globallink-ui-rooms-change-wrapper',
        'effect' => 'slide',
        ),
      // '#title' => t('select departing time'),
    );

    globallink_ui_rooms_change_callback($form,$form_state);

  //....
    $form['hotels']['submit'] = array(
      '#weight' => '7',
      '#type' => 'submit',
      '#value' => t('FIND HOTELS'),
      '#submit' => array('globallink_ui_search_hotels')
    );

  }

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

    $nradults=array();
    for ($i=1; $i < 10; $i++) {
      $nradults[$i] = $i;
    }

     $form['hotels']['rooms'] = array(
        '#collapsed' => '0',
        '#type' => 'fieldset',
        '#collapsible' => '0',
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $nrrooms=!empty($form_state['values']) ? $form_state['values']['hotels']['nrrooms'] : 1;

    for($i = 0 ; $i<$nrrooms;$i++){

      $form['hotels']['rooms']['room_'.$i] = array(
          '#weight' => $i,
          '#title'=>'Room '.($i+1),
          '#collapsed' => '0',
          '#type' => 'fieldset',
          '#collapsible' => '0',
      );

      $form['hotels']['rooms']['room_'.$i]['adults'] = array(
        '#required' => '1',
        '#default_value' => 1,
        '#type' => 'select',
        '#title'=>'Adults',
        '#options' => $nradults,
      );

      $form['hotels']['rooms']['room_'.$i]['infants'] = array(
        '#required' => '1',
        '#default_value' => 1,
        '#type' => 'select',
        '#title'=>'Infants',
        '#options' => $nradults,
      );
    }

    return $form['hotels']['rooms'];
  }

  function globallink_ui_search_hotels($form, &$form_state){
    dpm($form_state['values'],'search hotels');
  }

You need to place

 $form['hotels']['rooms'] = array(
    '#collapsed' => '0',
    '#type' => 'fieldset',
    '#collapsible' => '0',
    '#prefix' => '
',
    '#suffix' => '
',
);

in globallink_ui_search_form function. The wrapper tag must be loaded before callback send.


How to use pager or term limit for taxonomy_get_tree($vid)? How to use pager or how to limit terms, when using taxonomy_get_tree($vid)?

I have this code for terms generation:

<?php
$vid = 2;
$terms = taxonomy_get_tree($vid);
$max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;

foreach ($terms as $term) {
if ($term->depth == 0)
{
print "" .l("<b>Auto Insurance for &nbsp;</b> " .$term->name,'taxonomy/term/'.$term->tid, array('attributes' => array('title' => $term->name, ), 'html' => TRUE) ). "";

}}

?>

But there are thousands of terms or sub terms. Some pages are then loading more then 20 seconds. I need to improve this situation.

Can you advice me please? Do you know some solution? Pager, Jquery, Ajax?

Add a counter into your for each statement that counts the array index and terminates after X number of items.  That'd fix it.


How to set paragraph margin when editing in CKeditor? I want to make a subtitle on a page, which needs to be centered and to have no space between it and the title.

In the CKeditor window, I entered the subtitle as the first line of text and centered it. In source, CKeditor represented this as:

...

which results in a blank line above. I tried to remove the blank line by changing the above code to:

...

or just

...

But CKeditor didn't like either of those. It removed the center tag and replaced the
 with
.
I also tried to add an instruction in CSS as either:

...

or as:

...</style>

CKeditor also didn't like either of those and just removed the style attribute from the first one and removed the span tag from the second.

I'm not very conversant in CSS, so I'm not sure the above code is properly formed. But the problem is that CKeditor is just removing it so I don't even get a chance to troubleshoot errors in the CSS.

CKeditor seems determined to have that blank line there. How can I get it to let me adjust this spacing between paragraphs (not globally, but on an individual paragraph)?

Thank you.

In your example you have:

...</style>

I'm assuming that should be:

...

In general in terms of controlling the space between paragraphs I think the best way to do that is your CSS stylesheet, not really HTML.

Drupal and CKEditor do some HTML manipulation that you may want to checkout - admin/config/content/ckeditor, then choose your profile and click edit.
Under appearance you can select/deselect some plugins that you might not need.

In terms of a quick fix though I would think that this would work:

...

But it also depends on what is in your site's stylesheet and your theme.


Is it possible to accidentally enable all views at once? I found all views enabled on a client site. Is it possible to enable all views at once?

Disclaimer: I did a module and core update with drush two days ago, but didn't look at the views list.

Accidentally? Possible, but not likely. But I guess it depends what you mean by "accidentally" exactly...

There are perhaps 3 obvious ways to programmatically enable/disable a view (see https://drupal.org/node/820110), plus I'd imagine a few derivatives and/or lower level methods. But enabling a View isn't that straightforward, some manipulation of serialised PHP vars needs to happen somewhere, so I'd say the chances of it being done accidentally are slim at best.

But yes, it's possible to programatically enable all Views at once. It's also technically possible for it to be done via a DB query (i.e. outside PHP), but it would be messing with a serialised PHP array, which MySQL et al don't know how to process, so you can probably rule that out.

Now, if there's a legitimate code/process in your site that intentionally enables one or more Views in certain contexts, and it's being called accidentally, or without your knowledge, that's a different story. If that's the case you're probably in audit mode; get a backup of the site from before the update running, switch off modules until the problem disappears, and when you find the culprit, dig into the code to see what's happening.


How to create Block configuration form I am new to drupal. I have created a block from module using hook_block_info() and hook_block_view(). This block will be used as front page image slideshow. So I want to provide text fields in the configuration page of that block where user can add Image files for slideshow.

What is the process of creating configuration form for the block. I searched online but couldn't understandable solution. Thanks!

I am using Drupal 7

You can create block configuration page using hook_block_configure().
where you can create form with your required field like textfield, file etc.

function demo_block_configure($delta = '') {
    $form = array();
    if ($delta == 'demo') {
        $form['demo_number'] = array(
            '#type' => 'textfield',
            '#title' => t('Number of nodes you want the block to show'),
            '#default_value' => variable_get('demo_number', 10),
            '#size' => 60,
        );
    }
    return $form;
}

function demo_block_save($delta = '', $edit = array()) {
    if ($delta == 'demo') {
        variable_set('demo_number', $edit['demo_number']);
    }
}

now you can get this variable using variable_get function

$no_of_block = variable_get('demo_number');

you can see this page in configuration of your block


Admin permissions wiped out after git branching I've encountered a strange issue whereby creating a new git branch on a Drupal 7 site and switching to it causes admin users' permissions to seemingly disappear. After performing the git branch, all admin users (who normally have near full access) see the admin toolbar but only have the ability to add content. All other links are missing.

I have tried visiting admin pages directly and that yields access denied. I have tried rebuilding permissions and clearing cache as well. Has anyone encountered this?

I was able to determine that rows strangely went missing from the roles table (in particular admin roles) upon creating a new git branch. I have not tracked down why this happens, but I suspect that something in either one of the features or custom modules is causing this to happen.


How can I use a view on site2 that consumes data from site1? We have a Drupal site that exposes a JSON API for users (http://site1/api/users).

We need to create on site2 a view of users based on the data provided by site1. (We cannot store the users on site2).

How can I use a view on site2 that consumes data from site1? Which hook should I use? What approach should I follow?

The External Entities module can help you in this task.

  This module allow you to connect to datasets from external databases
  and use it in your Drupal 8 website. While content lives external,
  Drupal sees those remote entities as internal. This makes it possible
  to alter the field displays, add references, comments, pathaliases,
  share buttons, webshop products and more.

You can read to Drupalize remote data with external entities.


Is there a way to quickly disable caching for all views? (for dev work) Is there a variable/other way to quickly disable all views caching when working on a dev server?  I have a lot of views which have different caching settings, and there are times when I am doing testing that I would just like to turn all views caching off, similar to the way that you can turn CSS/JS aggregation off.

I found that the Views module itself has its own cache in the documentation, but this is not the caching for individual views-- and the caching for each individual view is what I want to turn off.

If You ask about drupal 7 can use

cache_clear_all('*', 'cache_views', TRUE);

in template file.

Refreshing page that is using the file will clear all views cache.


Assign different taxonomy terms to translations of content I've got some custom content translated with entity translation with custom taxonomy also translated.
Actually taxonomy terms are correctly shown inside the content page.
The problem is I need different taxonomy terms for different translation.
When I change the taxonomy terms in the translation edit page every translation of the content gets updated with the terms variation.

The logic behind would be:

- content A (english) --> taxonomy term 1 (english)
- content A (french)  --> taxonomy term 2 (french)
- content B (english) --> taxonomy term 2 (english)
- content B (french)  --> taxonomy term 3 (french)

If you don't want the node translations to share the terms they are tagged with you need to make the Taxonomy term reference field translatable. Then you will be able to enter different values into that field depending on which language you're editing.

You can enable the translations for Fields under Configuration > Regional and language > Content language and translation (/admin/config/regional/content-language).

Tick the box for your Taxonomy field and hit the "Save configuration" button at the bottom of the page.

After that you'll be able to save the translations with different values for that field than the original. The translations in languages other than the default one will probably have that field empty before you edit them, they will not "inherit" the values from the default translation out-of-box.


Add #states in a webform I have a webform in my site in that am trying to make toggle for a radio button but the field i require do not have #states .How to add the attribute #states in a webform component using form alter?

Try Webform conditional module, it provides you the same thing.


How to remove a specific item from the search index? I have a content type in a D6 site that allows the creator of a node to mark the node as "withdrawn" -- he can still see it, but attempts by others to see it are caught and redirected somewhere else, like their user page.  When this node gets withdrawn, I'd like to remove it from the local search index (standard Drupal search) as well.

My somewhat brutish way of doing this is:

    db_query("delete from {search_dataset} where sid = %d", $node->nid);
    db_query("delete from {search_index} where sid = %d", $node->nid);

which seems to work -- the node stops showing up in search results.  But I'm worried about {search_total} -- there are entries there that correspond to the words in the node's content.  I can't just remove all the node's terms from {search_total}, of course; is this worth worrying about?  Or am I seriously screwing up the search index by doing this in the first place?  Thanks!

Looking at the code executed from node_delete_multiple() (which is then the function used by node_delete()), I see that the function called is search_reindex().

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }

The code executed from that function to delete rows from the search tables is the following one.

db_delete('search_dataset')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

db_delete('search_index')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

// Don't remove links if re-indexing.
if (!$reindex) {
  db_delete('search_node_links')
    ->condition('sid', $sid)
    ->condition('type', $module)
    ->execute();
}

I suggest using search_reindex(), but to reply to your question, it doesn't seem that updating the "search_total" table is necessary, at this point; Drupal doesn't do it when a node is deleted. That table is updated from search_update_totals(), which is called from search_cron(). See the comment given for the following code, executed from search_update_totals().

  // Find words that were deleted from search_index, but are still in
  // search_total. We use a LEFT JOIN between the two tables and keep only the
  // rows which fail to join.
  $result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL", array(), array('target' => 'slave'));
  $or = db_or();
  foreach ($result as $word) {
    $or->condition('word', $word->realword);
  }
  if (count($or) > 0) {
    db_delete('search_total')
      ->condition($or)
      ->execute();
  }

In Drupal 6, the equivalent of search_reindex() is search_wipe(), which is called from node_delete(). The function contains the following code to delete the tables' content.

db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'", $sid, $type);
db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
// Don't remove links if re-indexing.
if (!$reindex) {
  db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type = '%s'", $sid, $type);
}

Also in this case, I suggest using search_wipe().


Token Content Access blocks access for author too I use the Token Content Access module to hide member created nodes from public view and allow them  to share private links with private links (URL tokens). My problem is when a user restricts access to individual nodes using URL tokens, he cannot access them without the token either!

I briefly looked at the module. I think you will need to make some serious code changes, I could not find an easy tweak.


Include the user history visibility settings in a feature I have two view modes for the user profiles, the default one and a custom view mode called "Header". In the default view mode I have chosen to show the user history information ("Member for...") but in the Header view mode it shouldn't be shown.

I have included the user account settings in a feature in order to be able to export them. Everything else is fine but I don't find how to include the history visibility settings in it. When I reinstall the site with my feature, the "Member for..." information is shown in both of the view modes. I can manually hide it in the configuration page, but I must find how to export it into the code.

Does anyone know how this can be done?

If you've added a custom visibility option to User accounts. You'll need to figure out a way to export it to code. if they are just Fields then they should show up under export options for Fields when building a feature.

If on the other hand you've created a custom tab of sorts on the User Accounts page and have a bit of code managing some settings there -- you need to inform Drupal of those pieces of custom data.

Features Extras supports exporting visibility settings for blocks, and blocks in general.

  To export a block, install FE Block, edit your block, give it a
  "machine name," export it with Features. You can export block settings
  (region settings, visibility settings, ...) of any block, and the
  content of blocks created with the Block module from Drupal core.

I recommend looking at that module and seeing how they export these settings. If I had to guess I'd say they use the Ctools Export API. There is a drupal handbook page on how to get started exporting configuration for your module.


How to theme the user profile page? What is the file I have to modify in order to get Drupal to output a custom user page.

The default link to the file I need to change is:

http://www.example.com/?q=user/xx

Where xx is the user id.

This page is not dysplaying correctly and I want to fix it, but how do I know which file is Drupal calling?

Is there a reference guide on Drupal 7 default pages and links?

Here is a brief list of template suggestions for Drupal 7: http://drupal.org/node/1089656

If you are looking to theme the user page, there are multiple templates located in modules/user that can be overridden. The template you should probably start with is user-profile.tpl.php.  Copy that file and paste it in your theme directory then edit it as you like and clear the cache and you should see the changes.


Problem displaying second level navigation in menu block I have something strange happening with a drupal 7 site i'm working on. I have a main navigation menu which also provides navigation via a menu block for all second level pages. this works fine - i have an additional main navigation menu which can be toggled with the main navigation at the user's discretion -this is also working fine. however, displaying the second menu in a menu block is proving difficult. i have matched the settings for both menu blocks so they are associated with the correct menus respectively, and yet on the second menu block, it will only display if the top-level links are included. so, if i want to display the second-level only, regardless of setting the maximum depth, nothing shows up. if i include the top-level and set the depth to include children, that works fine; the top level and second level are there. however i need to exclude the top level and this doesn't seem a simple task.

is this a common problem, or has anyone experienced anything similar??

Neil

I don't sure if you are using only Drupal standard menu system or any menu modules. If not, check Menu Block module.

This module gives you lot of options to place menu in blocks, including just some parts of a certain menu as I think you want.

For example, you define a block that shows the second-level menu of the current fist-level active item.


Any way to export webform node to other installation? Is there anyway to export a webform node to another installation in D7? I need to export a webform node with all its components and webform settings.

Updated: I already  tried with Webform Share, but I can't get the "email" setting exported, this settings are just ignored. I have a very complex emails setting that I'd like to export as well.

Have you tried the Webform share module (it is a helper module to prepopulate newly created webforms and to export / import webforms between sites), it may be helpful for this scenario as it provides the following feature:

  Example usage 1: Prepopulated webforms

Create a webform with the required components.
Export the webform
Edit the webform content type and paste in the content from the export (under Publishing options)
Use the standard node add content links and each new content item created should be prepopulated with the exported webform.

  Example usage 2: Synchronization of webforms

Export the webform that has the settings you want
Import these over the existing webform.

Note: Existing webform components are replaced with the new webform components. If a component is dropped or the key is renamed, you will no longer have access to any user submitted data.


how to create expire flagged node after custom time I need code that make expire flagged node after custom time, after custome time reached node become unflag automatically, have tried flag_expire module but it no work at all. any help?

You need the rules module along with its Rules Scheduler module. The flags module is well integrated with rules and you can do a lot of stuff with this combination.

A simplified instruction how to achieve your desired functionality:

Enable rules, rules scheduler.
In admin/config/workflow/rules/components crete an actions component which, when triggered by the scheduler, will unflag your node. You will have to set its inbound variable to 'content' (usage: parameter). Action will be unflagging your node.
In admin/config/workflow/rules create a rule which will start the scheduler (the triggering event should be 'node has been flagged' and the action should be 'schedule component evaluation' which passes the node id (content) to your component.

This way whenever a certain node is flagged with a certain flag, a new scheduler entry is added and when its expired, your node gets unflagged. Bear in mind the entry is only evaluated on cron run, so you will be hitting that cron button many times during debugging.

You can find rules tutorials all over the place, but not so much scheduler tutorials.
This comment is a good starter.


Extending Drupal Functionality to Custom PHP Page I have Drupal 7 site which is working fine. I added a custom PHP page to my site in the root directory of it. I want to extend the Drupal application functionality to that one page so that I can have access to the different Drupal classes and basically extend Drupal through my page. What includes do I need at the top of my page to be able to access the Drupal application as if I were within the Drupal site?

The only file you need to include is '/includes/bootstrap.inc', but you also need to define the DRUPAL_ROOT constant and run drupal_bootstrap() to have access to the API/database/etc.:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Your code here

It's exactly the same code that you'll find in the standard index.php file, minus a call to menu_execute_active_handler() which isn't necessary if you dont want to build and output a normal Drupal page.


Front page meta tags and multisite configuration I have a multisite install with 4 different URLs. How do I setup the meta tags (keywords and description) for each URL?

It seems like the keywords and description are the same for all of the URLs.

It depends on how your sites are structured. Are all three basically the same site only available via different URLs?
First off, be aware that this can penalize you for having the same content available via multiple URLs, search engines don't like that. You should use Nodewords' ability to hardcode a specific base URL to pick one of the domains to say that one is the primary domain; the others are secondary that will help avoid penalties.

That, of course, is if you're using Drupal 6; for Drupal 7 there are other options.

Disclaimer: I am the maintainer of the Nodewords module.


How do I make a form in Add Content using Drupal 7? I am trying to get my Drupal 7 website working with PHP and an external database. I would like to have user interaction via forms, but all the examples I can find on the web hint that you have to write your own module to do this. I couldn't find a good description of even that process from the ground up. Is there a way to add a form using the standard Add Content -> Article or Basic Page? Is that a bad way to do things? I would like a page that is a form and when the user presses the submit button the same page loads, but now with the data retrieved from the database that was requested.

I'm not sure if you really can do this with it, but have a look on:
Webform


Drupal 7 views - Contextual filter content: Nid content id from url I am working on a portfolio website where there are a lot of projects on the website.

When you have a project node open I want a view next to it with all the thumbnails of other projects.

The problem is the following:
When I have the view setting set to Contextual filter content: Nid content id from url I want the reverse effect to happen. Because now it only shows the same node.

Please forgive my bad english, I hope you can help me!

Let assume that you are using "Content: Nid" exposed filter.

Edit settings of your exposed filter and expand "More" section. If you choose "Exclude" check-box then it will show all nodes except current one.

Please see screenshot - how it used to be.


Ubuntu crontab is not triggering when site is in maintenance mode and also revert to online I am using the Ultimate cron module and I have set the main Drupal cron task in crontab to run every 5 minutes.

I have put my site in maintenance mode. Drupal cron tasks are not running when site is in maintenance mode, and it is not resuming its operation when I changed the site back to online.

Please suggest.

When the site is in maintenance mode it makes sense that regular cron tasks are halted. For example email notifications about new content should not be sent if you are working with content in maintenance mode - unless you want users to go to a site down page.

If you manually trigger the cron to run after disabling maintenance mode it should restart the jobs.


Having Problem editing product displays created by Commerce Feeds to add product flag link Hi all and I apologize in advance for what seems like a rudimentary question.

I have a drupal commerce site (drupal 7.38, commerce 7.1.11, Commerce Feeds 7.1.3) and I have a very basic flag set on my custom products. The issue is I have is that I cannot seem to be able to add the flagging fields to the products displays generated from the templates imported with commerce feeds. I use a template very similar to the attribute/taxonomy terms I import via feeds. The problem is that there doesn't seem to be an obvious way to do this through the UI when editing the Content Type for my custom product display.

I can confirm that there is a flag field listed for the custom product type, but it doesn't show up in the fields available in either the Manage Fields or Manage Display tabs of my product display. The field is visible in the Manage Display tab of the product type, but is not in the manage fields list and isn't obviously manageable in some other way.

Is this commerce feeds that's tying my hands, or how do I edit these?

As pointed out in the comments, this was resolved by using commerce reference flag and adjusting my flag and displays.


how to redirect user login from other server? The user login is from the other drupal site using cas(Central Authentication Service). Then it will lead to my main site and an authenticated user can view the contents. The main site is used Drupalgap to redesign the interface for mobile.

Now, when using the web browser, it works fine to login and start to view the contents. However, I don't know how to do it for Drupalgap. I saw some apps can login with the account from other sites, once the login is successful, it will redirect and come back to the app.

Does anybody know how to do it?

My attempt is trying to use the login url from the other site.

bl('Login', 'www.example.com/cas', { InAppBrowser:true });

This will open a new web browser, not inside my app page. When successfully login, there's a link to go back to my main site. These are operating through the new web browser, not inside my original app.

On the Drupal side, create a custom module to implement hook_form_alter() and use it to attach a custom #submit handler to the user_login_form. In the custom submit handler, you can redirect the user to the headless DrupalGap web app:

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_form' && arg(0) == 'drupalgap') {
    $form['#submit'][] = 'example_user_login_form_submit';
  }
}

function example_user_login_form_submit($form, &$form_state) {
  $uid = 123; // This id will be somewhere in the $form or $form_state object.
  drupal_goto('https://example.com/#user_' . $uid);
}

Replace drupalgap with your service endpoint path, but by default it is drupalgap.


rewrite custom field on user profile I have a custom field on my user profile pages where users can enter their Twitter user name. When the user's profile is rendered (either on the user profile page itself or via views) I would like to rewrite this field so that it links to the user's twitter profile following the pattern http://twitter.com/[field_twitter_name].

I discovered the twitter username project on DO yesterday (https://drupal.org/project/twitter_username) and this would help me accomplish the objective, especially for new users. However, we currently have ~900 active users on our site.

Is there a way to create a new field and update its tables with the existing user's twitter names? Or is there a way to change the field type from it's current setting of "Text field" to the new type made available by the twitter username project "Twitter username"?

Any help would be greatly appreciated.

You could write a small one-off DB copy function to accomplish the task. There a couple of modules around but they appear to be quite old, so it would depend on what version you run. Here's a tutorial for MySql (if that's what you use) DB access: http://www.w3schools.com/php/php_mysql_intro.asp


Embed some user profile fields in a block form I've added some fields to user profile.
None of these fields are displayed on registration form, but I want user can edit them quickly when he is logged.
I want to embed some fields in a static content and display them to the user: how can I manage this? Can I create a php page or is it better using hook_form?

This should give you a start. Probably it is not the most elegant solution, but after 5 minutes of hacking, this is what I got. It works, and updates the profile fields (alone).

  function custom_block_info() {
     $blocks['user_profile'] = array(
       'info' => t('User profile edit'),
       'cache' => DRUPAL_NO_CACHE,
     );

     return $blocks;
    }

    function custom_block_view($delta = '') {
      $block = array();

      switch($delta) {
        case 'user_profile':
          $block['subject'] = t('Fill your profile');
          $block['content'] = drupal_get_form('custom_profile_form');
          break;
      }

      return $block;
    }

    function custom_profile_form($form, &$form_state) {
      global $user;

      $form_state['user'] = $user;
      $form['#user'] = $user;
      $form['#user_category'] = 'account';
      $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#weight' => 100,
        '#value' => t('Save'),
      );

      $form['#action'] = url('user/' . $user->uid . '/edit');
      // $form['#validate'][] = 'user_profile_form_validate';
      $form['#submit'][] = 'user_profile_form_submit';
      field_attach_form('user',$user,$form,$form_state);

      return $form;
    }


How to create a block with taxonomy terms and their corresponding nodes? This is what I want to achieve in views:

Taxonomy vocabular "Categories":

Term 1 -> 3 node titles;

Term 2 -> 3 node titles;

Term 3 -> 3 node titles;

Well you need to use views_field_view module. In you views :

Create a view of Taxonomy type
Add a filter of Taxonomy Vocabulary = Categories
Add filed Term: tid (exclude) and Term: Name
Add Global View field pass argument tid (Another view in which contextual filter of tid is added and 3 items are displayed in views configuration)

Done.


How to see the individual fivestar ratings in a view? How do I design a view to see every user's fivestar rating? I want to see a node, and below that list all users' ratings (and not connect it to comments). The only thing I've been able to do is list every user that has rated a node and get the value of their vote (percent) but if I change the value to show the "rate widget", so that I can see the nice fivestar rating, it can either show me the logged-in user's rating or the average rating. It will not show me the actual user's rating.

I believe you can create a relationship to Votes, and then you can show the users who voted and their vote values.