Modal does not handle errors on login I have used 'use-ajax' class to render login form in a modal.
I want to handle validation errors on same modal without closing it.
On successful login it is redirecting correctly, but when an error occurs it closes modal and redirecting to login page i.e user/login and displaying errors on that page.
I tried to use ajax callback to display error on modal itself by altering the form which is working. But, it is giving me drupal ajax error.
Here is my code :

$form['#prefix'] = '
';
$form['#suffix'] = '
';
$form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
];
//$form['actions']['submit']['#limit_validation_errors'] = array();
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'setMessage',
    'wrapper' => 'modal-form',
);

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

    $response = new AjaxResponse();

    if ($form_state->hasAnyErrors()) {
        $response->addCommand(new ReplaceCommand('#modal-form', $form));
    }
    else {
        $command = new CloseModalDialogCommand('#modal-form', FALSE);
        $response->addCommand($command);
    }
    return $response;

}

The above code giving me session id also but due to drupal ajax error it does not redirect on success by closing modal.

I have resolved it by commenting redirection code from hook_login and added redirection code related changes in ajax callback function itself. Here is my code.

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

     $response = new AjaxResponse();
     $current= \Drupal::currentUser();
     if ($form_state->hasAnyErrors()) {
         $response->addCommand(new ReplaceCommand('#modal-form', $form));

     }
     else if (!$current->id()) {
         $response->addCommand(new ReplaceCommand('#modal-form', $form));
     }
     else {
         $command = new RedirectCommand(' ');

         return $response->addCommand($command);
     }
     return $response;
}


CCK checkbox or dropdown widget as a field? I am trying to setup a new CCK field for a content type to display as a checkbox but I see I don't have that option in the widgets type.
Shouldn't that be included in the default CCK?

I am using the latest CCK for Drupal 6.

The checkbox field is provided by the "Options Widget" sub-module included with CCK. From the .info file:

  Defines selection, check box and radio button widgets for text and numeric fields.

If you're not seeing checkbox as an available type you probably don't have that module enabled.


How do I keep multiple sites in sync using drupal-composer/drupal-project What is the correct process to keep local and production sites in sync when using drupal-composer/drupal-project. Most of the solutions online only discuss updating one site and not dev, staging and production properties.

This is the current process I am using

put live site in maintenance mode
run composer update drupal/core --with-dependencies -vvv

I run this on both local and production servers
I noticed that this does not sync alpha and beta contributed modules
I noticed that running 'composer update' from the root of the project updates core and all contrib modules

run drush updb

I run this on both local and production servers

I then commit changes to git from the local site

I just want to find out what otheres are doing to keep multiple sites in sync

There are a number of different options that are all viable here; this is what I would suggest:

On your dev site, run composer update with options to suit what you want to update.
Run drush updb on your dev site.
Test thoroughly; then commit composer.json and composer.lock and push to your repository.
On your test site, pull your repository and run composer install.  This will put all of your dependencies into the exact same state they were in on your dev site, so you will get exactly what you tested.
Run drush updb on your test site.
Test thoroughly again.
When you are ready to deploy to your live site, put it in maitenance mode and use a file copy program (e.g. rsync) to move the exact files from the test site to live. Alternately, you can use composer install again.
Run drush updb on your live site.
Confirm that all is okay and take your site out of maintenance mode.


Symfony\Component\HttpFoundation\Response is never cached My custom controller is returning data but it is never being cached.
My controller function:
use Symfony\Component\HttpFoundation\Response;

 $build = [
            '#theme' => 'search_form_suggest',
            '#nodes' => $nodes,
            '#term' => $term,
            '#type' => $type,
            '#cache' => [
                'keys' => [
                    'sg_search_term_suggestions_' . $term . "_". $type
                ],
                'tags' => [
                    'sg_search_term_suggestions_' . $term . "_". $type
                ],
                'contexts' => ['route']
            ],
        ];

$response = new Response($content);
return $response;
//retrun $build; //this does serve from CACHE

Looks like it never ends up hitting the cache mechanism. When I return $build then it does serve from cache.

Return a cacheable response. For example
use Drupal\Core\Cache\CacheableResponse;
use Drupal\user\Entity\User;

  /**
   * A route returning a CacheableResponse object.
   *
   * @return \Drupal\Core\Cache\CacheableResponseInterface
   *   A CacheableResponseInterface object.
   */
  public function cacheableResponse() {
    $user = User::load(1);
    $response = new CacheableResponse($user->label());
    $response->addCacheableDependency($user);
    return $response;
  }

From Drupal\dynamic_page_cache_test\DynamicPageCacheTestController.
There are multiple ways to add cache data to the response object additional to the one used in the example.
You can use addCacheTags()/addCacheContexts():
$response->getCacheableMetadata()->addCacheTags($tags);
$response->getCacheableMetadata()->addCacheContexts(['route']);

The route cache context is by the way not necessary in a controller because it depends already on the route.
Or add cacheable metadata contained in a render array
use Drupal\Core\Cache\CacheableMetadata;

$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));

See also How to handle cache metadata in a cacheable response? and How to get cache metadata from nested render array when returning response?


hook_node_presave() fires twice when adding a new node In a custom module I use hook_node_presave($node) on node objects with referenced fields.

When creating a new node, ddebug_backtrace() shows that entity_save is called first and then node_save. Which leads to two new nodes. At the end of hook_node_presave() I have one correctly created node and one with only partially filled fields.

How can I prevent node_save to fire in hook_node_presave() when entity_save was already executed? Or maybe the solution is to prevent entity_save to fire?

Could anybody please explain how to correctly use hook_node_presave() on node objects with attached referenced fields?

Just in case anybody else experiences the same strange problem. In my case the reason was module CER (Corresponding Entity References) 7.x-3.0-alpha7. For any reason after a complete uninstall and clean reinstall hook_node_presave() now works fine with entity referenced fields.


Media Mover and thumbnails As it stands now I have MediaMover move images uploaded from Image FUpload CCK to S3 while deleting the source images. However, all I see are lists of the image files that I've uploaded. How can I display a thumbnail instead? I believe that I need to use Views, but I'm a Views noob.

I can only assume your media mover process is upload file(s) to site, moved files to S3, copy S3 file location to the CCK field

For Drupal 6:

Install imagecache module and its dependencies.   Create a imagecache preset call thumbnail of the size you want.

Create a view.   Add the CCK field.   In the settings select the format of the thumbnail preset.


How to decide between Activity or Heartbeat (or DIY Rules?) I wish to create a site with status updates, and thus I want people to see those status updates.... (I am looking at the Facebook Style Statuses / Statuses module.)

It seems that I need to use either Activity or Heartbeat modules to get a stream of activity. However they both do similar things. How do I choose between the two? Is there a comparison anywhere?

I've seen a lot of discussion comparing them back in 2009 and talking about creating a unified version. However that discussion doesn't take into account Drupal 7 and doesn't seem to have resulted in a clear winner.

I am developing an SNS site and I chose Heartbeat.  I would choose Heartbeat again today for the following reasons:

Heartbeat has a stable D7 release.  Activity hasn't had any commits in 32 weeks (as of March 24, 2012) and is still in dev; there is no stable release yet.
Acquia chose Heartbeat over Activity for Drupal Gardens.
Heartbeat has rules integration.  This makes it very easy to customize to do what you want it to do, especially because you get access to tokens through the token module.  Activity lacks rules support.
Heartbeat has solid internationalization support.  This was a requirement as my site is multilingual.


How can I check that the file is present in database entry and also in files folder? I want to write a script where I want to check whether the files are present in files folder of drupal/sites/default/files and is it existing in the database table file_managed.

        $sql=db_query("SELECT * FROM `file_managed` WHERE `filename`LIKE '%.pdf' OR `filename`LIKE '%.doc' OR `filename` LIKE '%.doc' AND `timestamp` < UNIX_TIMESTAMP('2014-01-01')")->fetchAll();

function file_destination($destination, $replace) {

  if (!file_destination($uri, FILE_EXISTS_ERROR)) {
    switch ($replace) {
      case FILE_EXISTS_REPLACE:
        // Do nothing here, we want to overwrite the existing file.
        break;

      case FILE_EXISTS_RENAME:
        $basename = drupal_basename($destination);
        $directory = drupal_dirname($destination);
        $destination = file_create_filename($basename, $directory);
        break;

      case FILE_EXISTS_ERROR:
        // Error reporting handled by calling function.
        return FALSE;
    }
  }
  return $destination;

i am not able to find any way to get the fields delete.

You can use file_destination() drupal function to  check if file already exists in sites/default/files with second parameter as FILE_EXISTS_ERROR.

if (!file_destination($uri, FILE_EXISTS_ERROR)) {
  // The file exist
  // Do something
}


What is the best way to upload a PDF attachment, that can be attached to multiple nodes? I want multiple nodes to all have a download link on each node to one, shared PDF file.

What is the best way to upload the PDF file one time, but add it as an attachment to each of the multiple nodes?

This is easy to do for one node:one pdf attachment using the File Upload module, but I'm not sure of the best way to associate one single PDF with multiple nodes.

Two approaches spring to mind. Either you keep using a filefield and use something like FileField Sources to select already uploaded files; or you use a file-as-node idea, and create a content type for PDFs, use nodereferences to attach them to nodes, and use something like Nodereference Explorer for browsing.


Geolocation Field Oops! Something went wrong I use Geofield Gmap as Field in a Content Type. When I want to Add Node The -MAP- field display Error message

  "Oops! Something went wrong this page didn't load google maps
  correctly. See the javascript console for technical details."

How can I solve it?

BS: I already create API key For google map

UPDATE:

I try to apply a patch, I go to DIR
sites/all/modules/geofield/modules/geofield_map

Then I applied Like this

patch -p1 < https://www.drupal.org/files/issues/fix-api-key-not-being-used-2746209-5.patch

I see this message:

  No such file or directory

Usually you see this message when you don't have in the Geolocation module the Google API Key or the Google API Key is not working well. For this you need to go to:

http://YOURSITE/admin/config/content/geofield_gmap

Write your working Google API Key and save the Configuration.

Edit:

To apply the patch you need download the file to:

sites/all/modules/geofield/modules/geofield_map

then go to the dir and run:

patch -p1 < fix-api-key-not-being-used-2746209-5.patch


Drupal 6.x vs 7.x for Multiple Domains and LDAP We're looking at using Drupal for our public sites, which will have:

multiple primary domains
multiple sub-domains

We will need to allow our users

to authenticate against LDAP
to get different roles per site
to share content across primary and sub-domains.

Looking at the modules that are stable and under active development, 6.2x looks better than 7; of course 7 is very new. If we go with 6.2 now, we'll have to upgrade to 7 later; if we go with 7 now, we won't have all the functionality that exists in 6.2, specifically LDAP.

How would you address this situation of 6.2 vs 7.x? If you came across this situation, how did you make the decisions? What risks did you weigh? What direction did you go in?

This one is easy: go with 6.2.x!

Despite being new and exciting and all of that, Drupal 7 still is very lacking in the stable contrib department. Also, despite the huge number of modules that adopted the D7X pledge, a lot of important and frequently-used modules still don't have stable versions (ahem, Views! say what you want - "beta" and "dev" are not stable enough for enterprise purposes)

Drupal 7 also introduced some API changes that, despite not being huge, still mean that there's a small new learning curve to developing Drupal 7 modules.

Drupal 6, on the other hand, is more than stable and has plentiful offerings for modules including LDAP integration and anything else you might need. Since it's been around for a couple years now, there's no shortage of experienced developers who can aid in implementing the site and developing custom modules.

As far as having to upgrade to Drupal 7 eventually, despite it being a valid point in deciding which version to use, who said you have to be running the latest version? As far as I know enterprises take longer than most to adopt new technologies.

Quite frankly, developing for Drupal 7 (specially large and mission-critical software) is a lot more expensive and complicated at the moment than using Drupal 6 and I would strongly advice against it for at least 3-6 months to wait and see how contrib modules will react and see how it will be adopted in general by the community.


Using as shipping address the value entered as billing address In Drupal Commerce 2 how can we allow a customer to select as shipping address the same address entered as billing address?

Yes, you can try to custom jquery event.
1.To create a custom js file in your theme folder (/themes/theme-name/js)
Triger Function Like:
$("select[name='panes[delivery][select_address]']").change(function()
{
//your code
//.....
});

Thanks


Ubercart - how to alter button texts via hook_form_alter()? I am attempting to change the language of the buttons on the product and cart forms.

All is working well on product form but when the same is implemented on the cart page it stops submitting properly. Button values change but they stop working.

<?php

/**
**Custom Module for hook_form_alter
*/

function MYMODULE_form_alter(&$form, &$form_state, $form_id){

    if ($form_id == uc_product_add_to_cart_form_1){
            $form['submit']['#value'] = 'Register';
    }

    if ($form_id == uc_cart_view_form){
        //dsm($form);
        $form['continue_shopping']['#value'] = 'Back';
        $form['update']['#value'] = 'Update';
        $form['checkout']['#value'] = 'Continue';
    }
}
?>

Any help would be much appreciated.

There is a thread about this problem on drupal.org, and there is even a patch to solve this problem:
http://drupal.org/node/1170364

A quick explanation why the button text altering breaks up normal behavior (which is a bit "funny"):
Let's take a look at uc_cart_view_form_submit()'s code, mainly the part below the comment "// Specify the appropriate redirect based on the button used to submit". You can see that there's a switch block where the text of the clicked button is inspected ($form_state['clicked_button']['#value']), which is a very bad practice: the logic depends on what text this button is set to display. This means if you simply change the text of the buttons programatically, the appropriate redirections won't work anymore! To be honest, I don't really understand why this part of Ubercart was developed this way.

I just solved it with a custom module without patching the Ubercart core, and it works after some tests, you can find the code below.

About changing the "Continue shopping" text:

the "Continue shopping"  text can be easily changed on the /admin/store/settings/cart/edit/basic page, and as it's a multilingual variable, THIS is the appropriate way of changing it - you can do this by typing another name in the "Custom continue shopping link text:" textfield, and saving the changes. You can see a screenshot of it here:
BUT I also show you how to change it programatically (you can see it below in the code - you have to set the $set_continue_shopping_type_programatically to TRUE to try it - but I would suggest using the first method)
I also have to mention that the "Continue shopping" is a link (not a button) in Ubercart 6.x-2.7 by default - so if you would like to change its value programatically, and it is set to be displayed as a "Text link", its value has to be a link markup (not a regular string, because this way it won't work as expected) - you can use Drupal's l() function to create an appropriate link. But you can also set it to be displayed as a button, this way you have to use a plain text to modify its original text (and it turned out from your comment that you've already set it to be displayed as a button).

Here is the tested and working code:

// ...

// you should change MYMODULE to your module's name

/**
 * Implementation of hook_form_alter()
 * @see http://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_form_alter/6
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{

    // for testing, you can output the appropriate $form_id variable
    // to detect the form id(s) of the actual form(s) printed to the page
    // e.g. by using Devel module: http://drupal.org/project/devel
    /*
    if(function_exists('dsm'){
        dsm('Actual $form_id:');
        dsm($form_id);
    }
    */

    // You can just simply toggle overriding the default cart button values
    // with setting the variable below to "TRUE" or "FALSE" (without the quotes)
    // (this can be good for testing!)
    $modify_default_ubercart_buttons = TRUE;

    switch ($form_id) {
        // CHANGE IT TO THE APPROPRIATE $form_id!!!
        case 'uc_product_add_to_cart_form_1':
            // dsm($form);
            if($modify_default_ubercart_buttons){
                $form['submit']['#value'] = 'Register';
            }
            break;

        case 'uc_cart_view_form':
            // dsm($form);

            if ($modify_default_ubercart_buttons) {
                $form['#submit'][] = 'testModule_form_alter_uc_cart_view_form_submit';

                // 1.) changing the "Update cart" button's text

                $form['update']['#value'] = 'Update';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['update']['#name']  = 'update-cart';

                // 2.) changing the "Checkout" button's text

                $form['checkout']['#value'] = 'Continue';
                // if you modify the "#name" attribute, you also have to modify it in testModule_form_alter_uc_cart_view_form_submit()
                $form['checkout']['#name']  = 'cart-checkout';

                // IMPORTANT!!!
                // You should rather set the "Continue shopping element display" on the "/admin/store/settings/cart/edit/basic" page!
                // This is a multilingual variable, so setting it on the appropriate admin page is the best solution.
                // The code below is just a sample for setting it programatically!
                $set_continue_shopping_type_programatically = FALSE;

                if ($set_continue_shopping_type_programatically) {
                    $uc_continue_shopping_type = variable_get(uc_continue_shopping_type, 'link');

                    $continue_shopping_link_text = 'Back';
                    // $continue_shopping_link_path   = uc_cart_continue_shopping_url();
                    if ($uc_continue_shopping_type == 'link') {
                        $continue_shopping_link_markup       = l($continue_shopping_link_text, $continue_shopping_link_path);
                        $form['continue_shopping']['#value'] = $continue_shopping_link_markup;
                    } else {
                        $form['continue_shopping']['#value'] = $continue_shopping_link_text;
                        // the default "#name" attribute equals to "op" by default
                        // we change it to the desired button text to make it clear
                        $form['continue_shopping']['#name']  = $continue_shopping_link_text;
                    }
                }
            }

            // ...

            break;
    }
}
/**
 * Ubercart submit function needed because of button text altering
 * @see http://drupal.org/node/1170364
 */
function MYMODULE_form_alter_uc_cart_view_form_submit($form, &$form_state)
{

    // Specify the appropriate redirect based on the button used to submit.
    switch ($form_state['clicked_button']['#name']) {
        // Update cart button.
        case 'update-cart':
            // No redirect.  Just display a message and preserve the last URL.
            drupal_set_message(t('Your cart has been updated.'));
            break;

        // Checkout button.
        case 'cart-checkout':
            $form_state['redirect'] = variable_get('uc_checkout_enabled', TRUE) ? 'cart/checkout' : 'cart';
            break;
    }
}

// ...

I also posted some screenshots about the button text altering:

Modifying "Add to cart" button's text:

BEFORE:

AFTER:

Modifying "Shopping cart" page's buttons:

BEFORE:

AFTER ("Continue shopping" as a "Text link"):

AFTER ("Continue shopping" as a "Button"):


2 submits with same validation? I am modifying user_pass so that it also has an option to resend a user's activation email.

if($form_id=='user_pass'){
    $form['name']['#title'] = 'Email Address';
    $form['actions']['submit'] = array();
    $form['actions']['submit_reset'] = array(
        '#value' => t('Reset Password'),
        '#type' => 'submit',
        '#attributes' => array('class' => array('btn-primary', 'btn'))

    );

    //resend button
     $form['actions']['submit_resend'] = array (
        '#value' => t('Resend Activation Email'),
        '#type' => 'submit',
        '#submit' => '_mymodule_resend_activation', //gives invalid argument on foreach
        '#attributes' => array('class' => array('btn-primary', 'btn'))
    );
}

This doesn't seem to work bc I get an invalid argument for a foreach when I set the submit property for the resend button. But the reset functionality is exactly as I want it. Is there a way I can use the same validation for both submits and have a custom handler for the second one?

#submit and #validate each need to be an array:

$form['actions']['submit_resend'] = array (
  '#value' => t('Resend Activation Email'),
  '#type' => 'submit',
  '#submit' => array('_mymodule_resend_activation'),
  '#validate' => array('_mymodule_form_validate'),
  '#attributes' => array('class' => array('btn-primary', 'btn'))
);

As far as I know there aren't any limits on the number of elements that can share the same validation callback.


How to sort view by the weight of referenced nodes? I'd like to display the list of studies and their authors in a view. Authors are stored in a node reference field. It's very important to keep the original order of referenced authors in the view which is repredented by their weight.

I looked through View UI for a solution for this problem but didn't find any useful option.

I found out that the :delta component of the field (e.g. field_authors:delta) can do this trick.

-- EDIT--

Some more explanation: Let's say field_authors contains the reference to connected authors. Among the sorting options there's a field_authors:delta which contains numbers for each referenced node (0, 1, 2...) and represnts their actual order.


Trigger Crop API programatically after node is created Hi I am using Image Widget Crop so that users can crop images according to predefined image styles. All would have worked fine without any issues had I been using Drupal in the conventional 'monolithic' way. But I am not. Instead, I have a headless Drupal setup.
That means that I do not have a Drupal theme to render my content. The problem created because of that is that apparently (from what I've read online), the actual styled images created using Image Widget Crop/Crop API are actually created when they are called/loaded in a theme. Now the theme can be backend as well. Below is what I think this happens chronologically.

Create and save a post with an image cropped using Image Widget Crop.
Cropped/styled image does not get created in the file system.
Fetch the data using JSON API/Custom API Module
Returns with empty image field because cropped/styled image is not yet created.
Click on Edit post
Cropped/styled image created. Because the preview of the cropped image is called by the edit form/backend theme.
Fetch the data using JSON API/Custom API Module.
All works fine.

What I want to do is execute some kind of hook which creates the styled/cropped image when a post is saved(step 1). That way when I fetch the data using JSON API, it is readily available.

The solution is using Image Style Warmer


Error after validation by email I have the following problem with drupal 6 and I am using the Login Tobogan module.  When an user creates a new account in Drupal, the user receives the respective email.  When the users click in the link for validate the account, the account is validated but appears the next error:

Unable to send e-mail. Please contact the site administrator if the problem persists.
You have successfully validated your e-mail address.

Thanks for your help.

I have disabled the Login Tobogan and I have enabled again the Login Tobogan again and the error was fixed.


Custom default value for Webform's select options component I use Drupal 7 with Webform 7.x-3.9.

I have created a new component from type "select options". I also have chosen to display it as a listbox and I've populated it with a few strings from the type "safe_key|Some readable option" as expected. Here's an example :

1|Mr.

2|Ms.

3|Miss

Everything works perfectly well and the behavior is the following :

If I select this component to be mandatory, the display will be "-Select-"
If I don't select this component to be mandatory, the display will reflect the first string from the "Options" text area. In my example, it will be "Mr."

Now, imagine I want to have "Ms." but don't want to change the order. Nowhere I see this possible. Unfortunately, the "Default value" textfield is only used for tokens...

Any idea ?

All you need to do, it to put the key value into the default value field, in this case 2, to make Ms. the default value of the form. This is what the default value if used for.


Loggin into Drupal using Yahoo mail Merry Christmas to all,
I would like to allow users to log in my site using their Yahoo e-mail.
Is there a module for that?I am using Drupal 7.
Thanks

Try the RPX (Janrain Engage) module.

  Using Janrain Engage, Drupal sites can authenticate new and existing
  users with popular social networks, map user profile data from these
  websites to Drupal fields, and share Drupal content with a user's
  friends on their social networks.

  This includes Facebook, Twitter, Google, Yahoo!, LinkedIn, Myspace,
  AOL, PayPal, and Windows Live (see the complete list below).


Best practices for implementing custom caching? For every instance of every type of entity, I generate a number of caches, named something like: [module_name]__[entity_type]__[entity_id]__[string_depending_on_where_the_cache_came_from]

Now whenever a entity is updated, I want to drop all caches starting with the relevant entity type and id.

How should I store/clear these caches?

Currently I just cache_set(), but that presents a problem when I want to clear, as I don't know the names of all the relevant caches. Is it safe to drop cache entries with a db_delete()?

I can't think of a good reason why dropping the entries manually would cause a problem. This assumes, of course, that you're using MySQL as the backend for your particular cache; although I think the same applies to any other type of cache backend, the method to clear just wouldn't necessarily be a database query.

If you take the core update module as an example, it bypasses the cache_* functions and clears its cache manually:

function _update_cache_clear($cid = NULL, $wildcard = FALSE) {
  if (empty($cid)) {
    db_delete('cache_update')
      // Clear everything except fetch task information because these are used
      // to ensure that the fetch task queue items are not added multiple times.
      ->condition('cid', 'fetch_task::%', 'NOT LIKE')
      ->execute();
  }
  else {
    $query = db_delete('cache_update');
    if ($wildcard) {
      $query->condition('cid', $cid . '%', 'LIKE');
    }
    else {
      $query->condition('cid', $cid);
    }
    $query->execute();
  }
}

I always think "if it's good enough for core, it's good enough for me" :)


Create nested paragraphs programmatically Similar to the question here but for D8. I've managed to create the child paragraphs but failing to generate the parent paragraphs and attaching the child to them.

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ])->save();
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ])->save();
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);

save() returns the status of the save operation, not the entity. And you probably don't need to save the paragraphs, saving the node should save new paragraphs automatically.

So you can try this version:

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ]);
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ]);
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);
$new_submission->save();


How should I configure the wysiwyg filter to align the images? This is how my configuration in the wysiwyg filter looks like (in Drupal7):

a[!href|target<_blank|title],
img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd

However my configuration does not work for aligning images.

I have reviewed my code and the alignment is done using the "style" tag:

<img src="" alt="" style="float:right" />

I tried the following configuration for the image but that does not work either:

img[src|align<bottom?left?middle?right?top|alt|border|class|height|width|float|**style**],

Here is another attempt that did not work:

@[style]

And I also tried like so:

img[*],

Another attempt is what is detailed in this alternative: http://screencast.com/t/jUOwMxmpu

So what is the right configuration for the images to be aligned? What is my error?

Some people forget to turn off the built-in HTML Filter when they enable the WYSIWYG Filter.  If you double-filter, you will lose your img attributes.

For my part, though, I prefer to not put the float on the img; instead, I float the div that surrounds the image and caption, allowing them to float together.  (Example image, with floated caption "A battle...": http://www.westkingdom.org/content/new-members).  To give the content editors a good user experience, I allow them to set floats on images with ckeditor, but I move the markup to the div in a render hook when the content is displayed.  In this scenario, I don't need to allow floats on the image at all.

I have a writeup of how I achieved responsive images with captions using media 2.0, wysiwyg filter, and a couple other modules, and a couple of custom hooks.


Error when running update.php about field_data_body existing DatabaseSchemaObjectExistsException: Table field_data_body already exists. in DatabaseSchema->createTable() (line 660 of /srv/bindings/e27b77cd6512471f902f88e9e0704451/code/includes/database/schema.inc).

Any thoughts on where to track this down? Seems someone decided to delete all the field_body instances on the site and replace them with field_page_body, but I'm not sure why that would cause the above issue during an update.

I would recommend you to apply this patch, that can be maybe the solution for you :

https://www.drupal.org/files/issues/1551132-drupal-install-schema-shared-tables-69-D7.patch


Load a block contents dynamically / via AJAX? I need to have a custom block on the page (will be sitewide) that has two states - one for when a cookie is present and has a certain value, and the other for when that cookie is not there or the value is outdated. Think of it like login states, but no authentication through Drupal.

What is the proper way to go about this with the block build() method? Do I implement a lazy loader that has the logic in it that builds the render array? Do I also add a cache context based on this cookie and its value so it is unique to those users?

You can get the cookie from the request, see Can't find cookie for validation in EventSubscriber. Set the context and trigger the kill switch like in the code example and it should work. But this is not good for performance. So I would deliver an empty block container, attach a js library to the block, get the cookie value client side and then initiate an ajax request to get the block content.

See the code of the module Ajax Block as example how to lazy load a block client side: https://git.drupalcode.org/project/block_ajax


Theming Image fields in page.tpl.php I need to have have something like this:

....

My CCK Image field name is filed_image.
In page.tpl.php I have the following code:

    <?php foreach ((array)$node->field_image as $item) { ?>

<?php print $item['view'] ?>

    <?php } ?>

So with this I am able to print all images form my Image Field.

But I don't know how to dynamically change the value of id="r1", id="r2", id="r3" ....

That value must start from 1 and be auto increment. For example  if I have 3 images the id should be id="1", id="2", id="3" or If there are 10 images I need id from 1 to 10.

This code should do it:

    <?php foreach ((array)$node->field_image as $item_id => $item) { ?>
      <div id="<?php print $item_id+1?>" class="gallery"><?php print $item['view'] ?>

    <?php } ?>


How to manage form display non programmatically? In Drupal 8, using admin/structure/types/manage/article/form-display, you can manage the form display for your content type. You don't have to rely anymore on contributed modules or on the implementation of the hook_form_FORM_ID_alter() or hook_form_alter() to hide an element in your form when you go to edit or add a node.

But in Drupal 7 we don't have this functionality, at least not yet. So, how to manage form display in Drupal 7 non programmatically?

The most close approach that I was found is the Display Suite module.

Display Suite allows you to manage the display of content editing forms for entities (such as nodes, views, comments, users, et cetera). This can be useful if you want to provide the users of your website with a customized edit form (and you don't need to implement the hook_form_alter()).

When enabled Display Suite Forms takes over the Drupal core functionality that let you arrange the fields via the "Manage fields” tab.

Manage display of an editing form

Enable the sub module Display Suite Forms at Administration > Modules (admin/modules)
Go to Administration > Structure > Display Suite (admin/structure/ds)
Click "Manage form" for the entity (e.g., "User") that you like to change
At the bottom of the page, in the vertical tab "Layout for ... in form" choose "One column" and click "Apply"
Chose the Hidden option in the field.
Save the changes

Another way is the use of the Rules Forms  module, but you need make a rule for this after enable the module.

Go to the "Form events" page in the Rules administration menu
(admin/config/workflow/rules/forms).
Select the checkbox "Enable event activation messages on forms" and hit the "Save settings" button.
Go to the form on your site that you would like to customize with Rules, e.g. go to 'node/add/article' to enable events on the "Create Article" form.
On the top of the page you see a drupal message with a link to activate events for the form, click it.
Enter a human-readable label for identifying the form.
In some cases you may want to enable events for individual buttons on the form. To do so, check the checkbox labeled "Enable button level validate/submit events".
Confirm the activation by clicking the "Activate" button.
Go to the "Triggered rules" admin page (admin/config/workflow/rules) and click the "Add a new rule" link.
Fill out the label, choose a form event by selecting one in the "Rules Forms" group and confirm with "Save changes".
Now you can select "Hide an element in the form" and select the element to hidde.

Reference:

https://www.drupal.org/node/1795380
https://www.drupal.org/node/1456178


How to exclude non-physical products from shipping calculations? I have an show which sells physical products and virtual products like memberships. How can I set up a situation where there is no shipping charge for the virtual products? I know that I could set up free shipping if there are virtual products in the shopping cart,  but I don't want the shipment to be free if the cart has both physical and virtual products.

Would the solution be to set the weight of the virtual products to zero? Or is there another way to implement this?

Do you have separate product types? Commerce Physical has a function that determines whether a line item is shippable: commerce_physical_line_item_shippable().

This function looks at the weight of an item. If the weight of the item is 0, then it considers it to be not-shippable.

You can also implement hook_commerce_physical_line_item_shippable_alter() and define your own logic to determine if something is shippable.

It looks like Commerce USPS implements this functionality and so you should be able to depend on this. Ideally, you'd have different product types for your physical and virtual products and your virtual products would have no weight causing them to not be factored into the shipping calculations.


Save and preview differences in hook_form_alter() I've created a module which uses hook_form_alter(). When a form is loaded (node/add) I hide a field, and the hook works fine. The problem appears when I do a preview of the form. When the form appears again I see the hidden field (the hook doesn't work). Why?

I hide the field through the line:

$form['field_versio']['und']['0']['value']['#type']="hidden";

First, you should use #access = FALSE which will disallow access to a element. #type hidden is not safe, it means that it is printed as a hidden input field which can be easily changed by the user, for example with Firebug.

When you do that, you can also directly set #access on the field element, like $form['field_versio']['#access'] and it will disallow access to all subelements (if there are multiple).

Not sure why it doesn't work in Preview, try adding a drupal_set_message('test') call to see if your hook is called.


How to hide "do something on load" I am using drupal 7 with custom omega theme. I am developing a site for myself for a year now. I could find a solution to everything until now. Hopefully the answer is easy and simple I just don't see the wood from the tree.

How can I remove or hide the 'Do something on load' message, but keeping those messages what I want to appear?

Thank you for your time to read, and I'm hoping in a quick and good response

Thank you everyone who looked at it.
It seems I have found the answer.
Yes it really is connected to the Entity Reference field.
There is a sub-module called " Entity Reference Behavior Example".
All I needed to do is to disable this sub module.
I have fallen into that mistake to switch it on without knowing exactly what it is doing.
Simply switch it OFF.

I haven't seen that message myself yet, but just came across a suggestion how to avoid that message. I suppose you're using the entityreference module? At least for what I know the message seems to come from there – so hopefully this hint helps you:

  To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

As far as I know the author is relating to the entityreference settings – here's the source: "how to render a node field of a referenced node on the node form". I hope it helps somehow.


Aegir Installation - how to get the sender email correct to allow install to pass During the Aegir installation procedure, the
sudo apt-get install -y aegir3 aegir-archive-keyring

step runs through a series of installation commands that eventually try to send an email from the aegir user to the aegir user.
Depending on my build environment this may work or not depending on whether the the aegir user is set up as a valid email sender.  I already have the sending email squared away with MSMTP and can send email from my command line but the installer seems to always be assuming the sending is aegir@hostname.
It would be very nice if I could figure out how to 1) override the sender in the installation script or 2) set the email address of the aegir user manually via CLI.
You'd think that 2 would be very easy to find on the internet but, believe it has been anything but easy.
Does anyone know how to alter the apt-get install of Aegir to pick up the sender email address from some environment variable?
Thanks

Found the answer in section 7.1 at https://docs.aegirproject.org/install/#7-install-aegir
sudo apt install debconf-utils
mkdir -p ~/projects/aegir/core
git clone https://git.drupal.org/project/provision.git ~/projects/aegir/core/provision
echo "aegir3-hostmaster aegir/email string valid@email.com" | sudo debconf-set-selections
sudo apt install aegir3


Inline image update url I've got a content type with a field who contains a default value. In this default value there is an image and I would like to change the source of this image to all the existing contents.

from  to

How can apply this to the existing contents?

Thanks in advance.

You may do a SQL query to update the field.

Table: field_data_field_NAME

Column: field_NAME_value

Table: field_revision_field_NAME

Column: field_NAME_value

UPDATE `db_name`.`field_data_field_NAME` SET field_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');

You may want to update the revision table of the field as well

UPDATE `db_name`.`field_revision_field_NAME` SET field_cc_NAME_value = replace(field_NAME_value, '/sites/files', '/sites/files/images');


How can I output a text string when my dynamically built form is empty? I have a form that is dynamically built. It renders a list of check boxes, but sometimes there are none to render - it is empty. In this circumstance, instead of the forms #titles with nothing below them being rendered, I'd like to output t('None'). For the type #tableselect the option seems to exist: #empty, but not for checkboxes or any other type. How can I acheive this? Thanks.

Code added:

    // Form defintion.
    $form['posts'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Member responses to:'),
        '#options' => $options['post'],
    );
    $form['terms'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Posts tagged with:'),
        '#options' => $options['term'],
    );
    $form['groups'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Group posts for:'),
        '#options' => $options['group'],
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Remove'),
    );
    return $form;

I tried at the bottom:

if(empty($options)) {
  return t('None');
} else {
  return $form
}

...but this threw an error.

I don't know what's the code before/after and exact context in which you are using it., but this could work for you:

if(empty($options)) {
  $form['empty']['#markup'] = t('None');
}
else {
  // Form defintion.
  $form['posts'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Member responses to:'),
      '#options' => $options['post'],
  );
  $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Posts tagged with:'),
      '#options' => $options['term'],
  );
  $form['groups'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Group posts for:'),
      '#options' => $options['group'],
  );
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Remove'),
  );
}
return $form;


How should I handle container form elements? I have added some custom fields to the register user form and I'm discovered that they are sent back, packaged in a form element of type "container". My code needs to handle all kind of different custom register fields.

How should I parse these objects and extract the fields from them? Should I look into the arrays and what can I expect to find there?

I can't seem to find any good documentation on these objects.

Edit:

A regular fields received through user registration might look like this:

name
... (Array, 10 elements)
#type (String, 9 characters ) textfield
#title (String, 10 characters ) Username
#maxlength (Integer) 60
#required (Boolean) TRUE
#attributes (Array, 1 element)
class (Array, 1 element)
0 (String, 8 characters ) username
#default_value (String, 0 characters )
#access (Boolean) TRUE
#weight (Integer) -10
#fb_registration_field (String, 4 characters ) name

A form container looks e.g. like this:

field_birtyday
... (Array, 6 elements)
#type (String, 9 characters ) container
#attributes (Array, 1 element)
#weight (String, 1 characters ) 7
#tree (Boolean) TRUE
#language (String, 3 characters ) und
und (Array, 13 elements)
0 (Array, 12 elements)
#entity_type (String, 4 characters ) user
#bundle (String, 4 characters ) user
#field_name (String, 14 characters ) field_birtyday
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)
#columns (Array, 2 elements)
0 (String, 5 characters ) value
1 (String, 6 characters ) format
#title (String, 8 characters ) Birthday
#description (String, 0 characters )
#required (Boolean) FALSE
#delta (Integer) 0
#weight (Integer) 0
value (Array, 16 elements)
#entity_type (String, 4 characters ) user
#bundle (String, 4 characters ) user
#field_name (String, 14 characters ) field_birtyday
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)
#columns (Array, 2 elements)
0 (String, 5 characters ) value
1 (String, 6 characters ) format
#title (String, 8 characters ) Birthday
#description (String, 0 characters )
#required (Boolean) FALSE
#delta (Integer) 0
#weight (Integer) 0
#type (String, 9 characters ) textfield
#default_value (NULL)
#size (String, 2 characters ) 60
#maxlength (String, 3 characters ) 255
#attributes (Array, 1 element)
#theme (String, 25 characters ) field_multiple_value_form | (Callback) field_multiple_value_form();
#field_name (String, 14 characters ) field_birtyday
#cardinality (String, 1 characters ) 1
#title (String, 8 characters ) Birthday
#required (Integer) 0
#description (String, 0 characters )
#prefix (String, 42 characters ) <div id="field-birtyday-add-more-wrapper">
#suffix (String, 6 characters ) </div>
#max_delta (Integer) 0
#after_build (Array, 1 element)
0 (String, 30 characters ) field_form_element_after_build | (Callback) field_form_element_after_build();
#language (String, 3 characters ) und
#field_parents (Array, 0 elements)

You should use $form_state['values'] to handle submitted user data, not $form.


How to hide input from user inside a textfield I need text inside a textfield FAPI form element to be obscured visually, just like the password field when you type into it.

password FAPI form element does not have proper functionality for what i need, I need textfield functionality but with the ability to hide the input from user.

Is this possible with Drupal 7 FAPI?

You can add a CSS style to implement this.

However, currently, only Chrome supplies "-webkit-text-security" could do this. I find someone has some sample code:   https://jsfiddle.net/estelle/8WpNg/


Fixing Overridden state for features The feature are coming into override state always. After running 'revert', it goes into default state and everything is fine,however. My client are unable to do the revert every single time its being enabled.
Why is it coming into override state always? There are no changes made... fresh install, enabled and it is in override state. Running diff shows:

Component type: fe_block_settings
        ),
        'cascade' => array(
<         'region' => 'page_header',
---
>         'region' => 'sidebar_first',
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -10,
---
>         'weight' => -1,
        ),
        'seven' => array(
        ),
        'cascade' => array(
>         'region' => 'help',
>         'status' => 1,
          'theme' => 'cascade',
        ),
        ),
        'cascade' => array(
<         'region' => 'sidebar_first',
<         'status' => 1,
          'theme' => 'cascade',
<         'weight' => -11,
        ),
        'seven' => array(
        ),
        'cascade' => array(
>         'region' => 'sidebar_first',
>         'status' => 1,
          'theme' => 'cascade',
<         'weight' => -9,
        ),
        'seven' => array(
        ),
        'cascade' => array(
<         'region' => 'navigation',
---
>         'region' => 'footer',
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -9,
---
>         'weight' => 10,
        ),
        'seven' => array(
        ),
        'cascade' => array(
<         'region' => 'user_popover',
<         'status' => 1,
          'theme' => 'cascade',
        ),
          'status' => 1,
          'theme' => 'cascade',
<         'weight' => -8,
        ),
        'seven' => array(

Component type: variable
      'api_version' => 1,
      'name' => 'site_name',
<     'value' => 'Cascade ',
---
>     'value' => 'Cascade Site',

As you see one is variable 'site_name'. This variable is not changed, so i am coming to conclusion that when enabling the feature it is not setting the variable 'site_name'. Can it be true? if so, why and how to fix? The same seems to be the case with fe_block_settings. I really would appreciate your help as this is becoming the case with many of my features. I would really like become good at troubleshooting and understanding features. Thank You a lot

I think that if your feature set variables or configurations that are already stored on db, you have to revert it. instead this does not happen for "new" configurations.


Local vs CDN libraries and how to check for available updates For contributed Drupal modules, you can check whether you are using the latest version release of the module or not, by using any of the available methods such as Drush, Drupal console, Composer and UI.

What about the libraries used by those modules !?

How do I know if some of the libraries i have on my website are outdated and need to be updated ?!

To name a few, libraries for:

Webform.
Business Rules.
Font Awesome.

Note: I am asking about the libraires used locally and not via CDN.

I am aware of the "one question" policy to simplify the questions asked, but since my other question is related to the first one so:

I don't like to use the CDN version of any library because when switch to the development website on my offline localhost, the CDN won't work and I must anyway to download the Libraires locally on my machine.

So my second question is:

What is the best in term of performance, using the CDN version or the Local version of libraries ?

Maybe, not sure, for development website running on localhost we could use the local version of libraries and add those folders/files to the .gitignore file so they will be not added to the Git repo

Thank you,

We are using https://asset-packagist.org/ and manage our javascript dependencies just like any other, a composer update keeps those up to date as well then.

https://github.com/drupal-composer/drupal-project/pull/286 is a PR to add that to the drupal-project project by default.


loop view fields inside views-view--[view-name]--page.tpl I'm within the template views-view--[view-name]--page.tpl and I want to fully style the fields within the templates. So I do var_dump($variables) and within this I can see all my nodes seem to be there, but there so deep within the structure it's impossible to see where exactly, plus this can't be the correct way to loop around it as I'd have a crazy long query!

So how do I simply loop around the view in the template I mentioned and get lets say the title and the body for the nodes in my view?

Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

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

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

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

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


Custom template for view with block display in a page I created a template views_block__applications_block_1.twig for a block used on one of my pages. The block is based on a block view (unformatted list). Under blocks, the machine-readable name is views_block__applications_block_1. After searching around, I found that views_block__applications_block_1.twig should be the right template name. But no matter what I try, it doesn't seem to be working, all changes to the file are invisible. Can anybody point me in the right direction?

File content:

{#
/**
 * @file
 * Theme override to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 */
#}

TEST

{% if title %}

{{ title }} - TEST

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{ row.content }}

{% endfor %}

The correct naming is:

views-view--applications--block-1.html.twig

Also, the custom template should be based on the views-view.html.twig template, rather than on the views-view-unformatted.html.twig template.

The following are the possible template names sorted by precedence:

[base template name]--[view machine name]--[view display id].html.twig

[base template name]--[view machine name]--[view display type].html.twig

[base template name]--[view display type].html.twig

[base template name]--[view machine name].html.twig

[base template name].html.twig

(Source: http://redcrackle.com/blog/drupal-8/theme-views-templates)


Implement Menu block hook function hook_menu_block_tree_alter() to add/change/remove classes I have installed the plugin Menu block and I am very happy with the result, but I'd like to change some classes in the structure.

This is what I get right now:

            News

                    Test

..and this is what I want:

            News

                    Test

So I basically want to..

..add/change/remove the
's class and id attributes (level specific, so not the same for the primary/secondary
).
..add a has-submenu class to an
 if it contains another submenu.

What I've tried:

As explained in Menu Block's documentation, a hook function hook_menu_block_tree_alter() can be implemented. To start 'somewhere, I tried implementing this in template.php without any success (but doesn't even get called):

function THEME_menu_block_tree_alter(&$tree, &$config) {
  foreach ($tree as $key => &$value) {
    if ($tree[$key]['link']['access'] && !$tree[$key]['link']['hidden']) {
      $items[] = $tree[$key];
    }
  }

  $num_items = count($items);
  foreach ($items as $i => &$data) {
    $class = array();

    if ($data['link']['has_children']) {
      $class[] = 'has-submenu';
    }
    $element['#attributes']['class'] = $class;
  }
}

Any help would be much appreciated as I don't really have deep understanding of how and where to implement this hook function. Also my impression is, that some more detailed documentation is missing for this specific hook function..

Other than the regular clear cache I am not sure why that would not be called. I do not have much experience with that hook. However I am fairly certain theme_menu_link would work here as well. Take a look at the answer here. A test for $vars['element']['#below'] should allow you to accomplish what you want.

Note: If you have a small menu you can always add classes to menu items through the UI.

EDIT: To answer part 1 try something like this (taken from bootstrap_menu_link):

if ($element['#below']) {
  if ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
    // Add our own wrapper.
    unset($element['#below']['#theme_wrappers']);
    $sub_menu = '
' . drupal_render($element['#below']) . '
';
    // Generate as standard dropdown.
    $element['#title'] .= ' ';
    $element['#attributes']['class'][] = 'dropdown';
    $element['#localized_options']['html'] = TRUE;

    // Set dropdown trigger element to # to prevent inadvertant page loading
    // when a submenu link is clicked.
    $element['#localized_options']['attributes']['data-target'] = '#';
    $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
    $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
  }
}


How to link one given Image field to a specific view? I would like to link an Image field to a specific view (created with Views) in a given view mode, under "Manage fields" tab, making this opportunity available only within a given content type and only one specific field.

I could also "hack" it into a given theme_image_... function, but I think it would be nicer to make it easily modifiable via the admin interface like this:

Maybe this could easily be done with a given or a custom module, but I don't know what would be a nice solution to this.

Here is an idea:

On the content type hide the image from the display as you will show it with as an EVA field.
Using Views EVA attach the image to the content type so that the image is visible again, don't forget to check the views arguments to that the right images is shown in the node.
Re-write the image to be display as a link and there you can put the path to the view. Here you can also play with the image formatter as well.


Deleted my secondary_links block; where to find another? How would I re-add a copy of "secondary links" to my Bartik-themed installation?  I seem to have deleted it a year ago when I didn't think I'd want a blogroll, but would like one now.

Just create a new menu and add your new links to that you can call it secondary links if you like. Then add it to a region via the blocks menu or with php through your page.tpl.php


How is $search_results in search-results.tpl.php generated Where is $search_results generated?

I've got an Apache Solr search, and I want to reorganize the content in a certain way, and modifying the theming as well based on certain conditions, but all I have with $search_results is a string with a list.

What I want is to segregate search results based on a value in the object that Apache Solr creates.

About theming results, you should have 2 templates: search-results.tpl.php and search-result.tpl.php (without s).

The first one allows you to theme the list, the second one (without the s) allows you to theme the results individually.

So I would advise you to use a hook to sort/filter the results the way you want (see answers from Clive and arrubiu), but use the templates to define the design you want.


How to add a Google Maps containing GeoRss Feeds on a page - don't know exactly what module to use I have developed a Google maps following the example from https://developers.google.com/maps/documentation/javascript/examples/layer-georss but I am new to Drupal and I don't know how to include it on a page. Could someone please tell me what module should I use?

Some guidance would be very much appreciated!

Try to use GMap module. This module solve your issue.

How to use ?

If your issues not solved then try to use any of these modules :

Simple Google Maps
Google Maps Location

For GeoRSS try to use below module :

GeoRSS
Google Maps Tools


Where to put a script to provide AJAX/JSON response? I'm using drupal 7. I want to create a php script that uses Drupals DB abstraction layer to query the database and spit out JSON data.  Where would I place such a script?  At the moment, I've done it in a round-about way by create a new node, then in the function theme_process_page() of my theme/template.php, I wrote an IF statement to detect the node id, then run my code, then call a die() statement.

Is there a more appropriate place for me to put this script?

** additional notes **
This script is to be called every time a person presses "Provide a menu link" when adding/editing a node in the CMS.  The script will then automatically select the appropriate Parent Item and weight based on any other existing translation.

The easiest is to use Views datasources if it can solve your problem, in essence this means that if you can use views to display the data you need, you can use this module to return it as JSON.

Another option is to write a custom module and use hook_menu to define a 'menu' item which you can use from the calling code. To return your data as JSON you can use the standard php functions.

If you need multiple scripts and advanced configuration you can always have a look at Services or


How to add new tab in user edit page drupal How can i add a new tab in user edit page. In user view page it is coming , but user edit page is not giving any result.

function usermail_menu() {
$items = array();
$items['user/%/invoice'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Subscription Invoice',
    'page callback' => 'usermail_invoice',
    'access callback' => 'user_is_logged_in',
    'weight' => 3
);
return $items;
}

This is working correctly. For user edit page i changed the path as

function usermail_menu() {
$items = array();
$items['user/%/edit/invoice'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Subscription Invoice',
    'page callback' => 'usermail_invoice',
    'access callback' => 'user_is_logged_in',
    'weight' => 3
);
return $items;
}

But it is not coming. Please help me. Do i want to add something else?

You just need one item only. Please make the following change

$items['user/%user/invoice'] = array(
    'type' => MENU_LOCAL_TASK,
    'title' => 'Subscription Invoice',
    'page arguments' => array('user', 1),
    'page callback' => 'usermail_invoice',
    'access callback' => 'user_is_logged_in',
    'weight' => 3
);


How to test Mollom - want to test mollom_form_moderation? I have a custom form that I'm protecting with Mollom. Once validated, the form results in an entity being created and some emails being sent.

If the form is valid, but Mollom says it should be moderated, I need the entity to be created with its "Held in moderation" field set, but no emails to be sent (I'll do this once an admin has said it's OK).

I have Mollom working and testing mode enabled. Putting "ham" in works. Putting "spam" in stops it dead. Putting "unsure" with an incorrect captcha stops it dead and putting "unsure" with a correct captcha allows it through.

I'm trying to find a test to make Mollom say "hold this in moderation" and call the moderation callback that I have set in hook_mollom_form_info(). None of the test cases above result in this callback being called.

You need to enable testing mode and configure the form protected by Mollom to Retain spam posts manual moderation, e.g. in the below screenshot you see I had it wrong.

Then submit the form with "spam" in the main field and it will call your moderation function.


Drupal SOLR search for attachments Is there a way to search for files attached to taxonomy terms ?

I mean I have a vocabulary, with some terms. Each term have some files attached (Field) (Ex: example.pdf, Image.png).

I want my search to show that files, for example::

Search result:

--- Example.pdf

--- Image.png

Is that possible ? I don't want to search file contents, I just need filenames and path's shown on the search page.

Thanks and sorry for my english.

You can index taxonomy terms with this module:
https://drupal.org/project/apachesolr_term

There is a hook that allows you to specify a custom field for the solr index:
hook_apachesolr_index_document_build_' . [entity type]

Then you can add this field to the solr query by using:
hook_apachesolr_query_prepare

There is a more detailed article on how to do this here:
http://rapiddg.com/blog/adding-customized-fields-apache-solr-index-drupal


Entity query to select current dates The situation: I have a drupal 7 node which has a date field. This uses the date module and it has multiple values each with a start and end date.

The problem is that I want to query drupal for all nodes where the current date is between the start and end dates of a single delta.

The entity query I have at the moment doesn't check the same value for both start and end dates.

For example if the first date value started 1/1/2013 and ended 30/1/2013 and if there was a second value which started 1/12/2013 and ended 30/12/2013. Using the current date of today 11/10/2013 this node should NOT be fetched. However under the query below it is because there is a start date in the past and an end date in the future, even though they're not from the same field delta.

  $current_date = date("Y-m-d");

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=')
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=');
    ->execute();

Having actually read the fieldCondition documentation the fourth property turns out to be $delta_group which allows specifying dependent conditions. So it turns out all I needed was the below:

$current_date = date("Y-m-d H:i:s");
$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', RD_PRIZE_DRAW_NODE_TYPE);
    ->fieldCondition('field_rd_prize_draw_dates', 'value', $current_date, '<=', 1)
    ->fieldCondition('field_rd_prize_draw_dates', 'value2', $current_date, '>=', 1);
    ->execute();


Trying to render an array of items with the drupal_add_html_head function I have a preprocess_html function that gets an array of google fonts and adds them as an html class. I have it partially working but if say I have three fonts, only the last one gets into <html class=""> element. Here is what I have so far:

if ($families) {
   foreach ($families as $fontString) {
   $fontclass = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));

   $element = array(
     '#tag' => 'html',
     '#attributes' => array(
     'class' => $fontclass,
    ),
   );
   drupal_add_html_head($element, 'google_fonts');
  }
}

In the example above, I have these fonts in my site:

Montserrat
Actor
Pathway Gothic One

... but only the last one renders in my html class as:

<html class="pathway-gothic-one-regular">

If I do a dsm within my function:

dsm(drupal_get_html_head());

I see all three fonts print out in separate boxes as

<html class="actor-regular" />
<html class="montserrat-regular" />
<html class="pathway-gothic-one-regular" />

so I think I am not getting something right here.

Note, if I change my code to a body class array, it works as expected. e.g.

   if ($families) {
          foreach ($families as $fontString) {
            $vars['classes_array'][] = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));
          }
        }

yields:

<body class="actor-regular montserrat-regular pathway-gothic-one-regular">

From a build standpoint, I'd like to keep these classes one level higher than body so that's why I'd like them to be in <html class="">.

if ($families) {
    $element = array(
        '#tag' => 'html',
    );
    foreach ($families as $fontString) {
        $fontclass = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));
        $element['#attributes'][class'][] = $fontclass;
    }
    drupal_add_html_head($element, 'google_fonts');
}


Alter the exposed filter value on change of other exposed filter value I wanted to do an interdependent select boxes using views exposed filters. So when i select the 1st exposed filter, the second once should filter itself based on first exposed filter value and this should happen dynamically. I tried a lot with form_alter but did not work. Any example or any suggestion as to how to go about it.

The easiest way of solving this, would be to use JavaScript. You need to have all the options available, and with JavaScript you can alter the options based on what's selected. Something like this:

$("#field-1").change(function(){
  if ($(this).val() == 'option_1') {
    var options = '<option value="foo">bar</option>';
    $("#field-2).html(options);
  }
});

The above is merely example code but illustrates the approach. You might need to do some work, in order to get the different options that should be available.


Image shows on home page but not other pages I've added an image to a block that shows on every page and have the image added manually in the block like so:

<img src="sites/default/files/image-name" />

It shows fine on the home page as intended, but on the interior pages it doesn't show. I inspected element and for most pages it's using the same URL to try and access it.

I cleared cache.

Thoughts on why this might be?

right now its appending after the url of whatever page you are on.

yourwebsite.com/hello/sites/default/files/image-name
yourwebsite.com/article/sites/default/files/image-name
yourwebsite.com/contact-us/sites/default/files/image-name

instead of appending after your domain name.

yourwebsite.com/sites/default/files/image-name

so you just need to add a / at the beginning, so it appends after your domain name only.

so your code needs to be:


No result from an SQL query I have a view with a custom PHP field containing the following code.

$storeArray = array();
$result = db_query("SELECT nid FROM node WHERE type ='emp'");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row[nid];
}

if ($storeArray) {
  echo 'not empty';
}

The query doesn't return anything. Why?

You're mixing a couple of different things there :)

The resource returned from db_query() can be iterated over directly, there's no need for an intermediary function. The resource isn't the same as one that would be returned from mysql_query(), as the Drupal database layer wraps around PDO.

This is the standard way to iterate over db_query() results:

$result = db_query("SELECT nid FROM node WHERE type ='emp'");

$storeArray = array();
foreach ($result as $row) { // An object is returned by default
  $storeArray[] = $row->nid;
}

However, the db layer also has a handy shortcut method called fetchCol() that will fetch the results of the query's first column into an array. So you can simplify your code to a single line:

$storeArray = db_query("SELECT nid FROM node WHERE type ='emp'")->fetchCol();


Drupal gives error while add content or edit node Hi all i am facing this error when try to edit node or add content

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] =&gt; 1 [:db_insert_placeholder_1] =&gt; node [:db_insert_placeholder_2] =&gt; %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] =&gt; a:6:{s:5:&quot;%type&quot;;s:12:&quot;PDOException&quot;;s:8:&quot;!message&quot;;s:238:&quot;SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {variable} variable WHERE ( (name = :db_condition_placeholder_0) ); Array ( [:db_condition_placeholder_0] =&amp;gt; drupal_http_request_fails ) &quot;;s:9:&quot;%function&quot;;s:14:&quot;variable_set()&quot;;s:5:&quot;%file&quot;;s:74:&quot;/home/apetrdo6/public_html/Development/InfinityPups/includes/bootstrap.inc&quot;;s:5:&quot;%line&quot;;i:991;s:14:&quot;severity_level&quot;;i:3;} [:db_insert_placeholder_4] =&gt; 3 [:db_insert_placeholder_5] =&gt; [:db_insert_placeholder_6] =&gt; http://apetrailportfolio.com/Development/InfinityPups/node/add/dogs [:db_insert_placeholder_7] =&gt; http://apetrailportfolio.com/Development/InfinityPups/node/add/dogs [:db_insert_placeholder_8] =&gt; 103.63.25.150 [:db_insert_placeholder_9] =&gt; 1473159652 ) in dblog_watchdog() (line 160 of /home/apetrdo6/public_html/Development/InfinityPups/modules/dblog/dblog.module).

Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {variable} variable WHERE ( (name = :db_condition_placeholder_0) ); Array ( [:db_condition_placeholder_0] =&gt; drupal_css_cache_files ) in variable_set() (line 991 of /home/apetrdo6/public_html/Development/InfinityPups/includes/bootstrap.inc).

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {users} SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] =&gt; 1473159609 [:db_condition_placeholder_0] =&gt; 1 ) in _drupal_session_write() (line 219 of /home/apetrdo6/public_html/Development/InfinityPups/includes/session.inc).

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] =&gt; 80080962057cea1b962fce6.76953018 ) in lock_release_all() (line 269 of /home/apetrdo6/public_html/Development/InfinityPups/includes/lock.inc).

One possibility to solve is to increase "max_allowed_packet" .

    Go to xampp\mysql\bin
    Open my.ini
    Change "max_allowed_packet" from "1m" to "16m"
    Save my.ini
    Now restart MySql through the XAMPP control panel.

Or

settings.php

ini_set('max_allowed_packet', '1024M');


Setting entity reference field value in Drupal 8 programatically I have this following code that creates a node in the page.

$data = array(
  'type' => 'post',
  'field_post' => [
      'value' => 'test',
      'format' => 'basic_html',
    ],
  'field_visibility' => 1,
  'user_id' => $uid
);
$node = Drupal::entityManager()
  ->getStorage('post')
  ->create($data);
$node->save();

I have another field field_pattern that is an entity reference for another content type. How can I properly set it inside my code?

Since with creating the content from the site when dealing with Entity reference field selects autocomplete to Title, then I tried to test this but fails. Meaning no value is set to entity reference.

$title = $entity->label();
$data = array(
  'type' => 'post',
  'field_post' => [
      'value' => 'test',
      'format' => 'basic_html',
    ],
  'field_pattern' => $title, // this is the entity reference field
  'field_visibility' => 1,
  'user_id' => $uid
);
$node = Drupal::entityManager()
  ->getStorage('post')
  ->create($data);
$node->save();

If you are creating a node with reference field, see below code:

 use \Drupal\node\Entity\Node;
 $node = Node::create([
   'type' => 'post',
   'field_post' => [
     'value' => 'test',
     'format' => 'basic_html',
   ],
   'field_pattern' => [
      'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
   ],
   'field_visibility' => 1,
   'user_id' => $uid
 ]);
 $node->save();

If you are are not creating node then just replace your field_pattern like below:

'field_pattern' => [
   'target_id' => $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
],


Need a textfield required only when selectlist is set to 'Approved' within custom content type This seems like it should be simple, but has been challenging me for a few days now. I have a custom content type which contains a selectlist which defaults to 'Pending' for new nodes. Someone will later come along and set these to 'Approved' and when they do so I need a text field to be available and required prior to saving the node again.

I have tried the available modules 'Conditional Fields' and 'Field Conditional States' but they do not seem to work to make fields actually required. I assume this is because the JavaScript Form state has no effect on server-side logic and validation.

If I was coding this outside of Drupal 7 I would probably make the textfield disabled, required, and give it a default value. Then use an .onchange to check if it is set to “Approved” and, if so, enable it and empty the default value but I am not sure how to implement this with Drupal yet.

I didn't find anything else in the way of modules that seemed to work, so I have now begun looking at the function 'drupal_process_states'. This seems like it might be the right path, but is going to take me a while to figure out.

Any help is appreciated. Thanks!

Field Conditional States will help you modify the look of the field: it will make it appear or disappear, or will add the red asterisks to make it look required. But as you noticed, making it look required is not the same thing as making it required. What I have done is using a combination of Field Conditional States to change the look of the field, AND Field Validation to actually make it required (so that the form returns the "Field required" error message when submitted). Field Validation has a way to return the error by checking that the field is not empty, AND checking if a different field in the form has a particular value. You need the "PHP code" type of validation for this. Take a look at the documentation for this module's PHP code option.


Drush missing the "provision" and "Hostmaster" commands One of our boxes is missing these Aegir-Drush commands (from drush help):

All commands in provision: (provision)
 backend-parse         Parse the output of --backend commands to a human readable form
 hostmaster-install    Install and verify the Hostmaster frontend.
 hostmaster-migrate    Migrate an instance of the Hostmaster front end to a new platform
 provision-backup      Generate a back up for the site.
 provision-backup_del  Delete a backup file.
 ete
 provision-clone       Clone a site between platforms.
 provision-delete      Delete a site.
 provision-deploy      Deploy an existing backup to a new url.
 provision-disable     Disable a site.
 provision-enable      Enable a disabled site.
 provision-import      Turn an already running site into a provisioned site.
 provision-install     Provision a new site using the provided data.
 provision-lock        Lock a platform from having any other sites provisioned on it.
 provision-login_rese  Generate a one-time login reset URL.
 t
 provision-migrate     Migrate a site between platforms.
 provision-restore     Restore the site to a previous backup. This will also generate a backup of the site as it was.
 provision-save        Save Drush alias
 provision-unlock      Unlock a platform so that sites can be provisioned on it.
 provision-verify      Verify that the provisioning framework is correctly installed.

We're able to log into Aegir via the web interface, but none of the commands work. The best we could tell, the install went fine. I think it might be related to these commands missing from our server.

How do I get these commands back? We were able to verify the Hostmaster platform with no problem.

Have had similar issues with this in the past,

How many instances of drush is there on your server? In my case I had a drush 3.3 version in /usr/share/drush and the aegir 4.4 version (with provision and hostmaster commands) in /var/aegir/.drush

In order to get drush to work, I had to alter the path for the aegir user to include /var/aegir/.drush first

You can always tell which version of drush you are using by running the command

which drush


Pass nid as argument to embedded view I am using twig tweak to embed a view in node.tpl.twig

{{ drupal_view('testview', 'block_1', '12') }}

how can I pass current nid {{ node.id() }} as argument instead of static '12' in this case?

Oh - it is quite simple :)

{{ drupal_view('testview', 'block_1', node.id() ) }}

sorry still learning basics :D


Resetting a configuration object to "factory settings" My module defines a configuration entity (specifically a BBCode tag macro with a template) that can be created and edited with a web form.

It can also be created by other modules using a config/install/xbbcode.tag.*.yml file - and of course those objects can also be edited and deleted.

Is there a way to access and recreate the original version of a config object that has been edited, without having to reinstall the whole module? I like the flexibility of customizing these templates, but users need to be able to  restore the factory settings somehow.

Core does not provide such an API, not in a way that is easy to use.

There is a contrib module that provides this, but it's probably too complicated to rely on for a specific use case.


Disable translations update on module enable I have large site with 15 languages, when working locally If I enable some module over UI (or reinstall it) auto update of translations kicks off and this last for some time. I really don't need that while developing things, how could I disable this feature?

I was able to disable update by:

<?php

/**
 * Implements hook_module_implements_alter().
 */
function MY_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'modules_installed') {
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler->moduleExists('locale')) {
      unset($implementations['locale']);
    }
  }
}

/**
 * Implements hook_modules_installed().
 */
function MY_MODULE_modules_installed() {
  $moduleHandler = \Drupal::service('module_handler');
  if ($moduleHandler->moduleExists('locale')) {
    locale_system_set_config_langcodes();
  }
}


Merging duplicated nodes, and their fields I am looking for a coded way of merging two nodes (of same type), with user interaction ("guided merge").

In my case,I made a simple contact manager. It imports (Feeds csv import) from, and exports (node export to CSV) to various sources, e.g. some social networks contact lists, webmail and thunderbird files. I want to manage the people data from there exclusively.

I use in first place a content type "person" with mostly simple text fields (e.g. name, email, phone, city).
As you might have encounterd, frequently there will be duplicate nodes, but one of them most of the time holds the more accurate info about the person.

So I am in need of a tool to:

Let me checkbox-click two nodes (from the generic view)
Show both nodes side by side
Let me choose one as master
Click "Go" to start the merging:

Merge automatically all new fields from secondary node into master
For fields with values in both nodes, show them both
Let me click, which one should be used and provide an prefilled form to edit the value
Submit the field value, then show the next field
Continue until the node is done
Save the updated master node, and delete the second node

My research until now has not shown results (discussions, modules) in that direction.

Do you have any hint on what to search for? Should I start a new module?

I have never heard of such functionality.

The first idea that comes to mind: Ctools has contexts for both Node view and Node edit. One could use such contexts to display two nodes side by side on a page, in either view or edit mode. With some custom form logic for picking, "left", "right" etc, on top; one could get very far in this.

Ctools also provides other niceties such as an object cache and a modal framework that could potentially be useful for developing this.


how to open custom form in popup onclick in menu link drupal I made a custom form in drupal. I just want to open that form on popup form when user click on menu.

Here is my code

function acoma_extra_divide_element_horizontaly($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('At which height should the element be divided? (distance
    from cupboard floor)'),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Divide draw up horizontally'),
    '#suffix' => 'cm',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'OK',
  );

  return $form;
}

Menu code is:

Divide element horizontally

Divide element vertically

Reset element

I just want when use click on menu this form loads in popup. I used the popup module.

Any help would be appreciated.

There are many ways to do this.
You can use  Popup forms module. Its configuration is in documentation of module
or Modal Frame API module.


Rewrite Results -> Output as Link: How do I get this to work? Ok, so I have a table in my database that I am outputting by using a combination of the data module to bring in a table from my database and the views module so it can be displayed.  The page with the view can be seen at http://apollo.tbc.iit.edu/~spaceweather/?q=distribute-data.

I want to enable the column fileSymlink to output as a link.

Below is an example of what the table looks like.

In order to try to enable the links in the last column:

Go to edit view
Click on the column in the fields section that corresponds to that column (i.e., fileSymlink)
Open the drop down "Rewrite Results"
Check to enable "Output this field as a link"

There is then a text form I need to fill out and I'm unsure what to put there. The text in the column is the link. For example if someone clicked on the text in the column DownloadData/cases/grid108/297/txt/channel_dataout_2013_297_0100.log, it would take them to
apollo.tbc.iit.edu/~spaceweather/DownloadData/cases/grid108/297/txt/channel_dataout_2013_297_0100.log.

Am I doing this correctly, or should I be actually storing the HTML in the columns and having views render HTML instead?

I'm not set on one way of doing this, if there is any better way. Any suggestion is very appreciated.

Don't the instructions for the link field tell you that you can use tokens in the URL?  I do not have a view with a text field handy, but here is a screenshot from a view where I make a custom link for the title field:

Scroll down to the Replacement Tokens and expand that field.  One of the options should be something like [field_fileSymLink].  Then you should be able to use something like http://apollo.tbc.iit.edu/~spaceweather/[field_fileSymLink] or maybe just /[field_fileSymLink].


Multiple node access rules for same node? I'm using the Domain Access module to restrict content to specific domains. It uses the node_access table to do this.

I also want to make a single node hidden behind a login area. The problem is that when I add my node access rules to do this it overwrites all the Domain Access rules which mean that all the nodes appear on the same domain.

Is there a way to allow more than one module to use node access rules?

My node access code looks like this:

define('MYSITE_REALM', 'press');
define('MYSITE_GRANT_ID_PUBLIC', 0);
define('MYSITE_GRANT_ID_PRESS', 1);
define('MYSITE_PRESS_SECTION_NID', 554);
define('MYSITE_PRESS_USER', 'press');

/**
 * Implements hook_node_grants().
 */
function mysite_node_grants($account, $op) {
  if ($op == 'view') {
    $grants = array();

    if ($account->name == MYSITE_PRESS_USER) {
      $grants[MYSITE_REALM] = array(
        MYSITE_GRANT_ID_PUBLIC,
        MYSITE_GRANT_ID_PRESS,
      );
    }
        else {

      // everyone else
      $grants[MYSITE_REALM] = array(
        MYSITE_GRANT_ID_PUBLIC,
      );
    }

    return $grants;
  }
}

/**
 * Implements hook_access_records().
 */
function mysite_node_access_records($node) {
  $grants[] = array();

  if ($node->nid == MYSITE_PRESS_SECTION_NID) {
    $grants[] = array(
      'realm' => MYSITE_REALM,
      'gid' => MYSITE_GRANT_ID_PRESS,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  }
    else {
    // everything else is public
    $grants[] = array(
        'realm' => MYSITE_REALM,
      'gid' => MYSITE_GRANT_ID_PUBLIC,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 1,
    );
  }

  return $grants;
}

function mysite_user_login(&$edit, $account) {
  if ($account->name == MYSITE_PRESS_USER) {
    drupal_goto('node/' . MYSITE_PRESS_SECTION_NID);
  }
    else {
    drupal_goto('');
  }
}

Is there a way to allow more than one module to use node access rules?

The problem with hook_node_access_records() and hook_node_grants() is that, independently from the weight of the modules, once a module returns 1 for "grant_view," "grant_update," or "grant_delete" that permission is allowed to the user. If a module returns 1 for one of those operations, and another module returns 0, the access is allowed, independently from the priority given to the records returned from the modules for those records.

In Drupal 7 it is also possible to use hook_node_access(), which is able to report if the user has access or not to the node, or if the hook implementation let other implementations  decide if the user has access to the node (using the value NODE_ACCESS_IGNORE).

In Node access rights it is explained how the node access is checked.

  In determining access rights for a node, node_access() first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. User 1 will always pass this check.

  Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly deny, or ignore the access request. If at least one module says to deny the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted.

  If all modules ignore the access request, then the node_access table is used to determine access. All node access modules are queried using hook_node_grants() to assemble a list of "grant IDs" for the user. This list is compared against the table. If any row contains the node ID in question (or 0, which stands for "all nodes"), one of the grant IDs returned, and a value of TRUE for the operation in question, then access is granted. Note that this table is a list of grants; any matching row is sufficient to grant access to the node.


Cannot use object of type Profile as array Write a script to filter content by country.

  I have problem Cannot use object of type Profile as array in .... on line 19

Part of code with error

global $user;
$country = "";
if($user->uid!=1 && $user->uid!=0){
  $user_full = profile2_by_uid_load($user->uid);
  if(!empty($user_full['client'])){
    $country_parent = taxonomy_get_parents($user_full['client']->field_clcountry['und'][0]['tid']);

This

$user_full = profile2_by_uid_load($user->uid);

Returns an object, which you are then accessing as an array:

$user_full['client']

Which is illegal in PHP. You should access objects as objects, e.g.

$user_full->client

Or whatever it might be for that object type.


How to know that the node of a specific type is being viewed for the first time? I want to display a block on the node page if it is being viewed for the first time. After that that block will not be displaying.

It will be for all the nodes of a given content type.

I know the Drupal put the node in the cache if it is being viewed for the first time but I can't found its code.

Is it possible? Any Ideas?

Used the core statistics module.

and then on node view used the function statistics_get() function and then check it the total count is less than 1.


is there a way to hide a "custom field" in edit mode Drupal 8? I have a form with 5 custom fields. I would like to hide a couple of fields based on the view mode in the back-end while the user is editing the form.  Right now you can easily hide the field in the front end, but i am looking for way to not confuse the editors and hide the form fields while they are making changes.
Disable fields still show up in the back-end.

My goal is simple: if your view mode has the field disable it should not show up in the back-end and in the front end.

is there a setting or a hook that can allow me to accomplish that.

Making this based if it's printed on a view mode, makes things quite complex. You'll have to write a custom module.

Try using the Fields Permissions which is based on Roles. So just check mark the Roles that should be able to see the field in the front.


30+ small modules versus 5 large modules versus 1 HUGE module: Which is better? So, we have a large, complex Drupal 6 site, which has lots of secret sauce and magic glue making it work.

Where we can, we've contributed modules back and made them generic, but we still have 30 or so custom modules to keep it working the way we need it to. Each module (in most cases) has a specific function e.g. our hook alters for the notification system.

We are doing a huge code review at the moment and looking at improvements we can make. One thing suggested is to merge the large number of modules into a few smaller master modules, with lots of include files. We would, perhaps group by general site area e.g. "community", "admin" and "messaging", instead of specific modules per functionality.

Is the effort in doing this worth it? Will it speed up the site?
What module grouping would you recommend?

by site area ("community", "admin", "upload")
by hook ("form", "node", "user", "theme")
everything in one module
something else?

What naming conventions should we use for the include files to keep the codebase sane?
Am i right in assuming the goal should be tiny .module file with includes per hook / menu / area?

It sounds like you don't really know what your bottleneck is. This restructuring will likely have very little impact on performance (unless you happen to find and trim some major bloat in the process), but it may make things easier for you to maintain. If you do decide to restructure I would recommend splitting up along "site features" (blog, image galleries, etc.).

But if performance is your concern you first have to diagnose the problem before you attempt surgery.