How do I create a route with a query string? I have tried a few things and I cannot manage to make this working.

My route is the following.

    amu_hal.publicationsPerYear:
      path: '/publications/{year}'
      defaults:
        _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
        _title: 'publicationPerYear'
        year: 2016
        route_parameters:
          url: 'default'
      requirements:
        _permission: 'access content'

The code for the controller is the following.

    public function publicationPerYear($year,$url) {
      $url=urldecode($url);
      $url .='&fq=producedDateY_i:' . $year;

      try {
        $client = new Client();
        $response = $client->request('GET', $url);
        $content = json_decode($response->getBody(), true);
        // ...
      }
    }

The request http://mysite/publications/2016?url=https%3A%2F%2FmyWS%2Fsearch%2F%3Frows%3D5%26sort%3DproducedDate_tdate%2Bdesc%26fl%3Dtitle_s%2Cen_title_s%2Clabel_s%2Cen_label_s%2CdocType_s%2CauthIdHal_s%2ChalId_s%2CstructId_i%2Curi_s%2Ckeyword_s%2Cen_keyword_s%2CauthLastNameFirstName_s%2CjournalTitle_s%26fq%3DauthFullName_t%3A(%22M%22+OR+%22e+d%22) gives the following error:

  RuntimeException: Controller "Drupal\amu_hal\Controller\AmuHalController::publicationPerYear()" requires that you provide a value for the "$url" argument (because there is no default value or because there is a non optional argument after this one). in Drupal\Core\Controller\ControllerResolver->doGetArguments() (line 165 of /var/aegir/platforms/drupal8-dev/core/lib/Drupal/Core/Controller/ControllerResolver.php).

You cannot create a route based on the query string, but you still can retrieve query string values in your code:

amu_hal.publicationsPerYear:
  path: '/publications/{year}'
  defaults:
    _controller: '\Drupal\amu_hal\Controller\AmuHalController::publicationPerYear'
    _title: 'publicationPerYear'
    year: 2016
  requirements:
    _permission: 'access content'

public function publicationPerYear($year) {
  $url = \Drupal::request()->query->get('url') ?: 'default';
}


Update entity ref field in parent form with new node created in ctools modal I have a node_add form for Foo node-type with an entity reference field to Bar node-type. I'm trying to allow users to create Bar nodes inline from the Foo create form.

So far I've been able to get the ctools modal to popup, create and process the new Bar node and dpm the new Bar-type nid. but I'm stuck on how to push that to the parent Foo form and add this new Bar node into the entity reference field.

Here's what I tried using ajax_command_append in my callback for the ctools modal, but it doesn't append the new Bar node to the entity reference field values in the parent form:

function mymodule_add_bar_callback($js = FALSE) {

ctools_include('node.pages', 'node', '');
ctools_include('modal');
ctools_include('ajax');

$node_type = 'Bar';
$node = (object)array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $node_type,
    'language' => LANGUAGE_NONE,
);

$form_state = array(
    'title' => t('ADD A NEW BAR'),
    'ajax' => TRUE,
);

$form_state['build_info']['args'] = array($node);
$commands = ctools_modal_form_wrapper($node_type . '_node_form', $form_state);

// if the form was submitted, reload parent Event-Add form
if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ajax_command_append('#edit-field-bar-und-0-target-id', '<input type="text" id="edit-field-bar-und-1-target-id" name="field_bar[und][1][target_id]" value="" size="100" maxlength="1024" value="' .  $form_state['node']->title . ' (' .  $form_state['node']->nid . ')" class="form-text required form-autocomplete" autocomplete="OFF" aria-autocomplete="list">');

    $output = $commands;
}

There are few existing modules which gives the same functionality.
 - https://www.drupal.org/project/entityconnect
 - https://www.drupal.org/project/references

If you want to handle it in custom way, fetch the field and set the default (target_id) value in the form array element and use drupal_render/drupal_render_children to convert the form element array into html and try to replace it in the front end.


Webform default value of select list I have created a website for yacht charter http://cozmoyachts.com

I have created one booking form for yacht booking using webform module and used that form on all yachts pages.
Like 45 feet yacht, 55 feet yacht and so on...

In that form there is a select list to select a yacht.

I want to change the default value of that select list according to the URL of page.

So if the visitor is on 33 feet yacht page the default value in select of booking form should be 33 Feet Yacht.

Hope I am able explain my question properly.

If you fx want to set the default value using, given it is passed as a parameter in the URL:

function hook_form_FORM_ID_alter(&$form, &$form_state) {
  $params = drupal_get_query_parameters();
  if (isset($params['my_param'])) {
    $form['FIELD_NAME']['und'][0]['#default_value'] = $params['my_param'];
  }
}

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


How to attach files to node instead of uploading? I have 2 content types, Files and Events. Files content type is used to upload files like Image, PDF, Doc etc.

Events content type has a field to attach a document which is uploaded by files content type. The requirement, in event content type I need a field called 'attach files' with maximum five attachment. On click of 'attach files' button, needs to open a page which lists all files uploaded by files content type. On hover of any files an attach button will appear and while clicking it will get attached to the event newly creating event node.

Try the Attachment Links module

The Attachment Links module provides permanent links to files attached to a node. A single, easy-to-remember URL can be used to retrieve the preferred (canonical) or newest version of a file regardless of how many versions of that file have been attached to a node.
Typically, users will want to create a "File" content type and enable the Attachment Links module for that content type. Each "File" node should refer to a single file: "Handbook," "Company logo," "Team roster," etc. Though each node could contain multiple versions of the file, Attachment Link provides permanent link to access the preferred or newest versions.

It seems you can also use the IMCE for FileField module to get the uploaded files from other content type. check this answer  posted by me.


Filtering view by the referenced field I have a content type of Company, which can have multiple Images. In the company node, i want to display a slideshow of the images which belong to the company.

For some reasons, instead of storing the images in a field of Company, i created another content type of Image, which references the Company through an Entity Reference field type.

So now i have a view of Images which i want to filter using the reference field. I tried adding an Contextual Filter, but the filter cannot find the related images, which i think because the url is transformed. For example if the company has the name The Company, the path becomes /company/the-company (i am using automatic alias).

How can i filter the images correctly in the company page? Thanks.

To get your NID back (after it has been aliased) one of the solutions here is for you:

Drupal 7 Contextual Filter on URL Alias

But first I'd make sure your view is set up correctly with a contextual filter that has a relationship to the entity reference field ...

On your "view" click "Advanced". Click the "Add" button to the right of Relationships.

Find the "Entity Reference: Referenced Entity" relationship and check the box. Click "Apply". On the next screen, click "Apply" right away unless you want to change the identifier or make the relationship required.

Once you are back to your view's 'advanced options' Click the "Add" button to the right of Contextual filter and select "Content: Nid".

Under "Relationship", ensure that the entity reference relationship you added previously is selected. Next, select "Provide default value" and then set the type to "Content ID from URL". Click "Apply".

Stolen from here: https://www.drupal.org/node/1841004


Using Contextual Filters and Panels Hi Drupalites I need some help.

1.I was using relationship to output authors personal info associated with a piece of content which i did successfully. so i was trying something else but i didnt succeed.

I created a content type called State-Capital which has a list of of States and their respective capitals and I created another Content type called Misc Project which had different project details like Cost,Project Approve and State.Now i was trying to link the state field to output the capital associated with the respective state in Misc Project content type but i cudnt.The field name for States in both content type are same.Pls help.

I am trying to learn panels so wanted to know if there is any link or material for the same

Ranjan is correct, you should add a node reference field to the Project content type so it can reference a State-Capital

In order to display any info about the state on the Project page you can use the Views 3 and Reference modules.

For this example let's say the node reference is labeled "Project Location", and the State Capital is Austin, Texas.

Here are some steps you can follow:

1) Create a View

-- Create a new view block that displays State-Capital type nodes.

2) Add a Relationship to the view

-- Add a Relationship: Content: Project Location. This will allow you access to the fields of the Projects that reference Austin, Texas.

-- Give the relationship an identifier. Let's say related_project.

-- Save the relationship.

3) Add a Contextual Filter to the view

-- Add a Contextual Filter: Content: Nid.

-- Edit the contextual filter.

-- Set the Relationship in the contextual filter to related_project.

-- Look for WHEN THE FILTER VALUE IS NOT IN THE URL.

-- Set it to Provide default value -> Content ID from URL. This will get the nid of your Project.

-- Save the Contextual Filter.

-- Add in your fields. (Title at least)

4) Test it

To test in the preview, input the nid of your Project example as a contextual filter in Preview with contextual filters:

Save your view!

5) Enable the block in your node pages

After the view is complete, configure the new block to display in content type Projects.

I hope this helps.

Updated: 2014/06/18


How to add CSS to the module? I am very new to Drupal. I have an html form and I want to create a module that take the html of the form and create a table in the database and saves the form values in database.

what i have done i have created a form with form api (with buildForm method) my form is being rendered and i have converted it into Twig template (it is being shown in twig template), but first my CSS is not getting loaded.

My library file: mymodulename.libraries.yml

bootstrap:
  version: 1.x
  css:
    css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

global-components:
  Version: 1.x
  css:
    css/baselayout.css: {}
    css/form.css: {}
    css/wisdom.css: {}

  js:
    js/jquery.smartmenus.min.js: {}
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

CSS lives one level further down in a libraries file; under system, module or theme. e.g.:

bootstrap:
  version: 1.x
  css:
    theme:
      css/bootstrap.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once


Select query for get title and url of node I need to query the database directly using php. I need to limit my query to nodes created in the current year. I know that the node table contains the date the node was created in the 'created' column and that this contains a date as a timestamp.

I am not sure how to get the current year and express it as a range of timestamps and return only nodes that were created between the two timestamps.

You don't need to make any tricks like that to compare a timestamp to the current year.

You can obtain the year of the timestamp by using the PHP date function:

date('Y', 1394010573)

will return

2014

You can obtain the current year by using the same function but without mentionning any timestamp (it will take the current date by default):

date('Y');

Knowing this, you can easily limit your query.


Problem when agreggating CSS/JS files I'm working on a small D8 site. When turning the option "Aggregate CSS files" (admin/config/development/performance) on localhost, everything works fine. However, doing so when on my test server completely breaks the site presentation, both on the front (public pages) and back-end (admin).

It appears that when this option is on, the URL for the aggregated CSS is incomplete: the filename is not present, as well as most of the path, actually. Which means I have something like:

<link rel="stylesheet" href="/dpfolder/?okfo8d" media="all" />
<link rel="stylesheet" href="/dpfolder/?okfo8d" media="all" />

(the site lives in "dpfolder", although it's temporary.)

This happens with both the admin theme (seven) and the public theme (a custom theme based on Classy).

And it only happens when the option "aggregate" is ON. When it's OFF, everything displays fine (but then the CSS files are included via @import rules in a style element, and not via a link element like above).

Any idea what's causing this?

As a comment suggested, sounds like your server does not have a writable files folder. That folder should and is by default excluded from git, you need to create it and make sure that the apache user (or whatever user the processes run as) has write permissions to that.


Create a RSS using Views of a content type How to configure Views to display a RSS feed of certain content types, which contains several articles?

I would like the RSS to have 1 news feed for 1 content type. How to config it?

I can only set the feed to display all article titles in 1 news feed, which does not make sense.

The sample XML is like this:

<news>

        <title>Some Title Here</title>
        <content><![CDATA[Some Contents here]]></content>
        <pubDate>2011-09-20 10:01</pubDate>

        <title>Another Title Here</title>
        <content><![CDATA[Other Contents here]]></content>
        <pubDate>2011-09-20 11:01</pubDate>

</news>

where the 2 articles above is in certain content type.

Following comment exchange under the question - just add a new view showing "content" of type <your_type>, tick "Create a page" and "Include an RSS feed" underneath. This will give you a feed with list of all nodes of a specific type. Then just play with all other settings to get what you need, and that's it.


Trouble with Feeds Import CSV on Localhost I'm using feeds node importer to import a csv file on my disk. It seems like no matter what I do, select the file from file system or put in the path for the file. I always get Error Message "Resource is not a file or it is an empty directory".

my localhost is at /var/www
Drupal 7 Folder: /var/www/drupal7
I stored the file at /var/www/drupal7/sites/default/files/feeds/bsif.csv
so I put the file path as public://drupal7/sites/default/files/feeds/bsif.csv
but it's not working

In the case where you manually upload the file and then map to it, try public://feeds/bsif.csv
In the case where you try to upload using your browser, it should be working fine.  It could be that you're unable to upload files in general, not just with the feeds import module.
Check your server's access to upload to /sites/default/files... it could be that only your account has access to place the file there.  Also, Apache/PHP uses a tmp directory for file uploads, so it will need access there as well.


How to use User Points for storing Quiz scores? How can I add points directly to the User Points database? I have a quiz site and would like to use the User Points module to store quiz scores, instead of creating something from scratch. I have created a taxonomy "Quiz" for such points.

Every quiz ends by showing the score made (between 0 to 100 depending on how many answers they got right). I would like to go on and store this in the userpoint database.

I am using the following code but I'm getting 2 error messages:

  Notice: Undefined variable: user in ...
  Notice: Trying to get property of non-object in ....

The code I am using is the following one:

$params = array (
  'uid' => $user->uid,
  'description' => 'Totals points from quizes',
  'points' => $percentage,
  'tid' =>127,
);

userpoints_userpointsapi($params);

Userpoints has an API.

See especially userpoints_userpointsapi() Something like this: userpoints_userpointsapi(array('uid'=>$some_user, 'points'=>9000));

You might also be interested in the Quiz module which supports Userpoints.


My ajax is altering form action/URL thus makes me impossible to read the $tid from it I am using WEBFORMS which have as the topic taxonomy terms saved as hidden fields.

Unfortunate, after attaching files using Upload button this terms are lost ('No category'), as ajax is altering the form #action URL from

/tid e.g. /19

/file/ajax/submitted/file4/form-gTwVpNbQRszArGEUS1OfuwA8WgSLJOlcWGOuS6r9D5A

I have multiple file forms

From where to read $tid?

Therefore my $tid fail to load from URL

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

    if (strpos($form_id, 'webform_client_form_') === 0) {
        $tid = arg(1);
                  $term = taxonomy_term_load($tid);
                    if (!empty($term)) {
                        $category = i18n_taxonomy_term_name($term, $language->language);
                    } else {
                        $category = 'No category';
                    }
                    $form['submitted'][$category_fieldkey] = array(
                        '#type' => 'hidden',
                        '#value' => $category,
                    );

           // UP TO 10 FORM FIELDS
            for ($i = 0; $i <= 9; $i++) {
                $form['submitted']['file' . $i] = array(
                    '#title' => t('File'),
                    '#type' => 'managed_file',
                    '#description' => t('Please upload a document or image.'),
                    '#default_value' => variable_get('file' . $i, ''),
                    '#weight' => 100,

// ADD FORM SUBJECT
            $form['submitted']['subject'] = array(
                '#type' => 'item',
                '#title' => t('Subject'),
                '#markup' => '
' . $subject . '
',
                '#weight' => -100,
            );

                );
            }

    }
     return $form;
    }

At the very end, you could use a variable_set on if(!empty(arg(1))) and retrieve it with variable_get on if(empty(arg(1))), but I'm sure there's a cleaner way.


Integrate Mathjax and generate PDF Am working on the site with Mathematical content(Drupal 6.18).
Have success fully integrated Mathjax for representing mathematical equations. But have an problem to generate PDF of same content.
The issue is that Mathjax Processes the Equations after page is loaded and am using the Print,pdf module. While PDF generation, content is pull from the database which is not mathjax Processed. Hence scrambled data!!!
Is there anyway I can preprocess the content so that the PDF is generated exactly as shown on the web.
I know there are tools to convert HTML to PDF like wkhtmltopdf but any help doing this with Drupal core will be greatly appreciated.

After finding out all the possible options for implementing mathematical equations, and considering the requirement to create PDF, I got to the conclusion that the only way to do this is using a CKeditor plugin.

There is the fmath plugin, and I found a useful link: Configuration steps.

As JavaScript is loaded after page load, it was very difficult to generate PDF on the fly.


Display Signup info in custom node template I seek help on how to display the signup's module info in a custom node template.

I have created a node template for a specific content type, but by looking the variables inside $content I cannot seem to find something useful. There are several signup variables but not one "central" that can print the whole signup info. Plus the signup variables change whether the signups for the specific event are closed or open. I was hoping to be able to use something like print render($content['signup']) but that doesn't seem possible.

I have already asked help on the module's queue but without any luck. I have found several similar problems but some of the are really old versions and others refer on views integration.

Reference:

Node templates don't display Signup link
$node->signup_view available to view template
expose signup form to views
How to display the signup status of nodes in views templates?

I have searched a lot but I am still unaware how I can include the signup info into my node template. With so many people usually templating their nodes I am weird how the solution to this problem is not available.

I would appreciate any help to the right direction. Is there anything I can test out?

You can always built your own module and implement a hook_node_view() and put this form into the node content like:

function YOURMODULE_node_view($node, $view_mode, $langcode) {
 $node->content['signup_form'] = array(
  '#item'     => 'item',
  '#markup' => render(drupal_get_form('this forms ID')),
  '#theme' => 'my_signup_form_theme' //optional
 );
}

And to get even more configurable and cool-looking you could insert this new piece of content to the "Display fields" drag and drop form of the respective content type with

 hook_extra_fields()

like:

function YOURMODULE_field_extra_fields() {
    $extra['node']['node-TYPE']['display'] = array(
         'signup_form' => array(
            'label' => t('SignUp form'),
            'description' => t('SignUp form imported to Node Content'),
            'weight' => 10,
         ),
}

And now you have

$node->content['signup_form']

in your tpl


Missing "Clean URLs" option I have a new installation of Drupal 7. I was having a problem with administrative overlay URLs having URL encodings in them, which I asked about here. Another user suggested I confirm that I have clean URLs enabled.

When I went to Home » Administration » Configuration » Search and metadata » Cleanr URLs, all I see is this:

  Use URLs like example.com/user instead of example.com/?q=user. If you are directed to a Page not found (404) error after testing for clean URLs, see the online handbook.

The message was followed by the button, "Run the Clean URL test." that seems to do nothing: The browser tells me it's loading something from the site, but the page doesn't change.

I have no options to enable or disable clean URLs.
I'm pretty sure it's disabled, because when I go to website.com/user, I get a 404.

How can I troubleshoot this?

This is a known problem in Drupal 7. The "Run the Clean URL test" button does not behave like that page says it does, and this can be very confusing. Please see "Run the clean URL test" UX is broken; basically, what it comes down to is that the logic and UX of that page is broken, but the clean URL system itself (ie. the part in Drupal core that makes clean URLs work) does not contain any (known) bugs.

If you cannot enable clean URLs (you don't see the checkbox to enable it), this means that a test has already been run, it returned a negative result, and you should check your server configuration. See drupal.org - Clean URLs for documentation.

PS. If you can, test the patch from comment #87. This patch will improve the UX on the clean url's page, but it will not solve problems with an incompatible server configuration.


l() is printing "http://node/16" when gets "/node/16" as argument This site was copied to a new domain when it started breaking. Is there some setting somewhere I need to update, so it knows how to build working URLs again?

Pass node/16, instead of /node/16.

The API reference for l() tells you that the $path argument is passed to the url() function. url() considers "/node/16" as a full URL (although the term "full URL" is not formally defined).


Importing 'alt' and 'title' fields does not work for custom image migration I'm doing a D7->8 custom migration. While images (even multiple) get imported fine via a separate file migration based on d7_file, 'alt' and 'title' tags are not migrated at all.
The images are imported via

field_galerie:
  plugin: iterator
  source: field_galerie
  process:
    target_id:
      plugin: migration
      migration: luxus_files
      source: fid

Any help appreciated!

You're only mapping the fid there - you need to also map the alt and title for them to come over:

field_galerie:
  plugin: iterator
  source: field_galerie
  process:
    target_id:
      plugin: migration
      migration: luxus_files
      source: fid
    alt: alt
    title: title


Redirect /user/login to HTTPS, all other requests to HTTP I'm using Drupal 7. The login page for my users is located at /user/login, so the default login path.  I need that page to be encrypted using SSL so people aren't transmitting their passwords in the clear.

I have Apache configured so that the site can be navigated either over HTTP or HTTPS.  However, I want to implement some rewrite rules so that all requests other than /user/login are made over HTTP because it is INFINITELY faster and will result in better user experience.  I refuse to use Secure Pages at this point in time because of the bugged support in Drupal Core and I'm not going to patch Core manually.  That means I'm left with using Apache rewrite rules.

I have the following rules:

<VirtualHost *:80>
  ...
  RewriteCond %{HTTPS} off
  RewriteCond %{REQUEST_URI} ^/user/login$
  RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [L,R]
  ...
</VirtualHost>

<VirtualHost *:443>
  ...
  RewriteCond %{HTTPS} on
  RewriteCond %{REQUEST_URI} !^/user/login$
  RewriteRule ^/(.*) http://%{HTTP_HOST}/$1 [L,R]
  ...
</VirtualHost>

Now to me, that makes sense, but Drupal doesn't seem to like it.

What's happening is as follows:

If I navigate around the site using HTTP to any page other than /user/login, it works fine.
If I navigate to /user/login over HTTP, I get redirected to the front page.
If I navigate to any page over HTTPS, I get redirected to the front page over HTTP.

You don't really need /user/login to be served via https; you need the user login form to be submitted via https.

You should take a look at the module securepages_prevent_hijack -- not to use it directly, since it depends on securepages, but to see how the login form is altered.  Like so:

function securepages_prevent_hijack_form_alter(&$form, &$form_state, $form_id) {
  // Secure the login form, so that we always have a secure connection to transmit the
  // initial cookie.  Also, protect the password in transit.
  if ($form['#id'] == 'user-login-form' || $form['#id'] == 'user-login') {
    $url = parse_url($form['#action']);

    $base_path = base_path();
    $path = (!strncmp($url['path'], $base_path, drupal_strlen($base_path)) ? drupal_substr($url['path'], drupal_strlen($base_path)) : $url['path']);
    $options = array('secure' => TRUE);
    if (isset($url['query'])) {
      $options['query'] = $url['query'];
    }
    $form['#action'] = securepages_url($path, $options);
  }
}

You should also figure out whether the cookie that Drupal is setting for you is secure or not.  This will depend on your settings in php.ini.  Check to see if you have set session.cookie_secure to 1.  If you have, then the cookie will not be sent to your http sessions, which could be why you are ending back at the home page (no session cookie == no session == no login info == log out).  Of course, if the session.cookie_secure is 0, then it might be possible for other parties to observe your session cookies in transit, and masquerade as your users.  Perhaps you have already considered this risk, but it does bear some consideration.


Load a page with only the form, no drupal theme/element around In Drupal 8, I created a form Class. I can access to this form with the route defined in the yml file.

I want load the form page without any theme/elements Drupal, just show the form (with a minimal css for align the form to the center of the page). Is there a simple way for do that ?

I know it's possible to have a Controller action return raw HTML, by returning a Symfony\Component\HttpFoundation\Response object with the html string as an argument. IE

namespace Drupal\my_module\MyController;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {
  public function content() {
    $markup = '
Behold my markup!
';
    return new Response($markup);
  }
}

If that's what you are going for, you could hard code the form instead of using the drupal form api. It does mean abandoning the functionality of the form api as well though - you are basically creating a route to a plain html page.


How to add an edit and delete button to a custom html table? I've a db_select to fetch data from sql table, and $output .= theme('table'...) to generate an html table to display these data in columns. My question is, how can I add edit and delete buttons to each row?

Also, given initially these data are stored in the sql table from dropdowns, how can I redirect to the link containing the dropdowns load again and if for example I edit a row which has data from formID=5, each dropdown then shows the corresponding data for this ID, and allow me to modify accordingly to save again to the same sql table, and update the html table's view?

Example of my current sql is:

db_select('mytable')
        ->fields('mytable', array('formID', 'field1', 'field2'))
        ->execute();

$query = db_select('mytable', 'n')
    ->fields('n')
    ->execute();
  $rows = array();
  while($data = $query->fetchAssoc()){
  // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/mid-modules/component/' . $data['cid'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/mid-modules/component/' . $data['cid'] . '/edit');
    $rows[] = array('data' => $data, 'style' => 'word-break:break-all;',);
  }

  // Prepare table header
  $header = array( t('S.No'),t('Component Name'));
  // Output of table with the paging
  $output = theme_table(
    array(
      "header" => $header,
      "rows" => $rows,
      "attributes" => array(),
      "sticky" => true, // Table header will be sticky
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  );
  return $output;
//following menus that delete or edit your selected content

    $items['admin/mid-modules/component/%ctools_js'] = array(
    'page callback' => 'popup_callback',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'popup.inc'
  );
 $items['admin/mid-modules/component/%/delete'] = array(
    'title' => 'Delete Component item',
    'page callback' => 'delete_me',
    'page arguments' => array('delete_component_record_comfirm',3),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
    'file'=>'delete_record.inc',
  );

/**
 * Delete  Record Confirmation ------------------------------------
 */
function delete_component_record_comfirm($form, &$form_state, $cid){
   // print_r($cid);exit;
 $form['delete'] = array(
    '#type' => 'value',
    '#value' => $cid,
  );
  return confirm_form(
    $form,
    t('Are you sure you want to delete this?'),
    'admin/mid-modules/component/'. $data['cid'],
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}
/**
 * Delete Survey Record Function
 */
function delete_component_record_comfirm_submit($form, &$form_state) {
  $record = $form_state['values']['delete'];
  if ($record ) {
    $num_deleted = db_delete('mid_components')
      ->condition('cid', $record )
      ->execute();
    drupal_set_message('The record has been deleted!');
  }
  $form_state['redirect'] = "admin/mid-modules/component";
}


one view for each term or one view for all terms I have a vocabulary that contains terms and child terms, I would like to create a view to show the content of each child term.

Parent Term 1 > Child Term A
              > Child Term B
Parent Term 2 > Child Term C
              > Child Term D

So do I have to create 4 views for child terms (A, B, C, D)? Or I can create one view that show each child term in its page? and if it one view how to define path for them?

You just need to define the views path like taxonomy/term/%. It will override all the terms path automatically.


Access to other custom php pages I am new to Drupal, so please bare with me. I have a Drupal site that is working fine. Now what I want to do is allow access to folder which contains some custom php script.

I tried to put the folder in the /sites/default/files/ but it didn't work. I found a question on it  Extending Drupal Functionality to Custom PHP Page but not able to add Drupal functionality on this page. I just want to access that folder and its content.

So please any help would be appreciated. Thanks

The default path or root directory of any Drupal site is the same directory/folder which contains the site itself. ie. Same directory which houses the "sites" directory. If I put a php file there called "my_code.php", any reference to the file will be seen by everything as default. Its when other directories are created and the file placed there which make a file's location more specfic. So if I'm in a php file in another directory and I put in a statement like:

include 'my_code.php';

Drupal will start by looking in its default root directory. If I create a directory there called "my_php_files" and put the "my_code.php" file inside, then my reference to include that file would be:

include 'my_php_files/my_code.php';

Default permissions are normally 755 for directories and 644 for files.


CORS localhost ajax request I have an HTML page (http://localhost:8888/test/test.html) in which I'm trying to pull data from a Drupal 7 website.

I'm using this AJAX code with HTML-Request. I have tried JSON and the website prevents me from pulling, even I have added the following code to pull the data.

<?php header('Access-Control-Allow-Origin: *'); ?>

This is the HTML page that requests AJAX from Drupal 7 website. Could you please check it for me?

Please help me telling the website to accept my localhost request to pull data from the server. I have tested the same code on a pure PHP page and it is working fine.

You should wrap you javascript to user $ for jQuery, since it does not automatically refer to jQuery in Drupal 7. Try like that:

(function ($) {
  // Your code here
  $(document).ready(function() {
    // ...
  });
})(jQuery);

Reference: Managing JavaScript in Drupal 7


How to add [google ads] in between the views slideshow after completing four slides Any one can explain shortly ? How to add [google ads] in between the views slideshow after completing four slides .presently am having gallerific slideshow and slides are from specific content type. Thanks by advance.

Use the HTML code of google adds . Copy and paste HTML code of google adds in the body of new content. You can also use ck editor.In views also select body field along with image field.
Also add global php in which add a if else conditon to show either image or body.


Template for Views PDF I want to build a PDF with fields of a node. I installed Views PDF. Now I try to create a node tpl file. But Views PDF doesn't use my template.

How can I create a template, that is used by Views PDF?

thanks :)

You don't need any template files. All you need to do is to create a pdf document with d design u want, then include it in the template section in your views setup


Show a dynamic text depending on the day I'd like my Drupal website to show at the right top something like:

  ____ day (eg. Medicine day)

and fill __________ dynamically depending on the current day.

I will create a new content type DayType or something like that, with two fields:

Title
Date

My question is:

How can I show in __________ the title depending on the current day?

I could do that with a View, but what I don't know is how to show it on the right-top, and not apparently in a block or just in a new page.

You can use views_embed_view() to get the output of a view manually. Supposing your view is called 'days' and you want to display the output of this view:

print t('Today is @dayname day.', array('@dayname', views_embed_view('days')));

(This assumes the output of your view is just some text, and contains no HTML.)

By 'on the right-top', do you mean the page title? In any case, you could set a variable in your theme's preprocess function (which goes in the theme's template.php), like this:

function mytheme_preprocess_page(&$vars) {
  $vars['daystring'] = t('Today is @dayname day.', array('@dayname', views_embed_view('days')));
}

Now, in your page.tpl.php, you can write something like this:

print $daystring;


i want to disable the cloud zoom module in drupal commerce kickstart I am using Drupal Commerce kickstart. I including the demo site also. Cloud Zoom not working properly in my site, Please any one guide to me. I am new to Drupal commerce kickstart. I am using Drupal custom html theme convert to the Drupal theme.
Cloudzoom module installed in core.
I can't disable it.

Cloud Zoom is a module included in the Commerce Kickstart distribution, if you want to disable it to replace it with something else, just go ahead and disable it in the drupal Modules admin page as Molot suggests.

Update: You can't just disable the module as it's part of the product dependencies in Kickstart.

So the only way you can disable its effects is in each place you see it, for example for the product page, under the Products menu, click on Variation types and then Manage display. Find the view mode, i.e. Full content, and disable/change the cloud zoom options.

More info: http://www.drupalcommerce.org/questions/7582/disable-cloud-zoom


Adding like condition to db_select for section of string What I am trying to do is find all of the basic pages where their titles contain 'Meetings' for example January Meetings

Here is what I have tried so far

$string = 'Meetings';
    $query = db_select('node', 'n');
    $query->fields('n');
    $query->condition('n.type', 'page', '=');
    $query->condition('n.changed', $time, '<=');
    $query->condition('n.status', 1, '=');
    $query->condition('n.title', '%'.db_like($string), 'LIKE');
    $result = $query->execute();

Which hasnt worked as it is trying to find pages that only contain 'Meetings' in their title.

as it is trying to find pages that only contain 'Meetings' in their title.

Not quite - it's trying to find titles that end with the string "Meetings".

For a full wildcard match, the percent needs to be at both ends:

$query->condition('n.title', '%' . db_like($string) . '%', 'LIKE');


New commerce product doesn't have price I am trying to figure out what's the problem with my code. It creates the product, but the price field is allways empty.

$cp = commerce_product_new('deposit_temp_'.$_POST['importe']);
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = 'deposit_temp_'.$_POST['importe'];
$cp->title = t('Booking deposit');
$cp->language = LANGUAGE_NONE;
$cp->commerce_price['und'][0]['amount'] = 20;
$cp->commerce_price['und'][0]['currency_code'] = commerce_default_currency();

commerce_product_save($cp);

The price/amount is wrong. You do not have enough significant digits. Commerce works via a base price. Example:

A product that costs $20.00 (USD) is expressed as 2000 in Commerce. Basically all prices in Commerce should have the decimal point moved to the right by two or essentially multiplied by 100 and remove all significant digits to the right of the decimal point.

So in your case the price should be 2000 not 20.

Also I would like to point out a security issue in your code.  You are consuming a $_POST global variable directly into Drupal without first cleansing the $_POST.  This could open your site up to XSS attacks.  You should first past the $_POST global variable through filter_xss() before using the contents of that global variable.  Also note that Drupal Core offers ways to consume post variables if you use hook_menu for the page that this is running on.


How to remove "Show row weights" option on File Upload field? I have created a file field with multiple uploads allowed. Is there any way(except CSS) I can remove "Show row weights" link from file upload field? Or is there any way to remove weight drop down entirely from file field?

The first part of your question is regarding removal of link "Show row weights" (or "Hide row weights" if dragging functionality is disabled) in a form where table rows are draggable, so I'm going to answer that.

"Show row weights" string appears in Drupal.tableDrag.prototype.showColumns() method and "Hide row weights" appers in Drupal.tableDrag.prototype.hideColumns() method that is included in tabledrag.js file (see head in Drupal 7.x branch) so you need to override these methods in order to replace or remove these strings without losing row dragging functionality.

Place this code in a .js file that is loaded along with the form that uses tabledrag.js:

(function ($) {
  // Copy hideColumns() method
  var hideColumns = Drupal.tableDrag.prototype.hideColumns;
  Drupal.tableDrag.prototype.hideColumns = function() {
    // Call the original hideColumns() method
    hideColumns.call(this);
    // Remove the 'Show row weights' string
    $('.tabledrag-toggle-weight').text('');
  }

  // Copy showColumns() method
  var showColumns = Drupal.tableDrag.prototype.showColumns;
  Drupal.tableDrag.prototype.showColumns = function () {
    // Call the original showColumns() method
    showColumns.call(this);
    // Remove the 'Hide row weights' string
    $('.tabledrag-toggle-weight').text('');
  }
})(jQuery);


How can I replace certain strings in variable table all at once? I would like to replace all the 'aaaa' strings with 'bbbbbb' in value column of variable table.

I was initially trying to do that with just a simple query like this.

UPDATE variable SET `value` = replace(`value`,'aaaa','bbbbbb')

But this didn't work properly and I was taught that also the number between s: and :"  in value column has to be changed accordingly.

So variable_set seems to be the way to go but I'm not able to get it work.

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/variable_set/6

How can I do this?

The variable holds serialized data, so you can't modify what you want with a simple query. You have you to get every variable value  with variable_get, process the value making the needed replacement and the save the variable using varaable_set.

You can get all vlaues with this snippet:

$variables = db_query('SELECT name FROM {variable}');

foreach ($variables as $variable_name) {
  $variable_value = variable_get($variable_name, NULL);
  $fixed_variable_value = your_replace_function($variable_value);
  variable_set($variable_name, $fixed_variable_value);
}

You will need the your_replace_function(). This function must deal with all possible values because $variable_value can be a number, a string, an array, object or any other PHP type. In case of arrays and object the function must process its nested components.


Storing permanent value in Form while in validation handler We can store a permanent value in $form_state in the submission handler, which will be retained against form errors, but I want to know how we can do it while in the validation handler, where I show an error using form_set_error().

In short, I want to show an error in validation with the message "Press submit again to confirm". In this way, if the same form is submitted again it would skip the validation handler.

I can't do it in the submission handler, since it clears the values in the form.

form_set_value() is not able to retain a value.

EDIT (on 28th Dec)

I've found that $form_state['storage'] is works in validator also only if form_state['rebuild] is set to true. Infact this is how we use in submit handler. And if I call form_set_error in the validator form_state['rebuild] is simply ignored even if it is set and the storage value is not retained.

$form_state['storage'] is probably what you're looking for. I've used it on multi-step forms myself to preserve necessary data that I need during various stages of the form processing. As an example you can define a storage variable like this:

$form_state['storage']['mykey'] = 'myval';

Edit:
Considering the additional information you provided it is indeed not quite as simple in your specific case. Setting $form_state['rebuild'] = TRUE; in the form validation handler also means that the user set form values will be lost. So what I think you could do is the following:

In the form validation handler function:

if (!isset($form_state['storage']['mykey'])) {
  $form_state['storage']['mykey'] = 'myval';
  // Save all the user set form values.
  foreach ($form_state['values'] as $key => $val) {
    // If you want to skip some values do it here.
    $form_state['storage']['values'][$key] = $val;
  }
  $form_state['rebuild'] = TRUE;
  drupal_set_message('Press submit again to confirm');
}

In your form builder function use the stored values as defaults. Example:

$form['key_1'] = array(
    '#type' => 'radios',
    '#title' => t('Title'),
    '#options' => array(0,1,2),
    '#default_value' => $form_state['storage']['values']['key_1'],
);

Not sure how well the example code fits your needs, but it should get you started or at least give further ideas/options to try out.


Does everything need a bundle? I'm learning about the Entity API. I have a simple extra table that I'd like to "drupalize" so that I can use it in Views, for example.

I've read quite a bit, watched a few videos, looked at quite a few examples. I'm stuck on the concept of bundles. I understand what bundles are (e.g. node types are bundles of the node entity).

But for my use there will only ever be one bundle. In the examples I've seen the bundle is stored in the database table; this is not necessary for me as it would be the same value stored against every record. So I was thinking I could somehow skip this, or have my entity always return a standard string for bundle.

Have I misunderstood? Do bundles always have to be implemented, and implemented at database table level?

Yes a bundle is always, always necessary for entities.

If you don't define your own bundle(s), the entity system will assign a default one with the same name as the entity type for you, and that one will be used.

If you've only got one bundle, and only ever plan to have one bundle, then you don't need to have a specific field in your entity table for it. As you suggest in your question it would always be the same, so would be redundant and just add extra overhead (however tiny) to your db queries.

If you think you might need to distinguish between different sub-types of your entity at some point though, it would be worth building that in right from the start; it really depends on your use case.


Deleting a cloned node erases all paragraphs Suppose node A contains a paragraphs field with a paragraph entity X. Duplicating the node by means of Node clone will create a new node - let's call it node B - with an exact copy of paragraph X. It is even possible to change the contents of X in node A and B independently.
But when A or B is deleted, X will be erased from both nodes. Obviously this is because there has never been created a new entity when replicating the paragraph, but only a new entity revision.

For Drupal 7, this behavior is documented in Paragraphs data loss with Node clone module and at least partly fixed by a patch.
But none of this seems to be the case for the Drupal 8 dev version of Node clone. Has anyone found a solution or workaround for this issue?

Drupal 8.2.0

Paragraph 8.x-1.0+14-dev

Node clone 8.x-1.x-dev

Paragraph in 8.x integrates with the replicate project only at the moment: https://www.drupal.org/project/replicate

If you use that, cloning a node will also create clones of the used paragraphs.


Add A Redirect Link In Webform Submit Button I want to add a redirect link on Webform submission button when a user submit a webform I want to redirect them in different page.

How can I redirect a user after they submit the webform ?

This is duplicated question.

But here is the answer
If i had to redirect the users after submission than i would go to the already created webfrom, click on

Webform(on top of the form)->Form settings

After scrolling down a bit you will see Redirection location

Choose Custom URL and enter your Internal URL www.mysite.com/foo

Thats it you are done.


instant upload after select file in a file or image field (quit upload button) In the normal fashion you have to select the file you want to upload in a file field or image field and then click "upload" button.

this is not very "user friendly"

How to upload the image or file just after the user selects it in the window without the necessity of click "upload" button.

You can also use Drag & Drop Upload

Here you just browse the file.

select the file and it will be automatically upload.


Drupal put more values in #markup $form type Is it possible to add more values into the #markup of a drupal form?

At the moment it is a link but I also want to add an image. When I add another #markup it only takes the last one, and when I add $image to the other #markup it doesn't work.

My code:

$image_options = array(
    'path' => 'img_url',
    'alt' => 'App logo',
    'title' => 'App logo',
    'width' => '56px',
    'height' => '56px',
    'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

$image = theme('image', $image_options);

$form["link$key"] = array(
  '#type' => 'item',
  '#description' => t('Registered token(s): @total_tokens <br> Total sent push notifications: @push_notifications', array('@appname' => $record->app_name, '@total_tokens' => $total_tokens, '@push_notifications' => $sentMessages)),
  // '#href' => "admin/config/services/push_notifications/stats/". $record->app_id,
  '#markup' => l($record->app_name, 'admin/config/services/push_notifications/stats/' . $record->app_id),
);

So I want to be able to add $image to the current #markup..

The #markup property simply provides a string output.

Why dont you just concatenate your output into a variable.

$output = $image;
$output .= $link;

Then...

'#markup' => $output

Checkout the coding standards for Drupal around concatenation.
https://www.drupal.org/coding-standards#concat


How to change default "Create" label? I want to change the 'Create' label for a specific Content type.
I made a new content type called 'Bid Offer':

I want to show this to the users as 'Make Bid Offer' instead of 'Create Bid Offer'

Any help appreciated

Put the following code into a custom module.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

or

function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

To change the URL, you can just set a path alias and alias node/add/bid-offer to make-offer or whatever you fancy should you need to.

Just for reference:

hook_form_alter()

hook_form_FORM_ID_alter()

EDIT

Following on from your comment, please try the following code (I've used it recently so I know it works):

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bid_offer_node_form') {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
  }
}

or

function mymodule_form_bid_offer_node_form_alter(&$form, &$form_state, $form_id) {
    drupal_set_title(t('Make Offer'));
    $form['actions']['submit']['#value'] = t('Make Bid Offer');
}

Reference:

drupal_set_title()


hook_field_extra_fields: hidden by default When implementing hook_field_extra_fields(), can I make the extra field hidden by default?

Sometimes it is friendlier to offer the extra fields as an option, instead of displaying it immediately after a module is enabled.

In _field_info_prepare_extra_fields() the extra fields are set to visible by default, but the extra field settings are stored in the field_bundle_settings variable which you can change in your module's hook_install() like:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'my_extra_field';
$view_mode = 'teaser';

$field_bundle_setting = variable_get('field_bundle_settings', array());
$field_bundle_setting[$entity_type][$bundle]['extra_fields']['display'][$field_name][$view_mode]['visible'] = FALSE;
variable_set('field_bundle_settings', $field_bundle_setting);


How can i use bootstrap js library in my theme? I use bootstrap drupal theme. And i want to use collapse.

I added in theme.info the library path bootstrap.js have cleaned the cache, but after using the following code generates only the button, but the content is not deployed.

      <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">

Most likely is not initializing bootsrap.js, please tell me how to fix it?

Yes i fixed this problem by using jQuery with more higher version.


Writing PHPUnit tests for view plugins I am trying to test custom views field & filter plugins using PHPUnit, but I keep getting dependency issues. I am curious to know if:

It possible to Unit test View plugins?
Simulate DB interactions.
Is it possible to inject services e.g database, request, response etc via a constructor, setter or property injection?

Thanks in advance.

Views plugins are testable, and Drupal core has a lot of examples.  I believe most aren't UnitTestCase (or \PHPUnit_Framework_TestCase), but rather KernelTestBase tests.

KTB tests will boot a minimal Drupal setup so you don't have to set up extensive mocking for dependencies, especially config and database.

Views in particular has ViewsKernelTestBase, which does basic setup for testing Views plugins.  You can use your IDE to find usages of this for example, but I know some are in web/core/modules/datetime/tests/src/Kernel/Views/

Essentially, you make a test module that has YAML for your test views.  The test declares this in its $modules list, along with the module that is providing the plugin.  You also define the test views, and these get imported.  You can then use the Views API in your test methods.

Then, as long as you use the new ViewsKernelTestBase, you can run it directly through PhpUnit, assuming you have your phpunit.xml setup properly.


Why does the title callback of /user produce the title for /user/register? I'm a bit puzzled why the title callback of /user produces the title for /user/register and /user/password.

When I set the title callback of /user, I see this affects the title of /user/register and /user/password. However, setting a title callback for /user/register seems to make no difference; it appears to stick to the title callback of /user.

What is special about /user/register and /user/password which results in titles for these callbacks to have their titles produced by the title callback of /user?

function mytheme_menu_alter(&$items) {
  $items['user']['title callback'] = 'mytheme_user_title';
}

function mytheme_user_title($title) {
  return 'test';
}

For the user/register title to be changed in a theme:

function mytheme_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is 'register'
  $arg = arg();
  if ($arg[0] == 'user' && $arg[1] == 'register') {
    $variables['title'] = 'Test';
  }
}

For the user/register title to be changed in a module:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
  drupal_set_title(t('Test'));
  }
}

Hope that helps.


View showing Teasers - getting path for full content in teaser template I have created a simple view to list teasers of a particular content type.

I'm then using a simple view template, modified to suit the layout needed.
In the content type set-up there is not an option to display the path/URL to the full content. I can set the image if output to link to the original content, but I can't seem to find an option to just get the URL for the full content so I can link the whole teaser block to the full article.

Any clues? Know this should be easy - but can't seem to find it.

Normally, you can access nid with $row->nid in your template.

From that, you can easily build the link to your node content with node/ . $row->nid path.


How to customize message in maestro mail notification I am working on Maestro module. we have interactive tasks in the Maestro which are executed by the users to whom task is assigned. In Maestro, we can intimate the user by mail about the task assigned to him. Message in the mail is one paragraph. I want to customize this mail. I need to add table and send message in multiple pargagraphs.

I have tried adding br(I tried adding angular brackets but text after that is going to next line) in the message but message is being displayed along with br instead of going to new line.

I think html tags doesn't work there.

How to make html tags work in the custom mail or customise the message?
P.S: I am attaching the screenshot where I am writing the message

I know this has been up for a while but thought I would answer. Up until recently, Maestro was removing any HTML from that textbox using Drupal's checkPlain.

I added a patch which was accepted into the development branch so it should be sorted in the next release of Maestro. If you wanted a fix in the meantime, use the patch file here: https://www.drupal.org/project/maestro/issues/3076536


How to redirect a cancel button to destination on each form? I'm using the following code to add a cancel button on every form I have for add / edit of every content type. The target should be the destination adress in the url

In some content types it is working and some not:

$link = l(t('Annuleren'), drupal_get_destination());

      // add the actual button to the form
      $form['actions']['cancel'] = array(
        '#type'   => 'submit',
        '#value' => "Annuleren",
        '#access' => TRUE,
        '#weight' => 55,
        '#submit' => $link,
        '#limit_validation_errors' => array(),
        );

      dpm ($form);

It has something todo with #value. If I replace it to #markup like below example then it is working but I do not get a label in the button.

  '#markup' => "Annuleren",

How to solve this?

In your code above, you're using wrong value for #submit. #submit accepts an array of submit callback function names, check e.g. here.

You can either add a link in form, which will take user to destination and style the link to look like a button. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'markup',
    '#markup' => '
' . l(t("Cancel"), 'URL', array('attributes' => array('class' => array('form-cancel-button')))) . '
',
  );

  return $form;
}

OR you can create a normal submit button and add a custom submit handler which will take user to destination. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value' => "Cancel",
    '#weight' => 55,
    '#submit' => array('_custom_form_cancel')
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function _custom_form_cancel($form, &$form_state) {
  drupal_goto('URL');
}

Note: When you define a custom form element, you don't need to give #access property specifically, it is TRUE by default.


How to perform a REST request after a node created using rules? I have a backend service written by Python, which is exposed a JSON api. And I want drupal to perform an HTTP POST/PUT/PATCH/DELETE... request with json data (which is an output of a node) to the backend when a node have been created/modified/deleted.
I think that rules module should do this job. The trigger part and condition part are ok, but I can't find a suitable action part.
I hope to find a module that provides some rule actions, is able to let me define the JSON structure being used (using token etc.), is able to perform an HTTP request(GET/POST/PUT/DELETE) and let me handle the response (notify users or save to a status field).
When I google solutions, I only found two possible modules:

Rules HTTP Client, according to REST request through Actions and Triggers

This module adds an action wrapping of drupal_http_request() to use Rules for making HTTP requests.

But it seems not support authorization (OAuth/HMAC/token/...), and the data has to be HTTP query string (?name=value&name2=value2&...).

Web service client

This is a very powerful module, allows to define a series of actions: transform a node to a data structure and save as a variable, call http request with the variable and save the response as a result variable, handle the result at last. BUT, it only supports GET method (only option), query string, and no HTTP headers.
With these modules, I can work out a backup solution: my backend service may supply an endpoint that handles formed data, or supply an endpoint that receives a node id then make a HTTP request callback to Drupal (with services module).
Do I miss any module that do similar thing? Or is there any better solution?
P.S.: I'm not familiar with PHP, so I don't want to write any PHP code.

Guzzle is similar to Web Service Client and there is also Web Rules but I assume Guzzle would require some coding. Guzzle is a powerful HTTP client and library and itself can do whatever you want.

The reason there are few user interfaces to what you want is that they're annoying to build and add next to nothing to your client website. The UIs dont make the website any faster, they're just bloat.

This is why Views and ViewsUI are decoupled so you can turn 1 off in production environments.


Location's Distance/Proximity exposed filter without Node Location Submodule but with Location CCK Submodule instead I would like to stay a little bit more flexible and use Location CCK fields (from Location CCK Submodule) instead of Node Locations (from Node Locations submodule) on my nodes. However, in my view of nodes the "distance/proximity" exposed filter (distance from a user-entered zip code) only works when my nodes have a location attached to them via Node Locations Submodule. If I disable Node Locations Submodule and attach a location to my nodes via a Location CCK field, the "distance/proximity" exposed filter never returns any results.

Does anyone know how to get around this issue?

Best,
deinqwertz

I was faced with the same problem and "solved" with a little workaround:

I use both node and cck location. The one is hidden from the user, he only sees one, and if it is changed then I copy it into the other one.

That way I have both a cck field for flexibility's sake AND the node location for the views. :)


How is the module Userpoints Donation intended to work? I enabled the Userpoints Donation module (part of Userpoints Contrib). Then I put a check in the settings for the type of material - (Choose which content types should show a donate points link).

What's next? Nothing has changed. It says "Only the checked content types will show a donate points link". But no reference appeared.

The purpose of the Userpoints Donation module is mentioned near the top of the module's source:

  ... uses User Points API to give users ability to give points to users.

But "give" actually means "transfer", as shown in userpoints_donation_giveform_submit(), which:

increments the amount of points for the user who receives the donation (= receiver).
reduces the same amount of points for the user who donates them(= donator).

Before actually doing so, various extra validations are performed, such as:

Does the donator have sufficient points, so that after transferring the points the user points balance of the donator is still positive?).
The receiver has to be a valid user.
You cannot transfer points to yourself.
The amount of points donated cannot be below 1 user point (which also implies that the donator can only "give" points, not "take" points ...).
...

However, for an appropriate link (with title "Donate points to this user") to be shown to the user who wants to do such donation, it is required that such user has been granted the permission "give points to another user". So if "Nothing has changed" (as in your question), it could well be that the required permission has not been granted yet.


No "webform" link in operations column i'm new to Drupal and PHP in general, so this may be obvious - But I'm working with Drupal 7 with module webform installed. Recently, i don't know why the link stopped appearing in the Operations column on the Content list page in the admin.
 Any help would be appreciated!

Hi make sure you are enable the webform functionality  like this
check
http://prntscr.com/bur06a
 if not working then  follow  tutorial


Show term description when grouping by taxonomy term I have one vocabulary with two terms, apples and oranges.  Nodes are tagged with either one or the other.  I created a view at /fruits that shows the nodes tagged with either term.  I also have the field settings set to Group by Taxonomy term which works great.

It places the taxonomy term heading at the top of each section.  Now on to my question... Is it possible to display the term description under each taxonomy heading?  So it would look like below.

Oranges (Taxonomy Title)

Oranges are probably the best fruit on earth. (Term Description)

(Results of view)

One option for solving this is to rewrite the output of your view fields to meet your formatting requirements, which consists solely of configuration steps -- no code changes needed :).

On your view, add the Taxonomy: Term field and the Taxonomy: Term description field.  Make sure the Term field is above the Term description field.
Next, edit the Term field, select Exclude from display, and click Update.
Now, edit the Term description field and check Rewrite the output of this field. You can set this Term description field to include the formatting you desire of your Term name and Term description using the available tokens, which are listed in the Replacement patterns fieldset.

For example, try placing the following into the rewrite Text textarea:

[name]

[description]

Be sure to click Update after you have finished configuring the Term description field.

Last, in your field settings, select Group by Term description and voilà, you should have all the data you want in each grouping section. As long as your term names or term descriptions are unique, this should group as expected.


Bug/Issue tracker for Drupal 7? I would really like to port my website to Drupal 7, but my site requires an issue tracker. I tried the support module, but it seems heavily orientated towards support tickets (you must add clients, all users can't view eachothers tickets).

With the project issues module still working on complete Drupal 6 support, I really don't think I should be holding my breath.

What options are there, If I want a bug tracker on Drupal 7?

Solution 1: Do It Yourself

Add taxonomy terms

Status (Open, In Progress, Pending, Resolved, Closed) ,
Priority
(Low, Normal, High)

Create content type Issue,

add fields title, body, status, priority.

Set roles

Allow anonymous users to create content Issue
Allow administrators to edit and delete content Issue

Extras:

Use Views for issue reporting

Use Workbench for managing issues

Use Workflow for setting issue management workflow

Solution 2: Use an external issue management solution

Comparison of issue-tracking systems

I prefer an external solution because of its independency I can still handle issues even if my site is down.


Backing out of Drupal Commons We currently have a Drupal Commons website on version 7.50, commons 3.x. Our site is complex and we are no longer using many of the pre-packaged features in the commons distribution. We would like to simplify and modernize our website by "getting out of Commons."

I am wondering if it is possible to back out of Drupal commons without rebuilding from scratch and if it is possible, can it be done cleanly? E.g. Can we get back to Drupal Core and for every commons-specific feature we are using, could we theoretically replace the commons-specific configurations and modules with a Drupal 7 or native features and what are other the other implications?

This is a fairly arbitrary question but any information is appreciated. As I learn to re-frame the question, it will help to answer it. Guidance on asking is also appreciated, thanks!

Update and background info: I prefer Drush, use GIT and have a staging process as well as have set up sandbox copies of our site from back ups to be sure they work. I lack a good understanding about administrating Drupal itself and how Core differs from other profiles but am familiar with migrating Drupal sites and managing the database and codebase.

Nice question, but challenging. Basically you want to switch installation profiles (from commons to regular Drupal core). And that yielded some results on Google, including Profile switcher and This blog page. They might be of help during the process.

Before blindly installing modules, please read on, make sure you have proper backups (in fact try to verify your backup actually works) you might have to recover multiple times.
From what I understood these methods are usually from upgrading 'standard' Drupal to another profile, but it might work backwards.

I'd start by disabling and uninstalling (use the uninstall tab) all modules that come prepacked with your profile distribution. This will likely be the features, but there might be more. Then attempt the switch. See which method works best...


How can I change the user login tabs labels? I am pretty new to Drupal and wonder if there's any possibility to change the text of the user login / create an account and reset tab? I'd like to rename them to something like "sign in", "sign up" and "reset account".
I found no way through the backend UI. Neither in Tabs Block Content nor Menu structure.
Do I need to write a theme hook or a module to achieve that, or is there any functionality in the backend I've overlooked?

As shown in the answer to the duplicate question you can use template_preprocess_menu_local_task from a custom theme or hook_preprocess_HOOK from a custom module to override the tabs.
If you want to do it right, you also set the page title and the HTML title to display the same strings. Maybe keep things DRY and get the $target_routes array from a small helper function.
First the tabs:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_menu_local_task(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    /** @var \Drupal\Core\Url $url */
    $url = $variables['link']['#url'];
    $route_name = $url->getRouteName();
    $variables['link']['#title'] = $target_routes[$route_name];
  }
}

Then the page title:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    $variables['title'] = $target_routes[$current_route];
  }
}

And finally the HTML title:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_html(&$variables) {

  $target_routes = [
    'user.login' => t('sign in'),
    'user.register' => t('sign up'),
    'user.pass' => t('reset account'),
  ];
  $current_route = \Drupal::routeMatch()->getRouteName();

  if (isset($target_routes[$current_route])) {
    $variables['head_title']['title'] = $target_routes[$current_route];
  }
}


Custom Logout and Drupal Logout we are implementing a custom login (based on an auth cookie given by a third party authentication service). When the cookie arrives, we trigger the drupal user_login.
When the user logs out (via a custom box, NOT drupal logout link), we trigger the user_logout.

The problem is: if you clear the cookie auth, you remain logged on drupal.
What hook can we implement to trigger the logout anytime the cookie auth disappear?

There is no hook for 3rd party cookie removal, and there cannot be. You need to bootstrap Drupal and call user_logout().

You could also use hook_boot() to test for the cookie and logout if it's not there, but it is a bad idea - it may seriously hurt your performance and will not play nice with external caches.


Import a PDF from within a page (Feeds / Mailhandler) I am using Mailhandler to import quite a bit of content. The one piece I'm not able to get is a pdf.

The email body contains five links. The last link goes to a page that has an iframe with a source of the pdf I want. Example:

<iframe src="/files/20394.pdf">

However, the link in the email does not seem to have "20394" anywhere in it, so I can't even generate the link to the pdf myself.

At the end, then, I would have the importer import that link as a file.

Is there any other way to grab that pdf?

I was able to do this using curl to get the source code then preg_match to pull the URL. I haven't actually gotten the pdf, though, because it's using a form to generate the pdf. However, that's a different issue, so this question is answered.


Create link (url) to the full node from a Solr view (search results) with rewrite results In admin/config/search/search-api/index/default_index/fields I added URI field.

But how can I create a link to the full content? In the view, when I click on Add fields I am able to select: URI (indexed field)    Index Default index A URI where the item can be accessed

But in the field settings, when I select:

Link this field to its item
Display this field as a link to its original entity or item.

It doesn't become a link? How do I create a link to the full content in a Solr view?

I found the solution by Checking Retrieve result data from Solr in the solr server configuration (Advanced tab). After checking this box I am able to use {{ url }} in my view.


How does Drupal render a node I'm helping someone to maintain a Drupal site and I still have not figured out how drupal actually works, it's driving me bonkers.
I need to make a change to the way some content is displayed, but cannot figure out where that change needs to be made - I could go around just changing up the site until I stumble on it, but would rather not put a wrecking ball through their site like that.

Would appreciate if anyone can point me to a simple explanation of how to find out how a node is rendered and how I can track down the views involved.

The setup of the site is they have content types candidate and survey

When you view a candidate you see a nice table with info on the candidate and their survey responses.

I want to add some new fields (some to survey, some to candidate)
I've added the fields, but don't know which view is involved in rendering as the views are not named clearly.

How can I figure out which view is involved in rendering a candidate when I go to
www.site.com/candidate/bob
?

Your question is actually very generic and can have a big explanation but I will actually pickup a couple of points from the question description and will try to explain.

How is node is rendered?
Node is drupal's "most" core part. Most of the code is written in node.module in "modules/" directory.
https://api.drupal.org/api/drupal/modules%21node%21node.module/7

Drupal uses a theming layer to render the content to the browser. If you want to alter the display of any node, you can check node.tpl.php in the current active theme directory. You can override the HTML of a node using node--[CONTENT_TYPE].tpl.php. For example if you want to change the HTML structure of article content type, you can copy node.tpl.php to node--article.tpl.php and can update the structure.

How to check the view

The easy way
The easiest way is to login using admin and place mouse on the part of page you think rendered using views. You will see a dropdown menue with links like "Edit", "Delete" etc. If it doesn't help, there is a:

Technical way
You can check the css class of the div enclosing the view data. For example if a view's div contains the class "view-front-page", then most likely the views name will be something like "front_page" or "Front Page".

Thirdly, I will recommend that you install devel module. I have never seen any module for developers that is more helpful than devel. It helps your print a lot of debugging information like error stacks etc.

Hope this will help.


How do I delete the Edit Delete buttons suddenly showing above pictures? All of a sudden when I insert a picture into a page, it shows an edit and a delete button above the image to the end user.  These buttons take you to the default page.  Also, now when I edit a page from the edit button at the top of each page and save, I get the following type of message after a lengthy wait.

Fatal error: Allowed memory size of 356515840 bytes exhausted (tried to allocate 523800 bytes) in /data/www/luna/sites/all/modules/token/token.module on line 767

I can edit and save if I select the page under Content.

See http://lunahq.com/content/luna-rox-v8-simple-smarter

you need to increase the memory limit size in php.ini

That indicates that Drupal needed more memory than PHP was allowed to give it.

Drupal 7

Memory increase to 128M:
(This has worked every-time; and used to always work for D6 as well)

Create a new file php.ini, and add the code...
php_value memory_limit = "128M"
and put that file in your Drupal 7 (or D6) root folder.
    For step-by-step details, see comment below...
    Drupal 7 "Fatal error: Allowed memory size of ...".
If you need more than 128M:

Add the line
ini_set('memory_limit', '512M');
to your [Drupal 7 root]/sites/default/settings.php file.

I have yet to need this much memory, but I did achieve
a memory increase to 512M using this slightly more complicated
process that involved temporarily changing the permission level
for that file.
    For step-by-step details see the comment below Drupal 7 memory increase to more than 128M.

refer this link

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


How can I check if a select field has been used with states? I have a form where I'd like to hide a fieldset until the user has used a select (which option doesn't matter).

So far I've the following code:

$form['location'] = array(
  '#type' => 'select',
  '#options' => $locations,
  '#required' => true,
);

$form['uploads'] = array(
  '#type' => 'fieldset',
  '#title' => 'Foobar',
  '#states' => array(
    'visible' => array(
      'select[name="location"]' => array('empty' => false)
    )
  )
);

Apparently empty, checked, filled don't do the trick. If I check for one specific value with the following code works.

'#states' => array(
  'visible' => array(
    'select[name="location"]' => array('value' => 'foo')
  )
)

But what would be the solution for the check if any value has been selected?

I haven't tried it but a simple negate on an empty string might work:

'#states' => array(
  'visible' => array(
    'select[name="location"]' => array('!value' => '')
  )
)


When should I be using database transactions? I know this is a question that depends on the details of a specific situation, and a rather open-ended question at that.  But, nevertheless, are there any good guidelines out there about when database transactions ought to be used in the course of everyday module development?  I've begun to worry that I should be doing transactions a lot more than I currently am (which is to say almost not at all), but it would obviously be wrong to go off on a frenzy of wrapping transactions around everything.  Any thoughts out there?

When you're running multiple queries in the same function/context that change data in the db, and the failure of any one of those queries would leave your data in an inconsistent state...that's when you should be using a transaction.

To the best of my knowledge there's no point in wrapping single queries in a transaction (it seems redundant. The query will either fail or succeed and you can catch those on an individual basis). Even if you're running multiple queries that won't leave data in an inconsistent state should one of them fail, I would say the same thing goes. You can catch errors for each query individually, and fail/continue gracefully.


How to theme a field formatter? Context: using the registration module, I am trying to customize the entity registration form depending on the user:

show a 'please login in order to register' to anonymous visitors
show a 'edit registration' link to already registered users
show the registration form, as well as an info message (xx seats left / fully booked butwait list is still open), to not registered yet users.

Current status: I managed to customize the field display using a field template in my custom theme. Unfortunately the field is not displayed anymore when the event is fully booked (without a 'fully booked' message). I changed that by implementing a custom field formatter based on the registration 'form' field formatter.

Problem: In order to have the thing easier to maintain, it sounds like a better idea to have the theming done directly in the module (named 'zss'). Although it is probably easy meat for drupalers, I do not manage to do that so far. The current code reads like:

function zss_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // we know we should only have a single item
  if (isset($items[0]['registration_type']) && !empty($items[0]['registration_type'])) {
    $reg_type = registration_type_load($items[0]['registration_type']);
    $settings = $display['settings'];
    $label = !empty($settings['label']) ? $settings['label'] : $reg_type->label;

    if ($display['type'] == 'zss_registration_default') {
      // Enable registration link if accessible.
      list($entity_id) = entity_extract_ids($entity_type, $entity);
      if (registration_register_page_access($entity_type, $entity)) { // && registration_status($entity_type, $entity_id)
        $registration = entity_get_controller('registration')->create(array(
          'entity_type' => $entity_type,
          'entity_id' => $entity_id,
          'type' => $reg_type->name,
        ));
        $element[0] = drupal_get_form('registration_form', $registration);
//         I tried the following to theme the field:
//         $element[0] = theme('zss_theme_zss_registration_default', drupal_get_form('registration_form', $registration));
      }
    }
  }
  return $element;
}

/**
 * Implements hook_theme().
 */
function zss_theme() {
  return array(
    // The theme function that our formatter uses:
    'zss_theme_zss_registration_default' => array(
      // Don't forget that all Drupal 7 theme functions have only one argument,
      // so you declare what variables get passed within that argument instead.
      // See http://drupal.org/node/224333#theme_changes
      'variables' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'zss_theme_zss_registration_default' field formatter.
 */
function zss_theme_zss_registration_default($element) {
  // Here I would like to have a condition, depending for instance on the user id
  return $element;
}

Thank you in advance for your help.

What I wanted was actually to theme the registration field directly from the module, by implementing zss_field__field_registration($variables).

So, if you have a similar problem, you need to proceed in 2 steps:

create a custom field formatter for your registration fields (described above). This will allow to display the form even when the current user has already registered.
theme the registration field from your module so as to display it according to the current user and available seats.


Safe string checkup against user-supplied suffix/prefix strings Possible Duplicate:
  Is check_plain() enough?

When authoring own plugin/formatter and giving user an option to provide their own HTML prefix and suffix strings , what would be the Drupal way of ensuring safety of those strings?
Would it suffice to filter_xss with custom list of allowed tags, or a sequence of some functions would be required?

Treat it like any other user input; that is, not to be trusted. Do you have a reason to allow HTML tags in the prefix/suffix? If not, output only after running through check_plain(). filter_xss() is quite permissive in its allowed tags so just be sure you're OK with that before using. See also the drupal.org documentation on handling text in a secure way.


What will happen if I delete 'page.tpl.php file'? Is there any alternative for this file? I deleted page.tpl.php file from my current theme, and noticed that all content is still rendering in my Drupal site with a little difference in structure. What is the real use of this file? Can we have any alternative or a replacement for this file?

page.tpl.php file is used to render your page body content (i.e. content inside <body> tag). Below is one line description of file on api.drupal.org.

  Default theme implementation to display a single Drupal page.

If Drupal is not able to find page.tpl.php file inside your theme, then it will use one of the following file:

If your theme has Parent theme, then Parent theme page.tpl.php file.
If no, file provided by system module.

If you're using version control system like GIT, Bitbucket, etc. you can revert your file from last commit. If not you will need to create new file and do necessary changes


theme node add use custom theme I followed this answer to try and theme node add

https://stackoverflow.com/questions/1538600/how-can-i-theme-the-template-for-edit-or-add-a-node-for-a-specific-content-type

the only problem is my theme is using Garland in node/add so I can not theme it with mythemename_, how do I use my custom theme for this instead of garland

It sounds like you have enabled your Administration Theme for content creation.

Check www.yoursite.com/admin/settings/admin:

and see if that check box is checked.  If it is, uncheck it and then your custom theme should be used from then on, assuming, of course, it's enabled for the user.


Can custom module function names contain characters between 7F and FF? PHP defines valid function names as [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

I have already been bitten by Drupal name conflicts when using hook_form_alter clashing with my module name when it contained common words separated by an underscore "_" ("isys_helper_form_alter").

So I thought about using the broken pipe character instead like I have done in other PHP projects ("¦", char #A6, "isys¦helper_form_alter").

Unfortunately, Drupal does not seem to find any functions I name using characters in the 7F to FF range.

Is this a documented difference with Drupal vs. PHP?

Searching the documentation online did not state any such difference, but I could have missed it.

That's a bad idea. Please refer to Drupals Coding Standards under the section Naming Conventions.

In my opinion function/class/var names shouldn't contain anything else than A-Za-z0-9_.

If you don't want isys_helper_form_alter to be picked up by Drupal, you can always prefix it with an underscore: _isys_helper_form_alter.

Update

Here's another topic on why other characters are bad: https://stackoverflow.com/questions/6362241/php-variable-function-class-names-using-special-characters. And even if you remember to save it in the right encoding, other people who needs to maintain your code later on might not do that.


Currency module step by step guide I want to provide a block where user can convert the currencies as desired and get the latest conversion rate.

I'm using Currency module. But there is no any set up guide for it, so I'm unable to use it. Can somebody tell me how to set it up?

If it is not possible in this module, is there any other module?

You can also use below modules :

Yahoo! Finance currency converter

  This module provides Currency with currency exchange rates through
  Yahoo! Finance, which are updated continually throughout the trading
  day.

Currency Converter

  Currency converter module was created for quick currency convertation.
  It contains 10 currensies.

  It is flexibly configurable block. The currency undertakes from
  several banks (on a choice).

Open Exchange Rate Money.js

  This module provides support for the money.js currency conversion
  script from http://josscrowcroft.github.io/money.js/ along with
  support for the Open Exchange Rate currency conversion data.

Exchange Rate

  Exchange Rate API is an extensible module that allow users to display
  and manage the exchange rate in countries from around the world.

  Is common to see tools that present the official exchange rate, the
  problem is that each bank has his own rate, for this reason it is
  important to have a tool that can show the different variations across
  multiple financial institutions.


How Do I Change My Drupal Admin Password From a Drupal Test Install on My Local Machine I am a complete Drupal beginner. My Drupal site is hosted with a provider. I have these questions and would really appreciate your insight.

1) I want to be able to change the front end log in pass from cPanel in the event I get locked out. My hosting company has provided me with (a) a lengthy way to do it and (b) a short way to do it.

(a)

Set up up SSH access
From Mod Security
Add and whitelist my current IP address
Manage SSH Keys
Generate New Key
Find the Key under Public Keys section
Manage
Authorize
SSH Access screen
Manage SSH Keys again and under Private Key View/Download
Then "convert "id_dsa" key to PPK format"
Enter password and download key
Download/install PuTTY
In PuTTY go to connection, SSH, Auth and browse for coverted key file just downloaded.
Click Session and under Port enter 2222
Enter host name and Open to connect
Answer yes to all security prompts
When prompted to Login As, enter my cPanel username and for the password use the one I set for the SSH key.
Once connected via SSH enter "cd public_html" and go to Drupal root
Then enter ""php core/scripts/password-hash.sh 'NEWPASSWORD'"
Copy the text after where it says "hash"
Return to cPanel, open phpMyAdmin, click on database, look for "users_field_data table"
Find the account with the name "Admin"
Click Edit and replace the text in the pass field by pasting in the hashcode I generated.
Lastly, go to the table in the database named "flood" and delete any rows with my IP address.
Then they say "You may want to enter your IP at the top, under Filter rows.
Do the same for the cache_entity table.

(b)
    Go to your cPanel -> Databases box -> phpMyAdmin.
    Select the database which Drupal uses from the drop-down menu on the left.
    Select the right tab that says: (SQL)
    Click the SQL tab. (I tick SQL and a text field pops up with: "Run SQL query/queries on database" (database name)
    In the SQL text field page type the following text:

update users set pass=md5(’NEW PASS’) where uid = 1;

Where NEWPASS is your desired new administrative password.

Then click on the GO button and if no errors present, the Drupal password should have been changed.

(a) is very difficult.

(b) is easier but I'm not confident that (b) is correct. Is it?

(c) I want to download/install a test Drupal to my local machine and try these tasks before I attempt them on my live site.

(d) Can I test these tasks on a my local machine with Drupal installed as a test version?

(e) Of the three installers at https://bit.ly/2QeuFLd which one do you suggest for a beginner?

Thank you for your advice.

short version use "drush uli"
longer version have a local install with known password, go to your cpannel -> phpMyAdmin change the password to the known one. - done


How to set up webhooks with the Mailchimp module I just installed the newest version of the MC module into my D7 instance and was wondering how I can enable webhooks for the lists that I have within the lists tab.

I have already set up a test list on the MC side and created an API key and I see the list populating on the Drupal side so I have that working just fine.

When I go to enable the webhooks feature on my list on the D7 side I get this msg:

You can change this setting back from the mailchimp administrative UI. I then click on enable hooks. Its working to do something but then get hit with: Unable to perform webhook action "enable" for list my-test-list.

I also see that I need to enter a callback URL on the MC side but I'm confused as to what link I need to use there.

I had the same problem with my site, which is fixed now. It seems like the error message pops only if you are on HTTPS secure protocol. If you are on HTTPS try disabling it and try enabling your mailchimp lists. After you enable the mailchimp list now you can re-enable the HTTPS.

There is a bug on 7.x.3.1 version Make sure you are using the latest version 7.x.3.2

On secure pages settings you can ignore these pages loading from HTTPS.

example.com/admin/config/system/securepages

admin/config/services/mailchimp
admin/config/services/mailchimp/*


UC Feeds - updating products by SKU The main idea is updating prices via feeds. If SKUs are unique, we can update products using this parameter.

Unfortunaly module UC Feeds is able to create only new producs. How to modify UC Feeds for updating products ability?

How about following these steps?

Save the original import file
Update the original file
Delete the last import
Import again


Transactions and form api Is it possible to use FAPI and transactions?

I need to implement a validation that makes a query to check something and on the submit I need to update the database.

I thought to open a transaction on the validation callback and set it on the $form_state and then commit my transaction on the submit handler. I didn't liked this solution but was the best that I could think.

How do you solve this kind of things on drupal? What do you think about my solution?

Can you use FAPI with transactions: Yes.

But you can't or rather shouldn't use it the way you describe. Transactions only take effect when you commit them, so there really is no point in starting the transaction in the validation. Also what happens if you have a validation error, you won't commit the transaction. I believe that starting a transaction will effect other incoming queries as well.

Transactions are only good if you want to do multiple queries at once, and do all or nothing. Like insert data in main table and revision table and then update the revision number in main table.

What are you trying to do that makes you think that you should make transaction in such a way?


How do I remove the term ID from the view URL? I have a content view with an exposed filter based on a vocabulary.

In the URL (for example, mysite/myview?tid=taxonomy+term+(3)), and incidentally in my page title (I use argument.tid to display a title based on the term typed in the exposed filter), there are the name of the term (perfect) but also the term ID.

I only need mysite/myview?tid=taxonomy+term or, better, mysite/taxonomy-term.

How can I achieve this?

Perhaps you can do this using htaccess rules.

You can probably apply the patch from this issue and than according to the reports you will be able to create a path alias from within drupal that accept url parameters (as in your case)

But you can also try views_url_path_arguments which seems to be usable in Drupal 8 judging from the amount of downloads.

Perhaps you can also give this sandbox module Query Parameters To Url a try

Note: I have not tested the above 2 modules


Migrating CCK fields I'm in the process of upgrading to Drupal 7.12 from Drupal 6.25.
I have been upgrading all my modules as well, and now is time to figure out how to migrate the data from CCK to D7 Fields.

I found the Migrating D6 Content Construction Kit (CCK) to D7 Fields article, which explains how to do this.

Unfortunately I after I update the CCK module, and enable the Content Migrate Module, I don't see where the Content Migrate Module under Admin -> Structure -> Content Migrate!

I'm stuck and I don't know what to do. Any ideas/suggestions?

Before I could run the CCK migration I needed to run the mywebsite.com/update.php script before I could use the Migrate Fields.

That solved my issue.


Get current user password before it is overwritten in user form? I know this is probably unlikely, but I am doing the diligence anyway.

Is there any way to get the current user password from Drupal before updating it with a new one on the user form (user editing account info)?

When it is updated, I would like to trigger an API call to a remote system and update the account password there, too (authentication happens on an external system). However, the API call requires the old password as well as the new one before it will update it.

Otherwise, I need to lock off any way of updating a password in Drupal from privileged users.

Yes you can. The password only gets hashed when the user entity is saved as part of PasswordItem::preSave().

So you can add a submit handler to the user form, fetch both the old password and the new password (as users are required to enter both usually*) and do what you want with it.

There are discussions about that being insecure, so it is possible that this will change in the future.

There are exceptions to this, for example after using a one time login link, users are allowed to change their password without providing the current one.