How to add a button or link to perform an action on a node with node_view? I wonder how to add a button or link to perform an action of _create_node function. I understand on how to do it on the node edit screen, but not the display.

I want a button of create "new item" on the node display. I'm creating a custom module to create the new node, but need a button to call it.

Any suggestions?

You can implement the hook_node_view() like the following code:

function YOUR_MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'CONTENT_TYPE_NAME') {
    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;
 }
}

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('New Item'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    //here the path where you need to go
    $path = 'node/add/CONTENT_TYPE_NAME';
    drupal_goto($path);
}


Discount and coupon 100% off of for only 1 item in shopping cart I am using Drupal 7 with the 2.x version of the Coupon and Discount modules.

I am attempting to issue a 100% discount (free item) to my users, but I want to apply it only to 1 item in the cart. This way, 1 item is free but anything else is still full price. I want each user to be able to choose any item they want.

I would like the user to be able to browse the site for 1 item and, at checkout, apply the coupon code so that the item is free. To prevent people getting every item for free and adding many items to the cart, I would like the coupon to only apply to one item in the cart.

Is there a way to give each user the ability to get an item free?

You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag a user after such user applied (for the first time) the coupon code at checkout. To actually flag such users, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

Any time a user tries to apply such coupon code, you can then verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no been flagged already (by the flag you created for this purpose)".

If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.


Printing PHP to node I got hook in my *.modules file php_invoke_preprocess_node that should print data from JSON according to node type. I need to print it to node content everytime i run it but now it runs only once and print it at the top of the site and then it won't run until I clear cache.

function php_invoke_preprocess_node(&$variables) {
$node = $variables['elements']['#node'];
//check content type
switch($node->getType()) {
  case 'nodeType':
    $session = getSession('','');
    $data = ['additonal JSON headers'];
    echo (CallAPI($data, $session)); //return JSON array that i want to print to node but i dont know how
  break;

That was a hell of a problem to solve. I had to rebuild my code. Instead of hooks I took a bit different approach and I tried a solution proposed by @IvanJaros but I wasn't able to get lazy builders to work. I found that in drupal 7 there was a hook_init that was called everytime but it got deprecated in 8.

The answers are EventSubscribers, using them you can assign any function you want to specific event i.e. loading a page.
 Here's a great tutorial that intruduce you to that feature.

Here's my event code

    class MyEventSubscriber implements EventSubscriberInterface{

        public static function getSubscribedEvents(){
        // Its called when respond transfer ended
        $events[KernelEvents::TERMINATE][] = ['onRespond',28];
        return $events;
    }

  public function onRespond(FilterResponseEvent $event){
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $data = [];
    if(isset($node)&&isset($name)){
        $nodeType = $node->getType();
        switch($nodeType){
            case 'nodeType':
                $soap_response = new JSonGetter();
                $data = $soap_response -> getUserData($name);
                echo('<script>var JSONarray = ' . print_r($faktury,1) . ';</script>');
                break;
        }

    }
    }

}


How do I use "NOT IN" in a query? What is the proper way to write a query containing 'NOT IN' using a condition statement?

My query is the following one:

SELECT DISTINCT nid FROM node WHERE language NOT IN
  (SELECT language
    FROM languages WHERE language = 'ab');

I've tried something like the following:

$query->condition('n.' . $key, $value, 'not in (select language from
  languages where language = $value)');

In the specific example, you should simply write the condition as:

$query->condition('n.language', 'ab', '<>');

In the generic case, where you need to select the rows in a database basing on the values returned from a sub-query, you should consider what follows:

"NOT IN" is accepted as operator from SelectQuery::condition(). In fact, the following query would be executed:

$query = db_select('node', 'n')->fields('n');
$query->condition('n.nid', array(1, 2, 3), 'NOT IN');
$nodes = $query->execute();

foreach ($nodes as $node) {
  dsm($node->nid);
}

As reported in Conditional clauses ("Subselects"), SelectQuery::condition() accepts  also an object implementing SelectQueryInterface as value for $value, such as the one returned by db_select(); the problem is that actually you can just use it when the value of $operator is equal to "IN". See Subselects don't work in DBTNG conditions, except when used as value for IN.

The only way I can see to use the "NOT IN" operator with a sub-query in condition is to:

Execute the subquery to get an array
Execute the main query setting the condition as in the following snippet

$query->condition($key, $subquery_result, 'NOT IN');

$subquery_result is the array containing the result of the sub-query.

Otherwise, you could use where() as others said, which accepts a string for the part of the query you need to add.

Keep in mind that db_select() is slower that db_query(); you should use the first when you know the query could be altered by other modules. Otherwise, if other modules are not supposed to use hook_query_alter() to alter your query, you should use db_query().
In the case of accessing nodes, if you need to obtain only the nodes to which a user has access, then you need to use db_select() and add 'node_access' as tag of the query, with SelectQuery::addTag(). For example, blog_page_last() uses the following code.

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
  ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

Similar code is used by book_block_view().

$select = db_select('node', 'n')
  ->fields('n', array('title'))
  ->condition('n.nid', $node->book['bid'])
  ->addTag('node_access');
$title = $select->execute()->fetchField();


CSS not work after ajax replace I  have found that when I replace forms with AJAX, then the new forms loose their display styling. It seems like the css for the forms are not working any more.

How to solve this issue?
Do i have to write js bind with .on() function to add css again? Any other suggesions?

In some cases it can depend on how and where you have added your CSS to the page.

The best way to do it is using #attached on your field via hook_form_alter() or similar.

If your CSS is already on the page though it should work on new elements added with ajax.

One possible cause is that your CSS selectors are too specific and the ID/class used isn't matching properly with the markup added by the ajax.


How do I pass the nid of the current node to the first step multistep modal form? I am using the ctools plumbing to create a nodal form. This is what the relevant part of my code now looks like:

/**
 * Implements hook_entity_view_alter().
 */
function mymodule_entity_view_alter(&$build) {
  $nid = $build['body']['#object']->nid;

  // Set up ctools etc. to use modal omitted for brevity.

  $build['links']['popup']['#links']['mylink'] = array(
    'title' => 'show popup',
    'href' => 'mymodule/nojs/modals',
    'html' => TRUE,
    'attributes' => array(
      'class' => array(
        'ctools-use-modal',
        'ctools-modal-mymodule-style',
      ),
    ),
  );
}

The nid of the node this link will be attached to is known at this point. (See first line of function.)

However, my code need to be aware of the nid at each step in the modal form.

I think it possible to do this by stashing it in a session cookie, but I would like to avoid using cookies, if possible.

Is there another way to do this?

I think the simplest way would be to change your path to incorporate the nid, e.g.

function MYMODULE_menu() {
  $items['mymodule/%ctools_js/modals/%node'] = array(
    'title' => 'Title',
    'page callback' => 'MYMODULE_callback',
    'page arguments' => array(1, 3),
    ...
  );

  return $items;
}

Change the path in the link

$build['links']['popup']['#links']['mylink'] = array(
  'title' => 'show popup',
  'href' => 'mymodule/nojs/modals/' . $nid,
  'html' => TRUE,
  'attributes' => array(
    'class' => array(
      'ctools-use-modal',
      'ctools-modal-mymodule-style',
    ),
  ),
);

And in your callback:

function MYMODULE_callback($js, $node) {
  // $node is fully loaded, continue as normal...
}


How to fix "GeoType" plugin does not exist I'm following this tutorial. I've installed the geofield module and all needed for it wo work. I finally manage to create a content type "Place" with a field of type geofield. When i then create a new content of type "Place", i get the following message on drupal 8.0.3:
The website encountered an unexpected error. Please try again later.

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "GeoType" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 57 of C:\wamp\www\drupal8\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php)

I'm using drupal 8.0.3
with geofield 8.x-1.0-alpha1
Note i also habe geoPHP enable.
Any idea how i can solve this issue?

Alfter some reading and searching, i finaly found a solution. Just go here and apply patch #10. It's just one change that need to be done in the GeoConstraint.php file in src/Plugin/Validation/Constraint/GeoConstraint.php. In line 14,7 change "@Plugin(" to "@Constraint("


Can I publish something in my wall of facebook? I need to publish something in the user's facebook wall, when you entered the site, automatically.

This is the code that I actually use.

function publish(){
    global $user;
    $attachment = array(
            'name' => 'Name app',
            'href' => url('http://....', array('absolute' => TRUE)),
            'description' => 'Use this application.',
          );

    $user_message = t('Check out the latest application on !site...', array('!site' => t('My Drupal for Facebook powered site')));

    $actions = array();

    $actions[] = array('text' => t('Read More'),
                       'href' => url('http://....', array('absolute' => TRUE)),
                      );

    fb_stream_publish_dialog(array('user_message' => $user_message,
                                  'attachment' => $attachment,
                                   'action_links' => $actions,
                            ));
}

This code work, but it publish again the text when I edit the page, or I go to a different page.

Is there a module (for publish), or another way to do this?

Set a session variable, or a cookie, when sent the first time; check that always.


How to redirect a user to a personal area of page once logged in? I want to allow users to login to their area 'personal' and view their uploaded images/posts (basically creating an instance of the page) which is different to every user that logs in to my website --- similar to Facebook profile page which has the same layout for every user but different content in it.

So far, I have created a role called 'subscriber' (which are members of the page) and I have enabled front page module to re-direct subscribers to the 'personal' page.

I have read that the Views module is useful but I am stuck on how to do this.

You can create a View to show the infomation that you need and with the help of the LoginToboggan module you can redirect the users to the view's url.

  The LoginToboggan module offers several modifications of the Drupal
  login system in an external module by offering the following features
  and usability improvements:

  Optionally redirect the user to a specific page when using the
  'immediate login' feature.
  Optionally redirect the user to a specific
  page upon validation of their e-mail address.

For more info about creating Views, you can read:

  Creating new views (Community documentation).
  Creating your first View in Drupal 7.


Module installation issue I am attempting to install modules on Drupal 8 but I'm getting a failure that says i need to install commercial guys, addressing and zone libraries. When I put the libraries inside the library directory: (public_html/mysite.com/sites/all/libraries)  I still get this error. I'm thinking I need to install them somewhere else since I'm using Drupal 8.

Also, there is a module called composer manager which according to my reads automatically installs needed libraries for modules. The problem i'm facing is that its asking to use the command prompt to install them. see the link below:

How to install the commerceguys libraries for Drupal Commerce 2.x?

Im using Hostgator hosting, how can I install this using command prompt? Which command prompt do I use, Drush, Bash?

Probably better to ask the Hostgator support if/how they support that.

One alternative is setting up and running those commands locally, that will download the necessary files and you can then upload them.


Form API select list remove blank entry (default select an entry) I populate an select list using the following code.

$getCompanies = 'SELECT nid, title FROM node where type = "my_type"';
        $companiesResult = db_query($getCompanies);
        $companyArray = array();
        $companyArray['empty'] = "";
        while ($data = db_fetch_object($companiesResult)) {
            $companyArray[$data->nid] = $data->title;
        }
        $form['company'] = array(
            '#title' => t('Type'),
            '#type' => 'select',
            '#description' => t(''),
            '#options' => $companyArray,
        );
    }

This gives me an empty result first. I want to remove this empty result. I tried adding #required by it does not add a default selection. What can I do to remove an empty element?

The blank option was added by yourself:

$companyArray['empty'] = "";

If you remove that line you wont have a blank line, or alternatively your could change it to

$companyArray['empty'] = t("Please select");

To make the phrase Please select appear as default in the select option.


How can I find a list of fields output by a view block? FINAL UPDATE

Success! Apparently there were field-level permissions set on several of the CCK fields I needed, in spite of the original developer telling me that content permissions were not enabled. Once I allowed anonymous viewing of the required fields, they displayed with no problem.

I've created a view with a block display. The view has a grouping field, and in the views ui preview, the output displays as grouped by that field:

When I display the block using my template, though, it's not printing out the grouping info (Advanced Learning Session or General Session). That field is not a standard one, like title - it's a CCK text field on my content type. How do I access that field in my template? I've tried the solutions shown here to get a list of available fields, but none of them work.

Edited after trying @schnippy's answer

When I mouse over the field, I see this:

So I tried adding

<?php print "session type: ".$fields['field_session_type_value']->content; ?>

to my template, but although the "session type:" string prints, there's no value coming through after it. I've also tried writing just the value to the error log, in case there was something weird about combining it with a text string, but still nothing.

Edit again...

Just to provide a bit more info, if it will help - I'm using the mobile jquery theme, which has a views-view-list.tpl.php file to display views where the output is HTML List. That template looks like this:

<?php
// $Id: views-view-list.tpl.php,v 1.3 2008/09/30 19:47:11 merlinofchaos Exp $
/**
 * @file views-view-list.tpl.php
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

?>

<?php print $title; ?>

  <<?php print $options['type']; ?> data-role="listview">

    <?php foreach ($rows as $id => $row): ?>

      <li class="<?php print $classes[$id]; ?>"><?php print $row; ?>

    <?php endforeach; ?>
  </<?php print $options['type']; ?>>

I have a number of views that are being displayed via blocks with this template, and for the most part it's fine because they all are grouped by a title field. But for one view, the records are grouped by a CCK field called field_session_type_value, and if the value of that field matches a specific value, I want to print that field instead of $title.

Another update

According to views-view.tpl.php, $rows is the variable that views sends out as the results of the view query. Now, if I have multiple fields, I would expect that doing a print_r on $rows would return a multi-dimensional array - each record or row would be an array containing a key/value pair for each field. Like so:

Array (
  [0] => array('title'=> 'Advanced Consumer and Shopper Insight - An Interactive Symposium',
               'session' => 'general-session'),
  [1] => array('title' => 'Creating a Powerful Brand One Dirty Job at a Time',
               'session' => 'advanced-learning')
)

(Yes, I realize my pseudocode array is not formatted correctly. But you get the idea.) But that's not what I'm getting. What it's sending back is a single-dimension array, containing just the titles:

Array (
  [0] => Advanced Consumer and Shopper Insight - An Interactive Symposium
  [1] => Creating a Powerful Brand One Dirty Job at a Time
)

What do I need to do to make sure it sends all the fields through in the $rows array?

You're using the 'row style' type 'fields' here, correct? The field you are grouping on should also be added as a field in your 'fields' list in order for this to be showing correctly in your preview so all you need to do is find the name, which can be tricky to guess depending on the cck field type. One way you can do this is by hovering over the 'link' in the fields editor within views:

and get the name of the field from the url in your browser status bar, ex.

../view_name/display/field/<your field name>

and then you just print out the rendered view content of your field in your tpl with:

<?php print $fields['<your_field_name>']->content; ?>


How to display a pseudo field in a view I have created a pseudo field with this code:

/**
 * Implements hook_entity_extra_field_info().
 */
function MYMODULE_entity_extra_field_info() {

  $extra['node']['my_bundle']['display']['my_pseudo_field'] = [
    'label'       => t('Pseudo Label'),
    'description' => t('Pseudo description'),
    'weight'      => 100,
    'visible'     => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode, $langcode = 'fr') {

  if ($display->getComponent('my_pseudo_field')) {

    $build['my_pseudo_field'] = [
      '#markup' => 'This is my pseudo content',
    ];
  }
}

Everything is working fine, except that I couldn't add it in a view.

With the help of 4k4, I could solve my problem... I will start by explain my first try, which could be a good solution in some cases, then I will explain/show how I finally end up.

Firstly I created my computed field in hook_entity_base_field_info_alter [Note that this is not a pseudo field this time]

function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
    if ($entity_type->id() === "node") {
      ...field is created here... will show you how to after
    }
}

Secondly, we need to create a class (that will perform the calculation) for the computed field (will show you after)

Thirdly, we can display this field in a view simply by implementing hook_views_data_alter... This is the beauty of this solution: the view integration is made very quickly. Here is the how the hook is implemented

function my_module_views_data_alter(array &$data) {
  $data['node']['my_computed_field'] = [
    'title' => t('My computed field'),
    'field' => [
      'id' => 'field',
      'default_formatter' => 'string',
      'field_name' => 'my_computed_field',
    ],
  ];
}

What was not good in my case, is the fact that my computed field does appears in all bundles (even if I use setTargetBundle('my_bundle') like showed below).

Thus I changed a little bit my computed field process creation:

1-Create the computed field in hook_entity_bundle_field_info_alter ... not in _entity_base_field_info_alter (As you can see, it is a float field... youn could use a string)

function my_module_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if ($entity_type->id() == 'node' && $bundle == 'my_bundle' ) {
        $fields['my_computed_field'] = BaseFieldDefinition::create('float')
        ->setName('my_computed_field')
        ->setLabel(t('Nombre de litres total'))
        ->setComputed(TRUE)
        ->setTargetEntityTypeId('node')
        ->setTargetBundle('my_bundle')
        ->setClass('\Drupal\my_module\MyComputedFieldItemList')
        ->setDisplayOptions('view', [
            'type' => 'float',
            'weight' => 0,
        ])
        ->setDisplayConfigurable('view', TRUE);
    }

}

Note: if someone know the purpose of ->setTargetBundle('my_bundle') I would be glad to read anything on it as I added it without knowing if it is mandatory/usefull.

2-Extend FieldItemList (MyComputedFieldItemList) [use the same name as in ->setClass('\Drupal\my_module\MyComputedFieldItemList')]

The main point here is the protected function computeValue that will use $node to compute the value.

<?php
namespace Drupal\my_module;

use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * Item list for a computed field that displays the total liter for a soup.
 *
 */
class MyComputedFieldItemList extends FieldItemList
{

    /**
     *
     * {@inheritdoc}
     */
    use ComputedItemListTrait;

    protected function computeValue()
    {
        $node = $this->getEntity();
        if (! $node->isNew()) {
            $this->list[0] = $this->createItem(0, my_module_function_to_compute($node));
        }
    }
}

At this stage, you have a computed field that you can display in "my_bundle"... Lets go to the view integration

3-Alter hook_views_data_alter to tell views that you have a new computed field linked to a node. The main point here is the id my_computed_field

function my_module_views_data_alter(&$data)
{
    $data['node']['my_computed_field'] = array(
        'title' => t('My computed result'),
        'group' => t('Content'),
        'field' => array(
            'title' => t('My computed result'),
            'help' => t('bla bla.'),
            'id' => 'my_computed_field',
        ),
    );
}

4-Thanks to 4k4, I understood that you need to create a plugin class that will have a render function to show the result in the view. The second important thing here is the @ViewsField("my_computed_field") annotation that needs to be the same as the id in step 3

<?php
/**
 * @file
 * Definition of Drupal\my_module\Plugin\views\field\ComputeField
 */

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * Field handler to flag the node type.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_computed_field")
 */
class ComputeField extends FieldPluginBase {

    /**
     * @{inheritdoc}
     */
    public function query() {
        // Leave empty to avoid a query on this field.
    }

    /**
     * @{inheritdoc}
     */
    public function render(ResultRow $values) {
        $node = $values->_entity;
        if ($node->bundle() == 'my_bundle') {
            return my_module_function_to_compute($node);
        }
    }
}

Now, everything runs fine:

The field could be displayed (or not) in any display mode and you can change the settings in the UI as any regular field
The field could be inserted in a node view
There is a function my_module_function_to_compute($node) that you can put in your module. This function will compute the result of your field with the entity as argument (node here)

One thing is missing: the sort (in the view) doesn't work... I have to dig into it


Views not displaying on page, but show up in preview I have a view setup to display all properties where a drop down box = portfolio 1. However, when I set up the view everything looks correct but when I go to the actual url it does not display the teaser or full content in the body.

When I set it up as a block I can add it to my right sidebar and it displays fine...

here is the export of the view:

$view = new view();
$view->name = 'portfolio_1';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Portfolio_1';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Portfolio_1';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['view_mode'] = 'full';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'property' => 'property',
);
/* Filter criterion: Content: portfolio (field_portfolio) */
$handler->display->display_options['filters']['field_portfolio_value']['id'] = 'field_portfolio_value';
$handler->display->display_options['filters']['field_portfolio_value']['table'] = 'field_data_field_portfolio';
$handler->display->display_options['filters']['field_portfolio_value']['field'] = 'field_portfolio_value';
$handler->display->display_options['filters']['field_portfolio_value']['value'] = array(
  'port1' => 'port1',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'portfolio-1';

I can provide screen shots if that would help.

Few possible things you may try to resolve the above problem are:

Make sure the path you are accessing is same as the path you have assigned to page display.
Not using the same path elsewhere (e.g: either in the hook_menu, panels, etc.)
Try changing the path (adding some random chars) for testing and check if it works.
Perform a search in the menu_router table for the path you are using, and if it already had an entry than you need to change the path.


Always show next page link in pager function mythemename_pager_next($text, $limit, $element = 0, $interval = 1, $parameters = array()) {
  global $pager_page_array, $pager_total;
  $output = '';

  // If we are anywhere but the last page
  if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
    $page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);
    // If the next page is the last page, mark the link as such.
    if ($page_new[$element] == ($pager_total[$element] - 1)) {
      $output = theme('pager_last', $text, $limit, $element, $parameters);
    // The next page is not the last page.
    } else {
      $output = theme('pager_link', $text, $page_new, $element, $parameters);
      //$output = '

';
    }
  }

  return $output;

}

How to make NEXT PAGE link visible on last page? For example we have 3 pages and i am on the 3rd page and i should see NEXT page link. Please assist to me with function above, thanks!

The line

if ($page_new[$element] == ($pager_total[$element] - 1)) {

Will never fire because of the earlier line:

if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {

So if the current page is equal to (or higher) then the last page it will skip the whole code.

Try removing that line (and the corresponding closing bracket }).
I hovever don't know if it will keep working then because the following function seems to be assuming it can never load a pager higher then the current page. So prepare for some unexpected behavior.

$page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);


How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field? I have a content type that has 3 term reference fields:

Field A (required), which contains a single tag.
Field B (required), which contains a single tag.
Field C (not required), which contains a single tag.

The tags from those 3 fields all related to the same taxonomy.

When creating or updating a node, values are entered for field A and B. I want to have a rule ((using the Rules module) with some Rules Action to set a  data value for field C, equal to the concatenation of the value entered for field A and B. But "set a data value" only sets one value.

What can I do to set multiple values?

Some more screenprints to explain all this:

And here is my current Rule I'm trying to get to work:

{ "rules_juhe_xieru" : {
    "LABEL" : "\u805a\u5408\u5206\u7c7b\u81ea\u52a8\u5199\u5165",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--mfpf" : { "bundle" : "mfpf" } },
    "DO" : [
      { "data_set" : { "data" : [ "node:field-juhe-fenlei" ], "value" : [ "node:field-diqu" ] } }
    ]
  }
}

Your question is not clear (enough), at least not yet, so I'll try with 2 variations ...

Field C is about Single values

It think your rule needs at least 2 corrections:

Add a Rules condition like "entity has field", for each "token" that you want to use in any rules Action, but which is not (yet) showing up to actually select it in some Rules Action.
When using a Rules Action like "Set a data value", you can indeed only set such value for 1 variable. However if you want to "Set a data value" for another variable, just add a 2nd Rules Action to do so for that other variable.

Field C is about Multiple values

Maybe your question is rather something like so:

  If this Rules Event happens, then I want to add the node reference in field A to field C, and I also want to add the node reference in field B to field C (and field C is a multi value node reference field".

In this case, using "Set a data value" is completely wrong. Instead you need to use an action like "Add item to a list". I.e.:

Rules Action 1 is to add A to the list C (possibly you also need a Rules Condition like "Entity has field" (for A)).
Rules Action 2 is to add B to the list C (possibly you also need a Rules Condition like "Entity has field" (for B)).

Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for way more details about "Add item to a list".

Recommendations to improve the alternative answer

Now (after about a day of extra questions/comments to the question from No Sssweat and myself), it finally became clear what the real question was ...

Here is a variation of the Rule in the alternative answer:

{ "rules_improved_combination_of_taxonomy_terms" : {
    "LABEL" : "Improved combination of taxonomy terms",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "[node:field-a][node:field-b]" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[variable-added:value]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
      { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "entity-created" ] } },
      { "entity_save" : { "data" : [ "node:field-c" ], "immediate" : "1" } }
    ]
  }
}

These are the extra refinements needed to make it work:

Add an action to save an entity (twice), because since you used Rules Event to just wake up after viewing a node, you need to remind the Rules module to also save what you've been creating/updating.
Remove the Fetch entity (no need for that).

By the way, the clue to debug the rule in the other answer can be found if you turn on rules logging: you'll see that the fetch entity didn't return any results, so blank, which is also what got saved in field C ...

Demo:

Field A: Bonjour
Field B: World
Field C: BonjourWorld

At least that's what happened in my tests. If I change A to Hello (or No), B to Liu (or Sssweat), then C gets updated to HelloLiu (or NoSssweat) ...

Be Aware: I can think of some further improvements of all this, but for now I consider this rule as "Make it right before you make it better" ... try it in your own setup to confirm it does answer the quetion (but please don't post enhancement requests via extra comments, instead post a new question if needed).

Disclaimer: I don't have a clue what those non-English "pictures" are (I bet they are characters in your native language ...).


How can I save a file in specific folder? I want to upload files to specific folders. How can I achieve this programatically. How can I modify below code such that upload_location should be dynamic.

    $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );

In form submit action you can give the destination path.

function formname_form_submit($form, &$form_state) {
    $destination = $form_state['values']['foldername_name'];
    $validators = array();
    $file = file_save_upload('file', $validators, 'public://'.$destination);
}

More about file_save_upload get https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7.x.

more related links
https://stackoverflow.com/questions/1253094/howto-drupal-file-upload-form


error_get_last() doesn't show last warning Drupal has its own custom error handler, so when I try to get the message from the last warning (e.g. for an invalid regex), there is nothing there:

if (@preg_match($regex, NULL) === FALSE) {
  dpm(error_get_last());
}

The @ prevents it from being displayed on the screen, and without that I can see a warning for a $regex of '/(/' (about an unmatched paren), but the warning is not shown by dpm(), but rather by Drupal.

Is there a way I can get the warning from an invalid regex in this example, so that I could have the message in a variable?

Use the same PHP's error functions as Drupal to toggle PHP's error handling behavior.

In particular, you can use set_error_handler() / restore_error_handler() to toggle the PHP error code handling while you're debugging:

// Remove _drupal_error_handler() handling
restore_error_handler();

if (@preg_match($regex, NULL) === FALSE) {
  dpm(error_get_last());
}
// Restore _drupal_error_handler() handling
set_error_handler('_drupal_error_handler');

See the PHP doc links for more information on how these error handling functions work.


Update time zone when user travels I am creating a site that increments a "day" session at midnight. Is there a way to update the timezone set for that user when they travel between time zones?

Would using javascript to pull the value from the calendar on their computer be an option? Right now we are storing timezone values in the DB so this would be a major code change, but would it work? Is there any Drupal module that could help with this?

You can use javascript to get the browser timezone. Assuming their computer timezone is updated, their browser timezone will change.

var offset = new Date().getTimezoneOffset();

Or if you want the name you'll have to do something like https://stackoverflow.com/questions/2853474/can-i-get-the-browser-time-zone-in-asp-net-or-do-i-have-to-rely-on-js-operations

Sadly there is no way to do this without Javascript.


Add ajax on hook_field_widget_paragraphs_form_alter I'm working with paragraph and I try to change a paragraph with AJAX.
My content type have a content field which contains "section" paragraphs which can contain various paragraph types which themselves can contain various paragraphs types.
To do certain modification on paragraphs, I use hook_field_widget_paragraphs_form_alter. It's work well but I meet a problem when I try to use #ajax because I don't know how to retrieve which paragraph has been modified in the ajax callback because I receive the entire form from the content and no information on which part has been modified. Here my code:
function mymodule_field_widget_paragraphs_form_alter(&$element, &$form_state, $context) {
  switch ($element['#paragraph_type']) {
    case 'block_special':
      $element['subform']['field_type']['widget']['#ajax'] = [
          'wrapper' => 'type-bs-wrapper',
          'callback' => '_type_paragraph_callback',
        ];

        $element['subform']['field_content']['widget']['#attributes'] = ['id' => 'type-bs-wrapper'];

        $values_paragraph = $form_state->getValues();
        if(!empty($values_paragraph)) {
          foreach ($element['#field_parents'] as $field) {
            $values_paragraph = $values_paragraph[$field];
          }

          $type = $values_paragraph['subform']['field_type'];
        }

        if (!empty($type) && $type === 'exception') {
          unset($element['subform']['field_content']['widget']['add_more']['add_more_button_paragraph_type1']);
          unset($element['subform']['field_content']['widget']['add_more']['add_more_button_paragraph_type2']);
        }
  }
}

function _type_paragraph_callback(array $form, FormStateInterface $form_state) {

  return $form; // <- How can I know what I should return?
}

I don't know which paragraph have been return. I don't know if I can pass the argument $element['#parent'] from the function hook_field_widget_paragraphs_form_alter (but how in this case) or if I should do a recursive research between default value of all paragraphs of my form between form_values (which will be laborious).

You should be able to get this information from the submitted data in $form_state, specifically the triggering element.
For example:
use Drupal\Component\Utility\NestedArray;

function _type_paragraph_callback(array $form, FormStateInterface $form_state) {
  $button = $form_state->getTriggeringElement();
  // Go one level up in the form, to the widgets container.
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -2));

  return $element;
}

I've copied this from the Paragraphs module:
modules/contrib/paragraphs/src/Plugin/Field/FieldWidget/InlineParagraphsWidget.php


What would cause a duplicate session key? I occationally recieve the following error resulting in failure of several pieces of code later in the pipeline.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY-Cu6Y9OkPd1qJuonzHQw2' for key 1:
   UPDATE {sessions}
   SET sid=:db_update_placeholder_0, ssid=:db_update_placeholder_1
   WHERE (ssid = :db_condition_placeholder_0) ;
Array (
   [:db_update_placeholder_0] => QUyrgEInS_vO0GbrOhJffh6npb2ejlpllvS8Thn2pYY
   [:db_update_placeholder_1] => Cu6Y9OkPd1qJuonzHQw2JI67BDvO85pqp50SBsXE1ZU
   [:db_condition_placeholder_0] => fMabX3y84Ngm-HcGF8MomLvLp1kmceLRIwniv_dSj_M )
in drupal_session_regenerate() (line 393 of /var/aegir/platforms/demandmetric/includes/session.inc).

I am using custom code that rougly looks like this:

drupal_session_start();
_$SESSION[''] = bunch of generated info.
Authorize linkedin
create user
$form_state['uid'] = $account->uid;
user_login_submit(array(), $form_state);
Update profile from linkedin info.

The error occurs on the user login submit part.

I suspect that drupal_session_start is causing the issue but I don't understand sessions well enough to debug this. The issue occurs 1 in about 30 users. I added the session start because the session info on line 2 doesn't get set without it.

Other suspects are memcache (very unlikely) and secure pages.

Anyone know about session that can enlighten me to how to track this issue down?

Check your sites/default/settings.php file, if you have $conf[https] = TRUE; then removing it will fix the error.

Removing it also won't affect any security issues as long as your server/domain is configured properly. You can also check the Enabling HTTP Secure page from Drupal.


How to redirect programmatically inside a module to an external url? I am trying to redirect to a page after I unset a session.
I read this article but I am pretty new to Drupal module building.

Here this amazing guy says to do the comming thing:

  If you know that the destination is an external URL then you are
  encouraged to use TrustedRedirectResponse instead:

return new RedirectResponse(\Drupal::url('<front>', [], ['absolute' => TRUE]));
  return new TrustedRedirectResponse('http://www.bbc.com/');

I don't understand how I should use this code and where to put it...

Any help would be great
This is my controller file content.

<?php

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;

class SsoController extends ControllerBase{
    public function ssoLogout(){
        unset($_SESSION['name']);

        if(isset($_SESSION['name'])){
            $status = $_SESSION['name'] .' is logged in';
        }else{
            $status = 'is logged out';
        }
        return[
            '#type' => 'markup',
            '#markup' => '<p>' . $status . '</p>' ,
        ];

    }
}

Well if you want to redirect to an external page this can be your code:

<?php

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

class SsoController extends ControllerBase{
    public function ssoLogout(){
        unset($_SESSION['name']);

        // Redirect.
        return new TrustedRedirectResponse('http://www.bbc.com/');

    }
}

In this case, the redirection will happen when your ssoLogout() method will be called.


hook_user_insert() vs hook_user() can someone please explain the difference between

hook_user_insert() and

hook_user() with $op='insert'

i mean is hook_user with $op='$edit' is invoked after a user create an account??

cos i am trying to get some custom field values when a user create a new account.
i used this code for testing:

function myModule_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'insert' ){
    dpm($edit)
  }
}

and it don't return nothing after creating a new user account.

The simple answer is that hook_user is for Drupal 6 and hook_user_insert is for Drupal 7.

Most (all?) of the API functions in Drupal 6 and earlier that accepted an $op parameter got split out into individual functions in Drupal 7.  This happened with hook_block, hook_nodeapi, and some others.

For Drupal 7, the full set of user hooks is described at user.api.php.


How to call/submit Form from another page in custom module? I would like to set cron function in my custom module. I have created one form which is called with submit button from UI. Now I would like to submit/call that form from another page (.module file) where I have written my hook_cron function, how it would be possible?

In Drupal 7, I use

$form_state['values'] = "";
drupal_form_submit('customfeedimport_main_pagecallback_submit', $form_state);

But I am new to Drupal 8, so how to perform this cron thing in Drupal 8?

Also what should be included in the namespace, use?

You can do it with the FormBuilder::submitForm() function.

To register a new user (taken from the docs):

// register a new user
$form_state = new FormState();
$values['name'] = 'robo-user';
$values['mail'] = 'robouser@example.com';
$values['pass']['pass1'] = 'password';
$values['pass']['pass2'] = 'password';
$values['op'] = t('Create new account');
$form_state->setValues($values);
\Drupal::formBuilder()->submitForm('user_register_form', $form_state);

You might have to include the namespace for the FormState class before this code if not done already.


display suite: limit field - determine what bundle values? In display suite, there's a field to limit which bundle it's being displayed on.

How do you know what bundle / value to enter?

Is there a way to list all available values or find out all the values? Or does it go by the machine name?

It's the machine name. You can think of the bundle as the specific settings for a specific entity. So, DS is asking you for the machine name associated with the individual content type, vocabulary, etc. that you'd like to target.

For example, say you've created node configurations (Structure > Content Types) called "Article," "Store Location," and "Job Openings." If you'd like to make your DS custom code only available in the display settings for "Job Openings," you'd put in...

job_openings|*

...or you could limit it to a specific view mode by specifying which one in place of that wildcard, such as...

job_openings|teaser

Easiest way to find the machine name is to look at the edit url for your entity and/or view mode.


How to make form field read only? I want prevent any user from being able to change the value of a field, yet I want to display its value.

How can I achieve this?

This can be done via hook_form_alter

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   if($form_id == 'user_register_form') {
      $form['field_name']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
   }

}

Add some css:

input:read-only {
  background-color: #ddd !important;
}

Result:


How does Feeds decide if it is going to create a new (or update an existing) entity? I am using Feeds to map a CSV file to user entities and have the "Update existing users" setting in place. Everything is going great, except for the Telephone field... as it currently stands, the Telephone module doesn't have support for Feeds.

There is a patch that works for saving a telephone number when creating a new user, but not when updating an existing user.

Here's a CSV example (excluding headers for simplicity) for a new user:

demo,demo@demo.com,1234567890

Here's a CSV example for updating that same user:

demo,demo@demo.com,4567890123

When changing the value of the telephone number in the CSV file, and running it through the importer again, Feeds (or someone else?) doesn't see any incoming changes to be applied, so it skips the import entirely saying:

"There are no new users."

I've been looking at the Feeds API to see what hooks are available, and thought hook_feeds_presave() would be a nice one, since it talks about "skipping" an entity, but this hook only gets fired when creating a new user.

The hook_feeds_before_update() function gets called each time, but I'm not seeing a way to indicate to Feeds whether or not a value has changed, and to proceed or skip.

I'm guessing I need to expand upon the patch with hook(s)/other to make a simple decision for Feeds, pseudo code e.g.

...
// If telephone number has changed, tell feeds its OK to update.
if ($feed_item_value != $entity->{$field_name}['und'][o]['value']) {
  $feeds->update = TRUE;
}
else {
  $feeds->update = FALSE;
}
...

How does a module, that provides a field, tell Feeds that it detects a change with the field's value and to update an entity? Or does feeds and the internal entity system automatically do this?

The Feeds module uses the FeedsProcessor object to define what it calls mapping targets for an entity to determine what fields are unique and what can be optionally be set unique in the feeds importer mapping settings UI. It then uses the method existingEntityId to determine if the mapping targets are unique.

In the case of users, the hook_feeds_plugins method for the feeds module tells feeds to use the class FeedsUserProcessor. This class has a method named getMappingTargets to say that the optional unique fields can be name and mail. In the mapping ui for the user feeds importer (admin/structure/feeds/user/mapping), you can set name and/or mail to be unique. The existingEntityId method in FeedsUserProcessor.inc determines if it has found a unique value. If so, and the importer is set to replace or update existing users, then the feeds record will be updated.

If you really wanted to work with telephone number as a unique field attached to a user, then you use implement hook_feeds_plugins, define your own FeedsProcessor and extend FeedsUserProcessor, and overwrite the getMappingTargets to add the field as an optional_unique entry, and overwrite existingEntityId to find other users with a matching telephone number.

However, it sounds like you don't need to do that. Make sure your user feeds import is set to update existing users, and that it is reading the csv file properly.

I went ahead and enabled telephone, installed the patch you mentioned, and was able to see a user be created, and then be updated with a different telephone number. My import file looked like this:

name,mail,telephone
demo,demo@demo.com,1234567890

and then this:

name,mail,telephone
demo,demo@demo.com,4567890123

And here is an export of the feed import:

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'user';
$feeds_importer->config = array(
  'name' => 'User import',
  'description' => 'Import users from CSV file.',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'direct' => FALSE,
      'allowed_extensions' => 'txt csv tsv xml opml',
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsUserProcessor',
    'config' => array(
      'bundle' => 'user',
      'roles' => array(
        3 => 0,
      ),
      'update_existing' => '1',
      'status' => '1',
      'mappings' => array(
        0 => array(
          'source' => 'name',
          'target' => 'name',
          'unique' => 0,
        ),
        1 => array(
          'source' => 'mail',
          'target' => 'mail',
          'unique' => 1,
        ),
        2 => array(
          'source' => 'telephone',
          'target' => 'field_telephone:url',
          'unique' => FALSE,
        ),
      ),
      'defuse_mail' => 0,
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);


Access denied to my route, created in module.routing.yml I'm having a hard time trying to figure out why my custom route is returning a 403 status.

My routing.yml file:

lightbox.content:
  path: '/lightbox/content'
  defaults:
    _controller: '\Drupal\lightbox\Controller\LightboxController::content'
    _title: 'Hello World'
    requirements:
      _permission: 'access content'
      _access: true

My permissions.yml file

access content:
  title: 'Access Content'
  description: 'Read all content'

Permission page:

The issue, as mentioned in the comment was my indentation.  I will leave this for anyone that may run into this issue.


Bootstrapping Drupal from the command line Here is what I'm trying to do :

Write a php script that import external data into drupal.
Run that script every night with a cron that executes it using php, not wget.

In other words, I need my import script to run from the command line.

First step is done and working great when run as a module from Drupal. So I took all required bits of it, created a new file, and bootstraped drupal. After fixing a few warnings and errors (path issues mainly), the file is executed but actually no job is done.

So I start adding echo commands to see where everything goes to hell. And it appears that it's right after

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

What I mean is that no error, warning or whatever is raised, but it's like the script exit somewhere inside that call.

I tried to lower the boostrap level to DRUPAL_BOOTSTRAP_LANGUAGE, but then I get the following error :

  Fatal error: Call to undefined function field_info_field() in /www/includes/entity.inc on line 768

I'm a bit lost on what happens and would welcome any suggestion.

Also, here is the beginning of the script that bootstrap Drupal :

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
    chdir('/www/');

    $cmd = 'index.php';
    $_SERVER['HTTP_HOST']       = 'default';
    $_SERVER['PHP_SELF']        = '/index.php';
    $_SERVER['REMOTE_ADDR']     = '127.0.0.1';
    $_SERVER['SERVER_SOFTWARE'] = NULL;
    $_SERVER['REQUEST_METHOD']  = 'GET';
    $_SERVER['QUERY_STRING']    = '';
    $_SERVER['PHP_SELF']        = $_SERVER['REQUEST_URI'] = '/';
    $_SERVER['HTTP_USER_AGENT'] = 'console';

    define('DRUPAL_ROOT', '/www/');
    require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_LANGUAGE);

    // nothing gets executed past this point
    print("0\n");

Don't even try this. Use drush, it is meant for this type of things precisely.

The drush php-script command will allow you to run any PHP script in the context of Drupal, but I would recommend writing those as a proper command inside a custom module.


Prevent loading certain script set in .info file in Drupal 6 I have a theme with several template files using <?php print $scripts ?> to load a list of scripts set in the theme's .info file. What's the best way in Drupal 6 to exclude one of the scripts from being loaded in certain template files?

I do not think there's a way to really un-set scripts once they've been added, in D6.  D7 provides hook_js_alter, but not D6.

Do you have control over the theme? Your best bet would be to remove the scripts from the .info file and only add them as needed by calling drupal_add_js().  Which hooks or preprocessors you need to use to make those calls to drupal_add_js() will be something determined by the purpose of the scripts themselves.  But you'll want them added before template_preprocess_page() is called since that's where the $scripts variable is generated.


Print module and missing breadcrumbs of Crumbs modules I use crumbs module to maintain custom breadcrumbs. Also, I use print module to maintain printer's friendly pages.

The breadcrumbs works perfectly in the ordinary pages. However, using print module leads to missing section in breadcrumbs.

For example:

mysite.com/sports/the-winner-cups
return breadcrumbs: Home -> sports -> the-winner-cups

but
mysite.com/print/sports/the-winner-cups

returns Home -> the-winner-cups

The following is a screen shot of active rules weigts of Crumbs module:

It seems the router path for print/.. pages is always "print". See the print_menu() hook implementation in print.module.

You could write new Crumbs plugins for these paths (one for parent-finding, another for title-finding), with a logic somehow like this:

The parent path for "print/a/b/c" is "print/" + the parent path of "a/b/c".
The breadcrumb link title of "print/a/b/c" is the same as for "a/b/c".

The plugin could live in a custom module, or in the print module, or in the Crumbs module (patch welcome).

(This still needs some tinkering and experimentation. I'm afraid if I put it all into this answer, then I can as well just write the plugin myself and add it to the module - sorry..)


Dependecies prefix coding standard Running phpcs --standard=DrupalPractice in several modules *.info.yml file I get a warning message:

All dependencies must be prefixed with the project name

I've seen some modules that use the module name as prefix

dependencies:
  - modulename:modulename
  - modulename:submodulename

Others when it belongs to Drupal core:

dependencies:
  - drupal:modulename_already_in_core

Others when it belongs to always Drupal (doesn't taking into account if the module is in the core or not):

dependencies:
  - drupal:modulename

Which is the right syntax? Should I use "drupal" always? Just when the module is in Drupal (core)? What is the aim of this requirement?

Thanks!

More info: https://www.drupal.org/project/coder/issues/2854781

As described in Let Drupal 8 know about your module with an .info.yml file, the correct format is:

project-name:module-name for third-party modules
drupal:module-name for a core module

  Dependencies should be namespaced in the format: {project}:{module} where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name.

Since the project page for Drupal core is https://www.drupal.org/project/drupal, the case for Drupal core modules is the same as for third-party modules.


List 2 fields of a content type and group them based on one of them with views I have on coupon content type with 2 fields. One is named "Campaign Owner" and the other one "Campaign Name". One owner might have several coupons generated by the site for a campaign. So the owner will have for example 20 coupons with the same campaign name. I want to create a list of campaign names and group them with campaign owner. So the list should be something like this:

JACK(Owner Name)

Camp1
Camp2
Camp3

JOE (Owner Name)

camp4
camp5
camp6

I've tried to create this with views but what I get is not what I'm looking for. Here is it:

JACK

Camp1
Camp1
Camp1
Camp2
Camp2
Camp2

JOE

Camp4
Camp4
Camp4
Camp5
Camp5
Camp5

As you can see. It lists all the similar campaign names. But kneed to get rid of the
similar items.
How can I do such a thing?

The answer is "views distinct" module which checks the values of each row and then removes/aggregates the similar ones.


Why are no tests shown on testing overview? I want to run DrupalWebTestCases on my custom Drupal 7 module.

Following the Tutorial at https://drupal.org/simpletest-tutorial-drupal7 i'm stuck at running the tests:
also after cache deletion no other Tests than for SimpleTest are found on the /admin/config/development/testing-page.

I'm using the contributed SimpleTest module, added the testing_api = 2.x setting to my modules .info.

mymodule/mymodule.info:

name = Mymodule Reports
core = 7.x
php = 5.3
files[] = tests/*.test
testing_api = 2.x

mymodule/tests/mymodule.test:

/**
 * @file
 * Mymodule reports module tests.
 */

class MymoduleReportsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'MymoduleReports',
      'description' => 'Ensure that the locking of nodes functions properly.',
      'group' => 'Mymodule',
    );
  }

}

What i'm doing wrong?

Instead of using

files[] = tests/*.test

in mymodule/mymodule.info
it should be

files[] = tests/mymodule.test


Error while accessing admin section I am facing the following error while trying to access Admin section in Drupal 8 (WAMP Server). I tried to install the Update manager module and from then I am facing this error. I am unable to access any Admin section of the website. But, I am able to login and access the User account section (Ex: http/test.com/user/1).

  The website encountered an unexpected error. Please try again later.

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route "update.report_update" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 191 of core\lib\Drupal\Core\Routing\RouteProvider.php).

Any suggestion please?

Its problem with my custom module. Wherever I am installing that module, it is creating a mess. I am trying to sort out the issue with my module.

This is due to the menu routing problem in my custom module. Please see the below link: https://www.drupal.org/node/2635308


Alter menu link for taxonomy link I've path alias and taxonomy menu. Now menu displays taxonomy link as vocabulary_name/term_name.

For example, my vocabulary name is 'category'. I want to change into 'article'. I've to only for this situation. I've used path alias. Unfortunately my view link looks like same.

I've tired hook_menu_alter() and hook_menu_link_alter(). But there is no luck. I need your suggestions.

Go to the path alias, set your path to what you want, then from admin/config/search/path/delete_bulk delete all taxonomy path , then from admin/config/search/path/udate_bulk rebuild them.(this is is pathauto mdoule)if your menu link not worked rebuild them ( with taxonomy menu module)


Can we call submit handler of one form into another form? Can we call submit handler of one form into another form?

I have two forms say user profile form and  choose membership plan I want to unset submit function of choose membership plan and want to show in user profile form and also both forms field must save.

like  multi-step form.

 function myform_form_alter(&$form, &$form_state, $form_id) {
   if($form_id === "ms_membership_list_memberships_form") {
     $form['#validate'][] = "_myform_form_submit_handler";
   }
   if($form_id === "user_profile_form") {
     $form['#validate'][] = "_myform_form2_submit_handler";
   }
 }

 function _myform_form_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/user/1/edit';
 }

 function _myform_form2_submit_handler($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   $form_state['redirect'] = '/ms/checkout';
 }

You could pass the page number as argument to your hook_menu()

<?php
function mymodule_menu() {
    $items['abc/def/%'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(2),
    );
    return $items;
  }

Then if it is step-one for example, get your subscription plan form, render it then submit.
In the submit function use:

 <?php
// Force the form to rebuild. If we do not do this, the value(s) in $form_state['storage'] will be lost
$form_state['rebuild'] = TRUE;
//Redirect to step two
$form_state['redirect'] = 'abc/def/2';

In step 2 get the user profile so that in the next submission you'll have the data from both forms in the submit function.


Exposed field in view not showing I'm trying to build me a search function using the exposed fields in a view. But for some reason, the exposed fields don't show up...

My main search module is enabled, my D7-website is indexed and I have a module called Better Exposed Filters enabled. But still, no exposed fields are popping up. What do I do wrong not to get any exposed fields?

OK, I found it myself. The trick was to turn on AJAX (for some weird reason).


Adding optional insurance service to existing shipping service This is my first question here, sorry if I miss something and for my bad english.
I have a D7 drupal commerce site, and custom wants to add an optional insurance for shipping. There is only 1 shipping service calculated with shipping weight tariff module. At checkout users should be ablen to choice wether buying insurance for shipping or not. If yes I should add 10% of order total with at least 10€ amount.

Thank you very much.

You'd probably add this using a combination of Rules (module) plus an additional custom field for Shipping line items.


Is there Page bulk manager? I tried to look for bulk page manager for Drupal 7, but I wasn't successful. More specifically, I'd like to change access settings for multiple pages in one step. Something similar to what VBO provides for entities.

Any suggestions?

Content Access VBO

Maybe you want to look at Content Access VBO ... It's (still) a sandbox project, so not sure if you really want to consider it. Here are some details about it (quote from that link):

  ... creates an action for Views Bulk Operations to update per node content access (view/edit/delete etc). It adds a menu item to the Content menu tree and adds a new view which lists content with the VBO action as a button.

But at least it may help to get more inspiration to build your custom module to get this done.

Combine Rules with Views Bulk Operations or Content Access

Another approach is to use the Rules module, combined with modules Views Bulk Operations and/or Content Access. Here are a few questions that may help to get more inspiration about its possibilities (the sky is the limit ...):

Is there a module that lets one person do a bulk publish/update?
https://drupal.stackexchange.com/questions/159988/how-to-implement-a-complex-workflow-in-a-website-with-subsites-and-using-opensch/161616?s=8|0.2610#161616
How can an author mark the update date of a node to be visible or hidden for visitors?
Is there a module that lets one person do a bulk publish/update?
How do I publish nodes 3 times a day?.


Custom currency in Drupal Commerce Shopping cart summary views I need to display at the top of the default currency in drupal commerce view the specific currency at the Shopping cart summary view.
Something like on the image

I tried to ad a custom field if footer tof that view but there is no currency options.

Any idea how to do that?

I manage to do this using Views PHP module. The variable $results contains the array of all the data.

For "Shopping cart form" and "Shopping cart summary" view you have to add to footer this to the output value of Global: PHP:

<?php
$amount = 0;
foreach ($results  as $result) {
$amount = $result->field_commerce_total[0]['raw']['amount'] + $amount;
}
$converta = commerce_multicurrency_conversion($amount, 'HRK', 'GBP');
$formatcu = commerce_currency_format($converta, 'GBP');
echo $formatcu;
?>

To the "Commerce add to cart confirmation" you haw to ad to fields Global: PHP output code:

<?php
$amount = $data->field_commerce_total[0]['raw']['amount'];
$converta = commerce_multicurrency_conversion($amount, 'HRK', 'GBP');
$formatcu = commerce_currency_format($converta, 'GBP');
echo $formatcu;
?>


Adding CSS to specific nodes doesn't work I'm new to Drupal 8 themes and am trying to edit CSS on individual pages. I've read how to do it, and have attempted to implement, but when I clear my sites cache and try to view the page, the new CSS (or JS on some pages) does not seem to get utilized.

What I have done

In my .theme file I have this code

function odyssey_preprocess_node(&$variables) {
  // find node object
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) { //ensure object is a node
    if ($node->id() == 1 ) { //grab specific node (R&D page)
      //attach the library
      $variables['#attached']['library'][] = 'odyssey/research-devel';
    }
    elseif ($node->id() == 3 ) {//CR Calc node
      $variables['#attached']['library'][] = 'odyssey/cr-calc';
    }
  }
}

In my .libraries.yml file I have the following code

research-devel:
  css:
    theme:
      css/research-devel.css: {}

cr-calc:
  css:
    theme:
      css/cr-calc.css: {}
  js:
    js/cr-calc.js: {}
  dependencies:
    - core/jquery

I uploaded the named files from .libraries.yml into the appropriate folders (I have my global CSS and JS files working, so I know the locations are correct.)

Does anyone see any glaring errors? Am I going about this the wrong way? Like I said, fairly new to the game and I'm sure that adding specific page stylings to the global CSS is the "Non-Drupal" way to go about it, so any advice would be appreciated.

See if the hook is being called or not.
Try printing some of the node variables inside the hook.
Also try adding the libraries based on path alias which is configurable anytime unlike nids which differ based on the instances.
If you are to follow path approach,

function themename_preprocess_page(&$variables) {

   /*Get Url based on the url alias of current path */
    $current_path = \Drupal::service('path.current')->getPath();
    $Url = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
    /*Attached calendar script for this page alone */
   if($Url =="/contact/open-office-hour"){
     $variables['#attached']['library'][] = 'themename/calendar';
   }
}


Is table prefixing controlled by db_set_active()? If I use db_set_active() to fetch data from another database, how will that affect table prefixing?

Is table prefixing dynamic in the sense that it adjusts to the currently active database?

When you use db_set_active you change the config that Drupal uses, so in theory you could use db_set_active to use the same database but change the prefix used.

Drupal will use the configuration defined, and the changed they imply.

You should note, that db_set_active won't work if you use multiple db backends for older Drupal versions (Drupal 6 and earlier, several MySQL backends are fine, but you can't switch from PgSQL to MySQL)


How to modify the D7 user login page html to remove the register and new password options for non-admins? So, I'm maintaining a Drupal 7 site for which we recently switched the users over to SSO through a third-party OAuth provider. The implementation isn't fancy, but added a login link to what I assume is the standard login page with a tabs for "registration, login, and password reset."

What I would like to do is remove the menu options altogether for regular users, keeping just the OAuth login link and some additional text to inform users of new registration procedures. For admins, I would like to preserve the regular name and password based login options.

I am aware of the Tab Tamer module, but I'd like a little more granular control. I believe I need to approach this with hook targeting the login block, but I haven't found any examples on how to control what HTML in the block itself.

So, how to do modify the login block's HTML to remove the extra tabs for regular users, but preserve it for admin users?

I don't think you've thought this through. The standard login page (/user/login) only shows the login form when a user is not yet logged in. So if you want the ability for admin users to see the usual options on that page, you will need to show them to all users -- since you don't know whether or not the user is an admin before they log in. If a user is already logged in (whether through OAuth or standard login) they will not be prompted to log in again.

If, instead, you want to modify the user login options for all users, this can be accomplshed via hook_form_alter() in a custom module, replacing MODULENAME with the name of your module in the hook implementation:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Your code to modify the form goes here
    $form['some_text'] = [
      '#markup' => '
Some text to inform users of new registration procedures
',
    ];
  }
}

EDIT: If you have never made a Drupal module before, don't be intimidated! The type of thing you're trying to do can be accomplished with a very small module.

Keep in mind that the Drupal Form API is basically just a bunch of PHP arrays.

To add markup to a form array, use the #markup form element as I've shown im my example above.

To remove an element from a form array, you can unset() that value before the array is rendered. For example:

<?php
unset($form['buttons']['preview']);
?>

I'm not sure what form elements you'll want to remove, but this technique should help.

This stuff is well documented on Drupal.org and all over this forum.

Remove unwanted form elements
Add markup to a form
hook_form_alter()
Drupal Form API reference


Can blocks being exist and displayed without being stored in blocks table? I'm wondering what could be the problem.

When I queried the homebox_default table , it showed bids with 1950
1387
1382
953
958
1916

but when queried in the blocks table for these blocks with these bids are not existant there was no blocks with those ids. But when I see the homebox/1 page it shows page with blocks. How is that possible?

Homeblock is actually not storing the data in block, it is actually inserting the data in its own custom table, like homeblock_users.

  $data = new stdClass();
  $data->uid = $user->uid;
  $data->name = $page->name;
  $data->settings = $blocks;
  drupal_write_record('homebox_users', $data);

It is saving block data in hoemblock_users table. It is creating only one Block i.e. Homebox custom block.

homebox_prepare_block

Above is the function through which dynamic block is created for a page, and all the variables are assigned to it.


Page manager selection rules for a variant for the front page I'm trying to make a Ctools page variant for the front page but I'm not sure of the of the selection rules I need to use to make it apply to the front page.   I've tried making it apply to everything BUT any of the existing content types but that didn't work.

Does anyone know of a set of selection rules that can let me target the front page?

Thanks

If fron page point to "node" (in Site information administering page), just change it to show some selected node (blank node for example), then edit this node in panels as you want, if you want list nodes, enable there views...


Cron job to transfer files to remote server How would I go about scheduling a monthly file transfer (via FTP) to send files in a specific directory on my remote VPS to a server on my internal Corporate network? Once files are transferred, I'd also like to job to delete the files on the VPS?

If you absolutely need it, Drupal has hook_cron() for regular task running:

function MYMODULE_cron() {
  // Copy your files here using standard php FTP functions
}

But it would be considerably more efficient to leave Drupal out of this altogether, and set it up with a basic rsync/FTP cron job executed on the server.

Alternatively, Backup and Migrate can both take a dump of the public/private file system and transfer it to an FTP target. Again, a solution outside Drupal will always be more efficient as it won't bootstrap the application.


Get created term entity after creating term programatically I'm writing a custom Drupal Console command to import user data from a text file and create users, and as part of the process, I need to add data to a term reference field. In the case that a term in the data doesn't exist, I need to create the term and then add the new tid to the the field. I'm using the following code to create the term:

$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
])->save();

The problem is the save() method only returns a boolean indicating if the save was successful, NOT the created term object. This means that now that my term has been created, I have to go do an entity query just to get the object I just created.

Is there a simple way to get the just-created term in my code above, or do I really have to do a separate query?

Term::create() returns the entity that the save() method gets called on. So what you want to do is save that entity to a var before calling the save() method on it.

$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
]);
$term->save();

//Retrieve the tid of the new term
$term->tid->getValue();


How do I show user attributes on articles? I added a custom field "Twitter URL" to each of my users (on the page Home » Administration » Configuration » People » Account settings). I'm trying to display this "Twitter URL" on every article that that user makes. For example, under the "Published by someusername on Wed, 12/28/2011 - 02:57" that is already on every post, I want to have the "Twitter URL" for that user right under that.

  Published by mike on Wed, 12/28/2011 - 02:57
  http://twitter.com/someusername

I think I need to go into node.tlp.php and edit something, but could anyone give me a little more help?

If you take a look at node.tpl.php, you'll notice there's already a variable for this type of data: $submitted. You could replace that variable with your own data, but to do it the Drupal way, what you want to do is modify the value of $submitted using a preprocess function.

In your theme, create a template.php file (if you don't have one already). In it, add the following function (replacing example with the short name of your theme):

function example_preprocess_node(&$variables) {
  // Linkify the URL
  $twitter_url = l('http://twitter.com/someusername', 'http://twitter.com/someusername');

  // This is the same thing as saying
  // $variables['submitted'] = $variables['submitted'] . ' ' . $twitter_url;
  $variables['submitted'] .= ' ' . $twitter_url;
}

Clear the cache (Configuration → Performance → Clear cache), and check your node pages again: you should see the Twitter URL appended to submitted line.

But this is of course, static: to load the user's Twitter URL, you'll need to load the field data:

function example_preprocess_node(&$variables) {
  // Even though there's a user object in $variables['user'], we need to
  // load a new copy because the preloaded one doesn't have have field data
  $user = user_load($variables['uid']);

  // Retrieve the data and its value for the Twitter URL field
  // Replace field_twitter_url with the short name of the field
  // found at admin/config/people/accounts/fields
  $items = field_get_items('user', $user, 'field_twitter_url');
  $field = field_view_value('user', $user, 'field_twitter_url', $items[0]);

  // Get the rendered output of the field for use in the submitted line
  $twitter_url = drupal_render($field));

  // If you wanted to get more fields, repeat the last three lines, replacing
  // field_twitter_url with the names of the other fields.

  // Linkify the URL and append it to the $submitted variable
  $variables['submitted'] .= ' ' . l($twitter_url, $twitter_url);
}

The Field API isn't the most intuitive or straightforward API in the world, but here's what's going on:

Load the user object, which contains the information about the fields attached to it.
Load the specific data associated with the field_twitter_url using field_get_items().
Get the render array for the specific field you want to display using field_view_value().
Get the final rendered output using drupal_render().

Now, if you wanted to have the Twitter URL separate (so you can move it to where ever you want in the template), just create your own variable:

function example_preprocess_node(&$variables) {
   // ...
   // Do all the stuff from the previous sample function, except
   // setting $variables['submitted']
   // ...

   $variables['twitter_url'] = $twitter_url;
}

Now, you can add $twitter_url to anywhere in node.tpl.php. If your theme doesn't already have its own node.tpl.php, navigate to the modules/node folder, copy the node.tpl.php that's there to your theme folder, and clear the cache.


Get full expanded menu? How can I render out my main menu as entirely expanded? I am working on mobile navigation and need to have the entire tree rendered out in my code for this to work the way I want it to. I do not want to make admins go into the menu and select "expanded" every time they create a child item. Can this be done with a module or

I think menu_tree_all_data should do the trick.

You will need to put this in a custom module and then loop over the array to manually build your menu.


Does having too many content types negatively affect site speed and performance? I building a site that could potentially utilize 20 different content types. The content types are very similar, but may only utilize one or two fields that are unique to that content type, and they would use the same 5 fields with each other. Does having 20 different content types slow the site down? Would it be better to build one content type and display the unique fields on a case by case basis using FAPI or the conditional fields module?

The number of content types does not affect the performance of a Drupal site.

Sharing fields among the content types does affect the performance. This is because of the way CCK stores fields.

If the field is not shared and allows only one entry, it is stored along with other such fields in a table designated for that content type. That way, all such fields can be loaded in a single query.
If the field is shared or allows multiple entries, the field is stored in its own table, making an extra query (or join) per field necessary to load the field.


How can I transition an order from fulfillment to completed? I'm running Commerce Marketplace and provide store owners a back-end portal for managing their store.
In their portal, they can view orders sitting in the "fulfillment" state with the shipping address.  Once they fulfill that order, I need to provide a button for them to move that order to the "completed" state.
How do I move an order to the "completed" state?  Do I send the user to a specific checkout route, or can I move the order itself to completed via the API?
Currently, the only way to move the order to "completed" is manually in the order under the Commerce administration.

Perhaps one way to do this would be similar to what you can find in modules/contrib/commerce/modules/order/templates/commerce-order--admin.html.twig
{# If the order has possible transitions, render the field for transition buttons. #}
{% if order_entity.getState.getTransitions is not empty %}
<div class="entity-meta__header">
  {{ order.state }}
</div>
{% endif %}

If the order is configured to pass from state fullfilled to completed the appropriate button for moving state should be available there.  Make sure your order_entity is passed to the twig template.
Read more about order workflow states


React if user's text changes in existing node are major I would like to ask about some ideas about following issue:
I have a content type - answer, that can be created and edited (not deleted) by users. From time to time, for any reason an user can delete all text inside node, thus completely destroying it.

I do not want to be informed about every subtle change in node, but I certainly want to be alerted and possibly approve, if there is a major change in node's content.
So the requirements are:

detect negative change + restrict user to publish changes + alert admin for approval

Solutions?:
1) Count words in node and compare it to word count in node's revision. The word count may be saved inside a field in node and after compared by rules.

2) As suggested by @T-34, use custom module
I found some modules but none of them gives the ability to figure out the difference percentage and use it with rules:
https://drupal.org/project/diff
https://drupal.org/project/rules_diff
https://drupal.org/project/trevi - suggested by @T-34 gives me an error + it seem s to work only on node edit page.
Thank you for ideas.

I would use Diff and implement hook_entity_diff() (see diff.api.php), which allows modules to provide a comparison about entity properties.

Here you go:

function MYMODULE_entity_diff($old_entity, $new_entity, $context) {
  if ($context['entity_type'] == 'node') {
    $old_body = $old_entity->body[LANGUAGE_NONE][0]['value'];
    $new_body = $new_entity->body[LANGUAGE_NONE][0]['value'];
    $matching = similar_text($old_body, $new_body, $percent);
    $results['line'] = array(
      '#name' => t('Body'),
      '#old' => 'Number of matching chars: ' . $matching,
      '#new' => 'Percentage difference: ' . $percent,
    );
    return $results;
  }
}


Manage Display of Entity Reference Field: How to link to nodes instead of plain-text? I've got two Content-Types: Releases, and Scenes.

Releases contain Scenes as Entity reference fields.  I would like to link to the Scene Nodes rather than what the current options allow.  At the moment my only options for Format under Manage Display are:

Label
Entity Id
Rendered Entity.

These Display:

Plain-Text Name of Entity
Entity Id #
Renders Scene Nodes within Release Node

How can I make Drupal render a link to the Scene Nodes that have been selected in Entity reference fields?

Or, as an alternative, is it possible to display a Teaser instead of rendering the full Scene Node within the Release Node when using "Rendered Entity"?

On the Manage Display page for your Releases content type, select "Rendered Entity" for your entity reference field.  Then, to the right of the control that contains "Rendered Entity" you will see a little gear.  Click on the gear, and you will get another page with a "View mode" control.  The view mode has options such as "full content" and "teaser".  You can select exactly which view modes appear in this list by going to the Manage Display page for your Scenes content type, and open the "Custom Display Settings" field group.  If "Teaser" is not checked, then check it and click "save".  After you turn on "Teaser" in this way, you will have a "teaser" button at the top-right if the Manage Display page for your Scenes.  Click on this and you can control exactly what appears in a scene teaser.  If you want your scene teasers to hold different fields than scenes embedded in releases, then perhaps you could use "tokens" instead of "teaser" for your entity reference view mode.

Edit:  Sorry, I only answered the second part of your question.  If you want to render just a link to your scene, then select "Label" for your entity reference field, click the gear next to the control again, and turn on the checkbox "Link label to the referenced entity".


Modify a custom block field value with hook_form_alter and validate I'm trying to modify a custom block form with hook_form_alter .In its validate function I have a case where one of the field value needs to be unset. For modifying its value I tried with

$form_state->setValue('field_name', '') /

$form['field_name']['#default_value'] = '' /

$form['field_name']['#value'] = ''

But none of these approach seems to work.
Below is my code -

function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    //create or edit form
    if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
      $form['#validate'][] = 'coolblockvalidate';
    }
}

function coolblockvalidate(array &$form, FormStateInterface &$form_state) {
    //trying to unset the field value here, which is not working.
    $form_state->setValue('field_mycoolfield', '');

    //tried these approach too with no luck.
    //$form['field_mycoolfield']['#default_value'] = '';
    //$form['field_mycoolfield']['#default_value'] = '';

}

I'm very interested in knowing why the field value can't be changed. I tried the same with a custom form alter and it works.

Any ideas/ suggestions would save me.
Thanks.

Got this working by adding a submit handler.

Below is the code -

function coolmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //create or edit form
  if('block_content_coolblock_form' === $form_id || 'block_content_coolblock_edit_form' === $form_id) {
    //extra submit handler that will execute after default submit
    $form['actions']['submit']['#submit'][] = 'coolmodule_coolblocksubmit';
  }
}

function coolmodule_coolblocksubmit(array &$form, FormStateInterface &$form_state) {

  $entity = $form_state->getFormObject()->getEntity();
  // unset field.
  $entity->set('myfield', '');
  // Saving the entity.
  $entity->save();
}


What should I use to implement a shopping cart process? I'm developing a website for a group of human resource professionals.

The customer wants a way for people to go to their site and do the following:

If they have a job listing they want to post to the website, they'll click on a "Post a Job" link.
The job submitter will then fill out the content for a job posting
Before the job can go online, the job poster will have to pay a fee to have it posted
Once the payment is received, the job posts to the website

I'm curious if anyone has any experience with this, and if so, what would you use to build it? It's a fairly simple shopping cart experience I suppose. It's certainly not like a store or anything. But, I don't have previous experience with something like this.

Can anyone guide me down the correct path?

Here are a few typical solutions for implementing an online store:

Drupal Commerce, or its related Commerce Kickstart.
Ubercart.

However, as per your "Simple shopping cart experience", it looks like none of these is what you're looking for. So here are some other modules you may want to look at (excerpts are from their project pages):

Basic Cart:

... a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.

Rules:

Allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

Flag:

Flag is a flexible flagging system that is completely customizable by the administrator.

The 'Basic Cart' implements the cart, while with the 'Rules' and 'Flag' modules you can implement appropriate business logic (which does not require any PHP coding skills).
If you're not familiar (enough/yet) with Rules, then checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organised in 7 chapters.
Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.


Are proprocess functions cached? I'm using a MODULE_preprocess_node function to modify the node template and I'm experiencing strange things.

Basically my idea was to prevent anonymous users from commenting more than once. In the preprocess function, I check if the current hostname (if anonymous) has a previously submitted comment for the current NID and if it does, I empty the comment form array.

But the problem is that, even when caching is disabled, I'm experiencing strange behavior. I'm not quite sure whether it's because of caching. I checked my db_select call and it works.

Do you have any recommendation for me to prevent this from being happening ? May be I should ask if the output of *_preprocess_* functions are cached at first place.

I do not have (core) caching enabled  and I'm planning to do so. No other modules installed yet.

Thanks in advance.

Do not confuse the cache with the "theme registry".

If you're updating theme functions, flush the cache (which will also update the theme registry).

if you post code there could be other reasons it isn't working.  if you're dealing with comments I would look at using comment specific hooks rather than node submission hooks.


How do I get the weight of a multiple value field collection in a computed field? I have the following structure in a content type:

. field_collection_parent (multiple value = 7)

.. computed field (single value)

.. field_collection_child (unlimited multiple value)

field_collection_parent represents the days of the week and field_collection_child are some work reports of each day. The computed field returns the day (monday, tuesday, etc.)

The problem is that I can have data in the first and thrid items of the field_collection_parent (that is Monday and Wednesday), but when I save the node, I only have two rows, because the second was empty, and computed returns Monday and Tuesday.

So, is it possible to get the weight of each field collection item although they were empty, and code it in the computed field?

Thanks.

P.D. I tried

$wrapper = entity_metadata_wrapper('field_collection_item', $entity);
$entity_field[0]['value'] = print_r($wrapper->delta(), true);

as indicated in
"how to get weight or delta of current field collection item that is being computed" but it returns "Fatal error: Call to undefined method EntityDrupalWrapper::delta()"

Ok, finally I got a workaround. I was focussed on entities and computed field, but it turned out to be a death end. So, I change the approach and found the rules_form module.

This modules allows apply a rule in the node form, so I created an integer field called delta in my field_collection_parent and populate it with rules when the form is created. In this way, I always keep a seven-rows field_collection_parent even though the field_collection_child is empty (because the field delta is filled).


how to check non existent field added later using entityfieldquery? I added a required field in a Job type node later. So existing nodes don't have that particular field value.
I want to include all such field values. But how can I do it?

Here is query sample:

$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', array('central_government_vacancy','psu_vacancy','state_government_vacancy'))
    ->propertyCondition('status', 1)
    -> fieldCondition('field__expired_processed', 'value', 'NULL', '=')  //I'm looking for this field
    ->fieldCondition('field_last_date_of_application', 'value', $date, '<=');

In the above code I want to find nodes having uninitialized field values : field_expired_processed.

!=, or using NULL to compare does not seem to work.

If you look on the fieldCondition documentation page you will see the following warning:

  Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

This means you must use standard SelectQuery in order to achieve this. You must join the table which contains your data, and check whether the fiels IS NULL. It would be something like:

$q = db_select('node', 'n');
$q->condition('n.type', 'central_government_vacancy', '=')
->addJoin('LEFT', 'field_data_field_expired_processed', 'f')
->isNull('f.value');
$r = $q->execute();


Views, multiple pagers on same page I have multiple views with pagers on same page. But all of the pagers using the same GET argument "page", so when user chooses a page in first pager, all of the pagers changing their state to those page. How can I make things work? Drupal 6, Views 2.

Change the ID used for the pager: The setting is under the advanced options for the view, in the administration area.


hide if on front page and on taxonomy pages i wondering how i can hide $title if its on the front page and on taxonomy pages, I only want it to show on nodes.

here my code, I dont know if im close or not =)

function bartik_process_html($variables){
    if(!drupal_is_taxonomy()){
    $variables['title']['class'][] = 'element invisible';
    }
    elseif(!drupal_is_front_page()){
    $variables['title']['class'][] = 'element invisible';
    }
    else{

    }
}

Try something like this:

<?php
   function hook_preprocess_page(&$variables) {
       if (drupal_is_front_page() || drupal_is_taxonomy()) {
           $variables['title'] = NULL;
       }
   }

Change hook to the name of your theme.  Based on your example, it looks like you're hacking core which isn't good. Create a subtheme and implement your custom themeing there.