How to use standard Drupal 7 farbtastic component? jQuery error So, this is my code:

  drupal_add_library('system', 'farbtastic');

I've added it to a page callback function (also tried putting in an implementation of hook_page_alter()). It doesn't seem to initialize properly, it fails on the first line of the system library farbtastic,

  Uncaught TypeError: Cannot read property 'farbtastic' of undefined

Has anyone had this issue before? Any ideas? I get the sense I'm doing something wrong because farbtastic is part of Drupal core now...

The Drupal core's farbtastic works differently. You will have to attach it to a an element eg: a form widget.
Eg:

colour_mod.module

$form['colour1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enter Colour:'),
    '#tree' => TRUE,
    '#description' => '

',
    '#attached' => array(
        'library' => array(
            array('system', 'farbtastic'),
        ),
        'js' => array(drupal_get_path('module', 'colour_mod') . '/colour_mod.js'),
    ),

);

colour_mod.js:

(function ($) {
  Drupal.behaviors.colour1 = {
    attach: function(context) {
                var farb = $.farbtastic("#color_picker");
   }
  }
})(jQuery);


xpath XML parser is not parsing anything, neither does give any debug info Mappings:
https://www.evernote.com/shard/s61/sh/3e900019-a2c7-4a10-bc1c-0868341c4d9d/a735396d74047a86da8668c34c7a9f7d

Source feed:
https://www.monosnap.com/image/BmKv9p9ao4hua1wvWpRh2pl85

For some reason I can't get it to import anything. What am I missing?

Tried also context: //channel/item.

Feed path: http://poliisi.fi/poliisi/kanta-hame/home.nsf/feedrss.xml

This is very simple and basic feed which is giving me a major headache currently. Maybe a fresh pair of eyes is smarter than mine.

Solved. Module had some odd bug. Cloning earlier working importer and changing it identical to above worked.


Alter the results returned by "Display a summary" for the Addressfield module When I set contextual filters in a view for Content: my field: country and Content: my field: administrative area (state/province) and select "Display a summary" for "When the filter value is not available", it returns a list of country/administrative area codes (e.g. "JP"), not the names of the country/administrative area (e.g. "Japan").

How can I show the names of the countries/administrative areas instead of the codes?

Here is an alternative to @Kenny and @Bearden solution, using template preprocess instead of overriding the template. Not only it makes for a more readable solution, you can reuse it for other views. It should also work for list summaries, just remove _unformatted from the function name.

/**
 * Implements hook_preprocess_views_view_summary_unformatted().
 */
function MYTHEME_preprocess_views_view_summary_unformatted($variables) {
  if ($variables['view']->name == MYVIEW) {
    // Necessary for country_get_list().
    include_once DRUPAL_ROOT . '/includes/locale.inc';
    $countries = country_get_list();

    // Looping through the row keys for performance reasons.
    foreach (array_keys($variables['rows']) as $rowid) {
      $countryid = $variables['rows'][$rowid]->link;
      if (!empty($countries[$countryid])) {
        $variables['rows'][$rowid]->link = $countries[$countryid];
      }
    }
  }
}


How can I disable default blocks in Drupal 7 without touching the Blocks Config admin? I'm trying to disable the search form, navigation, and user login blocks from being enabled by default. My main goal is to not touch the admin at all because I want to version control this.

Is there a way to disable the blocks with some sort of hook? I'm newb when it comes to php and coding for Drupal so please be kind.

hook_block_info_alter() can be used to alter the default configuration of blocks. From there you can set the status, region, visibility and pages settings that match the wanted configuration. But once the blocks configuration has been written to the database, changes made with this hook will have no effect.

Sadly there is no other hook to configure blocks. But you can write the needed information to the database yourself as part of a custom module or profile hook_install() or hook_update_N() implementation. The standard_install() function from the standard module provide example code for that. If this is done from an hook_update_N implementation or a module, rows for the blocks may already exists in the database. You can then use a merge query for each block to avoid having to deal with the "is this an insert or a an update" question yourself.


How to make profile2 completely replace or override the core profile? I have installed the Profile 2 module. I want to make it replace or override the core profile module for the entire website but I don't know how to achieve this. I have searched a lot, but have not found a solution. This is a new website, so I would not need to migrate existing profiles to profile2.

Can this be done using the Panels and Page Manager modules?

Is it a good idea to keep using the core profile module?

Any help is highly appreciated.

I wouldn't recommend doing this as profile2 is designed to compliment the core profile module.

The simplest way of explaining this is that the core profile module handles your account while profile2 handles all the extra information not required in order to be a Drupal user.

On a large sports team website that I run we use profile2. When users go their user page they see in order:

Their picture (a field of the core profile module)
Their email settings (core profile module)
A heading titled "Personal Information" (profile2 module)
All their personal information (First Name, Last Name, DOB, Address, Contact Number) (profile2 module)
Another heading title "Medical Information" (profile2 module)
All their medical info (Injuries, Allergies, Medications, Emergency Contact) (profile2 module)

When they go to edit their profile, the main tab is titled "Account" and allows them to change their username, email address, password, email settings, and profile picture. Profile2 adds "Personal" and "Medical" tabs where users go to complete the other two profiles.

Our club contact list gives all users access to the main profile which contains the username, picture, and email address. Only club executives and coaches have access to the personal information profile and only coaches have access to the medical information profile.


add field with date field I have created new field for my content type "Flag", its list type field

possible values of it is

-Draft
-Sent
-Approved
-Rejected

now for this field new table is created,now i want to store date here,what i exactly want is like:

-Draft on date DD/MM/YYYY (the date of the creation of the project)
-Sent on date DD/MM/YYYY
-Approved on date DD/MM/YYYY
-Rejected on date DD/MM/YYYY

now how to achieve it.

am using drupal 7

Use Field Collections and add two fields to field collection and enable field collection field on your content type... Or Create two fields Flag and Flag date...

Flag
Flag Date

OR

You can use revisions to track these changes in Drupal. When ever you change above field make content as a new revision so that you can track dates too...

OR

Create a few more date fields, each for possible values to track the dates... use form api #states property to hide display fields based on selection of flag value..

Flag
Draft Date
Sent Date
Approved Date
Rejected Date


How to get list of cron tasks? Drupal 6 possible noob question. Is there a way to get a list of cron tasks from the Drupal 6 Admin? I am a themer for the site. The original dev is long gone. Everyone complains of slowness and 500.shtml errors. I looked in the log and noticed that these are most often associated with a cron task that runs hourly. But I can't see what those jobs are. Once I get the list is there also a way to disable unneeded tasks from within Drupal?

I'm running Windows on my client machine. I don't have DRUSH.

Thanks In Advance

Or simple use

drush ev 'var_dump(module_implements("cron"))'

For list the cron job that exists.


Programmically create a content type with publishing options I've been able to successfully create a content type on the install of my module by following Creating a custom content type in Drupal 8 in the drupal.org documentation, but I can't find a way to add the publishing options.

How should I add the publishing options when creating a content type?

You have to add a base field override to change the default value of status, promote and sticky for newly created nodes. For the first and second option the default value is predefined as TRUE and for the third option as FALSE in the base field definition of the entity type. See this example for promote:

Drupal\node\Entity\Node::baseFieldDefinitions

$fields['promote'] = BaseFieldDefinition::create('boolean')
  ->setLabel(t('Promoted to front page'))
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE)
  ->setDefaultValue(TRUE)
  ->setDisplayOptions('form', [
    'type' => 'boolean_checkbox',
    'settings' => [
      'display_label' => TRUE,
    ],
    'weight' => 15,
  ])
  ->setDisplayConfigurable('form', TRUE);

The base field override needs only to be present if you want to change this preset for a specific content type.

Example for the status field:

foobar/config/install/core.base_field_override.node.car_brand.status.yml

# core.base_field_override.node.car_brand.status.yml
langcode: en
status: true
dependencies:
  config:
    - node.type.car_brand
id: node.car_brand.status
field_name: status
entity_type: node
bundle: car_brand
label: 'Publishing status'
description: 'A boolean indicating the published state.'
required: false
translatable: true
default_value:
  -
    value: 0
default_value_callback: ''
settings:
  on_label: 'On'
  off_label: 'Off'
field_type: boolean

You can override the fields promote and sticky the same way.

The same task in PHP:

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'car_brand');
$fields['status']->getConfig('car_brand')
  ->setDefaultValue(FALSE)
  ->save();

The method BaseFieldDefinition::getConfig loads an existing base field override or creates one if none exists from the base field definition in the entity type.

Using the PHP code in an install hook is IMHO the better solution, because you only need to change the default value and don't need to repeat all other values.


How do I replace drush_set_error()? Just updating a module for Drupal 9 and Drush 10 and drush_set_error() no longer appears as a function in the Drush code (as far as I can see). What should I be using instead?

drush_set_error() has basically been deprecated in Drush 8 and has been removed in Drush 10. Hitting up Google for drush_set_error() will give you a blog post by one of the maintainers: Porting Commands to Drush 9. In there the following is stated.

Replace drush_set_error() with throw new \Exception()

Now let's compare a sample command in Drush 8 and in Drush 10 – the xkcd command.
In Drush 8 there's the following line:
drush_set_error('DRUSH_XKCD_SEARCH_FAIL', dt('The search failed or produced no results.'));

In Drush 10 this line became:
throw new \Exception(dt('The search failed or produced no results.'));

One more.
When you search the pull requests for drush_set_error() you'll find the following: Replace drush_set_error() and drush_log() via Drush::logger() #3810. In there drush_set_error() has been replaced by Drush::logger()->error().
Now what's the difference between Drush::logger()->error() and throw new \Exception()?

throw new \Exception(dt('My error messsage.')); is the last thing you do before Drush quits.
Drush::logger()->error(dt('My error message')); gives you the chance to print out multiple error messages and let your code continue.


Unable to add field on a view I am copying this question from https://stackoverflow.com/questions/25900553/unable-to-add-field-on-drupal-7-view as I can't see a move option sorry.

This has been driving me crazy, so let me explain why.

I am building a Drupal 7 site using kickstart commerce, I have been adding fields to the view for checkout, cart and orders fine.

But all of a sudden it seems to do nothing. Let me explain further.

In the edit view page, I click on Add to add the field I want.

I then find the field I want to add and then click on 'Add and Configure fields'

Then normally I would be able to configure the field, however that has now stopped.
Instead I just get the loading symbol  and then nothing no configure pop-up or the field added.

I dont understand why this suddenly stopped working, I have cleared the cache and disabled non-required modules, no luck. The fields are configured/added in the same way apart from being different the method they were created in was the same, I have deleted the fields and re-created them still no luck.

Has anyone had this with Drupal 7 or can give me some indication which direction to go in next, thanks in advance.

As I stated on the stack overflow question, its not a relationship things as fields configured the same way are able to be added. Existing fields can be removed and added ok.

If I rename to something like test it still fails to add.

I have checked modules that were installed after i noticed the issue, the only one i could see was context disabling this had no effect.

All out of ideas, Google has been no help either :-(

A further update to my question I just updated to the latest commerce kickstart(commerce_kickstart-7.x-2.17) and this did not help at all.
The issue still remains.

I have run into this issue repeatedly and often the only way I have been able to add the missing field/relationship is to export the view, add the new field/relationship in a text editor, and then re-import the view.


How do you create a colorbox popup on the frontpage of D7? I'm using Colorbox and Drupal 7. I'm trying to create a Colorbox of an Image on the front page in a POP-UP. The problem is I can't figure out how to get it to show up on page load. How can I achieve this without adding an additional elements showing on the frontpage?


Why would my Cron run fail when run by system crontab, but succeed when run manually? The Cron tasks on my website run perfectly fine if I manually execute cron. However, I have the server set up to automatically run cron every hour. When cron is executed automatically it fails... every time. The error message is always about memory usage exceeding the allowed levels (which are already rather high). Most of the time, though not always, this error is thrown from the Date module. I do have a feed set up that pulls from a large Google calendar, so I've been thinking that might be the problem. But why would it succeed when run manually? I understand that when run manually it's run as my admin user, and when run automatically it runs (correct me if I'm wrong) as an anonymous user. Does that have something to do with the failure/success pattern?

Edit: Posting the actual cron command as requested

/bin/php5 -q /path/to/my/account/public_html/cron.php

Check to see if you have a php-cli.ini file being loaded. From the command line, do:

$ php -i |grep ini

and see what ini file is being loaded. If there's a cli ini loading, it may not have the same memory limit as your 'normal' php.ini.


Display one time message to user upon logging in I'm looking for a module (or another way) of displaying a message to all users only once after they login. Basically, a client wants to add a newsletter on their site, and would like to give the change to all the users with accounts once they login to signup to the newsletter. They just want the message to appear once, the user can dismiss it, and then it will never display again. Ideally it would be possible to generate more messages at future dates for other reasons (changes to privacy policy, offers, etc).

I've looked at a few modules, including LoginToboggan, Rules, Flag, Absolute Messages and EU Cookie Compliance but none seem to do what I need.

Anyone know of a module or a method of implementing this with the above modules?

You can try the Splashify module

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.


Site caching a php page? I recently 'inherited' a website which has a Drupal installation on it. I know absolutely nothing about Drupal. I don't want to go on for too long, but the site is an absolute mess. It looks like there are two separate websites there that interweave. In all honesty, I dont think I could have paid someone to make a less understandable website. None of the code is documented, there is just no sense to any of it.

Well here's my problem -

I recently changed all of the FTP, SQL and site passwords so the previous ownership couldn't access the site.

On one of the pages there is a PHP script that processes a form. In the form, the php accesses a file called, "login_credentials.php" (sigh...) which contains the SQL login info.

Now, whenever someone tries to use the page, there is an error that says invalid password on line 12. I, of course, have gone into the login_credentials.php file and confirmed that the password is the new password.

I also went in and even changed the code so that the SQL connection is on a different line (line 13) but the error still says line 12. This is telling me that the page is somehow cached (maybe?), but I have no idea how.

What's even stranger is that if you are logged into the site as an admin, the error DOES NOT occur. This problem only occurs to the public. (only admins need to log in).

I honestly can't say what the problem is. I'm only moderately savvy when it comes to php/html etc, and know nothing at all about Drupal.

Any ideas?

Have you cleared cache yet? If not, go to the URL below to clear the sites cache. See if the error changes like you expected.

Drupal 6: /admin/settings/performance/drupal
Drupal 7: /admin/config/development/performance

It could also be that you changed the password of the SQL user that Drupal uses to operate, in which case you would need to update that information in /sites/yoursite/settings.php

What version of Drupal are you using?


Uncaught exception thrown in shutdown I am trying to solve this issue from last three days. Searched lot regarding this issue but not getting any solution.

I have also visited these links link1 link2 or duplicate questions

This error is occurring at the time of installation, I am installing Drupal7 on linux

I am using PostgreSQL 9.4.8 database, php PHP 5.5.9

The database user has granted all permissions

following are the exceptions

first exception

    Uncaught exception thrown in shutdown function.

    PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;semaphore&quot; does not exist LINE 1: DELETE FROM semaphore ^: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] =&gt; 2108550473576798c2ab0410.91648409 ) in lock_release_all() (line 269 of /var/www/html/rentspeak/includes/lock.inc).

second exception

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation &quot;sessions&quot; does not exist LINE 3: sessions sessions ^: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] =&gt; AqE0DsCH1bG6qk3nMspgcEW1J_FUDbF15vNkX5nSdUU [:db_condition_placeholder_1] =&gt; ) in _drupal_session_write() (line 209 of /var/www/html/rentspeak/includes/session.inc).

I just tried to setup a fresh Drupal 7.44 with Postgresql and I haven't encountered any issues. The setup went fine. Here are the steps I did.

$ su root - Switch to root user.
$ su - postgres - Switch to Postgres user. Note that you need to be root first before doing this.
$ createuser --pwprompt --encrypted --no-createrole --no-createdb gerald - Create a new user called gerald.
$ createdb --encoding=UTF8 --owner=gerald drupal - Create a new database called drupal.
Run the installation and select the Postgresql type.

Another way to determine the culprit is by reading the logs.

For Postgresql

$ sudo tail -f /var/log/postgresql/postgresql-9.3-main.log. In you case it should be $ sudo tail -f /var/log/postgresql/postgresql-9.4-main.log.

For PHP (if you're using Apache)

$ sudo tail -f /var/log/apache2/error.log

Additional Troubleshooting

Also check if there is a problem with timeout in PHP. You may want to increase to default timeout settings.

My stack:

gerald@von-viel ~/ $ psql --version
psql (PostgreSQL) 9.3.13
gerald@von-viel ~/ $ php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)

Note: I am using the default configuration of Postgresql.

Hope this helps!


Where to programmatically enable a Feature module I created a Drupal 7 feature and usually I would enable it with Drush, but someone suggested that I enable it with an update hook (which I assume means it gets enabled on updb or update.php).

I saw this discussion on enabling modules programmatically How do I programmatically install and enable a module?, but it blithely skips over where to write the code. Does it go somewhere in the installation profile? Does it have to be called from another custom module that is already enabled?

I'm actually an experienced Drupaler that has somehow managed to miss this one crucial lesson, I've just been using Drush to enable modules but I want to do this the best way.

A feature module is just another module. And you can enable it programmatically using the linked code from another enabled module's hook_update_N placed in this another enabled module's *.install file. This even can be another feature module. Then have this hook fired via drush updb on the command line or by visiting your site's /update.php.

You also could do that from a form submit handler. Or even from a menu callback providing some custom endpoint you can access with cURL for example.

It's safe to use other feature modules' *.install files. Since Features never touches *.module and *.install files during regeneration. So you are free to use them to your needs.


setup Drupal with Docker: clone repositories via deploy token I am quite new working with docker. I tried to set up drupal via docker and docker-compose.
So far i got a running instance and installed drupal via the installation script.

No i want to clone repositoires via the Dockerfile, which is a drupal module. So after cloning and rebuilding the module should appear in the admin/modzles page)

So i edited my Dockerfile so it looks like this (the last few lines).

FROM drupal:7-apache

RUN apt-get update && apt-get install -y \
        curl \
        git \
        mysql-client \
        vim \
        wget

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
        php composer-setup.php && \
        mv composer.phar /usr/local/bin/composer && \
        php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
        chmod +x drush.phar && \
        mv drush.phar /usr/local/bin/drush

RUN rm -rf /var/www/html/*

COPY apache-drupal.conf /etc/apache2/sites-enabled/000-default.conf

WORKDIR /app/web/sites/all/modules
RUN git clone -b <branch> --single-branch \
      https://<deploytoken>:<pw>@<gitlab-address>/<path-to-git-rep>.git \

WORKDIR /app

This is my docker-compose.yml

version: '3'
services:
  db:
    image: mariadb:10.2
    environment:
      MYSQL_DATABASE: drupal
      MYSQL_ROOT_PASSWORD: <pswd>
    volumes:
      - db_data:/var/lib/mysql
    restart: always
  drupal:
    depends_on:
      - db
    build: .
    ports:
      - "80:80"
    volumes:
      - ./app:/app
    restart: always
volumes:
  db_data:

Then i used docker-compose build and docker-compose up. It looks like the repository gets cloned and the latest images is used (no errors) but the repository is not in the folder. What did i do wrong?

The way I handle this is creating a gitlab auth.json file and with your token and using a volume mount to put it into the container.

volumes:
  - /Users/${USER}/.composer/auth.json:/home/wodby/.composer/auth.json # composer auth

In some instances I've wanted my ssh keys in there as well for certain operations, but shouldn't be needed for a pull off gitlab. This is just as easy.

volumes:
- /Users/${USER}/.ssh/id_rsa:/home/wodby/.ssh/id_rsa # ssh


How to redirect URL with language prefix to the same URL with no prefix (default language) I have installed i18n module so two languages Japanese and English are available. I have set Japanese to the default language and also "language Language negotiation" to "path prefix only". So all the URL without language prefix show the Japanese pages and English pages with the prefix of "en".

What I want to do is to redirect some of URL with prefix to the same URL without prefix as I need to make some of the pages available only in Japanese. For example, when a user is trying to view my-site.com/en/cart the user is automatically redirected to my-site.com/cart as I want to make the my-site.com/en/cart unavailable.

I have tried path redirect  but the redirect doesn't work though I set two cases as below

"Language" to "All languages " ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".
"Language" to "English" ,"From" to "my-site.com/en/cart" and "To" to "my-site.com/cart".

The below answer requires that at least part of your website is using Page Manager + Panels. In my opinion, they should anyway, but others will disagree.
Both of these modules are tools, as opposed to solutions, so this answer will require that you research and understand these two modules. Link to excellent video tutorial. At the time of writing, this requires the -dev version of Ctools.

At the time of writing, this Ctools patch must be applied for the following instructions to work.

Ensure that the page you want to redirect from, is managed by Page Manager. This page will have 2 variants.
Add a "HTTP response" variant, with a 301 response to cart. More details on this step in another question. It's important that this variant is the topmost one. You can reorder them afterwards, if need be.
On the HTTP variant, go to the "Context" tab on the left side, add a "Language" context, selecting "Current language".
Go to the "Selection rule", and add a "User:Language" == "English".
Add a second variant, this time a Panels variant.
In the second variant, add all the content that you wish to be part of the Japanse page.


List text field dependent of text field In my user edit form I want to add a text field where it asks name of class and I want to add other field List text type and it will display the grade for example:

Math        Grade 7
Now the issue is that teacher can add more than 1 class so and the option field I set unlimited elemts but it doesn't work properly because also I need to add element in List text.

I want to achive this:

Math   Grade 7
Bio    Grade 5

Add class

Issue:

Math Bio
Grade 7 Grade 5

one is not depending of other, please Help!!

You can use Field Collection module to achieve this.

Using this module you can create group of field, such as class and grade in one collection. Also you can set 'Number of values' to unlimited for field.

Thanks!


What does the checkbox "link to content" do? I am creating some custom content but have not got round to creating the views yet. When looking at the layout tab I see this

What content does this refers to? All my Plain text fields have this checkbox, but none of the others.

It seems you are in display settings of a content type and these are the fields it has. Link to content in this context means that when this field is displayed it will link back to the parent node.   It will be displayed as link similar to this
SurnameThis surname

where the /node/2 would be the url of the node you are actually viewing
NOTE: if you enable this on the default content type view mode it will not make much sense as it will link on the page you are currently on (node/2).  This makes sense for example when the node is displayed as part of a view and in that case if clicking on the link will take you to the full node.


CSRF validation failed issue on custom services! I have created a custom services API to save order records in database. I have checked on POSTMAN and it is working fine. But when i request from apps it gives me "CSRF validation failed" issue.

Am i missing something?

You can check workflow steps

First Time for login

POST /services/session/token to retrieve CSRF Token POST
myendpoint/system/connect with X-CSRF-Token header IF not Logged In
Try Log in /myendpoint/user/login Log in Success and keep
session_name=sessionid in Cookie Varible

Future Launches

POST /services/session/token to retrieve CSRF Token
POST myendpoint/system/connect with X-CSRF-Token header along with previousely saved session_name=sessionid as Cookie Header

Don't request for new CSRF token use the returned one for previous request.
You will find it in a key named token in the result returned.
Just request a new csrfCSRF token for the first time only.

Here is an example of a user profile request:

{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}


How do I correctly display OG content using Views? I have an Organic Group page, inside I have a view which lists out news items specific to this OG. However it is showing 'There is no content in this group' when I am not logged in. And shows up fine when I am logged in.

I have checked that the new article is published, the permission of the View is set to 'Permission' | 'View published content', and I also ensured that the 'View published content' permission is checked for anonymous user.

It's obviously a permissions issue, but I cannot see where else I can set permissions. I am using Workbench OG but there are no relevant settings on there.

How do I correctly display OG content using Views?

It could be that you use a relationship in the view that is restricted to only authenticated users.
Or it could be that you have set group content visibility to hidden.

But let's start from the beginning..check if it works with a simple view like this:

Create view of nodes, filter it by node type,
Add relationship: OG membership: OG membership from Node
Add contextual filter: OG membership: Group ID, and use the relationship you just created, and set default value: content ID from URL.

If the problem you describe still appears, you can check if it is a permission issue by selecting "Disable SQL Rewriting" in the views settings. But this will disable views permissions and is not wise apart from testing purposes.


A Content Type with custom fields How would you suggest approach this using Drupal 7?

I'd like to create a 'Video' content type with the usual videos fields but I would also like each individual video content type to have many images attached, with each image having fields of it's own.

Basically, each content type would require one video and many images, with fields relevant for each image.

I've looked for duplicate questions and can't see anything that fits but if you know of something please point me in the right direction.

Thanks,

Field Collection is a good option if the images will not be re-used across multiple Video content types. If you need to re-use the Images (and their field values) across multiple Video nodes, another option is to create a separate "Image" content type and use the Entity Reference module to link the Image nodes to the relevant Video nodes.


How can I restrict user access to view nodes based on field value? I am setting up a relatively simple website using Drupal 8.  There are several different content types.  Within each content type I would like some content to be available to anonymous users and some only available to authenticated users (i.e. 'member only' content).

I would like to add a simple tick box field that would control whether the content was publicly available or not.  i.e. if the field is ticked then it is available to anyone but if it isn't ticked then it is only available to members.

I have managed to get some way to achieving this by using Node View Permissions and creating a duplicate of each content type - both have the same fields but one is visible to anonymous users and the other is only visible to authenticated users.  This works, but isn't very satisfactory because it requires duplicate content types.  I would prefer to have a single content type with a field that controls view permissions.

Do you have any suggestions?

You could use a programmatically solution using hook_node_access(), in this example the field_YOURFIELD is a checkbox.

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  $access = new \Drupal\Core\Access\AccessResultNeutral();
  if ($node->hasField('field_YOURFIELD')) {
    $field = $node->get('field_YOURFIELD')->getString();
    if (empty($field) && $account->id() != $node->getOwnerId()) {
      $access = new \Drupal\Core\Access\AccessResultForbidden();
    }
  }
  $access->addCacheableDependency($field);
  $access->addCacheableDependency($node);
  return $access;
}


How do I download a form table in CSV or Excel format? I have a form whose class extends FormBase. The form has a table that gets populated with information.
Basically I'm trying to download the table into a CSV or Excel file. I've seen some old posts for Drupal 6 but I haven't found anything for Drupal 8.
How can I achieve this?

You can use the Forena module. Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

So if you'd install Forena in your site, then these are the steps for creating such CSV files are:

a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

For an online demo (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


Modify form elements based on current select box value in same form? I'm writing a custom module and I have a select box in a form with two values, Test and Production.  I want to remove a specific fieldset from the form if Production is selected, and add it back if Test is selected.  Is there a straightforward way of doing this?

Certainly, you can utilize the #states setting.  Information can be found in the Drupal Forms API as well as in the drupal_process_states() API where you can see examples and documentation on how you can toggle your fieldset based upon the value of that select box.


Custom module for adding CSS file in admin section How do I include admin.css in my theme so that it's loaded in the admin section (and preferably only the admin section)?

Right now when I add admin.css via the x.libraries.yml file, it's only loaded on the front-end.

Update:

So... based on your comments/answers I've created a module admin-css. But nothing happens. The file isn't loaded. What am I doing wrong?

Inside admin_css.info.yml :

name: Admin CSS
description: Alters the Admin CSS for better usability.
package: Custom

type: module
core: 8.x

Inside admin_css.libraries.yml :

admin-css:
  version: 1.x
  css:
    theme:
      css/admin.css: {}

Inside admin_css.module :

<?php

function admin_css_attachments(array &$attachments) {
    $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
    if ($is_admin) {
      $attachments['#attached']['library'][] = 'admin_css/admin-css';
      return;
    }

}

Unless you use the same theme for front and backend, that's not the right approach.

If something transcends the theme layer, e.g. you have functionality that you need to apply to two separate themes, it belongs in a module.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module for instructions to actually accomplish that, specifically the section on Attaching a library to all (or a subset of) pages which contains a contrived code example:

function contextual_page_attachments(array &$attachments) {
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
    return;
  }

  $attachments['#attached']['library'][] = 'contextual/drupal.contextual-links';
}


Drupal 8 secure session In Drupal 8.5.X I see that the session cookie is only HTTPOnly and not secure. Any idea how to enforce the session cookie to be always secured?

The HTTP flag is being set by your browser as you're accessing Drupal over HTTP (and thus vulnerable to cookie hijacking). Drupal creates 2 different cookies (an unsecure HTTP one, and a secure HTTPS one) depending on what protocol it detects.

If you want only secure sessions, force HTTPS at the web server or application level (depending on your stack configuration).


Content type Text field as Geolocation source field in View I have a text field(named as address) in my content type and I will store the address in that text field. Here I don't want to store the address in geolocation field so I have to use text field to store address.

I just created the View with page and have set Format as "Geolocation Google Maps API - CommonMap". In that Format settings I have to set Geolocation source field to display the Map. But I can't able to set Content type Text field as Geolocation source field.

Is there any way to set Content type Text field as Geolocation source field?

Map formatters usually only take geolocation data in order to display them (latitude and longitude for example). There is a way to "convert" a textual address into geolocation data with the help of a Geocoding service.

So you do have to create a geolocation field. You can set it to automatically take the address and convert it to points on a map, and you can hide this field from users. It's a problem though if the address someone enters isn't correct in some way.

With the geodata ready in that field you can set your views map to use that field as the source for geo points on a map.

Here's a comparison of modules that can help you with this: Comparison of Mapping modules.

It seems your best bet is Geofield Well Known Text and Geocoder.


Custom Ajax Route, I want to cache it I'm making an Ajax call to a route that performs an entityQuery.  I know that when a node is added, it will change the results of that entityQuery, but until then, I want the route to return cached data so it doesn't have to perform the full query every time.  What is the fastest way to do this?

Is there a way to put a cache tag on the route itself, that I can invalidate on node creation?

Should I do a $cache = \Drupal::cache()->get($cid) kind of thing in the route itself?

Thank you for reading.

What kind of ajax exactly? I guess it returns JSON?

Drupal's standard ajax API currently always does POST requests, those are not cached. So make sure you are doing a GET request.

Render caching is also only available for render arrays/HTML.

Your response would be cached if you return an object that returns CacheableResponseInterface but only by the (anoymous) internal page cache.

To have caching for all users, you likely need to implement your own logic  to cache the response object as you suggested. By default, the node_list cache tag can be used to have it invalidated automatically whenever any node is created or saved. You can define your own cache tag (any string works) that you invalidate yourself only when certain conditions are true (for example, a new node of a specific type, matching your entity query).


Store query result on an array This is a simple query

$sql = db_select('node','n');
$sql->fields('n', array('uid','title'));
$s = $sql->execute();

I need to check the uid of all records :

if('n.uid' !=1 ) { do some stuff}

Should I store query result into an array before the if condition ? If yes how to do it ?

Here you can replace $sql with $result.

<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);

// Retrieve a 2-column result set as an associative array of field 0 => field 1.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// If you need an array where keys and values contain the same field (e.g. for creating a 'checkboxes' form element), the following is a perfectly valid method:
$result->fetchAllKeyed(0,0); // would be field 0 => field 0, e.g. [article] => [article]

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>


Bootstrap from external script I am trying to create Drupal entity instances from an external script that is not part of Drupal or a Drupal module.

For Drupal 7 there was drupal_bootstrap to load the required Drupal dependencies. However, after a long search all I found for Drupal 8 was a note that drupal_bootstrap is deprecated for Drupal 8.

And indeed, I get a

  Call to undefined function drupal_bootstrap()

when I try to call it after including as in

define('DRUPAL_ROOT', __DIR__ .'/../drupal');
require_once DRUPAL_ROOT . '/core/vendor/autoload.php';
require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

So how can I use the Drupal 8 API from an outside script?!

For current version of drupal 8.x:

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
        array(
          'type' => "article",
          'title'=> "test entity",
          'body' => "body body body",
        ));

$entity->save();


How to place multiple form elements from a loop I have a table that will have multiple table rows that are generated dynamically using a foreach loop. In these rows will be textfields using the Drupal forms API.

Example:

$f = '
';
$f .= '
Something...
';

foreach($somethingAwesome as $val){
    $f .= '
';

    $form['blah'][$val] = array(
        '#type' => 'textfield',
    );

    $f .= '
';
}

$f .= '
Something else...
';
$f .= '
';

$form['woot'] = array(
    '#type' => 'whatever',
    '#prefix' => $f
);

This winds up outputting the form elements after the table in the page. This is not what I am expecting.

The output looks something like:

Something...
Something else...

Textfield
Textfield
(etc...)

It should look like this:

Something...

Textfield
Textfield
(etc...)

Something else...

I have tried using the #prefix in the textfield form elements but that produces some odd unexpected (at least for me) behavior.

I am using Drupal 7, if that makes any difference.

Edit: Added that I am in fact adding the $val to the $form element in the foreach loop

You could try this if I understand correctly:

$header = '
';
$header .= '
Something...
';

$form['header'] = array(
  '#markup' => $header;
)

$i = 1;

foreach($somethingAwesome as $val){

    $form['blah_' . $i] = array(
        '#type' => 'textfield';
        '#prefix' => '
'
        '#suffix' => '
'
    );

$i++;
}

$footer = '
Something else...
';
$footer .= '
';

$form['footer'] = array(
    '#markup' => $footer,
);

This should give you the output:

Something...

TEXTFIELD
TEXTFIELD
TEXTFIELD

Something else...

You'll need to do something to differentiate each $form['blah'] part too, otherwise you'll be running a foreach loop that overwrites that specific part of your form on every iteration.

You're running your foreach loop in the place where you want it, but all of the data you want surrounding the form is being put into one variable, and then added in one go as a prefix.  Suffix will add data to the end.

General Reference (in case you didn't know):

FormAPI Reference

Specific References:

#prefix

#suffix


How to restrict particular user roles from Adding child pages to the particular books only. I am using drupal 7. I want to restrict some users from adding book pages to the books.

I have several books on my site and each book has different authors. As i have given add book
pages access to authors any author can add book pages to any book which i dont want.

I just needed to give add book pages access to each author bookwise.
Is there any module available for this i am already using book access for editing the content but i didnt find for adding content restriction.

All node access modules, including Book access, are whitelist only.

  Node access modules always GRANT access and never restrict it. (It is a whitelisting rather than a blacklisting system.) If you use two node access modules and one grants access while another does not, access is granted. Exceptions are the Deny access module, as well as the old Module Grants module through which it is possible to combine access grants across multiple modules in a more intuitive way. Without it, the displayed behaviour may appear backwards from what most people would assume, and it's the reason why it is tricky to get involved with multiple node access modules. It is possible to use multiple node access modules in harmony however if for example they are applied to different content types or are giving out different grant types.

This means you need to deny access to books, generally, and then use  Book access to grant it per book. If you grant it via Drupal settings, you will grant it to all books, and grants are additive - so some people would be allowed, and some would be "doubly allowed", and no one will be denied.


Multiple user-selected front page layouts I would like my site builders to be able to select from three unique front page layouts.  The selection can be made either through config or through theme settings, but not require any coding.  The three pages have different pieces of content consisting mostly of fields.  I've looked at panels but I would prefer to use something a little lighter as panels seems like a lot for this one piece of functionality.  Has anyone here solved a similar problem?

You could add a checkbox in the theme settings and adjust the page template accordingly in a page preprocess.

Something similar to this would go in the theme-settings.php file in your theme...

function THEMENAME_system_theme_settings_alter(&$form, $form_state) {
    $form['front_layout'] = array(
      '#type'          => 'radios',
      '#title'         => t('Front Page Layout'),
      '#options'       => array(
        'layout_1' => t('Layout 1'),
        'layout_2' => t('Layout 2'),
        'layout_3' => t('Layout 3'),
      ),
      '#default_value' => theme_get_setting('front_layout'),
    );
}

Add new page template suggestions in a page preprocess ...

function THEMENAME_preprocess_page(&$variables) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['theme_hook_suggestions'][] =  'page__' . $layout_setting;
  }
}

This would allow you to have separate page templates for each layout. An example being page--layout-3.tpl.php.

If it's merely css changes you need, you could add a body class in an html preprocess ...

function THEMENAME_preprocess_html(&$variables, $hook) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['classes_array'][] = drupal_html_class($layout_setting);
  }
}

In this example you would have a "layout-1", "layout-2" or "layout-3" class on the body element.


Dynamic parameters passed to page callback I have the following hook_menu:

  $items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products')
  );

Here is the function:

function json_list_products($keywords) {

  $items = array();
  foreach(_sql_select_products($keywords) as $product) {
    $items[$product['Product_ID']] = $product['Product_Name'];
  }

  drupal_json_output($items);
}

$keywords is not populated with the value of the % as i suspected - how do I populate this value?

Alex

$items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products'),
    'page arguments' => array(2),
  );

view the documentation at this link


Cannot Upload Image or Cannot Display Image I am new in using Drupal.

First, I downloaded and installed a Drupal free template on my localhost. Everything works fine.

However, when I duplicated the site from localhost to sharedhost for testing, the image cannot be uploaded nor displayed in the test site when I am adding or editing contents. I went to check with the sharedhost provider, so far, it concludes that "safe mode off", and no error notice nor message is shown in the report.

I copy the reply:

"I am not sure if the paths set are the problem. I noticed your temporary directoy was set to C:/xampp/tmp and I have changed this to simply tmp for you as well as created the directory on the server with complete read/write permissions. It does not appear to have corrected the issue but will be good to have set down the road.

I beleive the issue is with the way Drupal handles image uploads. Unfortunately, it does not appear their are any error messages being generated or logged when an image is uploaded. This leads me to beleive Drupal is not attempting to generate the thumbnail instead of trying and failing.

I recommend creating a post in the Drupal forums regarding the issue. I am going to continue to investigate form here but perhaps someone on the Drupal team will have more insight into what could be causing this."

I just try to upload an image in a new content type and change an image in an existing content.  The error log shows:

"[Mon Aug 19 04:44:09 2013] [error] [client 218.102.131.79] File does not exist: /home/jwbb26i2/public_html/favicon.ico"

We have no idea about this problem. Can everyone help me know or solve this problem?

Thank you very much.

Make sure the directory exists and write permissions are set to 777 (probably 775 on production).

Check the permissions on site/default/files . You might have to ask your shared host admin for this. If you have ssh you can do chmod 777 site/default/files.


using contextual filters to filter with relationship I have articles and issue nodes, where every article is related to an issue. I am trying to create a Views block which shows related Articles. This block should show on on the Article node page.
What I tried was this:

I created a view of Articles. I set the relationship to Entity Reference: Referenced Entity field_article_issue and created a contextual filter on field_article_issue_number (a field in issues) using that relationship. This didn't work, and the block shows nothing. What am I doing wrong?

You can't show both. When you choose to show articles,  vieuws will select articles from the database using your conditions. Since an issue is not an article, they will not show.

What you probably can do is embed another view in your views header or footer section and display the related issues in that view.


Lost access to permissions checkboxes at admin/config/group/permissions/node/ Not sure what happened. I'm using Drupal 7.15 and the latest OG dev version (2.x) and for some reason, I lost access to all permissions checkboxes at admin/config/group/permissions/node/ - It's not even showing them in read-only mode, they are just not there.

I do have OG access control and field access modules enabled and I haven't done much but trying to create a new group and new content.

Rebuilding permissions or uninstalling the modules completely didn't help.

Any idea?

I think I found a corresponding bug: http://drupal.org/node/1649186


Make a from element visible when a radio button is clicked I have a problem to make a date and a list element in a form in HTML invisible if the user selects one way, and visible if the user selects two. How can I write the JavaScript code for that?

No need to write JavaScript for that; if you are working in PHP, you can use #states on the form element.

Example: form_example_states_form.

  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),

    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );


How to implement node.js For updating data in my block? I have one block in which I need to update data from database while on events like vote , comment , revision or creation of node?

I have set up node.js and can broadcast message to users accessing site but I have no idea how to use it for updating data in block.

Any help will be appreciated, please suggest?

Thanks!

node.js is event based. While implementing node.js have you implemented socket.io & express or you followed any other setup? By any means what you have to do in high level is,

Catch events on node CRUD or vote or if someone comments. Send these events to node server. Then emit those back to the clients.
In the front end your client javascript should listen to those events that you emit from the node server itself. Once you get those emitted events to your client just use jQuery/JavaScript in your client Javascript to update your block contents.

This is a highlevel algorithm that you have to follow. You can update your question with snippets of your code and may get more detailed answers.

EDIT # 1
Try to look in http://socket.io/get-started/chat/ for the event based implementation.
In that example you can see, a file called index.js. This is the node.js server file. And the index.html is the client. In both the files there are some events which are emitted. So I assume in your code you can add onclick function to emit an event to server. Then in the server you have to fetch the updated value. Then again emit a server event that will be received by the client.
I hope this makes sense. Well the implementation can become very complex.


Drupal Services 3.x - Custom error output Is there a way to control the output in the drupal services? Example, if a argument that is required, it not provided in the call, I get the following output as a JSON array.

Missing required argument title

I'd like to either override this output, or instead of returning a json object, just return plain text.

Is this possible to do?

You most certainly can.

If you open up the docs folder in the services module you can see the function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) in the file services.alter.api.php

<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}

Example output would be:

Array (
  [code] => 401
  [header_message] => 401 Unauthorized : Missing required argument username
  [body_data] => Missing required argument username
)

So you could alter it like,

function MYMODULENAME_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
 $error_alter_array['code'] = 500;
 $error_alter_array['header_message'] = '500 Come on man, send that username';
 $error_alter_array['body_data'] = 'Come on man, send that username';
}

Note: You do not need to return anything because it is alter by reference and two, make sure you clear cache after adding this function to a module.


Help Needed on Views UI in Drupal 7 I have two content types in my application:-
Student
Teacher

Teacher-Student has parent child relationship.
Inside Student there is a node reference field to Teacher which means that when creating a student user needs to provide one or more Teacher's before saving content type.
So one student is related to multiple Teacher here.

Suppose X is a student. Y and Z are teachers of X. Now when I opened the student(X) page then I want to see all the related students in a block who belongs to either (Y or Z) or Both.

Can it be possible using Views UI?Please let me know your suggestion on this.

Your invaluable suggestion moved me for searching deeply in the relationship of Views UI and guess what? I solved the problem after the hours of study in Views UI. Here in this case there are two relations involved. The 2nd relation is involving the first one. This will not be possible to sort out if I didn't know how to turn on the SQL query in Views UI. This link also helped me.

Use of relationships (joins) in Views

Thanks You Nikhil!


redirect or rewrite /user/xx links to a module page This should be easy to do, but its very hard to Google.

Within the admin and surrounding workflows, various links point to user/foobar. I have a different page to display users, say /faces/xx. I want to intercept (or rewrite) every url linking to user/foobar/ to faces/xx.

Pathauto lets you customize what paths user profiles have. If I set that to /faces/[user:uid], it will create aliases overriding my module router; so that faces/xx looks the same as user/foobar previously did. That is not what I want.

You can redirect users on login or other triggers. That is also not what I am looking for.

Most likely, I can override something in my module that intercepts user/foobar calls and does a drupal_goto('faces/xx'). Or there is a url_alter that I can override that writes out the user/foobar links. That, or something similar, is what Im looking for.

EDIT -- sample code from the module that generates the faces page

function faces_menu() {
    $items = array();
    $items['faces/%'] = array(
        'title'             => t('Face'),
        'access callback'   => true, // more complex in reality
        'page callback'     => 'faces_page',
        'page arguments'    => array(1,2),
        'type'              => MENU_CALLBACK,
    );
    return $items;
}
function faces_page($uid) {
    global $user;
    $output =  array(
        'faces-page' => array(
            'magic'     => voodoo($uid),
            '#theme'    => 'faces_pages'
        )
    );
    return $output;
}

and ofcourse theres a faces_theme() to match it.

d'oh! thanks to @geoff above .. this seems to work (in a module called 'faces')

function faces_user_view($account, $view_mode, $langcode) {
    if ($view_mode=='full') {
        drupal_goto('faces/'.$account->uid);
    }
}


How to install certain modules only for specific site using Acquia Desktop I am using Acquia Desktop for creating multisites.
Problem is whenever I am installing a module it gets replicated in everyother site.
What i need to know is that if i want to have a module only for specific site do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.? Is my approach correct
Moreover I have also heard that if we create modules for specific sites then we are going to find it difficult to export sites to FTP for making the site go online.?

do i need to first manually create a modules folder inside the site folder such as practice.localhost\modules (where practice.localhost is the site name) folder as the modules directory is not created by default for any of the subsite folder.?

Yes, you need to create a specific modules folder for the specific site(s) you wish that module to be available for. If you want it available on, say, 10 out of 20 sites, you'll need a copy in each site's modules folder. You can remove the need for this by making it available in sites/default/modules, but obviously it will be available to all sites in the multisite.

  are going to find it difficult to export sites to FTP for making the site go online.?

Completely depends on your deployment process. You'll probably want to review that process before implementing this on your live servers, but whether or not it's 'difficult' depends on what you need to do.


Views: How to list nodes by 2 vocabularies with “%” on url path for contextual filters I have a content type with 2 different Term references. I wanna use Views to list “Term one” with “%” on url path, and use “Term two” as section. See below for details.

Vocabulary term one:
Book type A
Book type B
Book type C

Vocabulary term two:
Book style A
Book style B
Book style C

List result: on Book type A
Book style A
    - node 101 title, author name
    - node 102 title, author name
    - node 103 title, author name

Book style B
    - node 111 title, author name
    - node 112 title, author name
    - node 113 title, author name

Book style C
    - node 121 title, author name
    - node 122 title, author name
    - node 123 title, author name

— — updated info @ Sep. 9th 2014 @ 1:16pm

I created a content View, which has “Content: Type Book A” and set the path as “/booka/%. It came out fine except I don’t know how to use the 2nd Term as section to list all those node under their style.

try this:

create the view as a table with fields
include the style field (exclude from display)
under table settings, 'group' the results by the style field

You can tweak the layout for the headers with some simple css


Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\drupal-8\core\vendor\react\promise\src\functions.php on line 62 I have just installed Drupal 8 development version (drupal-8.0.x-dev) but while running it on my web server I am getting this error:

Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\drupal-8\core\vendor\react\promise\src\functions.php on line 62

Line 62 has code:

59   return resolve($promisesOrValues)
60          ->then(function ($array) use ($howMany) {
61              if (!is_array($array) || !$array || $howMany < 1) {
62                  return resolve([]);
63              }

My PHP version is 5.3.8

Is there anybody else who has faced same issue?

Drupal 8 requires PHP 5.5.9 or higher (for short array syntax among other things).

You'll need to upgrade your version of PHP.

Source: System Requirements


How to display the output of my module without clearing cache and refresh page? I created a very simple module which generates a tag cloud based on user input; you can see the code here.

// wow.module
function wow_menu() {
    $items = array();
    $items['wall/of/words'] = array(
        'title' => 'Wall of Words',
        'page callback' => 'wow_page',
        'access arguments' => array('access content'),
        'file' => 'wow.inc',
        'weight' => 1,
    );
    $items['admin/settings/wall/of/words'] = array(
        'title' => 'On this date module settings',
        'description' => 'Description of your On this date settings page',
        'page callback' => 'wow_admin_page',
        'page arguments' => array('wow_admin'),
        'access arguments' => array('administer wow settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function wow_admin_page() {
    return 'hey';
}

// wow.inc
function wow_page() {
    $output = array(
        'form' => drupal_get_form('wow_cake'),
        'words' => _getWords(),
        'min_count' => 0,
        'max_count' => 999
    );
    drupal_add_js(drupal_get_path('module', 'wow') . '/js/jquery.tagcloud.js');
    drupal_add_js('jQuery(function(){jQuery("#wow-container .cloud a").tagcloud({size:{start:20,end:40,unit:"pt"},color:{start:"#46A7E3",end:"#0969A3"}})})', 'inline');
    return theme('wow_template', array('output' => $output));
}

function wow_theme($existing, $type, $theme, $path) {
    return array(
        'wow_template' => array(
            'template' => 'wow_template'
        ),
    );
}

function wow_cake($form, &$form_state) {
    $form = array();

    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Thank you for...'),
        '#size' => 60,
        '#maxlength' => 128,
        '#required' => TRUE,
    );

    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

function wow_cake_validate(&$form, &$form_state) {

    if (empty($form_state['values']['title'])) {
        form_set_error('title', t('Please leave a thank you message in highlighted field below.'));
    }
}

function wow_cake_submit(&$form, &$form_state) {

    if (_create_node($form_state['values']['title'], $form_state['values']['title'])) {
        drupal_set_message(t('Thank you for your kind words!'), 'status');
    }
}

function _getWords() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node', '=')
            ->propertyCondition('status', 1, '=')
            ->propertyCondition('type', 'wall_of_words', '=');
    $result = $query->execute();
    $nodes = $result['node'];
    $fields = field_info_instances('node', 'wall_of_words');
    $field_id = $fields['body']['field_id'];
    field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));
    $wall = '';

    foreach ($nodes as $node) {

        if (!empty($node->body['und']['0']['value'])) {

            $wall .= trim($node->body['und']['0']['value']);
            $wall .= " ";
        }
    }
    if (!empty($wall)) {
        $cloud = explode(" ", $wall);
    }

    return array_count_values($cloud);
}

function _create_node($title = "", $body = "", $language = "und") {

    $node = (object) array();
    $node->type = 'wall_of_words';
    $node->status = 1;
    $node->promote = 0;
    $node->sticky = 0;
    $node->revision = 0;
    $node->language = $language;
    $node->title = $title;
    $node->body[$language][0] = array(
        'value' => $body,
        'format' => 'full_html',
    );
    if ($node = node_submit($node)) {
        node_save($node);
    }

    return $node;
}

My issue: when I visit another page and come back to the page that I generated with my module the output of the content does not get displayed unless I clear the cache and visit the page again.

there's this method here :

drupal_page_is_cacheable

actually i never used it, but cacheexclude module does,
maybe you have to hook_init too and check for your path there !


Show node only to node author and author that is referenced by node Is there a way to allow only a node author as well as an author referenced by a node reference field to view the node and comments.

Example:

A listing content type. (for posting want ads)
An Offer content type. (for making an offer for referenced listing ad)

Listing has: Title, pics, description, location, etc... as fields'
Offer has: Title, Listing Node Reference, Message, Offered price, etc... as fields

I want to hide the offer nodes (in any view mode) from everyone but admins, the offer node author and the listing node author.

Basically, creating a simple private messaging system. with nodes as messages and comments as replies to the message that only those two accounts can see as well as admins.

Any suggestions on the best way to implement this? Thank you.

You could use Node Access User Reference for this task:

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

Or you could use OG groups for something like this as well: https://www.drupal.org/project/og It may be a little harder to setup at first but certainly more a more flexible option.


How do I calculate and permanently store a field value with code I would like to know how I can manually insert some PHP code inside a CCK node.

What I have is the following code for Drupal 6:

$output .= '<br>';
$mor = _pitch_detalle($cid, $previamente, $luego);
if (sizeof($mor) > 0) {
  $output .= theme('pitch', $mor);
}
return $output;

This code shows some information that changes from day to day, and each time the users view the page, the information changes.
I want the user to see an unmodified version of that code, the same information that existed when the user created the page.

As the user cannot edit the page, I´m looking to insert a php snippet inside a CCK field that will remain unchanged. But that could lead to problems, so is there any way to do that in a safe way?
Or maybe to insert code inside the template in other way?

I haven't done this myself before, so I cannot give really detailed instructions. I think I would do something like this:

Create a CCK text field in the content type(s) of your choice
Create a custom module and implement hook_form_alter
In your form alter function:

Give your CCK text field a #disabled property and set it to true (this will grey out the field so it cannot be edited)
Check if the field is already populated; if not, set the #default_value to the return value of the code in your question

This means that when Drupal builds the form, your custom module will disable the CCK field and put your content in it if that has not been done before. Because we're just populating a form field, all Drupaly stuff like the 'Display Fields' page will keep working.

I hope that helps.


Setting link field in menu content item as not required I am trying to make a field not required in drupal 8 through hook form alter in the following way, which does not seem to work:

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == "menu_link_content_menu_link_content_form") {
    $form['link']['#required'] = FALSE;
  }
}

To get this working in the form alter hook you need to set #required to FALSE in the widget:

$form['link']['widget']['0']['uri']['#required'] = FALSE;

The red asterix mark for a required field is no longer there, but the form does not validate. To get the form validated you would need to do this in the field definition. Implement a hook hook_entity_base_field_info_alter and set required to FALSE:

function mymodule_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content') {
    $fields['link']->setRequired(FALSE);
  }
}

But this doesn't help either, because there is code in the menu link content class that depends on $this->link, so even if you manage to pass the validation you get an error later, that the link is missing.


Rules reacting on an event that hasn't happened? Rules is acting weird all of a sudden. (v. 1.28)

It seems to be reacting on an Event that has not happened.

Using Commerce. Debug log shows that Rules reacts on the "Calculating the sell price of a product" event six times when I add a product to the cart, then reacts on "After adding a product to the cart", then reacts again on "Calculating the price", then reacts on "Select available payment methods for an order."

This last one seems really weird. We haven't even entered checkout. Why react on an event that definitely has not happened?

To make matters worse the Rules under the different events are firing multiple times, so I have customers receiving multiple emails and so on.

I have rebuilt the Rules cache. I have disabled Rules Conditional. I cannot understand why this is happening. Help, please?

Have a read of https://www.drupal.org/node/2403851 .

In short, Rules 2.8 is causing issues with Commerce. The module maintainers are aware and looking at the problem but until it is sorted they are suggesting rolling back to Rules 2.7.


Breadcrumbs from menu URL I have implemented breadcrumbs in Drupal 7, using the following code in mytheme.inc file. It is working fine for all the custom pages but for a particular content type lets say CT1, I have url alias setup as homepage/page2/page3/[node:title] so the breadcrumb trail display as homepage > page2 > page3 > title of content but it is only displaying as homepage > title of content. Please advise what I am missing here to make it work the way I want.

function mytheme_breadcrumb($variables)
{
    $breadcrumb = $variables['breadcrumb'];
    $crumbs = null;
    if (!empty($breadcrumb)) {
        $array_size = count($breadcrumb);
        $i = 0;
        while ($i < $array_size) {
            $crumbs .= '
' . $breadcrumb[$i] . '
';
            $i++;
        }
        $crumbs .= '
' . menu_get_item()['title'] . '
';
        return $crumbs;
    } else {
        return '
Homepage
';
    }
}

You might want to try a community solution for this like breadcrumbs by path

Your custom function isn't doing anything with the url path itself, it's just using the breadcrumb variable. You can get the path with:

$_SERVER['HTTP_HOST'] . request_uri();

Then you could split by '/' and use drupal_set_breadcrumb to set it.


Modifying my theme's template.php requires apache restart to see changes When I make modifications to my .tpl.php file, I assure that changes are "reloaded" by executing "drush cc all".

But when I change my template.php file, the only way I have to see the output of my new code, such as adding a simple dpm($form) statement, is by restarting apache.

I've tried:

drush cc all
Devel module -> Clear cache.
Configuration -> Performance -> Clear all caches.
Check that in Configuration -> Performance -> CACHING -> disabled.
Clear browser cache.
Test it in a different browser.

But the changes only appear when I issue /etc/init.d/httpd restart.

Any idea of why?

Thanks to Clive and MPD, that pointed to the answer.

It was because of APC.

I've installed the module apc_admin, which allows to access the APC interface (apc.php) from within drupal (Configuration » Development » Performance » APC).  That includes the "Reset APC cache" button. Just by pressing it, the changes in my template will show up.

Hope this helps also other users.


Send Mail After Checking Date Field Value My content type (product) has a date field named Expired Date. All I want is like this:

check value of expired date field from content type product. If value equal to 7 days from now, send mail with list of node title and node url.

How to do this with Rules? or any suggestion modules?

Yes you could do this through rules granted the product expiration date is a field.

Create a new rule to run on cron maintenance tasks
Condition--> has field name
Pick your field name
Action--> execute custom PHP.

I don't know what your level of PHP experience is so I'll hold off on putting any code down, but the next step would be to write a short snippet of PHP that takes the sites current datetime and checks the values of your chosen field for values that are 7 days away from expiration (rules should give you tokens for both items).

Then in that same custom PHP area use rules_action_mail() to send the email out with the results (for reference: https://drupal.org/node/322834).

You could also do this with a SQL query in the PHP area: http://www.barnettech.com/content/dbquery-drupal-creating-sql-queries-drupal-way . Just run through your field in the database and check for the values you need, then return the results in the mail message.

If I were to do something like this, I would implement hook_cron() in a custom module: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_cron/7 vs. using Rules since it would require less steps.

Edit: As requested:

See here to make a Drupal 7 module: https://drupal.org/node/1074360

Using hook_cron would go something like:

function mymodule_cron(){
 myfunctions();
}

function myfunctions(){
//do cool stuff
}

As far as what would go into "myfunctions", it would probably be a query on the database, returning those results, then sending those results in an email with mail(). That would be it.


Digg like site in Drupal Is there a way to create a "Digg" like site in Drupal. Basically I want to create a site based in "social voting". The users should be able to vote on specific items and based on this "democratic" behaviour the popularity of that particular item would be determined. I did come across a module "drigg" but was not too impressed with it. Any other alternatives ?

An easy solution is to use the Flag module to create your votes.  Then you can make a View, sorted by flags and potentially with other criteria (like date windows).  You may also be able fold in criteria based on Radioactivity.


Does Drupal detect if the user register email could not be delivered and removes the account? I got this error message back from the MTA:

  This message was created automatically by mail delivery software (Exim).

  A message that you sent could not be delivered to one or more of its
  recipients. This is a permanent error. The following address(es) failed:

  #######@***.+++
     Connection timed out:
     retry timeout exceeded

This is fine so far. What puzzles me is the fact that the created account disapeared. This is reproducible. The account was created again (same email address), the delivery error occoured again and the account disapeared.

Is this on purpose?

Drupal doesn't know about the status of the email. I'm not sure how Drupal 5 does it, but it would be possible to setup Drupal to delete accounts older than X that has never logged in.


How can i increase the size of color box pop up window in drupal 7. .? I have implemented Colorbox module and configured it for my image gallery. But the issue is when I load the colorbox pop up window it seems to be very small in size. Even I tried using CSS setting height and width as 100%, but it's not making any difference.

Can anyone tell me as how to adjust the height / width of colorbox pop up model window?

You should probably check the settings at

admin/config/media/colorbox

If the issue is that the image is too small then you need to change the Image style to a different one or perhaps make a new one.

If you want to make the Colorbox larger you can use the Custom options on that same configuration page and set your own defaults for size. The Colorbox module should allow you to specify

initial width
initial height
max width
max height

If you choose Custom under the Options setting.


How do I take payments via Ubercart and distribute them to vendors? I'm working on a site that needs to take custom payment and remit a part of it to one or more vendors that are determined by the products purchased (the vendors essentially create the products themselves in the shop). I have seen Ubercart Marketplace as a possibility for this, but it's rather old. However, it's the closest to what I need. Should I go with it or is there a better, more fully-integrated solution in Drupal (that uses Ubercart) that I should investigate?

This is outside Ubercart, but it's definitely possible with Drupal!

For this demonstration, I will use a point system. Let's say 100 points = $1.00.

Drupal 7 method:

Create a content type, called Products.
Install a Drupal module, called Entity Reference and add an Entity Reference field to the Products content type, select users. This will allow you to reference the product to vendors.
Create another content type, called Points. Also add an Entity Reference field to it, and select type as users, to reference users. In addition, add a decimal field (amount).
Install another Drupal module, called Rules
Create a rule that would, after a certain time (30 days, etc...) from the sale date, create a Point node with that User referenced and add the commission earned.
Create a rule, that would unpublish the Point node anytime the payment is withdrawn.

Another option is to use the Relation module. It's more work and still in early stages.

By creating a Point node for each commission, you're leaving all records of transactions. I would never overwrite the old commission value with new commission, i.e. $user->payment = $user->payment + 10. It will mess things up.

You can still use Ubercart with this, as it uses Drupal's entity/field structure. Simply skip #1 and use Ubercart's product content type.


Treating string field as numeric to use as an exposed filter I have a field in my users' profiles that has been defined as varchar initially even though it holds numeric values. I'm trying to use that field as an exposed filter and perform "greater than or equal" operation on it; however, since it's a varchar field, View doesn't give me that option.

In my module, I have come up with these two hooks to do a workaround:

function MY_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'manage_users' ) {
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
                $query->where[1]['conditions'][$key]['value'] = (int)$query->where[1]['conditions'][$key]['value'];
                $query->where[1]['conditions'][$key]['operator'] = '>=';
                break;
            }
        }
    }
}

function MY_MODULE_views_data_alter(&$data) {
    $data['field_data_field_count']['field_count_value']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_value']['argument']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['argument']['handler'] = 'views_handler_filter_numeric';
}

The first hook seems to be working fine and successfully changing the operator from LIKE to >=; however, that's not enough for me because it still thinks 2 is greater than 15. So I added the second hook to make sure the field is actually treated as numeric, but that doesn't seem to have any effect on how the results are returned and it still thinks 2 is greater than 15.

Excellent question!
You only need the hook_views_query_alter function, here is what it should look like:

function MY_MODULE_views_query_alter(&$view, &$query) {
  if ( $view->name == 'manage_users' ) {

    // For filtering
    foreach($query->where[1]['conditions'] as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
        $query->where[1]['conditions'][$key]['value'] = array(':val' => (int)$query->where[1]['conditions'][$key]['value']);
        $query->where[1]['conditions'][$key]['field'] = 'CAST(' . $query->where[1]['conditions'][$key]['field'] . ' AS UNSIGNED) >= :val';
        $query->where[1]['conditions'][$key]['operator'] = 'formula';
        break;
      }
    }

    // For sorting as well
    foreach($query->orderby as $key => $condition) {
      if ( $condition['field'] == 'field_data_field_count_field_count_value' ) {
        $query->orderby[$key]['field'] = 'CAST(' . $query->orderby[$key]['field'] . ' AS UNSIGNED)';
        break;
      }
    }
  }
}

Most important parts in this code snippet:

Using CAST to change the varchar into an integer [doc]
Using the 'formula' operator to instruct views that you are using a complex SQL expression, check the source code of add_where_expression!  [doc]

Good luck!

Update Note: Even though this is working fine, the more elegant/readable way would be to have a function (equivalent to add_where_expression) that would allow overwriting a where/having condition.


Taxonomy term not displayed in the current language My setup is simple:

A content type "film" with a taxonomy field "Type of film".

The content type "film" is translatable, but not the field "type of film" (same type for all languages): only the entity type "Type of film" is translatable.

If I display a film with an English interface, I will get "Comedy" as the type of the film and in French, I will get "Comedie".

If I create a view showing the films teasers, I will have Comedy/Comedie depending if I ask to display French or English films.

Until this point, everything runs fine...

But, as all the films are not translated, I would like to have Comedie if it is a French interface (http://domain/fr) even if the teaser is displaying an English (not translated) film.

In the view, I have used

FILTER CRITERIA: Content: Default translation (= True)

LANGUAGE: Rendering Language:Interface text language selected for page

In the Manage display of the film's teaser, I choose "label" to display my taxonomy field... without any option to display it into the current language (now it is displayed into the content type language)

EDIT TO ADD:

Following the advise from @Berdir, I have created a new formatter: /my_module/src/Plugin/Field/FieldFormatter/CurrentLanguageLabelFormatter.php

<?php

namespace Drupal\artprod\Plugin\Field\FieldFormatter;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter;

/**
 * Plugin implementation of the 'current language label' formatter.
 *
 * @FieldFormatter(
 *   id = "current_language_label",
 *   label = @Translation("Current Language Label"),
 *   description = @Translation("Display the label of the referenced entities using the language of the page."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class CurrentLanguageLabelFormatter extends EntityReferenceLabelFormatter {

    protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items,$langcode) {
        $entities = [];

        foreach ($items as $delta => $item) {
            // Ignore items where no entity could be loaded in prepareView().
            if (!empty($item->_loaded)) {
                $entity = $item->entity;

                // Set the entity in the current language for display.
                // HERE IS THE CHANGE
                if ($entity instanceof TranslatableInterface) {
                    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
                    $entity = \Drupal::entityManager()->getTranslationFromContext($entity, $language);
                }

                 $access = $this->checkAccess($entity);
                // Add the access result's cacheability, ::view() needs it.
                $item->_accessCacheability = CacheableMetadata::createFromObject($access);
                if ($access->isAllowed()) {
                    // Add the referring item, in case the formatter needs it.
                    $entity->_referringItem = $items[$delta];
                    $entities[$delta] = $entity;
                }
            }
        }

        return $entities;
    }
}

In the annotation, I have changed the id and the description

In the class body, I have copied the function getEntitiesToView from the class EntityReferenceFormatterBase except that I changed the chunk of code which is translating the entity.

After restarting Apache and clearing the cache, I could select this overrided formatter for my taxonomy field.... AND the label are now displayed in the current language (vs language of the parent entity)

The language of the parent entity is passed to entity formatters and they respect that when displaying referenced entities.

If you want to override that, you can for example provide your own entity formatter plugin that overriddes \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView() and ignores the passed in $langcode. There is no configuration for that.

Since you probably want the entity label to be displayed, you should subclass \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter.

Alternatively, you can also do something in preprocess/twig.


Stop displaying errors in production server in Drupal 7 How to stop Drupal from showing unnecessary errors?

I'm deploying my Drupal 7 site to production server, and I want to stop displaying general purpose errors.

EDIT:

I found something about showing errors in this link:

<?php
    error_reporting(-1);
    $conf['error_level'] = 2;
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
?>

Can someone explain what will be the appropriate value for $conf['error_level'] to stop displaying errors?

Did you try this way : admin/config/development/logging ?

(Where you can choose to display every messages, or just errors, or no message at all)


Remove id alias appending to confirmation page URL I have created a basic page in Drupal 7 that acts as a custom confirmation page for a web form. The url needs to be clean and static because it will be tracked by Google Adwords.

The problem is that an id is appended to the url, see example below. http://www.dynasty-autoglass.com/contact-confirmation?sid=230

The URL is supposed to end with only /contact-confirmation

How am I able to remove this id?

Thank you.

Option 1 (preferred)

This can be done with some code in a custom module.

You can use hook_form_alter to add an additional submit handler to every webform:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // All webform id's start with webform_client_form so check for that
  if(substr($form_id, 0, 19) == 'webform_client_form') {
    $form['#submit'][] = 'my_webform_redirect';
  }
}

And then in the additional submit handler strip the query string form the URL:

function my_webform_redirect($form, &$form_state) {
  unset($form_state['redirect'][1]);
}

$form_state['redirect'] is an array that consists of 2 parts. The first is the actual URL, so in this case it will be 'contact-confirmation'. The second part is the query string (sid=12), so all we need to do is unset it and it won't be appended to the URL.

Option 2

If you are tracking lots of pages over your whole site then it may be desirable to implement a solution that ensures that no query strings will appear anywhere on the site. Do bear in mind that this will break any functionality that depends on query strings. For this solution you need to put the following in your .htaccess file:

RewriteEngine On
RewriteCond %{QUERY_STRING} !="" #if there is a query string
RewriteRule ^(.*)$ /$1? [R=301,L] #remove query string

For more information on this technique there is a blog article here.


Drupal Commerce permission I've just noticed that the anonymous user can add staff to the cart but they cannot see the block. Also, I've create a display content view and anonymous users cannot see it.

I've tried to find the right permission but there is not a permission tutorial.

Is anyone has got experience with it?

I would like to leave anonymous users use the cart but then login once they have to pay.

How do i get it?

The problem comes when I add, in the view, the relationship with the product.

Thanks in advance

Two places that come to mind on the Permissions page (/admin/people/permissions) are:

Under Checkout, look for Access checkout
Under Order, look for View own orders of any type


Register a new user programmaticaly having id proof I want to create a user programatically. But I have a field id proof where user can upload files.

But I don't know how to save that file while creating user.

Here is my code

$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
//need to know about files

drupal_execute('user_register', $form_state);

Can anybody tell me how to do this

Thanks

Hope this will help  you.

In Drupal 7 you can use file_save_data and file_usage_add.

file_save_data : Saves a file to the specified destination and creates a database entry.
file_usage_add : Records that a module is using a file.

    global $user;
    $path = 'C:\...\Downloads\sample images\drupal_7_icon_0.jpg';//local path of id proof image
    $filename = drupal_basename($path);//get filename
    $file_temp = file_get_contents($path);
    //Saves a file to the specified destination and creates a database entry.
    //Dont forget to create id_proof folder inside files folder
    $file_temp = file_save_data($file_temp, 'public://id_proof/' . $filename, FILE_EXISTS_RENAME);

    // Record that the module (in this example, user module) is using the file.
    file_usage_add($file_temp, 'mymodule_name', 'user', $user->uid);//change the module name

    //Get the values to create new user
    $form_state = array();
    $form_state['values']['name'] = 'robo-user';
    $form_state['values']['mail'] = 'robouser@example.com';
    $form_state['values']['pass']['pass1'] = '1234';
    $form_state['values']['pass']['pass2'] = '1234';
    $form_state['values']['op'] = t('Create new account');
    $form_state['values']['field_user_id_proof'][LANGUAGE_NONE][0]['fid'] = $file_temp->fid;//change it as per your requirement
    drupal_form_submit('user_register_form', $form_state);
    drupal_set_message('User saved successfully');


How to link fields from a Content Type to an Entityform field Using Drupal 7. Our Recruiting department will be creating events & at these events want to be able to hand a tablet off to an individual so that they can enter info about themselves:

Name
Address
Email, etc...

After content is submitted the Recruiter then can go in & enter "Notes" about the individual.

I'm using Entityforms for that part.

I've also created a content type for Events.

Data would be Event Type (Career Night, College Fair, etc) Location (Rutgers University, etc) Date of Event, Recruiter (Last name) & after the event enter Number of Attendees.

I'm trying to figure out how to relate an applicant to the event that they attended. I'm not having any luck with Entity References.

I'm thinking the related items would be Event Date, Location, Recruiter. I can't figure this out. Any help would be appreciated.

Thinking of this leads me to the following conclusion. You want to hand over the tablet, meaning it should not be logged in as an administrator or by any other means allow people to see and edit more then then allowed.

So you could do this with simple comments.

Create a content type of event in which you have fields for the date, the name of the event, the location and the recruiter (author?).

Then edit the content type and navigate to this tab:

Here you can add comment fields, including the name and any other information you want from the person. Give anonymous users permission to create comments, but not view them and you are done.
Later if you log in, an admin can edit the comment and add notes.

Another solution would be the webform module. More or less allowing you to create any type of form on any type of node. It comes with a wide variety of fields and a clear admin interface, also allowing exports etc.
Adding notes can be achieved by editing the submission as well.

UPDATE:

I always thought entity forms were for backend forms. You can attach one to a node folloing this tutorial: http://www.sixmiletech.com/content/embedding-entiyform-node

That should solve your entity reference stuggles.

Summary of the video would be to create an entity reference field on the event-node. Configure it to reference to Entity form type(s). On the manage display tab of the content type configure the entity reference to 'Render the entity`.

Now create a node, select the right entity form type and save. You now have a node with an attached form.


Secondary & Tertiary links next to Parent links How can I print expandable secondary and tertiary links to the right of the parent?
For mobile, the secondary and tertiary links will need to stack below the parent links. Below is an example of what I am looking to achieve.

Menu tree

Menu on front end

You can achieve this by using the module menu block. This module allows you to display certain levels of a menu considering the selected parent item.


Pass a node reference to a module form I've created a bid module that allows the users to bid on an auction through a node reference. I'm using hook_form_alter() to create the form on the 'create bid' page, and I would like to perform some SQL queries dealing with the referenced node.

How do I load the node reference?

To load a node, use

node_load($nid);

This requires that the node is saved and that you have it's nid.

To give a better answer more details are needed