LogicException: The database connection is not serializable - when I try to open any "gear" on checkout flow page? So I'm on Commerce -> Configuration -> Orders -> Checkout flows. I'm editing a flow (it's the same with any of them), so i.e. I'm at page:
/admin/commerce/config/checkout-flows/manage/shipping

and for some items (i.e. "Login or continue as guest", "Contact information"...) with the option I also have gear icon on right for opening some settings block.
Until recently that worked well, but now, when I click gear icon spinner appears for short time and nothing happens.
In error log I see message:

LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect
reference to the database connection. Adjust your code so that is not
necessary. Alternatively, look at DependencySerializationTrait as a
temporary solution. in Drupal\Core\Database\Connection->__sleep()
(line 1573 of
/var/www/html/drupal/web/core/lib/Drupal/Core/Database/Connection.php).

From browser network tab I can see that url:
http://sitename.test/admin/commerce/config/checkout-flows/manage/shipping?destination=/admin/commerce/config/checkout-flows&ajax_form=1&_wrapper_format=drupal_ajax
is called and response was:
500 Service unavailable (with message)
Any idea what could cause this error and how to solve it?

I experienced the same problem. It's not a commerce issue, and there is no general rule which module causes the problem.
The problem probably occurs, because one of your checkout panes depend on a service, which has an indirect dependency to Drupals database connection -- Drupals database connection is not serializable and this causes the error.
It's not that easy to debug, because the form is soooo big, and loads all the CheckoutPane Plugin Forms. The good news: I figured out a way to debug the issue:
First of all, we need to determine the problematic checkout pane. To do that, we loop over all panes and try to serialize them independently.
Temporary add the following snippet to the Drupal\Core\Form\FormState::getCacheableArray()
if(!empty($this->getStorage()['panes'])) {
  // loop over all panes and try to serialize each independently,
  // catch possible serialization errors and dump the problematic pane.
  foreach($this->getStorage()['panes'] as $key => $pane) {
    try {
      serialize($pane);
    } catch(\Throwable $throwable) {
      // dump pane, which causes the error and die
      dd($pane);
    }
  }
}

FYI: The dd() output does not look very pretty in chrome's network tab (all the properties are expanded). I copied the request as CURL Request (in chrome: right click on the XHR Request --> copy as CURL) and pasted it into Insomnia (my Rest Client).  When executing the Request there, the dd() is displayed as usual with the possibility to expand and collapse the properties. That makes it much easier to find the problematic service..
There should be a dumped object, which is the non-serializable checkout pane. If thats not the case, you have a completely different problem than me and you can skip this answer.
But if there is a dump of the pane, you can now have a detailed look at the properties of the pane. It is necessary, that the properties which are services have a _serviceId property; if this property is missing, the Pane's DependencySerializationTrait isn't recognizing the Service as a Service.
Unfortunately, there can be Services, which haven't the _serviceId property. In my case, a contrib module (mail_login) provided a decoration service, which decorated the service user.auth. The service user.auth is injected as dependency to the Login-pane (and I think another one too).
This decorated service, had no _serviceId property, so Drupal tried to serialize the the user.auth Service.
The problem is now, that the user.auth service has a dependency to Drupals database connection, but no DependencySerializationTrait
--> Drupal tries to serialize the Database connection and throws the error.
To solve the issue, I created my own decorator service class within a custom module, which extends the original decorator class from mail_login (because i need the logic from the mail_login decorator). I just added the DepenencySerializationTrait to my own decorator and replaced the service class for the decorator service in my modules service provider (in my case, the decorator service is called "mail_login.auth").
I'll share my code too.. (I modified it for the post, so there may be errors. But you can use the snippets for better understanding)
My decorator only uses DependencySerializationTrait:
<?php

namespace Drupal\my_module;

use use Drupal\mail_login\AuthDecorator as MailLoginAuthDecorator;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;

class AuthDecoratorDependencyFix extends MailLoginAuthDecorator
{
  use DependencySerializationTrait;
}

My Serviceprovider just replaces the original service class:
<?php

namespace Drupal\my_module

use Drupal\Core\DependencyInjection\ContainerBuilder\ContainerBuilder;
use Drupal\my_module\AuthDecoratorDependencyFix;

class MyModuleServiceProvider
{

  public function alter(ContainerBuilder $container) {
    if($container->hasDefinition('mail_login.auth')) {
      $mailLoginAuth = $container->getDefinition('mail_login.auth');
      $mailLoginAuth->setClass(AuthDecoratorDependencyFix::class);
    }
  }
}

I'll create an issue for the mail_login module (maybe on Monday ;)).
Please let us know, if it's another service, or a completely different error on your side.


How do I change the machine name of a field once it's been created I spaced out while typing the field name an now the machine name is not what I wanted it to be. I know it's just an annoyance. but I'm wondering if there is some way to alter the machine name of a field once it is created.

I suppose this leads me into the second part of my question. if I created a field, and it is no longer being used, how do I go about deleting it, does this have to be done from the database, or can it be done somewhere in the UI.

My procedure is to use drush to clone the field first, then copy the field data with DB queries into the new field table. After I verify the contents of the cloned field, I delete the original field.

I do it this ways because I think the drush method of cloning fields will always be at least as reliable as any cloning code I might craft myself, the data copy query is pretty simple, and I get to check the new field before deleting the original.

drush field-clone field_my_field field_my_field_clone
Insert rows into field_my_field_clone, e.g., INSERT field_my_field_clone SELECT * FROM field_my_field;
Verify the contents of field_my_field_clone.
Delete the field using the UI, e.g., admin/structure/types/manage/my-content-type/fields


Search module in drupal 7 I am using drupal 7 built in search module, when I searched for example mechanics it will filter out the results successfully but when I used to write only mech or mechan something like this, it displays no results.

For this I have installed Apache Solr Autocomplete and Porter-Stemmer but I unable to figure out how can I improve my search filtration.

Look at the module  Fuzzy Search , this may solve your problem.

  This module provides drupal sites with a fuzzy search engine to allow
  for broader keyword matches including partial or misspelled keywords.

  Fuzzy matching is implemented by using ngrams. Each word in a node is
  split into 3 (default) letter lengths, so 'apple' gets indexed with 3
  smaller strings 'app', 'ppl', 'ple'. The effect of this is that as
  long as your search matches X percentage (administerable in the admin
  settings) of the word the node will be pulled up in the results.


Show certain slides only on specific urls on views slideshow Using views slideshow I want to be able to control what nodes of content type "slides" show depending on what URL, any ideas?  for example on page-front I would like to show slide1 and slide2, on node/43 I would like to show slide3 and slide4.

Having separate views is not an option because this is a slider that is on hundreds of pages and different content types.

Would you be better off having two separate views for the two URLs? If you do need this done in a single view, you will need to write custom module that adds filters to the view. Try using contrib module called views_arg_context


Can't delete content type that I created? I am running a Drupal 6 installation and created 2 content types through the admin menu (they are not programically created). Now I want to delete them but no delete link is visible in the content type screen. I do not have any pages created with those types so I don't understand why Drupal won't let me delete them.

I have searched this site and Google but I can't find an answer. Anyone here have any ideas how to get rid of them?

Thanks

Ensure you are user/1 and try navigating to this page

/admin/structure/types/manage/<content-type-name>/delete

replace <content-type-name> with the actual name of the content type


Modular Drupal content-type (variable sections) I'm trying to build a modular and quite dynamic backend. I'm using Drupal for the task but haven't been able to spin my head around how to make it happen.

I need ideas on how I might solve this rather complex task.

To explain what I would like to end up with, I've faked a screenshot showing in steps what I would like the end result to look like.

Step 1

Step 2

My client wants to display his different cases. To make each case different, he wants a system where he can pick and choose how parts of his content is displayed. I suggested a modular approach where he can choose a "module type" in a dropdown, and fill in the needed fields.

There are plenty more, but for the sake of this questions, lets just stick with those.

Needs:

Possible amount of modules should be infinite.
Possible to fill in all information on the different 'modules' on the 'case' page.

Do you have any idea on how this might be solved?

You can do this with the Field Collection module.

Add a field collection to your Case node and then add then add fields of the types you require to the field collection restricted to the amount of images or videos you want to display. An with the correct image styles assigned.

You could use the Field Group module to collapse the fields to improve the admin interface.

Edit:

Another option would be use Conditional fields module and add image fields to the case content type set the the amount of images to be displayed in each and the image style required. Then add a list field to the case content type with option on 1 image, 2 images, 3 images etc and then use Conditional fields to link this to display and hide the image fields.


Cannot login after moving site I am in the process of recovering from a catastrophic hard disk failure on a completely new machine. I am fortunate to have both a database backup and a backup of the folder with the D7 code that was running on the original machine.

After restoring everything to the original state the site at first appeared to be running well. All nodes that I clicked on worked perfectly and showed the data I expected. The problems began when I tried to login. It looks as if submitting any form whatsoever (including the login form) does not have any effect. I couldn't even login until I generated a one time login link with drush uli. Using that link I was at last able to login with the admin user, but whenever I try to change something in the admin area I simply can't do it - the page is reloaded after I submit the form and my changes disappear. There are no error messages 1) in the web UI, 2) in the Apache log files, or 3) in the watchdog database table.

Things that I tried without any effect:

Clean the cache tables. All of them, both with drush and with phpMyAdmin
Set up a completely new site using the same codebase (Drupal 7.14). The new site works perfectly, after the setup I can login and create content without problems. The original site still doesn't work. This shows me that neither the Drupal code I am using is the problem, nor the Apache setup (the vhost for the new site is practically identical to the vhost for the problematic site).
Upgrade to Drupal 7.44
Disable all modules (only disable, not uninstall)
Enable tracing using the xdebug PHP module, but the result gave me information overload. I'm no PHP hacker.

I am now pretty desperate. I must overlook something essential, but for the life of me I can't find what it is. I am aware that this is all pretty vague, but I hope that someone with more experience than me can offer me a hint what I am doing wrong.

Info on my environment

Server

Debian jessie
Apache 2.4.10-10+deb8
php5 5.6.20+dfsg-0+deb8u1
MySQL 5.5.49-0+deb8u1

Client

Mac OS X 10.11.4
Firefox 46.0.1 and Safari 9.1 on Mac

Configuration

Drupal 7.14 and 7.44
SSL-enabled vhost

In your new machine you probably installed Apache and did not enable a2enmod rewrite

To enable it, copy and paste the following line to your command line:

sudo a2enmod rewrite && sudo service apache2 restart

Another way to enable it (in case you're on Windows), you could edit /apache/conf/httpd.conf and uncomment (remove the #) from #LoadModule rewrite_module modules/mod_rewrite.so line and restart Apache.


Permission Issues for User 1 I have added pages, webform, and views to my site to customize the User profile experience. I can access mysite.org/user and it shows my user profile page as customized. I have a link on that page to Edit the user profile which is formatted as mysite.org/user/1/edit this works fine. I also have realname module installed so the Edit button on the User profile tabs has the url mysite.org/user/my-real-name/edit This link does not work. It gives an access denied when used even from the User 1 account. I have researched this over and over and over. I can't find the cause or the fix. Any ideas?

I've checked permissions, I've gone through the panel page, the view. I've disabled things and tried it and still issues. I'm at a total loss on what to do.

I don't think Real Name does what you think it does.  At least not by default.  The module is primarily for using parts of the user account other than the username when the user account is displayed (such as the by-line on an article).

You can set the edit link to send people to mysite.org/user/my-real-name/edit but unless you've done something to make that URL exist, which I'm not sure you can do with this module, it won't do anything.


User click on log in when user already logged in so should throw message. I am write some code for user login. But i want when user click on log in button every ,that time checks user already logged in or not . if user logged then throw the informative message and if not throws error. How i do this.. Please help me..

You can check value of field uid of global variable $user:

global $user;
Contains preferences and other account information for logged-in users. When a user is not logged-in, the $user->uid property is set to 0.

http://api.drupal.org/api/drupal/developer!globals.php/global/user


Define ckeditor add media library location we're currently using ckeditor successfully, but when i go to add media from the library tab it loads up all media, we want to exclude profile images from this, is it possible to define the ckeditor library path, or would we really want to move the profile images to private directory

You could use the Views Media Browser module

  This module adds a Views based Media browser to the site that allows filtering files based on fields attached to the various file types.


How to change the title of submit button when someone register in mailchimp? I want to be able to change the title of the submit button of the Mailchimp block when someone subscribes or unsubscribes to mail chimp list. I'm using mailchimp block on D7.
How shall I do it?

As mentioned, you'll want to use hook_form_alter(). You can check if the user has subscribed with mailchimp_is_subscribed() and change the submit button text accordingly.

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mailchimp_lists_user_subscribe_form_test') {
    global $user;
    // First parameter is the list id, which can be found here:
    // https://polkaspots.zendesk.com/hc/en-us/articles/201070513-Where-can-I-find-my-MailChimp-API-key-and-List-ID
    $form['submit']['#value'] = mailchimp_is_subscribed('123abc', $user->mail) ? t('Unregister') : t('Register');
  }
}


How to on Multisite manage users over 1 site My client need 13 Pages with different domains, so we decided to make different DBs with same codebase. Now, he want to manage the users (admin, editors) over 1 site, so he can select which user has access to which site.

We tested CAS which works so far but i'm not able to define which user has access to which site.

How can I do that?

LDAP, you should define in an external directory (openldap, AD or whatever) which website a user can access or not and define rules inside each website (mapping rôles/sites/ldap properties, more infos here).
From there, you can add SSO like CAS.


Is it possible to understand and use Relationships and Contextual Filters without knowing SQL? Are there any good, layman descriptions of contextual filters and relationships for those site builders that aren't developers?

Is it possible to be comfortable with Relationships and Contextual Filters without knowing SQL? If so, how?

By knowing SQL you can have better understanding but it is not necessary.

Relationships give you information about entities that are not listed in the fields b joining current content with other entities. For example detail information about the author of the node is not in the fields, Only it's uid is in there, so by selecting author as relationships you can get the rest of the information.
Contextual filters are similar to regular filters in that you can use mainly the same fields to filter the records on. Where contextual filters differ greatly is that you do not set the filtering value when you create the View, but it is taken from context. Contextual filters are great for when the View needs to display content dynamically depending on various contextual conditions


Disabling Twig cache does not prevent Drupal from caching I have the following content in menu.html.twig template.

Blog

Bilder

Kontakt

If I change the content of the menu.html.twig does not reflect in the site. If I have logged into the backend I can see the changes otherwise it does not apply the changes until I clear the cache.

I have disabled the Twig cache in development.services.yml file and made appropriate changes in settings.local.yml and uncomment the line which enables settings.local.yml  in the settings.yml

parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

Can anyone here know what is wrong here?

https://www.drupal.org/node/2598914

Follow the steps in the above link and it should definitely help with the caching issue.


Change values of nested fields with entity_metadata_wrapper The background of this question is that I'm trying to migrate data from Drupal 6 Imagefield Extended to Drupal 7 File Entity (with File Entity Inline). See also https://www.drupal.org/node/974888

First I tried to understand how entities work and how they can be extracted and manipulated using Entity Metadata Wrappers. That seems to work ok, for example, I can get the values of my imagefield like this:

$nid = 103025;
$node_wrapper = entity_metadata_wrapper('node', $nid);
$images = $node_wrapper->field_image->value();

And it seems that I could change the values of the images with something like this:

// Do something with $images
$node_wrapper->field_image->set($images);
$node_wrapper->revision->set(1);
$node_wrapper->save();

(For some reason it's not saving the values for the node in my case, but that's another question.)

My problem now is that I have nested fields, i.e. the imagefield has "subfields" for the source and license (that I had added in Drupal 6 using Imagefield Extended). I do get the values of those nested fields in $images - but only in the typical array with $images[und][0]['value'] and $images[und][0]['safe_value']. But there seems to be no way to get those values through the wrapper, for example like

$node_wrapper->field_image->field_source->value();
$node_wrapper->field_image->value()->field_source->value();

Now I have been trying for hours to figure out how I can change (or populate) those (sub) fields and then save the entire node, but to no avail.

I'm also wondering if it's necessary to do this on a node level as files are also entities, but it seems that there is nothing like entity_metadata_wrapper('file', $fid);.

I'd appreciate any hint that could point me in the right direction because the search has been kind of exhausting.

Using what Clive mentioned and with the hint eikes provided, this seems to be a way to accomplish what I want:

$nid = 108501;
$node_wrapper = entity_metadata_wrapper('node', $nid);

for ($i = 0; $i < count($node_wrapper->field_image->value()); $i++) {
  $node_wrapper->field_image[$i]->file->field_source->set('NEW SOURCE');
  $node_wrapper->field_image[$i]->file->field_license->set('NEW LICENSE');
  $node_wrapper->field_image[$i]->file->save();
}

// Just for dev: Check if the values have been saved
$node_wrapper = entity_metadata_wrapper('node', $nid);
dsm($node_wrapper->field_bild->value());

Erroneously I used the save() call on the whole node wrapper, but as files are their own entities, the call needs to be on the file, as eikes suggested.

Additionally, I noticed that calling $node_wrapper = entity_metadata_wrapper('node', $nid); after the above code doesn't reflect the changes (for checking). It seems I need to reload the entity first.

Thanks a lot to both of you!


First time user login, page redirect I am having difficulty getting drupal to redirect a user to a specific page after completing the registration form.

In the user.module file there is this:

// No e-mail verification required; log in user immediately.
elseif (!$admin && !variable_get('user_email_verification', TRUE) && $account->status) {
    _user_mail_notify('register_no_approval_required', $account);
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
    drupal_set_message(t('Registration successful. You are now logged in.'));
    $form_state['redirect'] = '';
}

I would have assumed that by entering the path you wish to redirect to, in the form redirect  ,it would redirect. For example:

$form_state['redirect'] = '/page/I/Want/To/Redirect/To';

However this is not the case. When the user is logged in after completing the registration form they are taken to the homepage.

Once the user is logged in (from the registration form) I wish to send them to our services page. But for them to be sent to the homepage every subsequent time they login.

There is a very simple way to that using the Rules module.


How to create a link from node view and pass information to a webform In Drupal 8, I have a webform field attached to a node with the Link to form formatter enabled.

Can I add the ID of that node in the Link custom attributes (YAML) textarea to display a block view of some node fields?

My goal is to be able to use a contextual filter on the block view to display the node information like title and some other fields around the form

I don't think webform link field can be used to accomplish this as the purpose of Link custom attributes (YAML) is for HTML TAG attributes like

target: _blank

You can use field_token_value to create a field on the node that has tokens as input. Install and enable the module and then add a token field.

The value of this field would be an HTML link with query parameters added (nodetitle in this example) you can browser for all available tokens under field value.

Then on the webform side you have to enable query parameter to populate fields by going to the settings of the webform > form > form behaviours > prepopulate > Allow all elements to be populated using query string parameters.

And then on the field to display the query parameter include the appropriate token.  Here adding the nodetitle to the subject field default value.

For token field to be populated a node needs to be saved.


How do I add a hyper-link as a content type field? I want to add a link as a content-type-field, so that it shows up under all the nodes of that content type.

This is because I do not want a link to a taxonomy-term; I want a link to the view I have created for that content type.

For this case you should use one of these (or both) hooks hook_node_view and hook_view


How to set Class for a particular image style? I'm trying to add a CSS class to a particular image style, in Drupal 8. For this purpose, I'm trying to set up a template, but am open to all solutions since I know I lack knowledge (I've been teaching myself this stuff over the past couple of months).

Specifically, I want all images with the style machine name 'feature_main_960_x_640_' and field machine name of 'field_image' to include the following class during 'Full content' view mode. I would like this class to be added to the img tag.

The purpose: to have my articles' feature images to be centered when the full content is being viewed.

Specifications:
Drupal 8, theme is Bootstrap 3, using Display Suite module.

I've used Display Suite to add the Bootstrap 3's 'center-block' class. The class is added before the img tag, in a div. This doesn't center the image. I could only get the image to center when I manually added 'center-block' within img. I also used the Field Formatter Class module for this purpose and it also added the class to a div rather than img: so the problem persists.

So far, I've taken a sledgehammer to the problem and used the following template to apply the class to all images but would like to be precise in application, as mentioned above. This is the template I used:

image.html.twig

{% set classes = [
  theme.settings.image_shape ? theme.settings.image_shape,
  theme.settings.image_responsive ? 'img-responsive',
  'center-block',
] %}
<img{{ attributes.addClass(classes) }} />

Any solution?

In Drupal 8 you can do this with hook_preprocess_image in your themes mytheme.theme file.

/**
 * Implements hook_preprocess_image().
 */
function mytheme_preprocess_image(&$variables) {
  if ($variables['style_name'] == 'my_custom_image_style') {
    $variables['attributes']['class'][] = 'my_css_class';
  }
}


Ajax not working with existing field in hook_form_alter If I add new select field and define ajax, all works fine. Whereas if I attach #ajax to the existing select field it just does not work. (I can see ajax loader spining for a while and that is all.) I'm also getting error: "An illegal choice has been detected. Please contact the site administrator."

I'm suspecting my callback function is not correctly implemented. Is it valid to make changes to the form in the callback function?

function hook_form_alter(&$form, &$form_state, $form_id) {
    //...

        // add wrapper to existing select field
        $form['field_event_1_role']['und']['#prefix'] = '
';
        $form['field_event_1_role']['und']['#suffix'] = '
';
        $form['field_event_1_role']['und']['#options'] = array('_none' => t(' - '));

        $events_list_options = array('1' => t('1'), '2' => t('2'));

        // **add new select field with ajax - This is working fine**
        $form['test_select_ajax'] = array(
            '#title' => t('Test select ajax'),
            '#type' => 'select',
            '#options' => $events_list_options,
            '#ajax' => array(
              'event'=>'change',
              'callback' =>'event_roles_ajax_callback',
              'wrapper' => 'select-event-role',
            ),
        );

        // **attach ajax to the existing select field - NOT working?!**
        $form['field_event_1']['und']['#options'] = $events_list_options;
        $form['field_event_1']['und']['#ajax'] = array(
            'event'=>'change',
            'callback' =>'event_roles_ajax_callback',
            'wrapper' => 'select-event-role',
        );
    }

    // Ajax callback function
    function event_roles_ajax_callback($form, &$form_state) {
        $form['field_event_1_role']['und']['#options'] = array('populated' => t('populated'));
        return $form['field_event_1_role'];
    }

Additional info: The form I'm altering here is registration_form from Entity Registration module

for this you can delete this line

$form['field_event_1_role']['und']['#options'] = array('_none' => t(' - '));

The problem is most likely because of a requirement for FAPI ajax which is documented, though can be easily missed:

  Changes to the form must only be made in the form builder function (ajax_example_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

From AJAX Forms in Drupal 7.

The fact that you're setting the form element [#options] in the ajax callback is definitely a problem. The ajax callback should only return the array or HTML to be printed, not change the form. Only the return line should be in that callback.

The changes to your form should be made in the form_alter. Also, you should use the form_state array to check whether a value has been selected for your first dropdown. This will be updated during an AJAX request.

I recommend looking at the examples module, as well as these pages for more information on AJAX in FAPI. It can definitely be tricky.

AJAX Forms in Drupal 7
AJAX Framework


Creating a periodic report in Drupal 7 or 8 I have the following use case: users have to report quarterly on their project used an unified form. For example, project 1 is implemented by organization X with contact person John and has to deliver 10 pcs. of A and 15 pcs of B; project 2 is implemented by organization Y with contact person Mary and has to deliver 20 pcs. of A and 3 pcs. of C.

I want to have a report for John and Mary to fill every three months, containing the name of project and submitting person, reference period, item and how many was delivered during the reporting period, as well as accumulated delivery from the project start. Further, I would like to retrieve summary reports on how many items of A. B and C were delivered so far by projects X and Y, and export the information to calculate further stats (i.e. % delivered by project and item, etc.).

The Q2 report for John and Mary should be pre-populated with the information on delivery for Q1 so far, contain fields to add the new performance and sum the new totals for their respective projects. Similarly, in Q3 the reports for both should contain the delivery for Q1+Q2 on their respective projects.

For most of the functionality described, it would be sufficient to use Webform for the reports and Views for accumulating the results; however, I have not found a way to add in a new webform instance representing the Q2 report the data from the Q1 report on the same project.

Could anyone suggest a solution, ideally without programming?

Below is a possible approach that may help to address the "reporting" part of your question (not how to pre-populate the webforms, which should really be a separate question I think). It's using "State" names (like Florida, Illinois, etc.) instead of "John, Mary, etc" and "Cities" instead of "A, B, etc". With "City attributes" instead of "pcs".
If I was to implement this in a Drupal site, I'd use either of these "displays":

Option 1 - Master detail with nested blocks
Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".

Option 2 - Report that filters based on some lookup
Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "How did you do that?!?!" ... then this is the answer: that's really a piece of cake using the Forena module. And (without programming" (unless you would want that instead ...), only using WYSIWYG editing features to either select the data (to build the SQLs) or to create the report that fits your needs to display those data. It also supports creating charts from these data.
Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead (about data contained in your Webforms), but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).
Disclosure: I'm a co-maintainer of Forena.


How to use Twig expression in content fields and render? How to use twig expression in Drupal 8 content field and render. If I embed following twig expression in field value

{% if variable == 1 %}
   you are logged in
{% endif %}

When I render the field template I want to print "you are logged in".

Right now it renders as:

{% if variable == 1 %}
  you are logged in
{% endif %}

Though views allow Twig expression. Can we achieve same in content fields?

You cannot use Twig code as field value. You have to put that code in a template file. Or you can use Twig code in Views field value rewriting (but not as field value). 2nd is limited to variables of the view that are before to rewritten field. The function can be found in Views UI by clicking on the field name in the "Fields" section.


How do I backup a site when it weights is more than 200MB and host can't do it? How do I backup a site when it weights is more than 200MB and host can't do it? I have it on hostinger.ru and can't backup with Internet server error 500. I cleared cache and deleted some modules.

Refer to my answer to "Which tables are safe to clear?", which should help to get the size of your database reduced.

And/or use the Backup and Migrate module, which also support exclusion of selected tables (typically the ones that are safe to clear also). Here is a quote from its project page (bold markup added here):

  Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


Better Performance by putting image dimensions YSlow advises that all images should have dimension attributes even if they are presented at 1:1 scale, so that the browser knows the dimensions before the images are loaded, to start rendering the page faster.

I have a view of 20 taxonomy titles and their image fields. How I can make Drupal put their dimensions attributes on each image html tag?

I have drupal 7.

This is a known issue in Drupal 7. A conscious choice, as it were, from the issue Remove unnecessary I/O from theme_image().

There is a patch to fix this here: Images are not printed with height and width.


Create a field with options are a combination of taxonomy terms, and content types linked to those taxonomy terms, for which the content type is used This is a decoupled drupal 8 back end with an angular front end connected over jsonapi and other custom restful inputs.

We have a coupon content type in out Drupal csm.  It is exactly what it sounds like, a coupon.

We have a content type "products" and you can assign a coupon to that product when creating or editing said product.

We have a taxonomy term list of product categories and sub categories.

Category A
    Sub Category 1
    Sub Category 2
Category B
    Sub Category 3
    Sub Category 4
    Sub Category 5

An admin can go into a taxonomy term, and add a coupon to an individual taxonomy term, or to a product content type.

This is where it gets crazy.

We have a listing of coupons, on that list we want to give the admin the ability to display a "featured product" and ideally, in the CMS they have a field where the only options are either a taxonomy term or a product content type that said coupon has been applied to.

Product A (Product)                  # (content-type)
Product F (Product)                  # (content-type)
Category B (Category)                # (product taxonomy parent (weight 0) term)
subCategory 1 (Sub Category)         # (product taxonomy sub parent (weight 1) term)

only products ( a content type ) or taxonomy terms with this coupon are shown.

We will then need to build a link pointing to the correct front end page.  The category list, the sub category list, or the actual product.

Thoughts on how to achieve this with no custom code?  If the only way to do this is with custom code, what's the best way to approach the task?

Thanks a million and 1.

[EDIT to change output options.]

There are some caveats in your question.

Caveat—no info to pick from

One caveat is marking "featured" items, narrowing down your pick from an already narrowed down list. This means that you have to save a new Coupon twice to get to the Featured option, the first time you save you pick the terms or products, and then you edit again to pick the "featured" one from the list you narrowed down previously. You could probably come up with some Ajax voodoo to do it all in one Save, but that is out of scope here and not very straightforward.

I'll assume the double-save is acceptable, that it fits with your project processes.

Caveat—Views don't mingle entities

To solve this without the custom code you need Views, but Views only ever list one type of entity (unless they're related, which in your care they aren't).

I'll assume it's ok to use two Fields then to mark your "featured", one to list terms, and the other for Products, and you'll have to rely on your admins to only select one of those, treat them like a single field even when it's not. (You ccould combine them with custom code, of course.)

Use Entity reference Views Display

Create a Taxonomy term Views type with Entity reference Display and limit to your Category vocabulary. You'll have to use Parent term Relationship and Contextual filters to show both levels.

Then use the usual Views magic to Contextually filter out only those terms that are shared with the node currently being edited (this is your Coupon node that has already been saved with chosen Categories and Products).

Create a new Entity Reference Field on Coupon CT and make it use the Views you created previously as a Widget.

Then repeat the procedure for Products. Create a Views Display listing Products, but limit Contextually to the Entity reference you're using on your Coupon, so that when editing a Coupon only Products that have already been chosen show up to be selected as "featured". When you have it working create a new ER field on Coupon using that ER Display as a widget.

This question is too complex to answer step by step, try looking at similar answers for each part, maybe here: How do I create a list of Nodes within a list of taxonomy terms, within a node? and Entity Reference widget selctor in view referring same reference

Links

I assume the links you mention are the links to the related Featured term or Product, showing on the Coupon list.

You can get this easily in Views by adding a Relationship (on the Coupon Views) to the ER "Featured" term, and then "Taxonomy Name" Field that uses that Relationship to show the related Category link.

Repeat similarly to show related "Featured" Product: add the ER "Featured" Product Relationship, and then "Title" Field that uses that Relationship. It will show the "featured" Product (the optin to make it a link instead of plain text are inside the Field settings).

Only custom code will give polished experience

This is perhaps a bit crude but you can always polish with custom code, in various steps along the way, or even the entire set of features, depending on your needs and resources.


Homebox column number different on mobile? I have created a 3 column homebox site with rss feeds in an attempt to roll my own replacement for google ig (which is to shut soon). It works perfectly for what I want. Is there a simple method to serve up a 1 column version of the same site to mobile users? I have been investigating browscap and adaptive theme (AT) but I was hoping there was a simple method of serving the same site with 1 column instead of three (must use homebox)?

Desktop:

Mobile:

Add the following to your css.

@media screen and (max-width:740px){
    .homebox-column-wrapper{
          width:100%!important;
          clear:both;
    }
}


Pulling data into a content type I'm hoping to get some opinions on the best way to proceed.  We are migrating our website from a Microsoft Environment to Drupal 7 and I appear to be having trouble wrapping my head around how to do a couple of things.

We have about 50 locations, and each location might have any number of workers.  I have created 2 content types, Location & worker.  What I want to do is to create a "view" (for lack of a better term) which will list all of my locations grouped by county.  No problem.  Now, when the user clicks on one of the locations, I want to show the data for the location (address, phone number, etc) but I also want the location content type to be able to pull a list of workers (from the worker content types) that are at that site.

I have a common field in each content type of location_number, so basically what I need to do is a SQL JOIN operation.  I've looked into the Views module and it seems that using that I would have to create a separate view for each location (unless I'm missing something), when what I really want to do is create a more 'generic' view which I can plug into node template and have it auto-generate what I need.  I don't want to have to manage 50+ views.

My first instinct is to say write some custom PHP code that gets the data I want.  In SharePoint, I would just write a web part with a simple LINQ query right back to the 2 lists and plug it into the page.  Is there something similar in to this in Drupal or is there an easier way to go about what I"m trying to do.

Any advice is appreciated.

This is core functionality in views and very easy to do with views relationships and entity references. Essentially, what you want to do is create a new entity reference field in your location content type to reference the workers, ex: "Related Workers". You would then add the workers to each of the locations using the normal edit form.

Now in the node output, you'll have a list of these referenced entities as a unordered list of links to the "Related Workers" node which you can customize using the display fields options.

To add these related workers (and all their fields) in a combined view (ex. the join you are referring to) you would just need to create a relationship, using this entity reference field.

This whole process is explained in this screencast from NodeOne

http://nodeone.se/sv/node/782


How to send notification emails in a journal style "Newsletter"? I am working on replace an existing, custom built website with a Drupal 7 site. In the existing website I've coded a more or less smart email-notification system which I like to re-build for the Drupal version (if possible).

The website allows members to create/edit/cancel events, participate/decline events, comment  events etc. If any of these action happened they where logged for email-notification. The user then could set an interval how often the so called "Action-Log" should be emailed to the user. eg. once an hour, every four hours, one a day or once a week. This is extremely handy to a) stay in touch with the event and b) to not fill the members inboxes.

Advanced feature (phase 2): Further more the website had some logic to reduce the notification if or example a member already declined an event he will not get any notifications about that event. Think this will get really tricky to do in a generic way.

Any hints about how to do this with Drupal 7?

I already had a look to the following modules:

Triggers / Actions (sonding email but not "cached/delayed").
EntityRegistration (used for event registration).
Notifications (is alpha on D7 and called "quick port").

PS: I was told this feature is normally called "digest".

For sending notifications you can use the Notifications module.


Empty field collection in hook_node_presave with entity_metadata_wrapper I have a node with a field type field_collection which has 2 items:

$node->field_field_collection['und'] = array(
  0 => array('value' => 1),
  1 => array('value' => 2),
);

on the save node drupal fire hook_node_presave:

/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  $ewrapper = entity_metadata_wrapper('node', $node);
  $wrapper_counter = 0;
  $node_counter = 0;
  foreach ($ewrapper->field_field_collection->getIterator() as $delta => $fc_wrapper) {
    $wrapper_counter++;
  }
  foreach ($node->field_field_collection['und'] as $key => $value) {
    $node_counter++;
  }
}

after runing code

$wrapper_counter = 0;
$node_counter = 2;

what am I doing wrong?
I want to walk the field collection using entity_metadata_wrapper.

Drupal: 7.34
Entity API: 7.x-1.5
Field collection: 7.x-1.0-beta8

By this way as per this post:

/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  if ($node -> type == 'my_type') {
    $field_field_collection = field_get_items('node', $node, 'field_field_collection');
    foreach ($field_field_collection as $key => $value) {
      $fc_wrapper = entity_metadata_wrapper('field_collection_item', $value['entity']);
      $fc_name = $fc_wrapper -> field_field_collection_name -> value();
      dsm($fc_name);
    }
  }
}

See: Understanding Field Collection Values and Entity metadata wrappers pages.


Attach the module "Insert" to ALL "Body" fields? I've just installed the Insert module. I have many many content types in my site and all of them contains the same "Body" field. It would take me much time to attach an Insert image-field to each one of them manually and I need a way to do that at once.

How will you achieve this goal? If you drop a module's name please also detail in steps where and what will you do to achieve it.

You may add this code snippet in the install file in your custom module and run update.php. It works fine, I've tested this code on my local site

<?php
/**
 * Add an image field to a node.
 */
function my_module_update_7001() {
  $field_name = 'field_insert_image';

  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'image',
    );
    field_create_field($field);
  }

  $content_types = node_type_get_types();
  $exclude = array('example');
  foreach ($content_types as $content_type) {
  if (!in_array($content_type->type, $exclude)) {
    $instance = field_info_instance('node', $field_name, $content_type->type);
    if (!$instance) {
      // Create the instance.
      $instance = array(
        'field_name' => $field_name,
        'entity_type' => 'node',
        'bundle' => $content_type->type,
        'label' => 'Image Insert',
        'description' => 'An image for the article.',
        'required' => TRUE,
        'settings' => array(
          'file_extensions' => 'png jpg jpeg',
          'file_directory' => '',
          'max_filesize' => '20 MB',
          'alt_field' => 1,
          'title_field' => 1,
          'max_resolution' => '300x200',
          'min_resolution' => '200x125',
          'default_image' => 0,
         ),
         'widget' => array(
          'type' => 'image_image',
          'module' => 'image',
          'active' => 1,
          'settings' => array(
            'insert' => 1,
            'insert_absolute' => 1,
            'insert_styles' => array_keys(insert_styles_list()),
          ),
         ),
         'display' => array(
          'default' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'full' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'teaser' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
       )
      );

      field_create_instance($instance);
    }
  }
 }
}


Boost crawler - maximum time to use for crawling on every cron run? I have a drupal 7 site. The site is really big and has few content types, and a lot of content.
I use boost and Cache expiration to improve performance.

I will be happy to get some information regarding the crawler of Boost.
I want to Pre-cache as much pages of the website as I can, so they get cached before anyone accesses them.

what is the maximum recommended time (in seconds) to use for crawling on every cron run?


SMTP module: The following From address failed all,

Here is something I don't quite understand.

First of all, my site-wide email address configured on Site Information page is my_gmail_address@gmail.com.

Then, I use smtp module to send emails out from my site. I configure SMTP settings with my yahoo email address my_yahoo_mail_address@ymail.com.

I tries to send a test email out to my other gmail address my_other_gmail_address@gmail.com, but failed. Email can never be sent out in this situation.

Here is watchdog log details:

Type    smtp
Date    Monday, September 22, 2014 - 11:29
User    lyon
Location    http://localhost:8888/drupal-test/admin/config/system/smtp
Referrer    http://localhost:8888/drupal-test/admin/config/system/smtp
Message Error sending e-mail from my_gmail_address@gmail.com to my_other_gmail_address@gmail.com : The following From address failed: my_gmail_address@gmail.com
SMTP server error: From address not verified - see http://help.yahoo.com/l/us/yahoo/mail/original/manage/sendfrom-07.html

Severity    error
Hostname    ::1
Operations

SMTP configuration didn't go wrong, because in the following two situations, email can be sent out well:

configure site-wide email address to be the same one configured in SMTP settings: my_yahoo_mail_address@ymail.com.
configure SMTP settings with a gmail address, then configuring site-wide email address to be any email address will work well. (People on Internet says Gmail can override it).

I don't want the SMTP configuration to be tied with Gmail account, it should support any mail host. How can I overcome this problem?

I appreciate your help.

I believe the problem lies with Yahoo not having your permission to send from the gmail account.  You could try setting up Yahoo to send from your gmail account but I'm not sure Yahoo will do that.

You could look into a mail service like MailJet, which is cheap and scalable.

Or, assuming you're using the drupal_mail function, simply set your $from variable in 'params' to 'my_yahoo_mail_address@ymail.com'.


"You don't have permission to access / on this server" I'm running my local development sites on a Windows machine with Uniserver. I have them all set up as vhosts and they work fine with Drupal 7. Recently I decided to install a vhost with Drupal 8, but when I go to the site I get the following error:

  403 Forbidden - You don't have permission to access / on this server

The error log for the site says:

  Options FollowSymLinks and SymLinksIfOwnerMatch are both off, so the RewriteRule directive is also forbidden due to its similar ability to circumvent directory restrictions

If I add Options +FollowSymLinks to the vhost's .htaccess file, it works fine.  How should I be doing this? I can't imagine Drupal 8 is supposed to have this done on every installation. For reference, I'm running the site on:

Apache 2.4.18
PHP 5.6.18
MySQL 5.6.28

I can't imagine Drupal 8 is supposed to have this done on every installation.

You're right, it only needs to be done in .htaccess where altering the web server config isn't an option (think shared hosting).

In a local dev environment you don't have that problem, so just update the vhost with something like

<Directory "/var/www/site/public_html">
  Options FollowSymLinks
  AllowOverride All
  Require all granted
</Directory>

and re-start/load Apache for it to take effect.


How to show in a view the total number of paragraphs for a node? I have a content type with a field of type paragraphs, with possible unlimited values. I need to show the total number of paragraphs for every node, in a column, in a views (table of fields). It seems to be only possible to render a preview of the paragraph. I tried to use "rewrite result" with "replacement patterns" but the only token available are the following:

{{ field_hours }} == Hours
{{ field_hours__target_id }} == Raw target_id
{{ field_hours__target_revision_id }} == Raw target_revision_id

How I can proceed?

I managed to achieve this doing the following:

Create a View to show Content of Type All. Add a page as well if you wish.
Format the style to be a Table.
Go to Advanced and turn on "Use aggregation".
Go to aggregation settings for the field "Content:Title" and set the aggregation type to "Count".
Change the label of this field to something like "Number of paragraphs in the node:".(*optional)
In Fields add field "Content:Title", aggregation type should be Group results together.
Add Filter Criteria "Hours (field_hours:target_id)", aggregation type should be Group results together, and set the operator to "is not empty(NOT NULL)".

This is how the Display settings should look at the end:

And here are the desired results in the preview:

I hope this helps.


How to partial search in taxonomy terms and entity references with Views Exposed Filter? I have a content type and the content type has a taxonomy term field (tags) and a entity reference field (author as another content type).
I'm trying to create an "advanced search" with views exposed filter.

What I want to do is to allow users to search in node titles and inside these fields without an autocomplete function. I don't want to force the users to write and select an author, but I want to let them to write a word and then search.
For example:
If a user enter John in the author field then search; all the nodes should be listed with the authors name that include "John": John A., Michael John, Another John etc.
How can I do this?

Use relationships to expose the exact field, for instance use taxonomy relationship and then instead of the taxonomy field expose taxonomy term name with the relationship selected. Do the same for entity reference.


Admin toolbar doesn't appear My admin toolbar doesn't showing up. $page_top in html.tpl.php doesn't have any value.

Why doesn't $page_top have any value? How do I fix this?

Try this CSS.

#admin-menu, #admin-menu .dropdown {
  z-index: 9999;
}

.logged-in #oa-navbar {
  top: 25px;
}


Authentication for iCal feeds I have a calendar feed (using the Drupal Calendar module) on a site and I'd like to add this calendar to Google Calendar. I have this working for a publicly accessible calendar and it works fine.

The problem now is that my calendar is only accessible for authenticated users and should remain so. I see no way to authenticate the application accessing a feed and therefore can't access that calendar from Google Calendar.

Is there any way to provide credentials in the feed url or something similar?

Secure remote access to an RSS page via HTTP authentication using the Secure Site module.

  This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.


How to access the full html of a drupal basic page? This is probably a dumb question. But I have not been able to find the full html of a basic page.
When I create a basic page, I can put a title and texts/images in the body. How can I access the <head>...</head> portion of a specific basic page so that I can edit that part and put a js script? or better yet the full html of the page?

Thanks!

You will need to edit your themes tpl files to make changes to those areas.  If you are adding a js file you can add it in your themes template.php file. I would recommend you read through this link for

Drupal 7:

https://www.drupal.org/docs/7/theming

Drupal 8:

https://www.drupal.org/docs/8/theming


Create a node programatically and set its CCK field values I've tried the technique described here:
http://lucasforge.2bopen.org/2010/06/drupal-6-create-a-node-with-cck-fields-programmatically/

and here:
http://drupal.org/node/1111514

Neither seem to work. The node gets created, but the CCK field I'm trying to set never gets set.

Both those just describe using "field_name[0]['value'] = 'something'" but even if I set the field value through the web form and DSM the result it never has 'value' set, just '#default_value'.

I tried setting "field_name[0]['#default_value'][0]['nid'] = 'mynodeid'" but that didn't work either.

This is the structure of the CCK field I'm trying to set:

field_application_discipline_id (Array, 13 elements)

#type (String, 20 characters ) nodereference_select
#default_value (Array, 1 element)
#required (String, 1 characters ) 0
#columns (Array, 1 element)
#title (String, 13 characters ) Discipline ID
#description (String, 0 characters )
#delta (Integer) 0
#field_name (String, 31 characters ) field_application_discipline_id
#type_name (String, 11 characters ) application
#tree (Boolean) TRUE
#weight (String, 2 characters ) 31
#access (Boolean) TRUE
#count (Integer) 9

Any idea why this wouldn't be working?

For nodereference fields you have to use "nid" instead of "value".

//123 is the nid of the node you want to reference
$node->field_application_discipline_id[0]['nid'] = 123;

The best way to discover what variable to use is to install Devel module and view the devel tab next to the view/edit tab on the node page.


Print login page url in node.tpl.php It seems nevertheless rather simple, but I do not find the solution.

How to print in node.tpl.php the url of the login page?

The url has to serve for a link:

<a href="<?php print ... ?>">Login

Use this if you just want the URL:

<?php print url('user/login'); ?>

If you want to print a link:

<?php print l(t('Login'), 'user/login'); ?>

And in your case it would be:

<?php print l('<span>' . t('Login') . '</span>', 'user/login', array('html' => TRUE)); ?>


FileField Permissions- How can I allow users to upload a file without giving them the ability to remove files that have been uploaded? I want to be able to upload a file into an article but without the ability to remove other files uploaded from other users to the same article.

Is it possible?

I tried the Field Permissions module; I can edit, but I cannot upload.

Try to add a second file field via the field UI; to set the permissions for a single field you could use hook_field_access().


In a group content add form, the og_group_ref is empty, except for the "_none" value This is only for non admin members. Administrators have the field populated, but logging in as anyone that isn't in that role produces an empty field, except for the "_none" value.

I've tried adding the value manually, like this:

if(!isset($form['og_group_ref'][LANGUAGE_NONE][0]['default']['#options']['MyGroup'][$gid])){
  $form['og_group_ref'][LANGUAGE_NONE][0]['default']['#options']['MyGroup'][$gid] = 'current MyGroup';
}

This adds the item, but I get an error about an illegal option, so it's not the solution.

Again, the field loads all groups for the admin members, but not for non admins. Is there a special permission that needs to be set?

It turns out that organic groups permissions were inadvertently changed, causing the issue, and attempts to fixed this made it only worse. Permissions have been restored, and the system now works as expected.


How to change the HTML of the commerce shipping service form on checkout pages? Right now, the HTML of the commerce shipping service consists  by input buttons, where you select the desired method.
I'd like to is to have it in the form of a select, and - more importantly - have no default shipping method selcted.
How to do it?

As suggested by clive, You should try this:

function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

or

function MYMODULE_form_alter($form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}


hook_menu() not available for ajax loaded links I'm loading a datatable and its data into a panel, through ajax. Below is the link which can add the row(entry) to favorites. When I click the link, the jquery animation is executed properly but the hook_menu and it's callback function is not being executed. It looks like the hook_menu is not 'available'

This is the link

$link = array(
    '#type' => 'link',
    '#title' => t('Favorite'),
    '#href' => 'favorite/' . $item->nid,
    '#attributes' => array(
    'class' => array('use-ajax', 'favorite_item_button'),
    ),
);

And this is the hook_menu

function favorite_item_menu() {
  $items = array();
  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Do you see any mistakes? Am I doing something wrong, forgetting something?

Advice is much appreciated.

Edit:
- no php error logs
- no js error logs

tried: sitename.com/favorite/501 - got the error 'access denied'

You need to add 'access callback' => TRUE, to your menu item.

Your menu callback should look like the following:

function favorite_item_menu() {
  $items = array();

  $items['favorite/%'] = array(
    'title' => 'favorite item',
    'page callback' => 'favorite_item',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}


Prefill Registration Form Fields Entity Registration
Commerce Registration
Drupal 7

Our site connects with Salesforce to input Entity Registration data as Contacts. I'm building in the ability to have users login and have their registration forms prefilled with the data I grab from Salesforce.

I have the data, but the prefill isn't working. Commerce Registration buries the forms a bit, as you will see below in my code example. I decided to step out of using the Salesforce data and just use a static value and try to set it. Both default_value and placeholder do nothing. If I try to touch ['value'] the site crashes.

Here is the trimmed down version of what I have:

<?php
function createFieldMap(){
    $fieldMapping = array(
        "LastName" => "field_last_name",
        "FirstName" => "field_first_name",
        "Salutation" => "field_prefix"
    );
}
function custom_module_form_commerce_checkout_form_registration_alter(&$form, &$form_state, $form_id) {
    $fieldMap = createFieldMap();
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            foreach ($fieldMap as $salesforceKey => $drupalMachine) {
                if($drupalMachine == 'field_last_name'){
                   $form['registration_information'][$name][$subname]['field_last_name']['#default_value'] = "Johnston";
                   $form['registration_information'][$name][$subname]['field_last_name']['#attributes']['placeholder'] = t("Johnston");
               }
            }
        }
    }
}

Just to point out, $form['registration_information'][$name][$subname] is valid and is done that way because if you have multiple forms, the productID is used as the form ID, twice. I can access $form['registration_information'][$name][$subname]['field_last_name'] if I var_dump it out. ['value'] represents entity data for some reason, which is probably why it crashes if I try to adjust that.

I can get this to work fine by setting the default_value of select lists. But the text fields don't do anything.

Fixed it. I had to work with
['und'][0]['value']['#default_value']

So my new code is:

<?php
    $fieldMap = createFieldMap();
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            foreach ($fieldMap as $salesforceKey => $drupalMachine) {
                $form['registration_information'][$name][$subname][$drupalMachine]['und'][0]['value']['#default_value'] = $contact[$salesforceKey];
            }
        }
    }


Get more sub level for in menu I'm able to get second level of the main menu by using below code.

$menu = '';
$menuItems = menu_tree_page_data('main-menu');
foreach($menuItems as $key => $m) {
    if ($m['link']['in_active_trail'] && $menuItems[$key]['below']) {
        $menu = render(menu_tree_output($menuItems[$key]['below']));
   }
}
print $menu;

If I want to get 3rd (like in image below), 4th or 5th level. how this will be done.

It is necessary that you want to display this using code?

I have a better solution for you. You can try with this module Menu Block for above achievement


Tying together creation of multiple content types in a form I need to make a content creation form that ties in the creation of two different content types.

Imagine garage and cars as an example. There is a one-to-many relationship between garage and cars, so one garage can have 0 to many cars.

I've created the content types and established the relationship between them but I need to figure out how to best support the user in creating content. I think it is important that distinction between content types  is more or less transparent to the user, so he could be creating his garage at one point, then later on come back to add cars. Or he could be creating a garage and adding two cars in one go. Or he could go in and create a car without even assigning a garage.

I imagine accomplishing this by having a form for adding garages and a form for adding cars, but near the end of the 'create garage' form I have the option of either assigning an existing car I have created earlier (probably using an autocomplete textfield) or load the 'create car' form in a modal window allowing to create a new car right before submitting the garage form (the relatioship will then be established right away).

My question is how to accomplish this best from an architectural point of view.

Should I write a completely custom module and maybe place it in a block with panels or could I get by simply by creating a hook that changes the content creation forms for cars and garages? Or maybe you know about a contrib module that fixes this for me out of the box?

Furthermore, I imagine the end result being soaked in asynchronous requests, allowing the form to be validated and saved asynchronously. For an early proof-of-concept I could live with "nested save buttons", though. I will most likely be using AngularJS for some of the realtime stuff. Should I look into exposing the content types as a REST service build and the entire page in AngularJS right away? (something I am planning to do further down the line anyway, but I also need to have something up and running quickly and I imagine a rewrite for Drupal 8 in a not too far future. So I would prefer not having to learn how to build services in Drupal 7).

The Field Collection module is a quick and easy solution. It lets you nest entities within your content type as a field. So you could have a "Garage" Content Type which then has "Car" field of type (field collection) with "Number of values" set to unlimited.

At /admin/structure/field-collections you can add fields to this Car type.

On the Garage edit form you can add cars to your garage as shown below:

Then while viewing a Garage node, a user with sufficient permissions will see edit and add links which work just like you would expect. See below.

The downside with this approach is that since the Car's information is tied closely to a specific Garage, it's not easy to move a car from one garage to another or have one car in several garages, etc. Those use cases are possible, but you will have to write you own code however.


author posts in views I have a content type and sort theme in a page with views as a table
And now, I want when users go to this page, they can see just the posts that the made them.
see just post made by their-self.
what filter should I do?
How?

Add an contextual filter of type Content: Author uid
Under WHEN THE FILTER VALUE IS NOT IN THE URL select Provide default value.
Select User ID from logged in user.


How to add a button in the header of a table form? I have this table form:

The corresponding code for the header is
$form['inscriptions'] = [
  '#type'   => 'table',
  '#header' => [
    [
      'data'    => '',
      'colspan' => 2,
    ],
    [
      'data'    => 'Distribution',
      'colspan' => 2,
    ],
    [
      'data'    => 'Réserve',
      'colspan' => 2,
    ],
    [
      'data'    => 'Référent',
      'colspan' => 2,
    ],
  ],
  '#id'     => 'planningofdistributions',
  '#sticky' => TRUE,
];

I would like to replace the (empty) content of the first cell by a submit button.
How can I do that?

Finally, I did it this way:
if (some condition) {
  $data = [
    '#type'     => 'inline_template',
    '#template' => '<input type="submit" id="edit-toggle" name="button" value="{{ foo }}" class="button js-form-submit form-submit">',
    '#context'  => ['foo' => $this->t('Toggle')],
  ];
}
else {
  $data = '';
}

$form['inscriptions'] = [
  '#type'   => 'table',
  '#header' => [
    [
      'data'    => $data,
      'colspan' => 2,
    ],
    [
      'data'    => 'Distribution',
      'colspan' => 2,
    ],
    [
      'data'    => 'Réserve',
      'colspan' => 2,
    ],
    [
      'data'    => 'Référent',
      'colspan' => 2,
    ],
  ],
  '#id'     => 'planningofdistributions',
  '#sticky' => TRUE,
];


How to deal with someone trying to login as admin? During these last days, I noticed in my dblog, that someone has been trying to sneak around.

The person tried finding the login url (my website isn't open for user registration) so they tried everything from my-domain.com/admin, my-domain.com/administrator.. and also my-domain.com/wp-login (which indicates that the person isn't familiar with drupal..)

Once the person ended up on /user he or she tried to login as admin by trying different usernames : admin, administrator etc... (I never use 'admin' as a username for the root user)

is there a way to prevent/protect a drupal website from this sort of things ?

Thanks

ps : i'm interested in how to do this both for d6 and d7.

These kinds of probes are very common across the internet. There are a few things you can potentially do to block this problem and reduce the success of an attacker.

First, I recommend everyone use Two Factor Authentication so that even if the attacker guesses your username and password they still can't login. There was a bounty for $500 to break TFA and although the white-hat attackers had username and password they couldn't break in.

The security review module or Droptor can help monitor these failed logins. If they happen a lot then you need to start taking more actions. Brute force attacks on passwords only work if someone does them a lot so if it just happens a few dozen times I wouldn't worry.

You can track the IP address in use by this person using watchdog entries and then use the built-in D6 Access Rules (or the d7 equivalent - http://drupal.org/project/user_restrictions ) to block access via that IP. You could also deny access to the IP in Apache or some other server level firewall. The firewall/webserver is a more efficient place to block the users in terms of load on the server, but it usually requires a bit more effort.

For Drupal 6 and 7, AjitS has provided an answer with a good description of how to use a rate-limiting feature to prevent repeated login attempts from the same IP.


How can I prevent placeholders to wrap the value with single quotes in db_query? I want to run a select query using db_query. Here is the code:

$nid_array = array(24,34,56,7,8);
$list_of_nids = implode(',',$nid_array);
$query = "  SELECT *
            FROM {table_name} as t
            WHERE t.nid IN (:list_of_nids)";
$placeholders = array();
$placeholders[':list_of_nids'] = $list_of_nids;

$result = db_query($query, $placeholders)->fetchAll();

This query does not return any results.
Although if I do not use placeholders & replace :list_of_nids with $list_of_nids, then I get proper results.

I believe that when using placeholders the value of :list_of_nids is taken as the $list_of_nids wrapped with single quote, which is causing problem here.

I want to use placeholders. So, how can use it without wrapping the value with single quotes.

You're imploding your array into a string, so PDO will (correctly) put quotes around it. PDO can handle arrays just fine, though, no need for manual manipulation:

$nid_array = array(24,34,56,7,8);

$query = "  SELECT *
            FROM {table_name} as t
            WHERE t.nid IN (:list_of_nids)";

$placeholders = array();
$placeholders[':list_of_nids'] = $nid_array;

$result = db_query($query, $placeholders)->fetchAll();


How can I allow anonymous visitors to submit content? I am working on a website that displays a list of historical events.  Most of the events have been added by a small group of users that manage the site.  However, I would also like to add the ability for anonymous visitors to suggest events to be added to the site.

I could make the node/add form available to anonymous visitors however this isn't ideal for several reasons:

the standard submission form is quite complex and I would like to simplify this for anonymous visitors e.g. some fields aren't relevant I want to hide these.
anonymous visitors should be able to submit partial information about the events and for an editor to add more details later.
anonymous submissions need to be moderated before being published.
I would like to guard against spam submissions.

How would you suggest I do this?

Is it possible to have two forms to add a new event, a more complex one for site users and a simpler one for anonymous visitors?

Create another content type, say "Event Suggestion", which contains only those fields you want anonymous users to submit suggestions for. Do not include the fields you consider as not relevant (and which you want to 'hide' for such anonymous users).

When creating such extra content type, for its fields just use the same fields as for the content type that you already have, say "Event". So the fields for this new content type (Event Suggestion) will be a subset of the fields that you already have for the content type already being used by your "small group of users" (= Event).

Related to permissions: allow anonymous users to create an Event suggestion, but do not allow Event to be created by anonymous users.

For spam reduction/prevention, use modules such as Honeypot, Mollom, Captcha, reCaptcha, etc.

Use the Rules module to finetune your workflow related to nodes of type Event suggestions being created (saved). To just mention a few options (the list is virtually unlimited):

Unpublish such nodes (so that spam submissions that are not caught by spam prevention modules, never get shown without reviewing them first).
Send an eMail msg to your small group of users who manage your site (something like "a new Event suggestion is waiting your approval".
Set some kind of "confirmation message" when an Event suggestion is beiing submitted (like "Thank you for your Event suggestion, it will be reviewed soon ...").

When your small group of users who manage your site then review such Event suggestion, they should use the Node Convert module to convert an Event Suggestion into an Event. Using the Rules module you could then automatically "publish" such event also. After such node got converted, your small group of users who manage your site could then complete what you described as "add more details later on".

Other modules like Flag and/or Content Access might further enhance the various features / functionality you might be looking for. E.g. as an alternative to working wirth "unpublished" content, you could work with content that is published, but can only be accessed by authorized users.

Bottom line: Rules and Node Convert could get you pretty close, possibly further enhanced with Flag and Content Access.

Note: Adding the View unpublished module seems like an interesting improvement also, i.e. to grant access for specific user roles (such as editors or reviewers) to view unpublished nodes of a specific type.


How to display an image from theme directory to a drupal block by php code? I want to load an image from my theme directory inside a block. I am using the following code:

<img src="<?php print $base_path .$directory; ?>/images/oil-ad.png" alt=''oil ad">.

But it is not working. However I have enabled PHP Filter and php text format.

In your image "alt" attribute, you have 2 single quotes before oil ad and a single quotation mark following it. That syntax doesn't look right to me. Maybe THAT is causing some error somehow? If not then read on below for further narrowing down your issue.

Assume you used admin/structure/block/add to create that block, with a "body" in which you added that img tag.

When doing so, you also need to select the "text format" (below the body) to be used. You wrote you used "php text format", though I'm assuming you mean "test format"="PHP code".

To further ivestigate where your problem is actually coming from, try to further narrow down your issue. By FIRST creating such image tag without using any PHP code. And instead use some text format like 'Full HTML' and/or 'Filtered HTML', something like so (I intentionally did not correct the syntax of the alt attribute, because that might produce the error you're searching for ...):

<img src="/some/path/that/is/hardcoded/images/oil-ad.png" alt=''oil ad">.

If that works then have a confirmation that your issue is NOT because of some text format configuration issue related to using the "img" tag.


Hook_init() and Hook_exit not triggering in template.php I have implemented hook_init and hook_exit in template.php

<?php
/* Alter variables */
function mytheme_exit(){
  var_dump("template Hook exit called");
}

/* Alter variables*/
function mytheme_init(){
  var_dump("template Hook init called");
}

When I cleared cache, loaded the page, it didnt print anything
I would really appreciate any help from you guys since when I implemented the hook_init and hook_exit in a custom module , it did work. Does these hook not work in template.php??

Unfortunately it's as you suspect - those hooks aren't invoked for themes.

Themes can implement hook_theme(), a variety of process/preprocess hooks, and alter hooks (there may be others but I can't find a reference right now).

For hook_init(), hook_exit(), and most other non-alter hooks you'll need to implement them in a custom module.


How can I call javascript from another site? I recently started working in collaboration with another drupal website, and we are trying to figure out how to get some of their content embedded into my site. They sent my some embed code for a widget, which is below (with some pieces changed for privacy:

<script type="text/javascript">
  widgetContext = { "url": "http://theirsite.com/mysite/[nid]", "width": "600", "height": 200, "widgetid": "web_widget_iframe_hash" };
</script>
<script id="web_widget_iframe_hash" src="http://theirsite.com/sites/all/modules/web_widgets/iframe/web_widgets_iframe.js">
</script>

The problem is that I cannot figure out how to get this embedded into my site. The widget generates calendars for venues, so the content is going to change based on which node is being viewed on my site. So, in my nodes, I added a field that stores the NID of the corresponding node on the other site so that the correct calendar is generated.

I'm trying to create a view, in order to dynamically call the above script for each page on my site. The view uses a token to take the NID field and place it into the first part of the script. However, when I place this code into a Custom Field, views strips the script tags and displays the rest of it as text. When I try to place it into a PHP field, it doesn't display at all.

Does anybody have a suggestion for how I can use the above code on my site? I'm at a bit of a loss.

You could add the JS in code.

e.g:

/**
 * Implements hook_init
 */
function mymodule_init(){
  if ($node = menu_get_object('node')) {
    if ($node->type == 'my_type') {
      $items = field_get_items('node', $node, 'field_my_nid_field');
      if (!empty($items[0]['value'])) {
        $nid = filter_xss($items[0]['value']);
        drupal_add_js('
        widgetContext = { "url": "http://theirsite.com/mysite/'.(int)$nid.'", "width": "600", "height": 200, "widgetid": "web_widget_iframe_hash" };
        ', array('type' => 'inline', 'scope' => 'header'));
      }
    }
  }
}

The other static script tag can be added in a custom Full HTML block / content pane or similar, where you want the content to display.


In a form, I want subsequent fields depending upon previous field? I have an entity creation form and I have a radio button as a field. Now what I need is, if while adding the entity, if radio button is set, then one more field just below should appear otherwise not.

If looking for a module, you can use the D7 -dev version of conditional_fields

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.

Alternatively, you can tweak the forms directly in code using hook_form_alter and the States API

In this example, I show the UPC field when the specified operation value is chosen in a select box:

  // Define available batch operation callbacks
  $operations = array(
    'infinity_batch_sync_products' => 'Import and sync product details',
    'infinity_fetch_products' => 'Fetch list of available products',
    'infinity_fetch_product' => 'Fetch detail on single product'
  );

  $form['operation'] = array(
    '#type' => 'select',
    '#title' => t('Select operation'),
    '#options' => $operations,
    '#required' => TRUE,
  );
  $form['upc'] = array(
    '#type' => 'textfield',
    '#title' => t('UPC'),
    '#description' => t('Enter the product UPC code (commerce product SKU)'),
    '#default_value' => 0,
    '#size' => 20,
    '#maxlength' => 20,
    '#states' => array(
      'visible' => array(
       ':input[name="operation"]' => array('value' => 'infinity_fetch_product'),
      ),
    ),
  );

The "UPC" field only shows when the operation is "infinity_fetch_product"


Custom redirect to an url with "+" I use search api module and a view of products. If I put the search text block and I do a search, It redirect to an url like this:
 <my domain>?search_api_fulltext=word1+word2+word3&sort_by=title_1&sort_order=ASC

Where all search words are separated by a plus sign ("+").
I have my custom search block and I want to redirect to the same url in the submit function of the form. This is my code:

public function submitForm(array &$form, FormStateInterface $form_state) {

if (!empty($form_state->getValue('textBox'))) {
  $text = str_replace(' ', '+', $form_state->getValue('textBox'));
  $option = [
    'query' => ['search_api_fulltext' => $text,
                'sort_by'=>'search_api_relevance',
                'sort_order'=>'ASC'],
  ];
  $url = Url::fromUri('internal:/shop', $option);
  $form_state->setRedirectUrl($url);
}
return;

}

But it redirect to <my domain>?search_api_fulltext=word1%2Bword2&sort_by=title_1&sort_order=ASC, where plus signs are replaced with %2B, and then, the search is incorrect.
How could I avoid this replacement?

The URL you're building is taking the query (e.g. "word1 word2 word3") and replacing it with literal "+" chars for spaces. Hence, the %2B encoding in the string.

You don't need to parse/encode $form_state->getValue('textBox'). Per the documentation of Url::fromUri() for the $options param:

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.

$options['query'] expects its key/value pairs to have the literal strings.

You needn't worry about +/%20 encoding differences. They are different ways to encode the space character. (the + is an older space-encoding spec which you can do if absolutely needed, see rawurlencode, urlencode, & http_build_query in the PHP docs).


Correct way to access field values? field_view_value after field_get_items? So I want to get some field values that I need as input, sometimes for rendering.  According to this page:

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

It is a mistake to hard-code 'und' for internationalization, so to avoid this the author says that we should use field_view_field().

I personally, don't need all info related to the field, just the value.  So I opt for field_get_items() and then field_view_value() as outlined in the blog post.  But this seems a lot of work just to get a single value of a field (plus we have to find and load the node).  Do we really have to do so many steps to get a simple field value?  I would have thought that this would be a very common function that users need.

I'm wondering that, barring any simple method, I could just grab the value directly from field_get_items()[0]['value'].  Maybe the drawbacks are that it doesn't pass through any sanitation routines?   You can see more info here (trying to grab 'axis1t'):

Just looking for possible alternatives because my code is becoming somewhat bloated to keep getting field values this way along with the fact that they are burried inside field_collections.

If you are worried about bloat, just write your own field processor and keep it all on the level. That way you are using safe values, your site won't trip over if the language settings wiggle about and you can reuse your code in your next site.

You would call it wherever you like and because you know what you're expecting to get back, you could work with it immediately.

Something like:

<?php
/* get the values out of a field */
function magic_field_values($node, $field_name, $delta = null){
  $field_items = field_get_items('node', $node, $field_name);
  /* if a delta value is supplied, render that item otherwise, send the lot
  back. */
  if ($delta){
    return field_view_value('node', $node, $field_name, $field_items[$delta]);
  } else
  return $field_items;
}
?>

Then call it with:

<?php
$cheese_samples = magic_field_values($node, 'field_cheese_samples');
foreach $cheese_samples as $sample {
//do stuff
}
?>


Query other external databases I'm trying to query an other mysql database that has an completely other table-structure than drupal (no session, semantics table and so on). When trying to add the database to my config file I get these strange errors that I'm missing the semantics table.

I get the feeling that drupal is expecting that the other database is an also drupal database, which it is not..

My question is: how do I query and complete other other database (other user and table) the drupal way?

I already tried this but it gives the same problems: http://drupal.org/node/18429

It sounds like one of two things might be happening:

You're overwriting the default database (which needs to be the Drupal database) with your custom database.
You're calling API functions that interact with the Drupal database before switching back from your external db.

In either case these are abridged versions of the code from the docs page you linked to with a few comments that will hopefully help it to make more sense:

Drupal 6:

// Define the default database, this MUST be the database containing the Drupal installation.
$db_url['default'] = 'mysql://drupal:drupal@localhost/drupal';

// Define your external database separately.
$db_url['mydb'] = 'mysql://user:pwd@localhost/anotherdb';

module file:

// Switch to the external DB
db_set_active('mydb');

// Perform a query. Note that you should not call any Drupal API functions that will
// interact with the database until you've switched back. If you need your data to
// interact with the API, save it in a variable, switch back to the Drupal DB, and
// THEN make the API call
db_query('SELECT * FROM table_in_anotherdb');

// Switch back
db_set_active('default');

Drupal 7:

settings.php:

$databases = array (
  'default' => array (
    'default' => array ( // Again this must be your Drupal database.
      'database' => 'drupal',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'mydb' => array (
    'default' => array (
      'database' => 'db1',
      'username' => 'username2',
      'password' => 'password2',
      'host' => 'db.example.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

module file:

// Switch to the external DB
db_set_active('mydb');

// Get some data. The same rules about accessing the API functions apply here.
$results = db_query($sql);

// Switch back to the default db.
db_set_active('default');


Looking for an entityreference widget that allows to preselect an entity bundle I'm using one entityreference field in many entity types (bundles) because of the convenience that gives in Panels (just one relation to add in context).

However, the drawback is that the standard entityreference widgets show one bunch of target entities, which is not userfriendly.

What I want is a widget that includes a select field for the entity type (bundle) in order to filter the select field next to it.

I saw the Entityreference View Widget but but I'm looking for something more simple, just two select fields of which the first filters the second.

This module does it: Entity Reference Dynamic Select
https://www.drupal.org/project/entityreference_dynamicselect_widget


Disable cache for specific blocks I would like to let pages continue to benefit from Drupal 8 caching mechanism for anonymous users, except for a specific blocks which should update on every page refresh knowing that they are generated from Views.

Is it technically possible? How?

If this is a custom block, then you can use the Cache API, and set the cache max age to 0, eg

$build = [
 // ...
 '#cache' => [
   'max-age' => 0,
 ],
];

If it is an existing block, then you can alter it to add this into the render array.


is there any option in drupal to create a node for a particular user? I am going to create a medical lab examination system.In which i would have to display lab results to users individually.i will implement it by creating individual node for different different users, is there any option in drupal to create a node for a particular user ?

The easiest way I see to do this is by following these steps:

Install References module.
Enable User reference module under admin > modules
Create a content type (say "lab result"), and add a field of type user reference.
Now, every time you create a "lab result" you could associate it with an user.
For listing the "lab result" of a particular user you could use the Views module.


Show all users except profile being viewed (views, panel node) I've got a view of type "users".  I have it filtered to a certain "role".  There are only 12 ppl in this role (it is for a calendar, and someone is sponsored each month).  When viewing a users profile I want to show a list of the other 11 below that user.  I currently have it listing all 12, I cant figure out a filter to exclude the current profile being viewed.

I have to be missing something easy

the last checkbox on the settings of the contextual filter - exclude :) (under more)


Can I modify guestbook.module safely? I want to make a few changes in the HTML output by the guestbook module.  For example, I want to enclose the submitters name in a <div> or a <span> (so I can style it better).

What's the best way to do this?  The only option I can think of is to modify the guestbook.module, but that could cause issues down the track.

Changing module code is usually a bad idea because it makes it hard to impossible to update to a newer version of the module.

Without knowing the structure of that module, changing the HTML/output should always be possible by overriding theme functions, which you can do without changing the original code.

See: http://drupal.org/node/11811


Need help changing out theme based picture on front page, can only be done through host site, not admin panel I have been taking care of the basic updates on a website for an old friend.  I can do everything through the admin panel except update the main picture on the front page.  You can see it at www.foxviewfarms.com.  It is running Drupal 7.0.  I do know this can only be done through the host site, but I am just a rookie self taught person...I have never done anything like this.

I do understand I should backup before any changes.

So from the host, I found two places that the home image resides.  The first pic here shows my folders.  I went into the public one:

Now I pointed to the two places I found the image and I circled its file name.  It would seem to me that I would upload a new picture to each folder, then delete the old picture that resides in the sites/all/foxview/images folder (while keeping it in the themes/foxview/images in case I want to use it again).  The themes/foxview/images folder has the current image and past images, while the sites/all/foxview/images folder has just the new image.

Am I looking at this right?  Is there anything else I would need to change to update this picture?  Any help is greatly appreciated.

I would guess that the current image is hardcoded into the template. Best would be create a content type, add an image field, (upload new image), and set that new node page as the home page in the system site settings.


unblock ip address after failed login attempts? I have a custom login page that I'm testing the javascript on. The events I'm testing happen after a failed login.

After running a couple tests, I've managed to get my ip blocked because of numerous failed logins!

I have access to the database. How can I unblock my ip so I can continue to test my features without interruption?

I presume you are using Drupal 7. Did you check the {blocked_ips} table?


How do I programmatically create a view? There is a set of products in Drupal Commerce. How do I programmatically create a view that would select products for a particular field?

The classic way is to create it manually, via UI, then click "export" (path like http://example.org/admin/structure/views/view/default_demo/export), and wrap resulting code into a module using hook_views_default_views(), maybe fine-tuning details.


Reason for adding .value to access node id? I was trying to access node id in twig. After debugging for a while I found that node.nid was holding the value I wanted. However, when I tried to render using that variable it didn't print anything. After struggling for while I found that I need to append .value in the end which obviously worked. But I am not sure reason behind using .value. Can someone tell me when and where should we use such?

Short answer: Because nid is a field and you want to get the field value.

Long answer: Node is like User or Taxonomy Term an entity and provides the method id(). So instead of accessing the id fields by their individual field name (nid, uid, tid), it's easier and better OOP practice to use the method EntityInterface::id:

{{ node.id }}


Can I Remove comment_body on my Node Is it safe to remove this when I create a custom node?  It is not relevant to what I am doing.  Thanks.

Yes,
It's safe to remove comment body from the type of node you have created.
One may turn off the comments settings from content-type settings.


How to change or update select list of field which is already filled with values How to change or update select list of field which is already filled with values.
When I try to remove or edit value the options, I got:
"Allowed values list: some values are being removed while currently in use."

That's quite a daunting task - in order to keep consistency of existing values already stored in your database you can either change all of the nodes containing the value you want to change or add a new option to the select-field.

Changing a lot of options at once could be done by a views-bulk-operation and the operator Change value (not sure, if it's called this way - but it exists ;)).

If i run in such a situation i often write an update_hook to change all values of the field in the db (do not forget to change revision table also) and change the select values afterwards.


How to completely remove Drupal from system to start over! I am an apprentice and am using Drupal for work it installed Drupal on to my machine and got it all up and running then I accidently logged out and now I can't log back in. I have tried to send a password reset but Drupal doesn't like the email address or username that I put in. I'm relatively new to this so I ask to keep it simple! :) What can I do?? Thanks in advance

This is easiest using Drush http://drupal.org/project/drush

drush user-password username --password="new_password"