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.

You can use anonymous_posting module
https://www.drupal.org/project/anonymous_posting


How can I disable future dates? I am developing a custom module, where I need to disable future dates in the date pop-up. How can I do this?

This can be achieved by adding an attribute max

$form['date'] = [
  '#title' => $this->t('Date'),
  '#type' => 'date',
  '#attributes' => [
    'type' => 'date',
    'min' => '-25 years',
    'max' => 'now',
  ],
  '#date_date_format' => 'd/m/Y',
];

Reference: https://api.drupal.org/comment/61733#comment-61733

$form['birthDate'] = array(
        '#type' => 'date_popup',
        '#title' => t("Birth Date"),
        '#date_format' => 'Y-m-d',
        '#date_year_range' => '-100:0',
        '#datepicker_options' => array('maxDate' => '-1 day' ),
        '#date_label_position' => 'invisible',
        '#required' => TRUE,
    );


How do I set a block title to the title of a referenced node? In Views 3, I have a block that is showing content from a particular Node ID. I'd like to have the title of that block set dynamically to what the referenced page's title is. I know this would be accomplished using Contextual Filters and that my display's title would be an argument, like %1 but I'm uncertain what the Contextual Filter settings should be. I'd rather not use PHP code if avoidable simply because I don't have the 'PHP Filter' module enabled on most sites I create.

Which settings should I use to make a block title the same as the title of a referenced node?

In Views, with a block output & Content Entity Relationship set up, in 'Contextual Filters':

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
- Override title (tick this & I used %1 with some text)

which offers "Override the view and other argument titles. Use "%1" for the first argument, "%2" for the second, etc."

I know this is old, but maybe it can help someone. Just put on the view title [title], and add the field title to field list in view; then, select Exclude from display. Done!


Display a Block for mobile only without creating new theme I'm trying to display a main navigation menu block but ONLY for the site when it's viewed on a mobile. I need to do this without creating a new theme to do so though so it all works on 1 theme only.

Any ideas how this can be done?

Thanks

Take a look at the Browscap Block module. Here is a quote about it (from the module's project page):

... adds visibility options to block configuration settings to allow you hide or show blocks in mobile devices.
If you are looking for the same thing for Panel panes check out Browscap CTools.

I've solved this myself. I used a combination of Context module and Mobile Tools module. From here, the context for mobile device is available where i select 'Mobile'. Then i set a reaction for the Blocks and then can select blocks to show just for mobile.


How do I remove  from output? I'm trying to theme the output of a Drupal 8 view to use via a token for email recipients of a YAML form. I'm on the latest Drupal 8 core release and using a Bootstrap subtheme.

I have successfully removed all of the other views markup with the following TWIG theme override templates:

views-view-fields--ts--page_1.html

views-view--ts--page_1.html

views-view-unformatted--ts--page_1.html

For some reason, I keep getting the following markup added:

I have tried using the views UI options to strip HTML and/or customize the markup output and this does nothing. I've also tried using the TWIG filters like striptags, but this either removes the entire views output (a comma separated list of email addresses) or doesn't work at all.

How do I remove
?

Okay, I figured it out. After setting the services.yml file debug to "true" and enabling comments in my Firefox console, I was able to get the theme output for the particular set of divs that was adding the unwanted markup (I tried this earlier, but I think I forgot to rename default.services.yml to services.yml).

Anyway, I found that the markup was coming from Bootstrap's container.html.TWIG template. Of course, this is one of the templates that doesn't come with override suggestions, just the hook theme_container() theme function. So I copied the default function into my [subtheme name].theme file at the top of my subtheme's directory and modified it thus to suit my needs:

<?php
// Implements hook_container().
use Drupal\Core\Template\Attribute;

function vatheme_container($variables) {

  $request = \Drupal::request();

  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }

// Special handling for form elements.
$element = $variables['element'];
 // Ensure #attributes is set.
$element += array('#attributes' => array());

        if (isset($element['#array_parents'])) {
            // Assign an html ID.

            if (!isset($element['#attributes']['id'])) {
                $element['#attributes']['id'] = $element['#id'];
            }

            // Add the 'form-wrapper' class.
            $element['#attributes']['class'][] = 'form-wrapper';
        }

        if($title == 'Contact Tech Support'){
            return $element['#children'];
        }
        else{
            return '<div' . new Attribute($element['#attributes']) . '>' . $element['#children'] . '</div>';
        }
}

So, that seems to do the trick. This was my first stab at doing theme work in Drupal 8 and there are a lot of not insignificant changes from Drupal 7 here, so I thought I'd go through the details of my solution. Hopefully this helps someone else out there.

If anyone stumbles here, I found this worked for me. You can override the twig in your theme.

Create this twig here: YOUR_THEME/templates/form/container.html.twig
In the twig file just put:

{{ children }}


How to provide a custom option for an exposed filter in Views? I have a site in which members can upload pictures of themselves (imagine a personals site).  Users can upload up to five pictures, and each time they upload a picture, a rule increases the value of a custom field, Number of pictures.

Members can search for other members using a view.  This view has a number of exposed filters.

What I would like to do is add another option, Show members with pictures only.  Ideally, this would be a checkbox.  However, I have no idea how to add such a thing to a view.  I could add the Number of pictures field as an exposed filter, but since this is an integer, users would have to type "1", which is ugly and unintuitive.  How might I start to go about this?

if you are not able to achieve what you need with views default options.
You can create your custom views handler. In this case, it would be a filter handler.

https://api.drupal.org/api/views/handlers!views_handler_filter.inc/group/views_filter_handlers/7

https://drupal.org/node/1239866

Extending views functionallity to provide an approach to your problem

You are looking for Sexy Exposed module. I think you can do it with this module, It makes any views exposed filter's select list as checkbox list.

  This module makes any views exposed filter's select list sexy using
  the jQuery Dropdown Check List plugin.

  After installing this module, you will get a new checkbox on your
  view's exposed filter settings form called 'Make it sexy'. By ticking
  it your exposed filter will be pimped up by some hot javascript magic
  thanks to jQuery Dropdown Check List.


Create referenced node on the fly in Drupal 7? I have a node called "house" which references another node called "room". When I create a house, i.e. go to node/add/house, there will be a block where I can choose all the rooms I've created. What I want instead is to create the room on the fly, right on that page, and then reference it automatically. So basically, next to where you can choose rooms, you must be able to click a button that says "create new" and then ajaxically it must then open a an area on the page where you can create room.

Does that make sense? Is there a way to do this? I have the entity reference part of things setup, but before I look into trying to figure out which hook to plug into, perhaps someone knows of an inherent way that already uses entity?

You should use the Inline Entity Form module.

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.

You could also look at
Entity connect

Entity Connect now expands both Entity reference and References (node_reference and user_reference) fields by adding "add new content" and "edit current content" buttons. It will work with all default widgets provided by Entity reference and References (node_reference and user_reference) .

or
References dialog

This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.


Views will display entities the user does not have "view" access permission I have a custom entity type that can be viewed by certain people only. This works just fine, when people go to "mysite.com/custom-entity/8" some can see the info, some get "access denied" error.
The problem is I created a view to display a list of those entities and all of them are shown to all users, even if certain users shouldn't have "view" access permission.
LE: Caching is set to "None"
Any ideas on how to fix this? Thanks.

Option A
Create a custom access handler for your view.
Drupal 8 - Views Custom Access with a Plugin is a great guide. It seems like your scenario may fit the use case outlined in the beginning:
"... prohibit the display of a Drupal 8 View dependent upon some custom rules that don't fit easily with Drupal's permissions model ..."
Pro: You will get exactly the control features you want.
Con: A lot of custom code.
Option B
If you want permission for viewing the entity to be directly tied to the view access, there is an "Access" section on the view configuration form. Select "Permission" and then select the permission for viewing the entity you have created.
Pro: Easy to set up.
Con: Your use case must fit into Drupal's permissions system.


Problem with aggregated CSS/JS on flush cache We are using Varnish and Pressflow (v6.30).  Every time we flush cache in Drupal, we encounter problems where browsers can not get requested CCS/JS aggregate files as they do not exist.  We have found that if we flush Drupal cache and then immediately flush varnish cache, problem is fixed.

Anybody else had this issue?   And is there a module (purge or similar) which automatically handles Varnish flush cache with Drupal cache?

https://drupal.org/project/advagg might be the solution you're looking for.

If you want to flush both caches this will help https://drupal.org/project/expire


Using Views' Contextual filters in a Panel for one taxonomy term I have one taxonomy term, Country, which is linked to another, People. One people is from one country.

How can I make a view in my Panel, using Contextual filters, in order to show the specific view I prepared for "Country" ? I tried to use contextual filters to do so, and it works when I use the preview with the Country ID - but not in Panels.

If you want to display a different view for a country, I think what you probably want to do is use the Taxonomy Term override page rather than using contextual filters.

To do this, go to the pages admin screen (/admin/structure/pages).  Then, enable the Taxonomy term template panel to override the display of taxonomy terms using Panels.

To show a custom view, you can edit the Taxonomy term template panel.  This will allow you to use the taxonomy term as arguments for your view, because Panels understands that you are overriding the taxonomy term display.

I managed to do what I wanted to by taking the problem reversely :

I created my view, then added a contextual filter not by "Country ID", as I did, but by "People ID"
Then I configured the argument input in Views by taking the source from the argument of the panel (which matched my "People ID") and it was taken in account by my Views and actually works.

Drupal is quite complicated to understand sometimes ! :) Thanks for advice Patrick Kenny ;)

Bye


Internal Server Error and Machine Readable Names I have installed a new local site using Drupal 8.1.10 which takes a lot of time whenever I give any command (lets say create a text field) and then sometimes it gives a 'Internal Server Error' after which the 'machine readable name' of the text field which I was creating becomes unusable.

It then gives the error 'The machine-readable name is already in use. It must be unique.' whereas the field was not created and the 'machine readable name' is not actually in use.

This has happened multiple times. How do I resolve this?

Just try this :
on .htaccess, replace Options +FollowSymLinks by Options +SymLinksIfOwnerMatch

Example from : http://www.drupal8.ovh/en/tutoriels/9/install-drupal-8-virtualmin-error-500


How long does it take for Drupal to unblock user after 5 failed attempts? I've tried to log in unsuccessfully to Drupal and I get the following error:

There have been more than 5 failed login attempts for this account. It is temporarily blocked.

Does anyone know how long the waiting time is for localhost?

To answer your question:

  The amount of failed logins is recorded in the table 'flood'. You can
  either wait before trying to login again (6 hours) or clean the
  flood table with the procedure below.

Options for not having to wait:

  Execute the following query on the Drupal database:

  DELETE FROM 'flood'; If command above doesn't work try this:

  TRUNCATE flood RESTART IDENTITY; To execute this query it will be
  necessary to login to the database. This is typically done through the
  command line or through a GUI interface such as phpMyAdmin. If Drush
  is installed on your server, the drush sql-cli command provides quick
  access to an SQL command-line interface.

  From the command line, with Drush installed:

  drush php-eval 'db_query("DELETE FROM `flood`");' NOTE: The query
  above will delete ALL entries in the flood table. If you want to
  remove only a specific user's entries from the flood table, the
  following is more specific.

  DELETE FROM flood WHERE event = 'failed_login_attempt_user' AND
  identifier LIKE '1234-%'; (where 1234 is the UID of the blocked user)

Source: Login blocked after 5 failed login attempts

Want to change the settings for this? You can by installing Flood control

You can cache clear if you are having admin login in any other browser using devel module or drush cr.
 You can also use Truncate command in php my admin for cache tables to get immediate user logins.


How to force the canonical URL to use http? On our page we use the Metatag module to show a canonical meta tag. In the configuration we use the [current-page:url:absolute] token. This works fine, but the problem is, that whether the page gets accessed by HTTP or HTTPS this protocol is used in the canonical URL.

For SEO purposes we want the canonical URL to be the same and use HTTP for both protocols.

How can we achieve this?

Drupal 7

You can implement hook_html_head_alter() to change head tags; the following is untested but should do the trick:

function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => &$tag) {
    if (strpos($key, 'drupal_add_html_head_link:canonical:') === 0) {
      if (strpos('https://', $tag['#attributes']['href']) === 0) {
        $tag['#attributes']['href'] = str_replace('https://', 'http://', $tag['#attributes']['href']);
      }
    }
  }
}

Call me crazy and please correct me if I'm wrong, but can't you just hard-code the URL with the HTTP?

I'm sure there's something I'm missing, but if you drop in the full URL instead of using the token, you'll end up with that particular URL as the canonical for every variation of the page Drupal creates.

The caveat is that it creates an update nightmare as you have to remember to change the canonical if the alias of the page ever changes.


Creating a custom FieldType (D8) I'm trying to create a custom FieldType which provides the fields for a complete address (street, house_number, post_code and city).

I created a FieldWidget, FieldFormatter and FieldType class and a "field"-template. (followed the guide at http://www.computerminds.co.uk/drupal-code/drupal-8-creating-custom-field-part-1-field-type and "seeing" Drupal core FieldTypes)

The widget does not get rendered unless I add an element_info()-Hook and a address_preprocess-Hook where I have to define the same stuff like in the FildWidget::formElement() method. But this is the Drupal7 way. Am I missing something?

FieldWidget class

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
{
  $element             = $element + array(
    'street'    => array(
      '#title'            => $this->t('Street'),
      '#type'             => 'textfield',
      '#default_value'    => isset($items[$delta]->street) ? $items[$delta]->street : null,
      '#required'         => false,

    ),
    'street_nr' => array(
      ...
    ),
    'zip'       => array(
      ...
    ),
    'city'      => array(
      ...
    ),
  );
  $form['#validate'][] = array($this, 'validateCompleteAddress');

  return $element;
}

FieldFormater class

public function viewElements(FieldItemListInterface $items)
{
  $elements = array();

  $elements['addresses'] = array(
    '#type' => 'fieldset',
    '#tree' => true,
  );

  foreach ($items as $delta => $item)
  {
    $elements['addresses'][$delta] = array(
      '#theme'     => 'fields_address',
      'elements' => $item,

      //'street'    => String::checkPlain($item->street),
      //'street_nr' => String::checkPlain($item->street_nr),
      //'zip'       => String::checkPlain($item->zip),
      //'city'      => String::checkPlain($item->city),
    );
  }

FieldType class

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition)
{
  $properties = array(
    'street' => DataDefinition::create('string')->setLabel(t('Street'))->addConstraint('Length', array('max' => 255)),
    'street_nr' => DataDefinition::create('string')->setLabel(t('Street number'))->addConstraint('Length', array('max' => 100)),
    'zip' => DataDefinition::create('string')->setLabel(t('Zip'))->addConstraint('Length', array('max' => 5)),
    'city' => DataDefinition::create('string')->setLabel(t('City'))->addConstraint('Length', array('max' => 255)),
  );

  return $properties;
}

public static function schema(FieldStorageDefinitionInterface $field_definition)
{
  return array(
    'columns' => array(
      'street'    => array(
        ...
      ),
      'street_nr' => array(
        ...
      ),
      'zip'       => array(
        ...
      ),
      'city'      => array(
        ...
    ),

  ),
  'indexes' => array(),
  'foreign keys' => array(),
);

}

It seems like I have to provide a custom Element class in the module\Element folder to define the custom input elements for the form rendering.

See \Drupal\Core\Render\Element\Textfield.


Customize menu local task links I am looking for a way to customize 'edit', 'view', 'delete' links.

I use bootstrap theme, but i use bootstrap v4 styles for it. I want to add 'nav-link' class to each link.

And find a way to display somewhere, not just below post title.

I couldnt find a tutorial about it. Where should i look for this? template parts (twig) or themename.theme file?

For preprocess function you can use HOOK_preprocess_menu_local_tasks(&$variables) {... where HOOK is the name of your active theme.
And for template suggestions you need to enable debugging and see with inspect element, as usual it must be menu-local-tasks.html.twig

You could create your own tpl.php! I think there should be a template file within your bootstrap theme. Copy that file to your subtheme templates folder and edit it the way you want it to look like.


Importing Group Audience data I have a site using OG7 and created groups to let users to access to some content as per the user membership and concent-type membership as well.

Each user has to belong to a group and I can select that group(s) for him/her in the corresponding Group-Audience list box when adding or editing user information.  I have also created content-types which should be attached to a group via Group-Visibility and Group-Audience Fields.  When creating content, let's say an Event, I just select in the group-audience list the group I want that event to stick to and also I choose private as the group visibility choice.

Now, the problem is that I need to import a huge number or nodes of different content types, say Events, and each one has to be associated to a group.  Currently I just import the content-type data using feeds modules (feeds-import) using a CSV file and once in Drupal I do the group associations by hand. I cannot find a way to import the content-type along with group association while importing the data, also I don't know how to do it directly in the database, I tried but it didnt work.  Anyone of you know how to import group-audiences? anyone knows which tables are affected when associating a group to a content-type?  Thanks in advance for your time in assisting me.

If you want to import a lot of different content types

you might want to check the Migrate Module out

It supports Organic Groups.

Migrate Documentation

// Maybe this can help you some of the way

Migrate Classes: Location CCK to Address Field

Migrate Extras

This might also give you a clue on how to do it. I know its

Migrate OG


Form type select with multiple values I have a form field with type select. The results values are taken from the database.
If the select list is with single value I'm displaying the value title on the submit like this:

   $selected_index = $form_state['values']['select_list']; //the field is select_list
   $display_value = form['select_list']['#options'][$selected_index];
   dpm($display_value); //it's showing the selected option value title.

When I'm using '#multiple' => TRUE; into the form field, It's showing error: Warning: Illegal offset type in...

How can I display the titles of the multiple values?

EDIT:

This is my code:

function mymodule_page($form, &$form_state) {

global $user;

$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid and type = :type', array(':uid' => $user->uid, ':type' => 'outlets'));

$droplist = array();
foreach($result as $record) {
    $title = $record->title;
    array_push($droplist, $title);

    $form['select_list'] = array(
       '#type' => 'select',
       '#title' => 'Select list',
       '#options' => $droplist, //I'm getting this list from my database
       '#multiple' => TRUE,
   );
}

function mymodule_submit($form, &$form_state) {
   $selected_index = $form_state['values']['select_list'];

   foreach($selected_index as $key => $sindex)
   dpm($sindex);
}

In case of multiple values, the return value is an array of all selected values. Therefore, $selected_index is now an array and not a string.

When you use multiple the value of field  is array instead of only one value
you can get them :

  $selected_index = $form_state['values']['select_list']['und']; //the field is select_list
  $values=array();
  foreach(  $selected_index as $sindex){
   $values=$sindex['value'];
   //dsm($sindex['value']);
}


Custom form to modify only some fields of an EntityForm I generated an Entity following this guide. Now I would like to create a custom form to modify only some fields inside a single entity.
I was thinking to create an action inside the controller calling a new/custom form:

I created the routing file to open the form with the specified path (I know I can also create an action inside the controller to open the form with a custom template)
I created the form that extends the main EntityForm:

class DetailedForm extends CompleteEntityForm{
    public function getFormId() {
       return 'detailed_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state){
        $form = parent::buildForm($form, $form_state);
        return $form:
    }
 }

I put some lines of code inside the functions getFormId(), buildForm(), validateForm() and submitForm().

But in the end the result is an error:

  Call to a member function getEntityTypeId() on null in
  \drupal\core\lib\Drupal\Core\Entity\EntityForm.php on line 79 #0
  \drupal\core\lib\Drupal\Core\Form\FormBuilder.php(196):
  Drupal\Core\Entity\EntityForm->getBaseFormId()

Any suggestions?

Based on the comments on the question, I fixed my issue.

I created the routing path to call the controller:

mymodule.manage_detailed:
  path: '/mes-detailed/cp/{eid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DetailedController::manageAction'
    _title: 'Detailed'
  requirements:
    _permission: 'access content'

Controller:

class DetailedController extends ControllerBase implements ContainerInjectionInterface {

public function manageAction($eid) {

    $entityForm = \Drupal::entityTypeManager()
        ->getStorage('main_entity')
        ->load($eid);
    $finalform =  $this->entityFormBuilder()->getForm($entityForm);

    $render['form'] = $finalform;

    $render['#theme'] = 'manage_detailed';
    return $render;

}

}

Then I put inside the template all the form with:

{{ form }}

Because using only some fields inside the template didn't allow to save data.
And finally I create the submit function to define the redirect:

public static function manage_form_submit(&$form, &$form_state) {
        $url = \Drupal\Core\Url::fromUri('internal:/link-to-go');
        $form_state->setRedirectUrl($url);
    }

To call the submit function I used the alter form function inside the module file:

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

 //drupal_set_message($form_id); //to show id of the form

 if ($form_id == 'name_of_entity_form'){

    $form['name']['#type'] = 'hidden';
    $form['status']['#type'] = 'hidden';
    $form['new_revision']['#type'] = 'hidden';
    $form['revision_log_message']['#type'] = 'hidden';
    $form['field_n1']['#type'] = 'hidden';
    $form['field_n2']['#type'] = 'hidden';
    $form['field_email_']['#type'] = 'hidden';
    $form['field_nd']['#type'] = 'hidden';
    $form['actions']['delete']['#type'] = 'hidden';

    $form['actions']['submit']['#submit'][] = 'Drupal\mymodule\Controller\DetailedController::manage_form_submit';

  }
}


Building Custom Drupal Form I am trying to display a custom form with Drupal 7.

Here is what I am trying:

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

  $items['pay-online'] = array(
    'title' => 'Pay Online',
    'description' => 'Pay Online',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form_generate'),
    'access arguments' => array('access content'),
  );

  return $items;
}

function mymodule_form_generate() {

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#attributes' => array('placeholder' => 'First Name'),
  );

// ... etc, more form code

return $form;

What I am getting on the screen is a form, but it is not a 'drupal' form. It's just an array of form fields. No form id, etc.

What do I have to do in Drupal 7 to accomplish this?

You should replace

function mymodule_form_generate() {
  $form = array();

with

function mymodule_form_generate($form, &$form_state) {

I'm not sure if this fixes things for you, but that is the only thing I can see that is out of order.

You should use return system_settings_form($form).

See system_settings_form(), and what googletorp reported.


I'm creating a form in a module but when I try to add a radio group the title displays but not the options $form['todo'] = array(
'#type' => 'fieldset',
'#prefix' => '
',
'#suffix' => '
' . $image,
'thot_dialog' => array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
'
),
'add_thot' => array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => t('Add New Thot, Related to Current Thot'),
  'new_thot_nid0' => array(
      '#type' => 'hidden',
      '#default_value' => "",
  ),
  'new_thot_name' => array(
      '#type' => 'textfield',
      '#title' => 'Name Your New Thot:',
      '#default_value' => 'Type Name Here',
  ),
  'new_thot_rel' => array(
      '#type' => 'select',
      '#title' => 'Select One:',
      '#options' => $t_rels,
  ),
  'new_thot_reverse' => array(
      '#type' => 'checkbox',
      '#title' => 'Reverse the direction?',
      '#attributes' => array('#id' => 'new-thot-reverse'),
  ),
  'new_thot_options' => array(
      '#type' => 'radios',
      '#title' => 'Choose One',
      '#title_display' => TRUE,
      '#options' => array(0 => 'Create the Thot', 1 => 'Edit the Thot (Add text, etc.)'),
      '#access' => TRUE,
      '#default_value' => 0,
  ),
  'new_thot_submit' => array(
    '#type' => 'submit',
    '#value' => 'Submit Thot',
  ),
);

Your #options setting only has keys, but no values. You need something like

'#options' = array(0 => t('Closed'), 1 => t('Active'));

Example from Radios form API reference.

i am getting the option for radio buttons. please check the above code or provide more detail what you want to achieve.

and you are missing one closing bracket for below code

'add_thot' => array(
  '#type' => 'fieldset',
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => t('Add New Thot, Related to Current Thot'),
  'new_thot_nid0' => array(
      '#type' => 'hidden',
      '#default_value' => "",
  ),


Trigger cron internally using PHP The server my site is on cannot use curl, wget or lynx to call the external cron address (eg http://example.com/cron/cron_key)

Is it possible to use php to 'run' the cron from inside the server.

I'm was thinking something like php -f /home/docroot/core/Drupal/Cron.php with a query string for the cron key, but I notice there isn't a query string as in Drupal 7.

I cannot use Drush since it's not installed on the prod servers.

I also cannot use a third party external cron service.

Any ideas?

a way to do that :

create customcron.php in the drupal root with the content :

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// Load cron service and run cron.
\Drupal::service('cron')->run();

$kernel->terminate($request, $response);

then run :

php customcron.php

i would not let the file customcron.php in the root because anybody could then execute it from the browser.

A simple way to avoid that is moving the file customcron.php to drupal root only for the time you execute it or maybe have an unguessable file name instead of customcron.php

In general, using Drush to run cron via drush cron or Drupal Console cron:execute drupal cron:execute would be a first suggestion.

If you are interested in command line, it's likely that Drush and Drupal Console will become valuable tools for you, so to not have them because they aren't on prod is a bummer.

There is also the concept of site aliases in drush that can work on remote servers.

Drupalize.me
Drush docs


Remove or hide the submit button on search block in Drupal 7 I need to do some custom theming on the search block in Drupal 7.

Specifically, I need to add a class to the submit button that makes it invisible and removes it from the content flow.  So:

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

Becomes...

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

I added element-invisible to the edit-actions div element.  However, I can't figure out how to do this.  What's the best practice for doing this sort of thing?

One of the standard ways to do this would be to use hook_form_alter() and add the attributes to the actions element directly:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['#attributes']['class'][] = 'element-invisible';
  }
}

You can also hide it using a php condition like this:

<?php
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
      unset($form['actions']['submit']);
  }
}
?>


Get the uri/path value of an image in the field template I have created a custom field template for an image - field--field_images.tpl.php with the following code:

<?php $url = file_create_url($field_images['uri']);
$url = parse_url($url);
$imglink = $url['path'];
?>

<?php foreach ($items as $delta => $item): ?>
<div data-thumb="<?php print render($imglink); ?>" data-src="<?php print render($imglink); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" >

<?php endforeach; ?>

currently $imglink returns the value of the root folder "www". I need to find a way to get the path to the image file associated with the field e.g "http://www.example.com/sites/default/files/image.jpg" any help with this would be greatly appreciated.

UPDATE:

I think I'm almost there. Here is the code in my field-field_images.tpl.php file:
<?php foreach ($items as $delta => $item): ?>
    <div data-thumb="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = image_style_url('thumbnail', $img_src); print ($link);   ?>" data-src="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = file_create_url($img_src); print ($link);   ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ><?php render($item); ?>

   <?php endforeach; ?>

and you can see the output here: http://www.kfpa.co.za/dev/?q=node/2

The one problem is that it loops through and creates the correct number of elements for the uploaded images, but when it creates the URLs it's only creating for the item as specified for by 'x' in <?php $img_src = $element['#object']->field_images['und'][x]['uri']; i.e if I change 'x' to '2' the third photo displays. How do I change this code so that it finds the correct URL for corresponding image in the loop?

you want file_create_url().

Note: Usage of drupal_realpath() is discouraged.

Similar question: What is the alternative to drupal_realpath()?

There is drupal_realpath

  Returns the absolute local filesystem path of a stream URI.

drupal_realpath($uri)

Also there is image_style_url

image_style_url($style_name, $path)


Drupal Core Auto Update? Is there a way to update Drupal Core without reuploading files and following the UPDATE.php file?  Something similar to how you can update a Wordpress install with a click of a button?  I wasn't sure if there is a module that will allow this?

--edit--

I've attempted the "drush up" command per @Enxebre's suggestion.

I installed Drush to my shared host and it seems to be running correctly. The site is still not updating though. I checked for updates and its still at 7.22 instead of 7.23.

I also had to run an update on Drush.
Here are my results from the terminal command:

Drush self update:

drush self-update
X-Powered-By: PHP/5.2.17
Content-type: text/html

A newer version of drush, 7.x-5.x-dev (2013-Aug-06), is available.  Would you like to back up your current drush, version 4.3-dev, to /home1/munortap/drush-backups/drush/20130912205746 and replace it with the newer release? (y/n): y

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/drush.inc on line 576

Drush up:

[~/public_html/misadventureinc]# drush up
X-Powered-By: PHP/5.2.17
Content-type: text/html

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in         /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

Notice:  Use of undefined constant STDERR - assumed 'STDERR' in     /home1/munortap/public_html/drush/includes/drush.inc on line 1668

Warning:  fwrite(): supplied argument is not a valid stream resource in     /home1/munortap/public_html/drush/includes/output.inc on line 34

If you like you can use the CMS Updater module to enable automatic Drupal core updates. Find the module on drupal.org here: https://www.drupal.org/project/cms_updater

If you need more information about the service behind, lokk here: https://cms-updater.com

Excerpt from project page:

  CMS Updater module helps you to keep your Drupal site secure at all times.
  Right after a new Drupal core release is published, this is recognised by the CMS Updater Service, which in turn will update your Drupal system.

  There is no need for intervention on your part – just check your mailbox from time to time, read your PDF update, and see if the automated updates have been successfully completed (or not).

  The use of this module requires the purchase of a CMS Updater licence key for € 29.99 incl. VAT. This fee covers one year of updates - your subscription will not be automatically extended, although you will be reminded when your subscription is close to expiring. You can buy the licence key directly in your Drupal admin area under /admin/config/system/cms-updater. If you need a hand or more information, visit https://cms-updater.com.

Emphasis on price added for purpose of this answer.


How do I write a left join query? I want to get the value of "vid" knowing the node ID, and get the value of "name" for those rows where "vid" is equal to 2.

If it were a plain query, I would not know how to write it; I don't know how to write a left join query.

The "plain" SQL query in Drupal is the following:

$result = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid'=>$nid));

The equivalent raw SQL query is the following:

SELECT did, name FROM taxonomy_index as ti LEFT JOIN taxonomy_term_data AS ttd ON ti.tid = ttd.tid WHERE vid = 2 and nid = $nid

$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute();

while ($term = $terms->fetch()) {
  // $term contains the object for the taxonomy term.
}

//Don't forget "fetchAll()" function:

$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute()
  **->fetchAll();** // an array of objects

**$i = 0;
while ($i < count($terms)) {
  $terms[i]->...
  // $terms[i] contains the object for the taxonomy term.
  $i++;
}**


Form api: Combine two text fields into a div? Using the form api is it possible to combine two text fields onto the same row?

E.g. form

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  )
  // ...
  return $form;
}

Desired output

Range

  <input name="min" /> to <input name="max" />

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
     '#suffix' => '
',
  )
  // Remaining code
  return $form;
}

There's a module that may be of assistance: Field Collection (7.x)


Adding a custom js file to a core theme like Seven I've copied over the Seven theme to my /theme folder on Drupal 8 and I'm trying to customize it by adding in my own js file called custom.js. I added it to the seven.libraries.yml file as shown below, but I don't see it loading up on any of the pages. I even did clear the cache. Nothing shows up. I did add a custom.css file and that is showing. What could be wrong or that I'm missing?

global-styling:
  version: VERSION
  js:
    custom.js: {}
  css:
    base:
      css/base/elements.css: {}
      css/base/typography.css: {}
      css/base/print.css: {}
    component:
      css/components/admin-list.css: {}
      css/components/content-header.css: {}
      css/components/breadcrumb.css: {}
      css/components/buttons.css: {}

Asset injector has been made specifically to carry out the functionality that you stated. Simply install the module & flush cache.

Within configuration you'll see the link Asset injector and there you can select the theme to add your custom CSS/JS.

Hope that helps!

Actually it was indeed working after I read up on the following about how to declare these assets: https://www.appnovation.com/blog/how-add-js-and-css-assets-drupal-8-theme

In one of my previous posts I wrote about creating a Drupal 8 theme and declaring assets (JS and CSS) associated with it. Recently there were a few changes in Drupal 8's core and the way these assets are served to a theme or a module. Drupal 8 introduces a concept of asset libraries for JS and CSS in themes and modules. One of the recent core updates was about changing the way these assets are attached to the theme .In this post I wanted to go over a few practical examples of how these assets can be added and customized. Here are some scenarios:

Through a global library
Deleting or overriding existing styles served by core
Declaring various dependencies that are provided by Drupal 8's core
Specifying assets scope or sending JS to the footer
Specifying media type
Adding external CSS or JS library, e.g: Google Fonts
Adding conditional CSS or JS for older IE browsers
Adding custom libraries to specific pages, e.g: front page
Global styles and scriptsIn the example below global-styling is a name of a library (a file or collection of files) that is used for global styles. It is declared in a theme_name.libraries.yml and then also added to the theme_name.info.yml file. This specific library will now be available across the whole site.Here is how it will look in the theme_name.libraries.yml file.
global-styling:
version: VERSION
css:
theme:
css/style.css: {}

Then it's declared in the theme_name.info.yml file.
name: Example
type: theme
core: 8.x
libraries:
- theme_name/global-styling

Declaring scripts would be very similar. In the theme_name.libraries.yml
global-scripts:
version: VERSION
js:
js/script.js: {}

Then in the theme_name.info.yml file, we add these libraries.
name: Example
type: theme
core: 8.x
libraries:
- theme_name/global-styling
- theme_name/global-scripts

Now these two libraries or collections of JS and CSS files are available across the whole site. These two separate sets of CSS and JS can also be combined into one library.
global-styles-and-scripts:
version: VERSION
css:
theme:
css/style.css: {}
js:
js/script.js: {}

Deleting or overriding existing styles served by coreIn the theme_name.info.yml file:
stylesheets-remove:
- normalize.css

or to override the core's stylesheet:
stylesheets-override:
- normalize.css

Declaring dependenciesBy default Drupal 8 doesn't load any additional scripts. For example jQuery is not loaded, but it can be declared as a dependency. For all core assets look into /core/assets/vendor. You will find modernizr, jQuery and other useful things in there.Example of declaring a dependency.
global-scripts:
version: VERSION
js:
js/script.js: {}
dependencies:
- core/jquery
- core/jquery.once
- core/modernizr

Specifying scope of a JS file or sending it to the footerThere are many cases when it would be best to have a JS asset at the footer of the page. By default they will be included in the header but you can easily send them to the footer by specifying the scope in the theme_name.libraries.yml file.
js/script.js: { scope: footer }


Exposed filters with dropdown selections I have a project where I've created a View with some basic information, showing for example Year, Manufacturer, Product Type. They are all custom text fields. I can expose a filter on them which lets me manually enter in a search, for example, 2008 for year and it correctly shows me all the entries for 2008.

Is there any way to have these fields available as a dropdown selection based on the content saved within each node, eg so that the Year field shows 2001, 2002, 2003 ..... 2012 etc, or Product Type shows "Table, Chair, Lamp etc" that the user can choose from? I'm fairly new to using Views and struggling to find an answer.

I'm using Drupal 7 and Views 3.3.

The problem here is that the fields are custom text fields. If the "product type" field was of the type "List (text)" instead it would be a drop down in Views when exposed.

Maybe the product type would be good to have as taxonomy terms instead? Then product types could easy be added to the vocabulary as the site grows. The field in your content type would then be a "Term reference" to the Taxonomy vocabulary product type. If the product types rarely or never change you could stick with "List (text)"

I would probably make the field year into a date field or taxomomy, or list (integer).

I hope you see where I am trying to go here, the fields needs to be of the correct type for Views to be able to interpret the fields correctly and "automatically" give you dropdowns when the filters are exposed etc.

Found a solution. Worked for me.Check it here. http://bryanbraun.com/2013/08/06/drupal-tutorials-exposed-filters-with-views


Differences between Location and Location CCK? Location has three modules: Location, Node Locations and Locations CCK

What are the primary differences between them? Are there any advantages to using Node Locations over the Locations CCK?

Thanks!

Location: provides the Location API; handles address storage and geocoding. Essentially the base of the location module to which the other modules rely upon.

Location CCK: provide a Location behavior as a CCK field. This module uses the field API properly rather than its legacy node location module which implemented its own fields and storage.

If you are evaluating which one to use, I would recommend the cck one. The others are being deprecated soon.

Via the project page:

  Location 7.x-4.x is planned to be a stripped out version of location
  7.x-3.x, which has no node location, user location, location taxonomy (at least in its curren form), location add another sub-modules. It
  will only have location field, which will essentially be the current
  location cck module.

The Location module allows real-world geographic locations to be
  associated with Drupal nodes, including people, places, and other
  content.

  Location: provides the Location API; handles address storage and
  geocoding. Allows users to attach locations to nodes.

  User Locations: allows admins to associate locations with users.

  Location CCK: provide a Location behavior as a CCK field.


What is the basic concept behind hooks? I am intermediate in PHP. To polish my skills I start learning Drupal 7. While learning Drupal architecture concepts, the terms hooks and bootstrapping puzzled me a lot. I read the "Pro Drupal development" book, and some documentation on drupal.org, but it is so advanced for me to learn how hooks work in Drupal to display the web page.

Can anyone tell me what hooks are in simple words?

The other answers are great, accurate, detailed, but I'm not sure they're the "simple words" explaining the bare bones of the concept that the asker was looking for.

I think of hooks as a point where the code pauses and shouts "Anyone else got anything to add here?". Any module can have a function that replies to this, and gets triggered with appropriate data passed to it at that point in the code.

A nice straightforward example is hook_node_delete(). Any module can use it to make things happen every time a node is deleted. The docs tell you this hook passes the module the object of that deleted node to work with, and outlines other useful information such as about the exact timing of when it's called (e.g. that it is before the node data is actually deleted from the database), and where in Drupal's code the hook is called (which can be more than one place).

You can explore what hooks exist and find out what data is passed to them by exploring things starting with "hook_" in the Drupal api.

Hooks work by a name conventions: using hook_node_delete as our example, when the node deletion process reaches the point where the hook is called, for every module with a function like this [modulename]_node_delete() where the word hook in the hook's name is replaced with the module's name (e.g. my_amazing_module_node_delete() ), those functions get called.

Why? So any module can do anything at these key points: for example you could look at the deleted node and do things if it meets a certain condition (say, email an administrator, or launch some long process).

Some hooks let you alter things that have been generated just before they're processed. For example, hook_menu_alter() passes you the current menu items that the system has generated. Any module can define a function some_modulename_menu_alter() and look at them, optionally change them (delete some, add some, sort them...), and pass the newly altered menu back in.

It's simple, really powerful and is at the heart of how Drupal works as a modular system. Implementations of hooks are at the heart of most Drupal modules.

When looking through the code of a Drupal module, you can spot which functions come from hooks (as opposed to functions that are simply called from within the module code itself), as the Drupal community enforce a convention whereby each implementation of a hook has a comment in front of it like this (note the "Implements hook_..." bit):

/**
 * Implements hook_some_hook().
 *
 * Some descriptive summary of what this does
 */
function my_amazing_module_some_hook() {

Some modules that act as APIs define their own hooks. For example, Views defines many hooks that allow you to add to, read and edit data at various points in the process of creating or displaying a view. You can find information about hooks created in custom modules from two places (assuming the module follows conventions etc):

The code and comments in the modulename.api.php file in the module folder
drupalcontrib.org - for example, here's their list of D7 modules they have info on, and here's their page of Views hooks

Bootstrapping is, as others explained, basically booting up - I won't duplicate the other good clear explanations.

You have a lot of answers above but i want to give an answer in much simpler way to understand the very basic concept behind hooks.
Hooks are actually built in functions in drupal core to manage different things & done different jobs in core, you can synchronized your own functions with these built in functions of drupal core to add their functionality in your own functions by calling different hooks.

I hope you will get the point!


How can I uncollapse a footer menu? I'm theming with Boostrap right now in Drupal 8 and created a footer menu with a bunch of links. The menu is displaying collapsed right now, but I want it to be uncollapsed and display like a default navbar.

While bootstrap displays as collapsed

Edit all of your footer's child menu links and check-mark on each of them show as expanded.


Add a block to a region How can I add a block to a region using Drush?

I'm using Drupal 7.0 and Drush 4.3.

The Drush extras project has commands for administering blocks.

Short instructions (following their README.txt):

Install this Drush add-on:

drush dl drush_extras

Determine desired module name and delta of block, and the desired region name and weight for adding the block:

drush block-show

Add the block to the region:

drush block-configure --module=block_module --delta=block_delta \
  --region=region_name --weight=-12

More instructions via:

drush help block-show
drush help block-configure
drush help block-disable

I think you maybe asking the wrong question here. I think your question might be - "how do I automate deployments to include blocks being placed in regions"?

In this case you have a few options, I would recommend:

Use panels and the page manager (currently on alpha 3)
Add blocks to a page layout and get this exactly how you what it. Views etc can also be added to the layout
Export the pages to features (current just hit beta 2 for drupal 7)
The feature can optionally have dependencies on other modules that may provide blocks for you module
On deploy, revert the feature to enable the dependent modules and place the blocks in the right spot on the panel layout

I prefer this approach as it keeps your entire site layout in code, thus making it able to be stored in version control, and of course deployable to your production web servers with little hassle. Roll back is also made easy.


Force redirect back to password form until password got set after one-time-login When my users click on a one-time-password-reset link then I log them in and then show them a page where they can choose their new password.
Problem is that there are two additional links on that page (one for dashboard and some other one) and they can click on them and visit the linked pages.

I want that until they change their password they cannot navigate to other pages. For now I managed to set a custom value in $_SESSION, but I can't figure out how I can intercept their further request (once they land on password change page). How can I check for such a session value and redirect them back to password-reset page (if they haven't changed their password yet) and allow them to navigate to other pages only after they changed their password?

You should be able to use hook_init to check for your custom $_SESSION variable (along with other conditions), and then leverage drupal_goto() to send the user back to the password change page.

Rough example:

function MODULE_NAME_init() {
  // Check that the session key exists.
  if (!empty($_SESSION['my_special_session_key'])) {
    // Check to verify the path the user is currently visiting is not the
    // password change form, or related path.
    // This needs to be customized according to your needs.
    if (arg(0) != 'user' || arg(1) != $GLOBALS['user']->uid || arg(2) != 'edit') {
      drupal_goto("user/{$GLOBALS['user']->uid}/edit");
    }
  }
}

You'll also need to unset that $_SESSION key after the user successfully changes their password. You'll likely want to do this using another hook related to the password change form.

Usinghook_form_FORM_ID_alter to add a custom submit callback to the form is a reasonable choice.

Here is an example that adds the submit callback to the user's edit form if the $_SESSION key exists.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state) {
  if (!empty($_SESSION['my_special_session_key'])) {
    $form['#submit'][] = '_MODULE_NAME_unset_session_key';
  }
}

/**
 * Custom callback for removing the special session key.
 */
function _MODULE_NAME_unset_session_key() {
  unset($_SESSION['my_special_session_key']);
}

Hope this helps.

I did similar years ago in 7 using rules + roles although obviously you could do it in code too. Once they've done what you want them to do then you assign them a different role, until then they will always get redirected back to the page you want.

I'm only answering from vague memories so initial thoughts are you may need to store the password hash before and check to ensure it's changed after, YMMV, IANAL, etc.!!


A way to make one Drupal site act like several sites I would like to create several sites each with same number of features (content types) but the ability to select different theme.
If I go with multisite feature of Drupal I will have difficulty in setting up and managing all the sites.

I can achieve different sites with Organic groups. But the spaces module is pretty much not working and needs serious development for 7.x version. I tried with all the patches but still it gives me a lot of trouble.

My requirements are more or less same as OpenScholar distribution but I would rather like to use Panopoly (panels) than boxes and context.
Also Openscholar has way too many features that I dont care of and exerts some serious load on the server.

Are there any alternatives to spaces module? Any help would be appreciated. a Case study perhaps.

Have you looked at the Domain Access project?


How to order views by taxonomy term name? for some reason the sort criteria by taxonomy term field do not work properly.

This is the view:

Here you can see the field I order by.
The options of the field is the default. Only one taxonomy term per node.

And this is the result:

As you can see the '2005' node is at the end and not a the start of the view's result.
I have no idea why this happened.
I tryed to delete the node and create a new one, delete the taxonomy term and recreate this but nothing happned.

Can someone help me to understand what is happening? I do not want to add queue module and order the view by queue order..

NEWS

SELECT ... ORDER BY field_data_field_edizione_field_edizione_tid ASC
The view order by tid and not by weight T___T
Now I understand what is the problem.. how can I create a new views sort criteria?

Solved!
I create a relationship beetween the nome and the taxonomy term using the term weight to order the nodes ^^
Now it works!

Thank you Mołot to let me see the SQL query ^^

You can also do this without creating a view. Within your template.php file, you can do the following.

function yourthemename_preprocess_page(&$vars) {
    if($vars['node']->field_services['und']) {
    // Create an Array
    $termresult = array();
    // Iterate through the tids, load their names and add to our array
    foreach ($vars['node']->field_services['und'] as $termobject) {
      $term = taxonomy_term_load($termobject['tid']);
      array_push($termresult, $term->name);
    }
    // Sort the returned array
    sort($termresult);
    // Print them out based on our new sorting.
    foreach ($termresult as $termobject) {
      $vars['terms'] .= "<li>".$termobject."</li>";
    }
  } else {
    $vars['terms'] = "";
  }
}


How can I make SMTP plugin work with multiple languages? I'm using the SMTP Authentication Support plugin for mail from my Drupal 8 server.

Sending mail from a webform works fine as long as the visitor is using the default language, which is English. It does not send when using any other language.

The message in the error log is not helpful:

  Error sending e-mail from email@site.com to email@site.com: SMTP Error: Could not connect to SMTP host.

This makes no sense to me. How can it not be connecting, when the same connection information is ok on English?

How can I resolve this? Here's what I've tried to do:

I've asked for support on SMTP's issues page, but have not received any response yet.
Set the language detection up two different ways: by domain or by URL. Same result on both.
Tried two different SMTP servers, with the same result on both.
Tried SSL and standard protocols for SMTP.

The problem is that the parameters are not translatable. In my case it has been solved by overriding the values of the port and protocol variables in settings.php.

$config['smtp.settings']['smtp_port'] = '587';
$config['smtp.settings']['smtp_protocol'] = 'tls';

Just for someone who is using Drupal 7 to fix the same issue, because this module's Drupal 7 version does not even have that stupid smtp.schema.yml file. For Drupal 7, go to /sites/all/modules/smtp and in that folder, edit the file called smtp.phpmailer.inc. Find out "Sets connection prefix." and change the "public $SMTPSecure    = '';" into "public $SMTPSecure    = 'ssl';". Then remember to clear the cache and reenable the SMTP module.


Programmatically set date fields in Drupal 7: Date, Date (ISO Format) and Date (Unix Timestamp) Using the Form API and hook_form_alter(), how can I manually set (force) the values for each of Drupal 7's date field types using a valid Unix Timestamp?

When the form is finally submit the field_date types are always empty arrays.  Below is the broken code I'm working from.

hook_form_alter(&$form, &$form_state, $form_id) {

    // http://drupal.org/node/1455576 - Date
    $form['field_date'][LANGUAGE_NONE][0]['value'] = time();

    // http://drupal.org/node/1455576 - Date (ISO Format)
    $form['field_date_iso_format'][LANGUAGE_NONE][0]['value'] = time();

    // http://drupal.org/node/1455576 - Date (Unix Timestamp)
    $form['field_date_unix_timestamp'][LANGUAGE_NONE][0]['value'] =time();
}

I should mention the fields widget is set to text and it's format is 'Y-m-d H:i:s'

I have also tried date('Y-m-d H:i:s', time()) instead of time().

Example dpm() output.

I should also note that as a workaround I can set the field if I modify it in hook_node_presave().  To do this I set $node->field_date['und'][0]['value'] = date('Y-m-d H:i:s', $my_unix_timestamp); I would still like to understand how to do this using hook_form_alter instead.

Here is a code that treat site timezone right for me:

 $node->field_date[LANGUAGE_NONE][0] = array(
    'value' => format_date(strtotime('now'), 'custom', 'Y-m-d H:i:s', 'UTC'),
    'timezone' => 'UTC',
    'timezone_db' => 'UTC',
  );

used time() and worked OK....

$fc_item_wrapper->field_data_pedido->set(time());


Theming Form Fields: Alter all fields In Drupal 7, you can put the following code in template.php to add the class 'vr-paragraphs' to the field called 'field_title'

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
       $form['field_title']['#attributes']['class'][] = 'vr-paragraphs';
}

How can I modify this code to target all fields on the form and not just 'field_title'.

Also, this code only adds the class to the form-wrapper part of the filed. How can I alter the label part?

Thanks for any help!

When you need to find the child items present in a form, you need to use element_children(), as Drupal functions like filter_process_format() do.

The reason is simple: In a Drupal form array, as well as in a render array, not all the keys are child items; those keys with a name that starts with # are properties. Consider, for example, the form returned from forum_form_forum(); if you loop through it with the following code, you would add values where you should not.

foreach($form as $key => $value) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

In fact, $form['#submit'] is not a child item, nor is $form['#theme']. In particular, when your code will be executed for the last key, you would get a PHP error. $form['#theme'] is a string, and $form['#theme']['#attributes'] would select a character of that string, supposing that '#attributes' would be evaluated as the integer 0; even in that case, $form['#theme']['#attributes']['class'][] would not be a valid PHP construct.

The correct code would be the following one.

foreach(element_children($form) as $key) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

Implement a for loop over each form field to add the class.
eg.

foreach(form as $key => $value){
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

You may have to check if it is actually a field though, maybe by checking if $form[$key]['#title'] is set.

If I remember correctly, the label is usually taken from the '#title' of the field.


How to set type="email" attribute on a Drupal form textfield I'm doing some mobile forms with Drupal and have an email address textfield that currently has type="text" in the resulting HTML. I'd like this to be type="email" instead so that iOS shows a more useful keyboard when entering the email address.

I tried adding:

"#attributes" => array("type" => "email")

to my field but it seems to just get ignored by Drupal. Is there a correct and/or supported way to achieve this?

Elements which are input[type=email] are a builtin as of Drupal 8. They can be added (along with other HTML5 elements and markup) to Drupal 6 or 7 via the Elements module.

As of writing this answer, I found the Element-module docs quite scant; they don't explain that the method for getting an e-mail input-element is slightly different than how it's done in D8. For Drupal 7:

/**
 * Implements hook_form().
 * "For long-lasting relief you can count on!"
 *
 * hook_form() functions are passed a form-node,
 * plus extra state-info if present.
 *
 * At the end of the function, the form-node should
 * be returned to the caller.
 *
 */
function mymodule_form($node,&$form_state) {

    $node['primary_email'] = array(
        '#type' => 'emailfield',
        '#title' => t('Submitter'),
    ); // in Drupal 8, it's '#type' => 'email'

    return $node;
}

Be sure to have the Elements module enabled before you expect the above to work. Also, if you haven't already, you'll also want to make the form accessible by doing something like:

/**
 * Implements hook_menu().
 * "Money back guarantee!"
 */
function mymodule_menu() {

    // create primary menu-entry for module:
    $items['mymodule'] = array(
        'title' => 'My Very Own Module',
        'page callback' => 'mymodule_description',
        'access callback' => TRUE,
        'expanded' => TRUE,
    );

    // create menu-entry for form:
    $items['mymodule/myform'] = array(
        'title' => 'My Very Own Form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('Behold, the form.'),
        'file' => 'mymodule.module',
    );

    // ...[maybe add more stuff here]...

    return $items;

The other elements made available by Element are listed at cgit.drupalcode.org/elements/tree/elements.module#n7.

on Drupal 7 you can:

 $form['msg'] = array(
   '#type' => 'text',
   '#attributes' =>array(
     'placeholder' =>  'some text' ,
     'required' => "" ,  //required field
     'type' => "email" ,
   ),);


drupal 7 + services 3 - inserting nodes with select fields I'm using Drupal 7 + Services 3 to create nodes with POST and JSON. Everything works fine, except field types of select - entity reference select or plain text.

The entity reference uses the autocomplete widget, while the text select is a plain radio button.

This is the format I'm using:

"field_urgency": {
    "und": [  {  "value": 1    }   ]
}

Eventually I figured this out:

    {
    "title": "some more tests",
    "type": "weed",
    "field_sprouts": {
        "und": [ 8,9 ]
    },
    "field_urgency": {
        "en": [
            {
                "value": "2"
            }
        ]
    },
    "field_species": {
        "und": [ 4 ]
    }
 }

species and sprouts are entity references and only need the nid of the target (no value= or target_id= or anything).
For unknown reason (as of yet), the urgency field required a language to be defined (other then und[efined]). Its the only select field here with a normal select list, not entity refernce.
Make sure your widgets are select list and not auto complete.

The PUT format for boolean or select list :

{
  "field_order_status":{
    "und":["1"]
  }
}

it would be ok.


CKEditor simple image upload functionality I'd like to have a simple, one-click, image upload functionality with CKEditor. I'm using D6 and CKEditor 3.6.1. I do not want a server file browsing functionality, only uploading images from the user's own computer.

I've done a thorough search on this subject and have tried different suggested approaches. It seems like the solution that best suits my needs is installing the IMCE module and the CKFinder plugin for the CKEditor module. So I did just that, and followed the installation instructions found here: http://drupal.org/node/738092

The uploaded image manages to get to the destination folder on my server, but when I open CKEditor's 'Image properties' dialog and hit the 'Send to the server' button, nothing changes on the UI.

What I wish to happen is for CKEditor to close the 'Image' dialog and insert the uploaded image into the textarea.

Here are some screenshots to better explain my situation:

- Uploading a file from my desktop

- Expected result - 'Image' dialog automatically closed and image inserted to textarea

- Actual result - 'Image' dialog stays open and nothing changes

Does anyone ever implemented an image upload functionality this way? Is there a better way to get what I want?

If you ever get to D7, this module does exactly what you're looking for:

One Click Upload module

  Button for BUEditor and CKEditor which allows upload files in one click.

  Features

  Upload images and insert into editor image code
  Upload files and insert into editor link code
  Multi-upload files and images
  Integration with image styles
  Editable html templates

To upload an image, simply drag-and-drop from your desktop or from anywhere. You can also copy the image and paste it on the text area using ctrl+v.


How to display custom table without using views? I have tried it to display the table by using core PHP concept and it display the table but at the top of the page now i need to display inside my page my current display is below

and my code for view is

function testing_db_viewall($form, &$form_state){
    $result = db_select('infobox_new')
    ->fields('infobox_new', array('name','emailid','contactno','nid'))
    ->execute();

    $entries = $result;
    $output ='';
    $rows = array();

    foreach ($entries as $entry) {
    // print_r($entry);
    // echo "<br>";
        $rows[] = array( $entry->name, $entry->emailid, $entry->contactno, l('edit','examples/edit/'.$entry->nid), );
    }
  // Make a table for them.
    $header = array(t('Name'),t('Email id'), t('Contact No'),t('edit'));
    $output .= theme('table', array('header' => $header, 'rows' => $rows));

     echo $output;
}

I want to display my table after my title i.e. "Custom Table View"

Thanks in advance

Instated of "echo"

  echo $output;

You have to write

  return $output;

My issue has been resolved

I made silly mistake in my menu creation link.


How to setup event registration and paypal payment? We have events and we take registrations for them. Entity Registration module is installed for that purpose and it's working great. Now, since those events are paid events, we want to implement PayPal payment method as well.

The problem is we need to combine the registration process and the paypal payment into one process. That said, user should click the button Register & pay and that should do 2 things:

Register the user for the event (this is already working as a part of Entity Reg module)
Redirect the user to PayPal payment gateway

Any suggestions on how to achieve this?

You should use Registration Commerce module. This module acts as a integration point between entity registration and drupal commerce enabling you to implement paid registration using entity register. Also use Commerce paypal for paypal integration with drupal commerce.

I think the Commerce Paypal IPN Rules integration module should fit your requirements. Here is a quote about it (from the module's project page):

... comes to give modular capabilities for Paypal IPN handling.
Combined with Drupal Commerce, Rules and the Paypal payment method, using this module you will be able to change your site workflow and logic.
As an example, while the "Commerce subscription products PayPal" integrates with the IPN to start/stop user subscription, but depends on specific user fields and content types, in this module you will be able to achieve the same, but for your own selected fields, content types, etc.


Permission for anonymous user I got custom registration form under /user/register URL but anonymous user gets denied access what type of permissions should I set.
 I tried:

 requirements:
   _permission: 'access content'

and

requirements:
   _permission: 'none'

or I deleted it completly but it didn't help.

'access content' should be good in general, check it under "people/permissions" to seem if also anonymous users have right to "access content".
You can also declare:

_access: 'TRUE'

In this case you don't need the permission part, this one should definitely work!

Try this.

  requirements:
    _role: 'authenticated'

or use the User service.

  requirements:
    _user_is_logged_in: 'TRUE'


How can I display the of result count of a view in its header? Without writing using any Drupal db functions, how can I display the total/count/number of results of a view in its Header?

Do you not mean these predefined value(s) in the Header area ?

Return a view's total_rows in Drupal 7 without php filter?

You could count the number of rows using PHP in views_pre_render() ... but I bet this is what the above is doing already ....

Warning: this tip requires enabling the core PHP Filter module, which opens up security concerns that could potentially allow the entry of PHP code into the site in ways that you may not want, if permissions are not configured correctly.

Here is how using the core PHP Filter module:

In your view, add a header element of type Global PHP
Then add this snippet to text/php field in the header

<?php echo $view->total_rows; ?>

That should do it. There are a tonne more variables in the $view array.

Edit: As @Motot suggested, added security note.


Modify data structure of a view REST export I need to build a sitemap.xml with a REST export with a view.
By default I get this data structure with a REST export.

<?xml version="1.0"?>
  <response>
    <item key="0">
      <field1>...

How can I modify the tags of this structure? I need to get this tags.

<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>...

These tags must be changed.

<response> > <urlset...
<item> > <url>

Do I write a custom serializer for the REST export or a specific encoder? How do I proceed?

In D8 you need to create custom serializer and encoder to alter the XML tags.

Create custom serializer
Ref :  https://gist.github.com/BERRAMOU/dd21e009eec0e3d98733e78360122892
Write custom encoder

-

namespace Drupal\custom_serializer;
use Drupal\serialization\Encoder\XmlEncoder as SerializationXMLEncoder;
use SimpleXMLElement;
 /**
 * Encodes xml API data.
 *
 * @internal
 */
class myXMLEncoder extends SerializationXMLEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['myxml'];

  /**
   * {@inheritdoc}
   */
  public function getBaseEncoder() {
    $base_encoder = parent::getBaseEncoder();
    $base_encoder->setRootNodeName('jobs');
    return $base_encoder;
  }
}

Then in View under 'FORMAT' you will see both options.
After save, you should get XML with required tag.


How to log to console when in a Drupal attach behavior? I'm using Drupal 7. I have the following code that tries to log to the console:

function mymodule_get_jquery() {
  $jquery = <<<JAVASCRIPT

  console.log("here");

  (function($) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery);

JAVASCRIPT;

  return $jquery;
}

If I open the Console in Firefox or Chrome, the log outputs the following:

JQMIGRATE: Migrate is installed, version 1.4.1
here
there

Why isn't the "everywhere" line getting logged? Is there any way to log JavaScript info in the Drupal behavior attach function?

UPDATE:

Here is how I am calling the mymodule_get_jquery() function:

/*
 * Implements hook_page().
 */
function mymodule_page() {

  /* ... */

  $jquery = mymodule_get_jquery();
  drupal_add_js($jquery, "inline");

  /* ... */
}

Drupal object should be passed as function parameter like below:

(function($, Drupal) {
    console.log("there");

    Drupal.behaviors.addHighStockChart = {

      attach: function(context, settings) {

        console.log("everywhere");

        /* ... */

      } // end attach
    } // end Drupal.behaviors.addHighStockChart
  }) (jQuery, Drupal);


Region not displaying in module I'm working on a site where much of the back-end is handled by a site-specific custom module.

I have a sidebar region and within

Within module-thing.php is a call to <?php print render($page['sidebar']); ?> to print a region but it is not showing anything despite the region being set with content within the Blocks administration. I'm wondering if this is expected to work from within a module.. is there something i can do to show it?

I found this (right at the top) but doesn't seem to work in drupal 7 http://www.chrischen.me/content/drupal-how-access-regions-blocks-themes-or-modules..

The code to print page regions must be in your theme's page.tpl.php file, not in a file in a custom module.

If you want to put your code in a separate file (sidebar.php) you need to make sure it's included in page.tpl.php, like

include './sidebar.php'; // file is in the same folder as page.tpl.php

or

module_load_include('php', 'MYMODULE', 'sidebar'); // file is in a module folder

hope it helps

I found the easiest way was to do this:

<?php
  $region = block_get_blocks_by_region('region_name_here');
  print render($region);
?>

See the docs for more information:  https://api.drupal.org/api/drupal/modules!block!block.module/function/block_get_blocks_by_region/7

In your module where you tried to print the sidebar region using the method used in a page template, use this snippet above instead. This method can also be used in html.tpl.php where the "usual" method cannot.


Loading a jQuery plugin from the Libraries 2.X module in Drupal 7? I am using the jQuery Easing plugin (http://gsgd.co.uk/sandbox/jquery/easing/) for one of my Drupal 7 themes. I see that there is a Libraries module that loads this plugin in a way that allows other modules and themes to use it: http://drupal.org/project/jqeasing.

Is this the correct way to load the library?

After loading the library, Do I need to explicitly call drupal add js from the template.php theme file? The documentation for the Libraries module for theme development is terrible. I may contribute to it, once I get this sorted out.

Yea using a module that exposes it as a library is totally the way to go.

And you certainly don't want to use drupal_add_js because drupal_add_library  [link] will do it the proper way.

And for your case:

drupal_add_library('jqeasing', 'easing');

inside the template.php file

Mytheme_preprocess_html(&$variables) { if (drupal_is_front_page()) { libraries_load("easing"); } }


Adding #ajax to checkboxes and getting selected values in callback I've been trying to use #ajax callbacks on a form. I've got this working with radio buttons, so when I've debugged the form I get the value associated with the radio button as '#value' under 'triggering_element' in $form_state; what I'm struggling with is doing the same thing with a group of checkboxes. The first checkbox checked seems to work correctly, and I can see the correct value, but if I click a second checkbox, the value doesn't come through correctly (triggering element is the field that was returned in the previous #ajax callback for some reason??) and '#value' is a string and not an array as I would have expected. Also $form_state['#values'] doesn't contain the previously selected checkbox or the current checkbox.

How do you correctly add #ajax to an element  of type 'checkboxes' and how is it possible to get the value of all checked checkboxes when the ajax callback is fired?

There is a module that can trigger an ajax callback on a form (content type) maybe that modules solves your issue http://drupal.org/project/conditional_fields.


Get all users with specific roles using EntityFieldQuery I thought this was an easy task, yet there does not seem to be a Drupal-method for this. I came as far as knowing I have to use EntityFieldQuery for this - because the API said conditions for user_load_multiple() are deprecated.

So I tried this:

  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'user')
    ->propertyCondition('rid',array(1,2,3);

  $result = $query->execute();

Yet I got this:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'users.rid' in 'where clause': SELECT users.uid AS entity_id,
  :entity_type AS entity_type, NULL AS revision_id, :bundle AS bundle
  FROM {users} users WHERE (users.rid = :db_condition_placeholder_0) ;
  Array ( [:db_condition_placeholder_0] => 3 [:entity_type] => user
  [:bundle] => user ) in EntityFieldQuery->execute()

So my first thought was, that I'd have to join with users_roles-Table and so on, but that will lead to duplicates.

Does anyone have an idea how to do it?

To be honest, I have no idea on how to achieve this. Good examples of how to use the EntityFieldQuery are hard to find. Since noone has answered this question yet and I'm also interested in the solution I'll try to help you out. Described below is my best guess.

A thing to keep in mind: roles are stored in a different table than users. They are added using UserController::attachLoad.

There seem to be three different conditions that you can use with an EntityFieldQuery:

entityCondition (Entity specific conditions:'entity_type',
'bundle', 'revision_id' or 'entity_id')
fieldCondition (Conditions on fields maintained by the Field
API)
propertyCondition (Conditions on entity properties)

The most logical option (if there is one) would be to use a propertyCondition, but as roles are added to the user in UserController::attachLoad I don't think the EntityFieldQuery has access to it. I think the EntityFieldQuery just uses the schema defined in hook_schema().

This leads me to believe that what you're trying to achieve is impossible. A workaround would be to get all the uids with a normal query:

I don't have access to Drupal right now, so the code below might be off. I'm sure somebody will edit the mistakes.

// Use $query for readability
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(1,2,3)));

$uids = $result->fetchCol();

$users = user_load_multiple($uids);

If it is possible to achieve what you want with EntityFieldQuery, I'll be enlightened.

I have no doubt this can be simplified.
This can be done though for drupal 8:

//retrieve all "VIP" members
$query = \Drupal::entityQuery('user');
$nids = $query->execute();
foreach ($nids as $nid){
    $user = \Drupal\user\Entity\User::load($nid);
    if ($user->hasRole('VIP'))
        $emails_VIP_members[]=$user->getEmail();
}
 $send_to=implode(',',$emails_VIP_members);


Views: List of recent months containing nodes Using Drupal 7, views 7.x-3.0-beta3. I am trying to make a display containing a list of links which direct users to an archive page containing posts of that month (eg. all news messages posted in march 2011).

Tried to solve this with a contextual filter 'Created year + month',
which, when no parameter is given, gives a summary list of links like 'march 2011, december 2010' linking to the URL 'news/201103', 'news/201012'.

Is there a way to change the formatting of that URL to 'news/YYYY/MM' ?

You can create path alias to make the URL look how you want, but views need the year and month as a single argument.

Replace Content: Created year + month with 2 separate contextual filters:

Content: Created month
Content: Created year


Using jQuery $.ajax() on my site won't work This is the first time for me to use the jQuery $.ajax() in Drupal. The code is a simple test code but it keeps going to the error: section instead of success:. Could my url path be wrong? The .js file and the test-ajax.php file are in the same folder named "code".

    //This is Javascript
    $.ajax({
        url: 'code/test-ajax.php',
        data: 'a=hello&b=world',
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(){
            alert('FAIL'); //Keep getting "FAIL". It's like it can't find the php file.
        }
    });

Nothing fancy inside the file test-ajax.php:

<?php
$a = $_POST['a'];
$b = $_POST['b'];

echo "$a, $b";
?>

EDIT: To avoid confusion on the paths (I keep it organized):

Main theme files: <templatename>/<.info, template.php, style.css, etc.>
Template files: <templatename>/templates/*.tpl.php
AJAX files: <templatename>/code/<PHP and .JS files>

In Drupal, JavaScript files are added via the drupal_add_js() function or in the
theme’s .info file.
A simple example of using jQuery in drupal is

    <?php
    drupal_add_js('jQuery(document).ready(function () {
   jQuery.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });
    });', 'inline');
    ?>

you have to use 'jQuery' instead of $.

How odd, I got it to work but only by using the complete URL path for the AJAX file.

url: 'http://mydomain.com/sites/all/themes/<themename>/code/test-ajax.php',

This just doesn't feel right. Is there a Drupal way of doing this instead of entering the complete URL path?


Change contact setting flood limit I want to change the contact setting flood limit, but I don't find the correct place. How I change the flood limit for sent messages?

There isn't an interface to change this, but you can do it by importing a config file. You need to get a hold of contact.settings.yml file. Default looks something like this:

default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true

You can see the flood limit and interval which you can change and then import the file using the config management system.

If you just want to change it for testing purpose (not for production!) and if you are okay with a quick-and-dirty solution (e.g. in a case were you have no drush available), you can temporarily change the following file:
/core/modules/contact/src/MessageForm.php
Here you search for a line (in my case ~196) that contains:
$limit = $this->config('contact.settings')->get('flood.limit');
You change it to e.g. 500:
$limit = 500; //$this->config('contact.settings')->get('flood.limit');
And that's it. But don't forget to bring it in its original state after testing has finished! ;)
Hope that helps.


Solr indexing on custom tables We are implementing apache solr search in drupal 7.. after installing the module if you run the index, the apache solr is returning results from the drupal tables (nodes,users,taxonomy,content type).
But we have created custom tables (example: product table) where apache solr is not able to index those table data.. how to make it index the custom created tables

There is a patch available for this. Please refer the below link

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


How to Embedd youtube video in body field (converts URLs into embedded players)? Is there a simple way to insert youtube video in body field like other CMS where you copy a youtube link in the article body and it is automatically converted into a video player in front end.

I’ve search here and some topics talk about modules but there are not drupal 8 yet.

Is there a module that can do that or Drupal 8 maybe can do that natively ?

I’ve found and tested this module which do excaly what I want :

Url to Video Filter

  This module adds a new input filter that automatically converts URLs
  for various video sharing websites into embedded players into the
  text.

Here is a screenshot of the CKEditor filter :

I’ve tested this module on multiple sites and it works very well.

Currently this module supports the following services : YouTube / Vimeo

EDIT
Now, It also supports Youtube URL with parameter like ?rel=0 (rel=0 is used to disable related videos shown at the end of a video)

Get the embed URL of the Youtube video which will be a iframe.
Place that iframe markup in body field. Use Full HTML format to allow iframe tag.
Since CKeditor is the default editor in Drupal 8, you can also use iframe tool.


How to add content filter into a content page(not in a view)? So I'm totally new with the drupal and try to wrap things around my head, which is quite overhelming at first, so my question might be a simple one for pro's.

I'm building Property Listings site where users could submit their own listings, add comments and search and view Property Listings sorted by location, type, price and etc.

So when you search the site on the Search Bar it gives you a page with all the relevant content. For example: If i search for 2bed flats at around 50k they open a page with url defined in taxonomy term"around50k". And now, i have no idea what to do to add a filter for "Location" on that page.

I could make the whole new page with a view for that exact type of listings and add whatever filters i want, however as there a hundreds of categories it would be a nightmare.

I know i could add more filters to a search bar, however i will have all Property Type menu on the site and i need *location and price* filters for each page on that menu.

Is there any functions that would create filters for content on pages or any other solution to this problem?

You probably want to add the Panels module.  There's an excellent series of screencasts on Panels/Page Manager at NodeOne.

Basically, you can use Panels and Page Manager to override paths on your site.  For example, you can override all taxonomy terms.  You can break this down however you like, such as "all taxonomy terms," "all taxonomy terms from a specific category," "one specific taxonomy term," "users with this role on a taxonomy term in this vocabulary," etc.  Then you can create Variants, which are page layouts that dictate how the content should be formatted.

Using Panels, you can take the views you make and stick them wherever you like on the site.  It will certainly take some time to learn how to set this up, but learning how views and panels work together will allow you to create very complicated sites with little duplication and certainly no "hundreds of pages" created manually.

Looks like you need to look into the search_api Module

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc. Also,
  with the Apache Solr integration, a high-performance search engine is
  available for this module. Developers, on the other hand, will be
  impressed by the large flexibility and numerous ways of extension the
  module provides. Hence, the growing number of additional contrib
  modules (linked below), providing additional functionality or helping
  users customize some aspects of the search process.


How do I delete content (nodes) that a user no longer has the right to create? Suppose a user of my site has had the right (the correct role with sufficient permissions) to create content of a certain type.

If the right (role) is taken away from them, how could I make the users content automatically be deleted? (the deletion doesn't have to be instant, eg. once a day is fine) i.e the content will be deleted from the moment they no longer have permissions to edit it or create such content.

This code gives you the basic idea:

$nodes = node_load_multiple(array(), array('type' => 'my_type'));// load node by certain type
foreach ($nodes as $node){
    $uid= $node->uid;//get the node author id
    $nid = $node->nid;// get the node id
    $author = user_load($uid);//load the author of the node
    if (!in_array('your_role', $author->roles)) { //the author has not your_role role
        node_delete($nid);
    }
}

if you copy this code in the theme_preprocess_html of your template.php, for every page it checks the nodes and its author roles and delete the node id its author has not the role.

If you need to run this code once a user role is updated, you can use Rules module :

I am not able to run this code right now, but it should work correctly. You can use devel module to correctly get the $node properties ($nid and $uid).


Security Review - Untrusted users are allowed to input dangerous HTML tags I am getting the following error in my security review:
Untrusted users are allowed to input dangerous HTML tags.

Is this because in my text formats I've got the following:
Plain text  All roles may use this format

Should I disable  anonymous users from being able to access plain text?

Also, it is saying:
It is recommended you remove the following tags from roles accessible by untrusted users.

img

Should I remove the img tag from authenticated users???? Does this mean that authenticated users will not be able to uploaded images to their site at all?

Plain text is just that, no html tags, so this shouldn't be a security issue.

Perhaps the img tag is considered dangerous because it is possible to use a specially crafted png or jpg to launch an attack against a users browser.

img tags are vulnerable to XSS attacks

Since my site required roles higher than authenticated to submit content, I simply unchecked "authenticated user" from admin/config/content/formats/filtered_html and that solved my audit report.