Help With Audit log Setup I'm setting up an audit log for a large network of Drupal 7 sites with dozens of editors and 5 developers.

These events are already covered:
Content Create, Content Update, Content Delete, User Login, User Logout, User Create, User Update (hook_user_update).

But I'm having a hard time logging:

Change in permissions
Change in settings

Any ideas how to go about logging that to watchdog?

Both of these are forms, so you can do something with a hook_form_alter.  The easiest thing to do is do a View Source, find the form, and look at the ID on the <form> element.

The permissions form is user_admin_permissions.  My suggestion would be to alter the form to add a new submit handler, eg

function mymodule_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
  $form["#submit][] = 'mymodule_log_permission_change';
}

The settings changes are going to be tricky, as they are spread across many, many forms.  The idea is the same, you just need to figure out whether you are on a setting for or not.  You could alter all of the important setting forms, or you could try using the base hook_form_alter() and check the $form_id.  You could also try checking the URL from withing the submit handler, as many of the settings live under /admin.


Facet API, exclude option, and a field with multiple values Im getting headaches concerning this one ...

Ive got a field, say a text field nammed "MyField", which can have multiple values.

Ive created a feed that imports the data for this filed.

After the import, my content looks like that :

Content A
Myfield :
- Element 1
- Element 2

Contnent B
Myfield :
- Element 1

Content C
Myfield :
- Element 2
- Element 3

Now im trying to create a facet with an exclude option.
What I would like is when I choose an element, all content, having at least the choosen element as a value of the Myfield field, should be hidden.

So if I check "Element 1", I want the content A and B to be hidden.
And if I check "Element 3", only the content C would be hidden.

The fact is that this is not the way it works ...

If I check "Element 1", only the content B will be hidden, because Content A has another value "Element 2" for this field, so it is not retrieved during the query.

I found something ...

The file "sites/all/modules/contrib/search_api/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc" contains the "addFacetFilter" function. This is where the exclude cases are processed.

If the Exclude settings is checked, this function changes the query condition to "<>" (instead of "=")

This is the query that is generated concerning an exclude facet :

SELECT COUNT(*) AS expression FROM (SELECT DISTINCT t.item_id AS item_id, :score AS score, 1 AS expression FROM search_api_db_default_node_index t LEFT OUTER JOIN search_api_db_default_node_index_field_produit_organisation_pa t_2 ON t.item_id = t_2.item_id LEFT OUTER JOIN search_api_db_default_node_index_field_derniere_liste_allergen t_3 ON t.item_id = t_3.item_id WHERE (( (t.created >= :db_condition_placeholder_0) )AND (t_2.value = :db_condition_placeholder_1) AND( (t_3.value <> :db_condition_placeholder_2) )))

Retrieved results are wrong.

AND( (t_3.value <> :db_condition_placeholder_2) is the default part added to handle the excluding setting.

Ive managed to modify the SQL Query so that the retrieved results are the good ones :

SELECT DISTINCT t.item_id AS item_id FROM search_api_db_default_node_index t LEFT OUTER JOIN search_api_db_default_node_index_field_produit_organisation_pa t_2 ON t.item_id=t_2.item_id LEFT OUTER JOIN search_api_db_default_node_index_field_derniere_liste_allergen t_3 ON t.item_id = t_3.item_id WHERE (( (t.created >= :db_condition_placeholder_0) )AND t_2.value = :db_condition_placeholder_1) AND NOT EXISTS (select t_4.item_id FROM search_api_db_default_node_index_field_derniere_liste_allergen t_4 WHERE t_4.value = :db_condition_placeholder_3 AND t_4.item_id=t_3.item_id))

Ive replaced the excluding condition with :

AND NOT EXISTS (select t_4.item_id FROM search_api_db_default_node_index_field_derniere_liste_allergen t_4 WHERE t_4.value = 'moutarde' AND t_4.item_id=t_3.item_id)

Now it returns only items that have no occurrence of the selected term in its values

Now I need to know how I can manage to get these correct results with views ... any idea ?

I did ask the same question in search_api issue queue and this problem needed 2 patchs to be commited.

One for Search_api_database_search : https://www.drupal.org/node/2361329

Another for Search_api : https://www.drupal.org/node/2371099

Hope it can help !


How do I check that the private file system is setup correctly from hook_requirements()? I'm working on a module that will need to place files in the private file directory.  I'd like to check that the private file system is working from within hook_requirements() so I can provide both an install requirement and a status check.

There are a few different ways.
Use the \Drupal\Core\Site\Settings class static method get:
if (\Drupal\Core\Site\Settings::get('file_private_path')) {

}

Check for the existence of the stream_wrapper.private service, which is only instantiated when the above check passes. Need to catch the appropriate exception coming from Symfony. Update 2017.01.23 @Berdir suggests using the getContainer method, which means we don't have to catch the exception!
if (\Drupal::hasService('stream_wrapper.private')) {

}

Use the file_system service to check if it's a valid scheme. This will basically check if the above service's class exists.
$fileSystem = \Drupal::service('file_system');

// Check if the private file stream wrapper is ready to use.
if ($fileSystem->validScheme('private')) {

}


Image Files Uploaded via REST got Temporary status - Cannot be refereced by Media Image Drupal 8.9.11
Image File Uploaded via REST gets "status - Temporary" while setting explicitly "status" case to True server error 403 (code in python)
   "status": [
      {
        "value": True
      }
   ],

The sever returns code 403, an exception:
Status: 403, Message: {"message":"Access denied on creating field \u0027status\u0027."}

The error on the server:
$ vendor/bin/drush watchdog-show
access denied Warning Path: /themag_dp8/entity/file?_format=hal_json.
   Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: Access denied on creating
   field 'status'. in Drupal\rest\Plugin\rest\resou

If I'll not specify "status = true" The next REST call to Create Media fails to reference it due to its temporary status.
   payload = {
        "name": {
            "value": name
        },
        "field_image": [
            {
                "target_id": file_id
            }
        ],
        "field_description": [
            {
                "value": description
            },
        ],
        "bundle": [
            {
                "target_id": "image"
            }
        ],
        "_links": {
            "type": {
                "href": oauth.base_url + REST_TYPE_MEDIA_IMAGE
            },
            oauth.base_url + "/rest/relation/media/image/thumbnail": [
                {
                    "href": oauth.base_url + "/file/%d" % file_id + FORMAT_HAL_JSON
                }
            ],
            oauth.base_url + "/rest/relation/media/image/field_image": [
                {
                    "href": oauth.base_url + "/file/%d" % file_id + FORMAT_HAL_JSON
                }
            ]
        }
    }

Status: 422, Message: {"message":"Unprocessable Entity: validation failed.\nfield_image.0.target_id:
This entity (file: 119) cannot be referenced.\n"}

Server error:
$ vendor/bin/drush watchdog-show
access denied Warning
    Path: /themag_dp8/entity/paragraph?_format=hal_json.
    Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException:  in
    Drupal\Core\Routing\AccessAwareRouter->checkAccess() (line 120 of
php           Error
    Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException: Unprocessable Entity:
    validation failed.
    field_image.0.target_id: This entity (file: 119) cannot be referenced.
    in

When I manually, via web site admin (https://drupal8.site/admin/content/files), change the file status to "Permanent", this Create Media REST call succeeds to create a new media/image entity.
Seems the Rest user missing some security allowances, but which one?
Did anybody succeed to create a node consisting of the teaser image, paragraph video and so?
Sure I'm not the first who attack this issue, where the relevant documentation, working code examples?

The solution I found so far is to fix a Drupal module code:
modules\contrib\file_entity\src\Normalizer\FileEntityNormalizer.php
on line 48 add:
$entity->setPermanent();

See:

Which Drupal 8.1.x Rest API property in the JSON request controls
Drupal's File status (Temporary and Permanent) logic?

Files created with REST API are only temporary


Getting User Entered Form Data within a hook function Problem

I need to use the following hook function to edit a similarly-named function in a contributed module (PayPal WPP), but I don't understand how to use it.

hook_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method) { }

When this function is called I need to pass some variables to PayPal, based off user-supplied input in a form. By the time this function is called the user has already supplied their input in the form and clicked 'submit'. The form is now ready to send it's data to PayPal and this hook alters what is being sent.

So I need to figure out how to add additional data. Specifically I want to alter a variable $nvp['custom']. The main problem is I don't know how to get the values the user entered in the form into this function so I can pass them on.

I'm told I need to get the user-supplied values using $form_state['values'] but I have no idea how to get those inside this function, which isn't passed $form_state as a parameter. I was hoping to do something like this:

$name = $form_state['values']['field_name'];
$organization = $form_state['values']['field_organization'];
$arr = array($name, $organization);
$allthedata = implode('+', $arr);
$nvp['CUSTOM'] = $allthedata;

As it may be obvious I don't even know how to refer correctly to the passed $form_state values, which is probably a large part of my problem.

Question

How do i get my user-supplied form values into this function so I can use them (and then pass them on to PayPal as part of the $nvp['custom'] variable?

You can user this code in which you can add your form data in array and pass it to the Paypal api.

function do_custom_commerce_paypal_api_request_alter(&$nvp, $order, $payment_method){
    if ($payment_method['base'] == 'commerce_paypal_wpp' ) { //check payment method

        //save form data
        $name = $form_state['values']['field_name'];
        $organization = $form_state['values']['field_organization'];

        $nvp += array(
        'name' => $name,
        'organization' => $organization,
    );
  }
}

Here is the similar solution for your problem in which user has passed order details. Click Here


Customizing node reference widget As you now, when we use node reference field in a data type, during inserting a content, a list is very simple and it shows only node title.

I want to know is there any way to customize the list. for example I want to add css classes to list or add additional field such as thumbnail image and other field in this widget.

Please guide me. How can I do that ?

You can create own field formatter in code. Or use field preprocess function.

But I would suggest you to render this references as view. Than you can do with field anything you want


Confirmation popup before delete file/image I'm working on a D8 project and in many cases I use file and image upload fields.

The files and the images are visible above the field and the user can delete them by using the default 'Remove' button.

What I want to do, is to add a confirmation popup asking if they really want to delete that files/images.

Is there any hook that I could use to make that check?
If I use javascript, how can I say to drupal that now can proceed to deletion?

Thank you in advance.

EDIT:

I tried to do what @Ivan suggested but I can't make it work.
My form has submit and ajax callback. Should I alter both?

Is there any working example? I am so desperate!!

After long time I managed to find the solution. I didn't manage to make it work server side with modals so I managed to solve it using jQuery.

So I created a javascript file:

    Drupal.behaviors.confirm = {
        attach: function(context, settings) {

            $.each($('.form-submit'), function(){
                var str = $(this).attr('id');
                //find the id for each button
                var remove_btn_id = '#' + $(this).attr('id');

                //apply only to remove buttons and only to those that the functionality is not applied yet.
                if (str.indexOf("-remove-button") >= 0 && !$(remove_btn_id).hasClass('custom-handler')){

                    //Drupal.behaviours are triggered every time my ajax was submitted and I ended up with multiple events to each button.
                    //In order to avoid it, add a class to check if the button already has that functionality.
                    $(remove_btn_id).addClass('custom-handler');
                    $(remove_btn_id).bindFirst('mousedown', function(e, next) {

                       //Display popup and get user's decision.
                        var choice = confirm('Are you sure you want to delete that?');
                        if(!choice){
                            //if user clicks cancel then do nothing
                            e.stopImmediatePropagation();
                        }
                    });
                }
            });
        }
    }

I'm not sure if this the right way to implement that functionality (I guess is not the Drupal way) but at leat it works!


How can we check whether block is enabled or disabled in .theme file? I am displaying a block in twig and i am passing twig variable from hook_preprocess_page. But the issue when i disable the block from backend still its showing up in frontend. Im not able to get status of the block. Can anyone help me. Below is my code:

$lang_block = Block::load('dropdownlanguage');
  //if (!empty($lang_block)) {} also i tried.

  if (isset($lang_block)) {
    $content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($lang_block);
      $variables['language_block'] = $content;
  }

In .twig file :

{%  if language_block %}
   {{ language_block }}
{% endif %}

Use ConfigEntityBase::status:

if (isset($lang_block) && $lang_block->status()) {
  // block is enabled
}


How to display referenced field data in view? I have two content types named as "abc" and "xyz" respectively.

"xyz" content type having field called "field_abc".
Its a referenced field to "abc" content type.

I create a view by taking "abc" contents.
Is it possible to show the title of "xyz" in which "abc" taken as referenced field?

I think the reverse may works. Means if I create a view by taking "xyz" contents. But i need to know if I create a view by taking "abc" contents. It will work on not?

You want a backreference. For D8 this is an open feature request:

Implement Entity Reference Backreferences

You should consider to this is in a forward reference (what you call reverse). Because even if the feature Backreferences is available, you would also somehow need to manage that there is only one reference, which you want to get the title field from. You can control this in the forward direction by making the reference field single value, but not in the other direction.


Missing node_reference warning User warning: The following module is missing from the file system:
  node_reference. For information about how
  to fix this, see the
  documentation page. in trigger_error() (line 1138 of
  /[localdevetc/drupalrootetc]/docroot/includes/bootstrap.inc). =>

This error usually occurs when module files are removed without a module being disabled and uninstalled first. Typically it's corrected by simply re-downloading the module files and then uninstalling it. The problem is that there doesn't seem to be a module called node_reference for Drupal 7. I tried drush dl node_reference and got:

  No release history was found for the requested project
  (node_reference).
  Could not download requested project(s).

Any ideas?

node_reference is just a sub-module of the References module; that's why you can't download it using Drush. Instead, download the References module.

drush dl references


How to use entity reference field titles in Views exposed and combined filters I have two content types: Institution and Contact.

Any number of Contacts are associated with any number of Institutions.

Contacts are associated with Institutions via an Entity Reference field.

I have a view defined as follows:

Format: Show: Fields
Content: Published (Yes)
Content: Type = (Institution)
Content: Title (exposed)
Content: Contact (exposed)
Combined: Titles and Contacts (exposed)

The current sticking point is the exposed filter for Contact (an Entity Reference) requires the integer value of field_data_field_contact.field_contact_target_id, which frontend users have no means of knowing. I need a way of translating a Contact node's Title to the target ID transparently, and this method must also be accessible to the combined field Titles and Contacts.

Result sets for contacts are in the thousands, so providing a dropdown to the view is not workable.

The view type is likely set in stone, because it has been in production for years and has a great many fields.

You just need use Views Reference Filter module


why is the node id missing from the comment:edit action? When I setup a trigger on comment creation and edit that fires the action "send email" I have the folling tags available in the action editor that seem to be missing the nid on output:

[comment:edit-url]
[comment:url]
[comment:url:absolute]

This gives me the following output in emails

http://example.com/comment//edit
http://example.com/comment/#comment-
http://example.com/comment/#comment-

Is this a flaw in the D7 or and I not doing it right?

Thanks in advance for any insights.

@Denford: You are right in saying that comments do have ids. They are just called cids and not nids :-)

What is the trigger that you are firing? My guess is that for a new comment posted, you are not seeing the 'cids' because they would be available only to the trigger 'after saving a new comment' and not the trigger 'when either saving a new comment or updating.. blah blah'.


Sending webpage through email I've implemented hook_menu and in page callback there is a function in my module which retrieves some records randomly and theme them with theme_table. Now I want a button on the page for sending this page exactly as it is to a predefined email address without refreshing the page because of randomly selected records.

I placed a button through simple HTML code but don't know how I can implement it's onClick function. Or is there any better way to do that? Thanks

It is simple javascript... The returned value can easilly be sent through ajax (there are good tutorials on sending mails with ajax).

<button onClick="alert(document.getElementsByTagName('body').innerHTML())" value="serialize">

You might run into trouble though, at first email clients can have trouble accessing images from remote locations (eg. from your own url). So you might have to attach them to the mail.

Also most email clients are very picky when it comes to css. They refuse to load a remote sytlesheet. You will have to hardcode all css classes in the respective elements, the old fashioned way... By using the object style attribute.

<body style="background: red; font-size: 9pt;">

So as you see it is harder then just sending the HTML to an email receipient. In fact you might want to have a look at HTML2Canvas (or other alternatives) to make a 'screenshot' of a webpage and just send one image.


How do I add a pager for the following code? On the page--product.tpl.php I use node_load() to get all the nodes of a content type. I want to shows 15 post titles per page. How do I add a pager to the page?

I am using the following code.

$terms = taxonomy_get_children(arg(2));
foreach ($terms as $term) {
  $whole = taxonomy_select_nodes($term->tid, TRUE, 1, array('t.created' => 'DESC'));
  foreach ($whole as $nid) {
    $node_this = node_load($nid);
    echo '
'.$node_this->title.'
';
  }
}

I think you are trying to do a custom pager, not based on db query something like this, but it is D6 code.
For D7, check Extenders and what the Database Abstraction Layer page describes is

  Most Drupal database SELECT queries are performed by a call to
  db_query() or db_query_range(). Module authors should also consider
  using the PagerDefault Extender for queries that return results that
  need to be presented on multiple pages

You may also need to check theme_pager which displays the pager result.
When calling theme('pager') outside a pager query, it's necessary to initialize the pager first with a call to pager_default_initialize.


Drupal Pricing Table Module What is the best way to create a Drupal pricing table for Drupal Commerce? I love the pricing table mentioned in this discussion. But I can't believe there is no ready-made module. What's your recommended architecture?

I think your Google-fu has failed you  :)

Commerce price table:

  Drupal Commerce contrib project that allows to have a secondary price field that considers the quantity for displaying and using the prices. It also provides a field formatter to display the price/quantity values as a table.


Enable field formatter settings I have a field that I created using hook_field_extra_fields, and I want it to have a cogwheel like in the image below, so that I can customize it. Right now the only format setting for the field is "Visible". Any ideas on how to enable the formatter settings for that field?

Note that I am also using display suite.

You can use hook_field_formatter_settings_form to add formatting of the field as shown in example below:

function example_field_formatter_info() {
  $info = array();
  $info['default_formatter'] = array(
    'label' => t('Show as link'),
    'field types' => array('example_field_type'),
     'settings' => array('target' => '_blank'), // <--- THIS
  );
  return $info;
}

function example_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $element['target'] = array(
      '#type' => 'select',
      '#title' => t('HREF target'),
      '#options' => array('_blank' => 'New window', '_self' => 'Same window'),
      '#default_value' => $settings['target'],
      '#description' => t('Control where the link opens (i.e. set the TARGET attribute of the A element).'),
    );
  }
  return $element;
}

function example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $target = $settings['target'];
    foreach ($items as $delta => $item) {
      $element[$delta]['#markup'] = "{$item['label']}
";
    }
  }
  return $element;
}

Update #1:

/**
 * Implements hook_field_formatter_settings_summary().
 */
function example_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Show as link'); // we use t() for translation and placeholders to guard against attacks
  return $summary;
}


how to insert image inside an existing image hi i'm working on my sample site.in that I've done the background image blue sky into the respective region how can i add one more image in center of that like below ? and more over
I've to add an web form in that center image i'm going to add? how can i achieve this?

It depends on your theme which you're using. Normally you've to create a block with image in its content and assign to the right region.

If you don't have the right region to assign to, try changing the existing content, or expand your theme and add new region based on your needs, or use Panels and replace your current page with custom layout (e.g. by using a flexible layout).


Unable to add patches via composer when we run "composer install" or "composer update" I am facing an issue wherein I have added a single patch in my composer.json under "extras"
   "patches": {
            "drupal/field_validation": {
                "Declaration of (...)FieldValidationRuleAddForm::buildForm": "https://www.drupal.org/files/issues/2941006-php-incompatible-buildform-signature.patch"
            },
            "drupal/ubercart": {
                "Not_yet_ported (missing)": "https://www.drupal.org/files/issues/2020-05-28/ubercart_remove_not_yet_ported.patch"
            }
        },
        "enable-patching": true

After adding the patch under composer.json
I ran
composer install

but still it does not apply the patches listed.

The solution was
composer require cweagans/composer-patches

we need to be sure that above package is included
After adding the above I was able to add patches via composer.json


Twig error "Uknown image_style filter", but the filter isn't missing I'm migrating a site to a new host.  On the front end, I see...

Twig_Error_Syntax: Unknown "image_style" filter. in Twig_ExpressionParser->getFilterNodeClass() (line 57 of /var/www/prod/web/themes/mytheme/templates/paragraph--paragraph_image_block.html.twig).

However, I checked the filter referenced in the error, and the filter is not missing.  I see the filter at admin/config/media/image-styles and its machine name is spelled correctly in the template.  I have tried rebuilding the cache.  Why is this filter unknown?

Here is line 57 in the template:

{% set img_url = file_url(content.field_paragraph_image['#items'].entity.uri.value | image_style('max_1300x1300')) %}

The 'max_1300x1300' filter isn't missing.

The error message isn't complaining about a missing Drupal image style - it's complaining about a missing Twig filter named image_style.

That filter doesn't exist in Twig/Drupal core, but it does exist in the Twig Tweak module. Make sure that module is available and installed, and the error should disappear.

If you've never had Twig Tweak installed then it's probably custom. In that case search your codebase for Twig_SimpleFilter('image_style' and you should find the culprit.


hook_entity_bundle_field_info_alter() only validates article bundle I used hook_entity_bundle_field_info_alter to validate fields in node as below:

function my_module_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && !empty($fields['title'])) {
    $fields['title']->addConstraint('UniqueField', []);
  }
}

The validation I wrote in UniqueFieldConstraintValidator Plugin works for "article" bundle but not for any other bundles. What am I doing wrong?

You're using the bundle alter hook, which is only called on by-bundle fields.

Title is a base field but it can be overridden by a per-bundle through field override.. this is what happens if you chose a different title through the node type settings form. I guess that's why it's only available sometimes.

Try to use my_module_entity_base_field_info_alter(). Due to the override, which completely replaces the base field, you actually might need both hooks.. I don't know if the constraint is transported to the field override correctly and certainly not if the field override already exists when you add the alter hook. Not much that can be done about that I fear.


How can I programatically prevent users from saving the same entity twice in a row? My server sometimes gets overloaded, and sometimes people press the "Save" button on an entity creation page several times, which results in multiple versions of the same entity being created.

So, I want to prevent users from saving the same entity (an entity that has the exact same field content as the immediately previous entity saved by the user).

One fix is to get a better server.  I'm working on that.

Still, I would like to programmatically prevent users from saving the exact same entity twice in a row.  In my specific use case, this entity is a new private message from the Private Message module.

Is there a "best practice" way to do this?

Here is what I have considered.

On hook_entity_presave(), query the database and check if the last entity saved by the user had the same values.
Add an entity reference to the user profile for the last saved entity, and update the user profile entity reference field with the value of the new entity every time it is saved.  When saving a new entity, check it against the values of the entity reference entity.

I find this to be a UX issue. 1 thing I would recommend is to allow certain high-traffic forms on your site to show a throbbing/progress/submit indicator upon click.

I believe you can do this using the Form API by overridding the default submit element on your site forms as needed. This is explained some in this related SO post with links to documentation:
https://stackoverflow.com/questions/6100970/how-do-you-remove-the-throbber-from-drupal-7-ajax-link


Creating user profile types I'm trying to make a record of different user profiles.
And each of them, possess or display different items, apart from those who normally come (Username, Email, Photo, etc..). Something like:

Profile of Visitors         ==>>>> Only Images / Photo
Employee Profile            ==>>>> Birth Date,  Curriculum Vitae, etc.
Artist Profile,             ==>>>> Albums of: Videos, Music, and / or Photos
Business Profile            ==>>>>Photo Albums / Images.

And each user is able to handle each of these elements.

E.g.:
- If I am a musician, update my music files or Albunes Photo.
- If employed Update My Currillo vitae. And so on ...

It will be possible to do this with Drupal 7?. Please Any suggestions?

Best Regards

There is Profile 2 module

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)

Also check this wonderful answer by kiamlaluno


views Relationships and argument? What are the relationships and arguments in Views? How do I use them? I have read some tutorials, but still don't know how to use them. Can someone explain them more clearly? Thank you.

Relationships are the way Views expresses SQL joins. For example, when viewing a node, you can add a relationship to it's author, pulling in even more data.

Arguments have been renamed "Contextual Filters" in Views 7.x-3.x, which is a better name. Basically, it's a filter that gets its input from the the page, either by the page's URL or the node or user being viewed, etc.


Simple AJAX callback fired on form submission button click I am trying to fire an AJAX callback when the user presses the submit button. This is such a simple thing but trying to debug Drupal's Form AJAX API is driving me crazy. At this point I just need a fresh set of eyes to look over it. Currently, when I press the button the page just refreshes and the AJAX callback is never fired. I have a form being built with the following code:

class OnlineRevenueForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['resetbutton'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#prefix' => '
',
        '#suffix' => '
',
        '#ajax' => array(
            'callback' => 'Drupal\revenue_projection_model\Controller\RPMController::ResetFields',
            'event' => 'click',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        )
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild(FALSE);
  }
}

Inside of my controller I load this form using the following code:

class RPMController extends ControllerBase implements ContainerInjectionInterface {
 public function rpm() {
    // Load the module's template file
    $TemplateFilePath = drupal_get_path('module', 'revenue_projection_model') . "/templates/revenue_projection_model.html.twig";
    $template = $this->twig->loadTemplate($TemplateFilePath);
    //Load Forms
    $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
        $markup = [
         '#type' => 'inline_template',
         '#template' => $template->render(
            ['online_rev_form' => $OnlineRevForm]
         )
        ];
   return $markup;
 }

This form is then displayed via the twig template file. The callback that I'm trying to call is also inside of the Controller:

public static function ResetFields(array &$form, FormStateInterface $form_state) {
     $ajax_response = new AjaxResponse();
     $ajax_response -> addCommand(new AlertCommand("Testing"));
     return $ajax_response;
}

Update 1:
I have updated how the form is being return in the controller. It is now being returned as a unrendered form in a render array.

public function rpm() {
  $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
  return [
        '#theme' => 'rpm_page',
        '#online_rev_form' => $OnlineRevForm
  ];
}

I have also added this code to the .module file:

function revenue_projection_model_theme() {
  $theme['rpm_page'] = [
    'variables' => ['online_rev_form' => NULL],
    'template' => 'revenue_projection_model',
  ];

  return $theme;
}

You also need a submit function.

You can have a look here. It's a complete example with submit handler and callback. In this case I altered the form as I didn't create it but is quite similar. Also a really nice post is here


Get fields to appear in fields list, arguments list and filters list in view I am using hook_form_alter and adding a extra form field to drupal node form. All works fine, but in view this field is not show up. How do i add this field?

Instead of adding form element using hook_form_alter use CCK field. View will not understand your custom field but a CCK fields are integrated in views.

EDIT

Please check for Tag User module.


Change Hyperlink Color in Views I am looking for a way to change the hyperlink for Node title on a view. So far have tried rewriting the Node title field and also tried a global text field but links still show as blue.

Tried this but did not work:

{{ Node Title }}

What is the best way to change link color in views?

The correct way to style websites is with CSS.

You can use a selector from the existing Views output, or you can assign a special class to your Content: Title Field under Style settings. You can Create a CSS class for the field wrapper or the HTML element.

Then use the class selector in your CSS inside the theme:

.my-class a {
  color: #cc0000;
}

If you're not creating your own (sub)theme and only want to make minor adjustments you can use the CSS Editor or CSS Injector modules.


Is there a performance hit to using persistant variables? While working on some old custom code I noticed that variable_set() was being used in a manner that always made new key pair values and never made a call to variable_del. These values would be read once under a certain condition and never read again.

Are persistant variables something that get cleared on clear cache or are they always building up?

if they are building up does this affect the size or speed of page load?

example:

variable_set('key_name_' . $increment, $value);

In Drupal 6 and 7, variables created with variable_set() are stored in the {variable} database table. They are not automatically cleared when the cache is cleared. They are only removed when variable_del() is called.

Whenever a page is loaded, all variables in the {variable} table are loaded into the global $conf array. So yes - if a site is automatically creating new variables at a constant rate without cleaning them up, it could in theory cause performance degradation.

You can see in the variable_get() function that it is simply loading the global $conf array and looking for the requested variable within that.

It sounds like the custom code should have been using a dedicated database table for the data it was storing, because then it would only load that information when it needed to. Variables are loaded on every pageload.


List nodes from a taxonomy based on a field I'm looking for the most "Drupal" way to create either a view/block (not sure about either) that contains a list with the top level items being the parent taxonomies from a certain vocabulary (4 parents in total), and then nested under each taxonomy, the first 5 products that have a certain field on them set to true.

Essentially a "featured products"-esque block that will have 4 tabs.

So you need to do the following:

1) Create a view for products

Install Views Field View module
http://drupal.org/project/views_field_view Create a view for 4
products. Make sure it has contextual filter for term id set.
Save it

2) Create a taxonomy view

Create taxonomy view, set display as block, so you could output it in
a block
Add 'taxonomy term parent' filter and make it equal to 0. This way you'll select only parent terms
Select Views Field View in Fields and set it to output a view for products
Save

So now you should have a block which outputs parent taxonomy terms and under each term you have a list of products.

Let me know how it works.


How to access the raw content of a views field, for use with Services Views I have a user that I want to expose to services. Using Services Views. I'm using fields as the format, and adding the "photo" field to my display. My issue is that when I view the service (as JSON). I get all the HTML as well as th image URL, for instance

users_node_picture: "<img typeof="foaf:Image" src="http://mysite.com/sites/mysite.com/files/styles/thumbnail/public/pictures/picture-36.png" alt="" />",

I need just the url, I've tried the following with no luck.

Strip HTML (removes everything)
Rewrite output (same result)
Row theming (does not effect the services result, only the html page)
Installed Views PHP (by returning the row, I simply get the field id)

Is there any other way to effect the output of this field before it is outputed by Services Views? I thought perhaps I could do something with template_preprocess, but I'm not really sure how I would go about doing it.

You can do it using relationships! Under Advanced, add the relationship File Usage: File. Then go add a new field, and you'll see File: Path.

Alternatively, you could use the Image URL Formatter module. This allows you to print an image as a URL. Then in the field settings in Views select this under 'Format' for the image field. The module has some features that would be harder to achieve with the relationship, but for most cases the relationship should work.


Next/Prev buttons for nodes based on nodereference field By using this tutorial http://blog.urbaninsight.com/2011/09/12/adding-pager-navigation-nodes-drupal-7 I have created next/prev buttons for my images.

But as I have a lot of galleries and I need to filter images not only by node type but also by node reference field value.

The machine name of my field is field_pers_gallery and in phpmyadmin it is assigned to a particular gallery by field_pers_gallery_nid.

I'm note good at creating db query, could anybody help with any advices?

I don't know if you managed to get your pager working yet, but I've just modified a piece of code to create a pager based on node reference. You're free to use it as you see fit. You can go to my blog to see it:

http://www.visionarymedia.nl/blog/drupal-pager-based-node-reference


How to get the untranslate original string? In a form, there a submit button:

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

In the form _submit function:

  switch($form_state['values']['op']) {
    case 'Modify' :
      // ...
      break;

the case 'Continue' will not match if Modify is translated. How can I always get the original untranslated Modify string for the sake of string comparison?

If there are multiple submit buttons on the form, I always prefer to have different submit functions for them. In your case I'd go for something like :

  $form['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Modify'),
    '#submit' => array('_my_function_to_go_to_previous_function'),
  );

and implement the logic inside the submit:

function _my_function_to_go_to_previous_function($form, &$form_state) {
  // Logic to go to previous step.
}

In this way you'll have more control over whatever you do. Works well with multistep forms.
You can also implement separate #validate function per button too.
Note that the $form_state parameter is passed by reference, which would mean you don't have to return anything from the submit function. Just manipulate the values inside the variable as per requirement, and then call

$form_state['rebuild'] = TRUE;

inside the submit function, so that the form rebuilds itself with the new values.


Drush contrib modules not available if executed externally Using Drush 5.8 contrib modules are not available if executed externally.

E.g. Drush Entity is not available if executed on a Django view via a check_output:

check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True)

Any command regarding Drush Entity return an error specifying that the command "could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions."

The same command is available if executed via an interactive python shell or via ssh.

I've installed Drush Entity in this way:

drush dl drush_entity

This command on my system put drush_entity into /home/admin/.drush directory. This directory seems to be ignored, since site-alias too are ignored if i put them inside that directory.

The solution is to pass the environment variable $HOME to check_output, in this case /home/admin:

check_output("drush -l example.com -r /var/www/my/example/site/ entity-read node", shell=True, env={'HOME': "/home/admin"})

This force the /home/admin/.drush directory to be read. If everything is fine this command:

drush ev 'print(drush_server_home());'

should return /home/admin. If drush_server_home() returns an empty string, contrib modules installed inside .drush on home directory will not be available.

Ensure to install contrib modules with the same user controlling the /home/admin directory.

Read the documentation of the language you're using to pass the $HOME variable on command execution.


How can a user join a group in Drupal Commons? I'm using Drupal Commons (unfortunately 7.x-3.0-beta1).

In Drupal Commons, how can a user join a group?

Either my site has been customized out of all recognition or I simply can't see where a normal authenticated user goes to join a group.

In your Drupal admin area, go to "Administration → Structure → Content types → Group → Manage Display → Default" (/admin/structure/types/manage/group/display).
Set column "Format" for field "Group" to "OG subscribe link".

Your groups will now display a "Subscribe to Group" link on the groups' pages. This only applies for users who have the privilege to request membership to a specific group (which can be set in both the global OG permissions, and can be overwritten per group).


How do I programatically generate multiple "add to cart" forms on product display? I've got a matrix of 12 products, which can be added to the cart by users after selecting different term reference fields, which then select the appropriate product. This is shown on a product display.

However, I'd like to have multiple add-to-cart forms, each with a different line item selected on the product display field.

Basically, I've got a field collection, and I'd like to iterate through each of the field collection entities and display an add to cart form, with my full 12-product matrix of options, for each of these field collection items.

It would seem that I could get the add to cart field, all formatted, using

field_default_view($entity_type, $entity, $field, $instance, $langcode, $items, $display)

But I am currently on the node.tpl.php file, and I can't quite work out which entity objects are which to pass to this function. Nothing really resembles what I'm seeing passed to commerce_cart_field_formatter_view.

Am I thinking about this wrong? Is there a better way to accomplish this?

I implemented this through patching Commerce Add to Cart Extras. My patch can be found here: https://www.drupal.org/node/1836200

In brief, the line item type contains a reference to an entity, a field collection item, actually.

I used views to generate a list of products with an add to cart form using Commerce Add to Cart Extras, joining (by a views relationship) on my field tables that provide the reference which must be attached to the line item.

Next, I had to alter Commerce Add to Cart extras so that the views result containing my entity id which must be added to the line item will copy that id over to the line item when the line item is created.

In the end, I have a list of multiple instances of the same product with a quantity field and a single add to cart button. Each product has the entity which must be added to the line item. When one of those products is added to the cart, the entity id gets copied over to the line item.


How to distribute a Drupal website on a flash card? I would like to take a Drupal website and distribute the information on it on a flash card or DVD -- even if it is a read only version. The people who will be using the website will not always have internet access. Plus, it's the type of information that somebody would like to sponsor. So at intervals the website will be published onto a flash card or DVD with a company logo on it and the website will be branded to the company. Any ideas?

You can run a dynamic, database-driven Drupal site from a DVD or Flash memory stick using a system like portable XAMPP, which is designed to run on removable drives, and includes Apache, PHP and MySQL.

If you only need static pages, you can use the HTML Export module, which will export all your image, JavaScript and CSS, and export your nodes as HTML pages. I've tried it and it works as advertised.


Email verification programmatically I have a custom registration form with three options(premium, trial and group).
The premium user does not need email verification but other two do. So I need to send verification email pro-grammatically.

I have searched google where I got only options for some modules. But my need is only sending an email with unique URL for verifcation.

Please suggest me the drupal function that helps me achieve this.

Thank you

You could use hook_mail_alter to abort the verification email being sent in the condition that the user is using the premium option. As stated on the api.drupal.org page if you set the 'send' parameter of the $message data to FALSE it will abort sending the email.

You'll need to retrieve the 'premium' context within your implementation of hook_mail_alter() to achieve this, which may require setting that property on the user, the session, or in a custom database table.


Allow comments only for author of the node and certain role I'm using Drupal 7. It is possible to disable the comment form for a specific node type for authenticated users? What hooks should I use if I want to allow only the author of the node and the administrator to post comments. The normal users (authenticated role) should only read them.

Thank you

You can probably unset the comment form using hook_form_alter on the basis on certain condition:

function MODULENAME_form_alter(&$form, &$form_state) {
  if ( $form_id == 'comment_form') {
    global $user;
    if (!user_access('administer nodes') {
      // Form alter here to unset comment form
      unset($form);
    }
  }
}


Media images link to their own image I have inherited a site which had no image management. Instead each image field required you to upload an image instead of reuse an existing one.
I enabled Media Browser and updated to 8.7.
I am also using the following modules [these are the ones I have installed ontop of existing]:

embed
entity_embed
editor_advanced_link
inline_entity_form
entity_browser
media_entity_browser

The problem is every image, either added via an image filed or in CKEditor wysiwyg is now wrapped in a link to the image file:

Twig template: \core\modules\image\templates\image-formatter.html.twig

has the following:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

But I cannot see where the URL is set in the CMS admin, or how to stop it creating a link to itself. So far I have just copied the template to my theme and removed the url, but I would like to know how to manage this properly.

In:
structure -> media types -> image -> display

/admin/structure/media/manage/image/display

the image field settings had 'Link image to' -> file

Set this to nothing, removed the theme image-formatter.html.twig template and the file link added to each image was no longer there.


How can I use View modes for entity without bundles? I have an entity that has no bundles(ie. it has itself as a - 1 - bundle) and I need to be able to use View modes for it.

My understnading is that the Field UI needs the 'bundle of' entity to exist in order to attach itself to it.

Is somehow possible to get around this?

Should I file an issue on d.org?

tl;dr: If your entity annotation contains an admin form, field UI will work.

This is what they would mark on Quora as 'Questions That Contain Assumptions' and those questions usually contain false assumptions. In this case 'bundle of' doesn't even appear in the field UI directory anywhere. Instead, here's how I'd found the answer to your question -- it's not hard at all. First look in core/modules/field_ui/field_ui.routing.yml. Nothing. Well, it's dynamic, if it's dynamic then it's going to be in core/modules/field_ui/lib/Drupal/field_ui/Routing/ and it is. Let's look in RouteSubscriber.php in that directory:

foreach ($this->manager->getDefinitions() as $entity_type_id => $entity_type) {
  $defaults = array();
  if ($entity_type->isFieldable() && $entity_type->hasLinkTemplate('admin-form')) {

Now a quick counter check on the Node annotation and see, under links, there's "admin-form" = "node.type_edit" so that's that.


How to create fake nodes I would like to know how to fake a node in Drupal. I have a table with drawings. The drawings have non unique names. For each drawing I want to be able to create a page using the unique id of the drawing:

like so: http://mysite.com/drawing/100

I don't want to create nodes for each drawing but still be able to have a theme template to show the contents of the drawing record.

How do I do that. And if this is possible how do I access the drawing number in my template page?

Thanks a lot!

What you are asking is rather basic module development. Setting up a page that takes an argument.

Check out the Example module, and more specifically the page_example module and page_example_arguments(). That contains the base of what you need.


How to programmatically set the node updated/changed timestamp Some migrated content needs the "updated" timestamp set to the original timestamp, instead of the time the node was saved duration migration.

Setting the "changed" field in the database appears to have no affect for the node updated time?

Here's a sample query:

update node_field_data set changed = 1535805325 where nid = 2148716;
Query OK, 1 row affected (0.01 sec)
...
select nid,changed,from_unixtime(changed) from node_field_data where nid = 2148716;
+---------+------------+------------------------+
| nid     | changed    | from_unixtime(changed) |
+---------+------------+------------------------+
| 2148716 | 1535805325 | 2018-09-01 12:35:25    |
+---------+------------+------------------------+
1 row in set (0.02 sec)

When loading the node, the original changed timestamp is returned:

[changed] => Array
(
    [x-default] => 1532090833
)

I've tried clearing all caches, including clearing the cache tag and fully restarting the cache services (redis+varnish), but to no avail, the previous changed timestamp is always returned!

Any suggestions on how to set the updated/changed timestamp for this case?

OK, for this approach, the solution was to ensure another table was also updated with the changed timestamp: node_field_revision

e.g:

update node_field_revision set changed = 1535805325 where nid = 2148716 and vid = 2803575;

After that, a normal cache clear showed the new updated timestamp for the node.


Child pages in books module I can only create 8 child pages in a book not beyond that,It seems like the depth of the child pages is set to 8 but i could not find the location where the depth was set.Please help me

The book module has this bit of code in it to enable a user to choose which parent a node has:

$form = array(
  '#type' => 'select',
  '#title' => t('Parent item'),
  '#default_value' => $book_link['plid'],
  '#description' => t('The parent page in the book. The maximum depth for a book and all child pages is !maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
  '#options' => book_toc($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['mlid'])),
  '#attributes' => array('class' => array('book-title-select')),
  '#prefix' => '
',
  '#suffix' => '
',
);

Take a look at the description in particular. When you sub in the relevant variables, it reads:

  The maximum depth for a book and all child pages is 9. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.

Emphasis mine.

So the limit intentional, it (necessarily) matches up with the maximum depth for a menu in the same system.

It would technically be possible to patch core and increase MENU_MAX_DEPTH to something larger, but bear in mind that other parts of the system rely on it (for example the number of p* columns in the menu links table), so it probably won't be as simple as all that.


How do I execute this SQL query I'm trying to execute the following :

db_query('SELECT FROM_UNIXTIME(`created`, "%Y") as year, FROM_UNIXTIME(`created`, "%m") as month, FROM_UNIXTIME(`created`, "%d") as day FROM users ORDER BY `created`');

And because of the % sign the result is :
PDOException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '%Y' in 'field list'

I tried escaping the % with a double %% resulting in : PDOException : SQLSTATE[42S22]: Column not found: 1054 Unknown column '%%Y' in 'field list'

Of course this query works in phpmyadmin

Help ?

PDO requires that you use single quotes, e.g.

db_query("SELECT FROM_UNIXTIME(`created`, '%Y') as year, FROM_UNIXTIME(`created`, '%m') as month, FROM_UNIXTIME(`created`, '%d') as day FROM users ORDER BY `created`");


access field data in template.php and create variable for header image in page.tpl.php I am trying to allow the user to set a custom image to display in the header on node pages that have a header_image field and to display a default header image on all other pages (including system and module generated pages).

I thought I could do this by creating a "Header Image" view and using a contextual filter to get the header_image field on the displayed node. This works okay when displaying a node that has the header_image field but not on a page that doesn't have that field. Because this view is a block the contextual filter uses the default value of "Content ID from URL" and I can't use a fixed default value.

I am guessing I have to use the preprocess_page function and field_has_data or perhaps the Entity API Module to check if the node has data in the header_image field. If there is no header_image field or it has no value I would like to use the default image for that field. Is there anyway to specify using the default image that was set by the user? other wise I would use the default image at file_stream_wrapper_get_instance_by_uri('public://')->getDirectoryPath().'/default_images/default_header.jpg'

There must be a common solution to this problem.. Actually I just had a thought.. what if there are multiple nodes on a page? Any suggestions what I should do to accomplish this?

I recently tried to do this but stumbled then over the Header Image Module which does this perfectly. It allows you to create a block which holds any content (for example a custom content type) and ads it to a block. You can specify on each content where it should be displayed (nid, path, term etc.).


Drupal 8 - Variables - Template Twig - Cache In the HOOK of my project XXX_preprocess I am defining a variable based on a cookie.

My Hook function

function XXXXXX_preprocess(array &$variables) {
if (isset($_COOKIE[personsSearchCookie]) && !empty($_COOKIE[personsSearchCookie])) {
    $personsFilter = explode("-", $_COOKIE[personsSearchCookie]);
    $variables["personsFilter"] = array (
        "filterType" => $personsFilter[0],
        "filterId" => $personsFilter[1]
    );
}

But in the Twig template, it always gives me the initial value of that variable, it never changes.
My Twig code:

Filtering results by [{{ personsFilter.filterType }}]

{% if personsFilter is defined and personsFilter.filterType is defined and personsFilter.filterType is not empty %}
    {% if personsFilter.filterType == "area" %}
        Filtering by Area

    {% endif %}

    {% if personsFilter.filterType == "office" %}
        Filtering by Office

    {% endif %}
{% else %}
    No filtering
{% endif %}

This should be a cache theme, right?

How can I make so that when my cookie changes, the variable is modified and since twig can access the new value?

In the prepreocess function in all re-loads, the variable change correctly, but, in twig, the variable have bad value.

Thank you!

In your question, it wasn't clear how you are defining the render array (a block, a form, etc.) Assuming you are rendering this twig file through a render array, you could add the following to the render array for this particular element to turn off caching of this element:

 '#cache' => [
    'max-age' => 0,
  ],

You could get more specific by implementing conditional logic to clear the cache on a certain condition. From the examples module, in the cache_example, we have the CacheExampleForm function createExpiringItem():

/**
* Submit handler to create a new cache item with specified expiration.
*/
public function createExpiringItem($form, &$form_state) {

$tags = array(
  'cache_example:1',
);

$interval = $form_state->getValue('expiration');
if ($interval == 'never_remove') {
  $expiration = CacheBackendInterface::CACHE_PERMANENT;
  $expiration_friendly = $this->t('Never expires');
}
else {
  $expiration = time() + $interval;
  $expiration_friendly = format_date($expiration);
}
// Set the expiration to the actual Unix timestamp of the end of the
// required interval. Also add a tag to it to be able to clear caches more
// precise.
$this->cacheBackend->set('cache_example_expiring_item', $expiration_friendly, $expiration, $tags);
drupal_set_message($this->t('cache_example_expiring_item was set to expire at %time', array('%time' => $expiration_friendly)));
}

And, also shown in the examples is invalidating:

$tags = array(
  'cache_example:1',
);
Cache::invalidateTags($tags);

So in your preprocess, you could use this type of logic to invalidate the cache. Hope this helps.


Enforce rule on Sticky to the top of lists I have x amount of nodes of content type "job", all of which are presented on page using two views, one that sits at the top "job-highlighted" and one that sits at the bottom "rest-of-jobs".

One job is selected to be displayed in the top view. It is selected using the "Sticky at top of lists" option in the back end.

The rest are displayed in the "rest-of-jobs" view.

The problem is that the user can set a number of jobs to have the sticky at the top of lists selected.

My question is, is there a way to enforce the content type job to have only one node with the sticky at the top of lists functionality. Can I implement a procedure that updates these or is there a module that already introduces this functionality?

Can anyone offer a solution. Thanks in advance.

Do you have a node for the overview page? If so:
Instead of using the sticky to top button add a relationship field to the job overview node and set that to allow 1 value, and show the selected job in the highlight field.


How do I add fields to an existing custom entity? I have a custom entity that fieldable. I need to add a field to it, and I want to do it through the UI. The entity was created in a custom module, which I can modify.
How can I make the entity fieldable?
/**
 * Defines the Quiz entity.
 *
 * @ingroup qwizard
 *
 * @ContentEntityType(
 *   id = "qwiz",
 *   label = @Translation("Quiz"),
 *   bundle_label = @Translation("Quiz type"),
 *   handlers = {
 *     "storage" = "Drupal\qwizard\QwizStorage",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\qwizard\QwizListBuilder",
 *     "views_data" = "Drupal\qwizard\Entity\QwizViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\qwizard\Form\QwizForm",
 *       "add" = "Drupal\qwizard\Form\QwizForm",
 *       "edit" = "Drupal\qwizard\Form\QwizForm",
 *       "delete" = "Drupal\qwizard\Form\QwizDeleteForm",
 *     },
 *     "access" = "Drupal\qwizard\QwizAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\qwizard\QwizHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "qwiz",
 *   revision_table = "qwiz_revision",
 *   revision_data_table = "qwiz_field_revision",
 *   admin_permission = "administer quiz entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/qwizard/qwiz/{qwiz}",
 *     "add-page" = "/admin/structure/qwizard/qwiz/add",
 *     "add-form" = "/admin/structure/qwizard/qwiz/add/{qwiz_type}",
 *     "edit-form" = "/admin/structure/qwizard/qwiz/{qwiz}/edit",
 *     "delete-form" = "/admin/structure/qwizard/qwiz/{qwiz}/delete",
 *     "version-history" = "/admin/structure/qwizard/qwiz/{qwiz}/revisions",
 *     "revision" = "/admin/structure/qwizard/qwiz/{qwiz}/revisions/{qwiz_revision}/view",
 *     "revision_revert" = "/admin/structure/qwizard/qwiz/{qwiz}/revisions/{qwiz_revision}/revert",
 *     "revision_delete" = "/admin/structure/qwizard/qwiz/{qwiz}/revisions/{qwiz_revision}/delete",
 *     "collection" = "/admin/structure/qwizard/qwiz",
 *   },
 *   bundle_entity_type = "qwiz_type",
 *   field_ui_base_route = "entity.qwiz_type.edit_form"
 * )
 */

You just need to add a field_ui_base_route to the entity annotation. The value should be the route ID for the edit form of the config entity type used to provide the bundles.
So if your entity ID is foo and the bundle config entity ID is foo_type, that would be:
@ContentEntityType(
  id = "foo",
  ...
  field_ui_base_route = "entity.foo_type.edit_form"
)

Rebuild the cache, and you should see the relevant menu links and tabs when you manage your bundles in the UI.


What is difference between a custom block and a Bean block? As I am new to Drupal 7, I want to understand the difference between custom block and Bean block.

Can someone please help me on this?

Custom block

If you'd created/configure a block using the typical Admin UI, located at admin/structure/block, you enter configuration options like visibility, block title, etc. That's what I would consider as "an" example of a custom block.

And when some module that you enable causes some block to become available (related to that module), it could be considered as a similar block, though "custom" does not apply to it (maybe call it a module delivered block?).

Bean block

Bean blocks are (also) blocks, but what is special about them is that you use the Bean module to create such blocks. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting Bean permissions, it gives you a lot of flexibility about how exactly you want to use this (great) module.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A rising star ...

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has about 32K reported installs. Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.

I'm not aware (yet) of any other contributed module that "only" started in D7, and made it right into core in the very next major Drupal release ... If there are other modules with a similar track record, I doubt there would be many of them ...


How to have a field that counts the nodes submitted by the current user? My site with existing content needs a field that shows the number of nodes of a certain content type that have been created by the current user.

I can't use Views because the field needs to be able to be used in a Rules condition.

Nor can I use Rules Actions and Flag at the time of adding nodes because so many nodes are pre-existing.

Nor can I use Display Suite code fields because I don't think they are able to be used in Rules either.

Is a computed field and a custom query the best option?

I have so far failed to find a code snippet and I am not experienced in PHP.

You can use the Computed Field module but you need to consider this:

  When is the field actually computed?

  If you wish to store the values
  in the database then you have to update or re-submit the node to
  compute the value of the field.

  If it is not stored in the database then the value computes when the
  node loads and only when the node is loaded. The field will not work
  in views nor will it function properly if it depends on other
  non-stored computed fields.

This is the code of your field:

global $user;
$type = 'article';

$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('status', 1)
->propertyCondition('type', $type)
->propertyCondition('uid', $user->uid)
->execute();

$cant = count($result['node']);
$entity_field[0]['value'] = $cant;

Another way that come to my mind is have a variable to store this value, and you will edit this var each time a new node is created (hook_node_insert) or deleted (hook_node_delete), so in this case you will have always the real value.

Rerefences:

Computed Field


Commerce file description as text only I've got a shop selling downloadable product variations. I'd like to display the Commerce Files field description to anonymous users as text only.

Here's how it currently appears for registered users:

The field description visible is an active link...

--

Here's the current display for anonymous users

No description available

--

I can't find anywhere in the UI that allows for displaying the description without a link to all users. Here's the display options
.

Any ideas?

I figured this out. ticking the 'display' box on the file field in the product form and settings appropriate permissions worked.


GraphQL query not returning data I have 5 different content types and I've added content / nodes. I'm using graphQL to fetch the data, however in 1 of the content types the data is not being returned. This is the latest content type I've added, so I can query data from all 4 other content types and get the data I expect without any problems using fragments.

My query for the new content type is simple.

{
  nodeQuery {
    entities {
      ...on NodeGlobalContent {
        title
        body {
          value
        }
      }
    }
  }
}

The empty result is the following.

{
  "data": {
    "nodeQuery": {
      "entities": [
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {}
      ]
    }
  }
}

If I query the node by ID, I get the following data.

query {
  nodeById(id: "20") {
    entityLabel
    entityBundle
  }
}

{
  "data": {
    "nodeById": {
      "entityLabel": "test",
      "entityBundle": "global_content"
    }
  }
}

Why can't I retrieve the data using a fragment?

The answer is to filter by content type:

{
  nodeQuery(
    filter: {
      conditions:[
        {operator: IN, field: "type", value: ["global_content"]},
      ]
    }
  ) {
    entities {
      ...on NodeGlobalContent {
        title
        body {
          value
        }
      }
    }
  }
}


URL encoding in admin overlays - breaks overlay I have a fresh install of Drupal 7 with no content, and a few extra modules installed. Recently as I've navigated on the admin side, the URLs for the overlays have escaped HTML in them, like this:

http://mywebsite.com/#overlay=%3Fq%3Dadmin/config

Which of course is supposed to mean

http://mywebsite.com/#overlay=?q=admin/config

But still, the overlay doesn't show up properly.

I've found a few reports of this, but no fixes, other than to disable overlays. Can anyone offer anything?

What's tricky about this is that I can't get to administrative features because the overlays can't show up.

Apparently this error is not related to URL encoding, but the lack of overlay module support when mod_rewrite is not properly configured in the Apache web server.

See http://drupal.org/node/1337420#comment-5238454.


How can I make a view to show all own comments? I'm trying to show all comments the logged user did on a forum from the module advanced forum.
I've tried using views, adding a relationship with content:autor and filtering by user:current. But didn't work. Also I've tried contextual filter with the parameter comment :author id.
Anyone can help?

I'm using D7.

Follow below steps to create a view.

Login as admin
Go to admin/structure/views/import
Copy paste below code in "Paste view code here"

$Below code

$view = new view();
$view->name = 'user_forum_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'User Forum Comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE;

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User Forum Comments';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Comment: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'comment';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 1;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'nid';
$handler->display->display_options['filters']['type']['value'] = array(
  'forum' => 'forum',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'user-forum-comments';

Click on Import
Go to user-forum-comments to see results
Go to admin/structure/views/view/user_forum_comments/edit to see how view is constructed.

Hope it answers :-)


Problem with mobile_theme theme switcher module I've tried using mobile_theme to switch to a selected mobile theme when a mobile visitor browses. But using online mobile emulators: mobilephoneemulator.com and transmog.net I found that half of pages get shown as Desktop version pages.

I thought of using ThemeKey but I'll need to use  browser version, operating system to serve mobile content. But it could fail for Googlebot, Bingbot etc, they also need to see my mobile pages.

Is there any alternative auto theme switcher for mobile? I'm on shared hosting and can't use Browscap etc php modules.

mobile_theme wouldn't work with Drupal cache on. It is not mentioned anywhere in the documentation. We should use m.example.com for mobile url's for Drupal. I tried many such modules except for ThemeKey but the same problem( since I was using the cache).

I finally wrote my own module. But later found : simple_mobile_redirect to be good one but have not tried yet.


Preventing SQL injection In Drupal 6, queries are issued with db_query(). Using %-modifiers, query arguments are substituted into the query after being filtered. Strings %s (and only strings) are ultimately run through mysqli_real_escape_string() (using db_escape_string()).

Looking at the php docs for mysqli_real_escape_string(), I see the following security warning:

  The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string().

The answer to another question about mysql_real_escape_string / SQL Injection explains that:

  Another way to get yourself into hot water using
  mysql_real_escape_string is when you set the database connection
  encoding using the wrong method. You should do this:

  mysql_set_charset('utf8', $link);

  You can also do this though:

  mysql_query("SET NAMES 'utf8'", $link);

  The problem is that the latter
  bypasses the mysql_ API, which still thinks you're talking to the
  database using latin1 (or something else). [...] This can be used for
  injection attacks in certain multibyte string situations.

Drupal does not call mysqli_set_charset(), and instead issues the query 'SET NAMES utf8'. This can be seen in db_connect().

In order to properly protect Drupal 6 against SQL Injection, does the charset need to be set at the server level?

This answer to a stackoverflow question does a great job at explaining the attack that can get around mysqli_real_escape_string() using multi-byte character sets.

I've concluded that when running Drupal 6, we do not have to set the charset at the server level in order to be safe from the attack.

Drupal always sets the client to UTF8 (and not the GBK or BIG-5 charsets that are required for the exploit). Newer versions MySQL (> 5.1) are also not vulnerable.

HOWEVER, although Drupal is safe from this exploit, we should still follow the installation documentation which states, "The database should be created with UTF-8 (Unicode) encoding, for example utf8_general_ci.".

One helpful comment on the installation docs outlines how to create your database with UTF8 encoding, and how to ensure that UTF8 is used when performing a backup/restore:

  To achieve this by the mysql command line interface use the following commands:
  $ mysql -u root -p # Login
  mysql> CREATE DATABASE databasename CHARACTER SET utf8; # Create with utf-8

  When using mysqldump/mysql for backup/restore also force both server and client to utf8 by inserting into /etc/mysql/my.cnf:
  default-character-set = utf8 # Server
  skip-character-set-client-handshake # Force client


What is the Drupal's way of wrapping fields inside a field? It seems that many Drupal gurus disfavor using Field Collection module to wrap fields inside a field. They say it's not the Drupal's way of doing it.

In my current scenario, I need a single field with before & after image subfields. I also need a recipe ingredients field, with ingredient name, unit size (using taxonomy reference) and serving amount subfields.

What is the preferred Drupal's way of doing such a thing? Should you have to code an entirely custom module for each field type?

Update

It seems that the ideal approach is to use a custom field type. Optionally you can use Drupal modules to group fields, such as Composed Field and Multifield, and not-so-favored, architecturally cumbersome, Field Collection. Another solution is to create a content-type for each group of fields and use Entity Reference to reference the field to it.

Ideally I'd like to see an example of a custom field type which implements a text and an image field, or something similar.

You can try https://drupal.org/project/composed_field

  The Field collection uses a different approach for creating composed fields. Here are the main differences between this module and the "Field Collection":
  The host field created by "Field Collection" is in fact an entity that gets attached to the fieldable entities (nodes, taxonomy, comment, commerce products, etc). So, although you attach a Field Collection through the Field UI, what is being attached is not a field but an entity.

  Once you get your new entity (host field) attached to your fieldable entity (node, comment, taxonomy, commerce product, etc) then you have to attach the fields ( what would be the subfields ) into the host field ( Field Collection entity).

  Each subfield is actually a field on its own, that is, from the database point of view, each subfield is a single field.

  "Composed Field" on the other hand attaches a field (host field), not an entity, to your fieldable entities (node, comment, taxonomy, commerce product, etc) through the Field UI. At the end of the day, even if you set a field with say 4 subfields, you will end up having only one field and a single value saved into the database.

  Unless you have a very specific use case need "Composed Field" should do what you need with less effort and less resources.

One more module availabel to achive the similar task is https://drupal.org/project/multifield but it is currently in unstable status

  This project seeks to provide a true compound field solution for Drupal 7. As much as I love Field collection, it still has to save actual entities, and can cause performance problems due to having to load all the referenced field collection entities on node, or parent entity load.


Why do form builders have a $form parameter? In Drupal 8, the first parameter of FormInterface::buildForm() is $form.

When implementing a form builder, one has the option of either adding stuff to this existing array and returning it, or creating a new $form array, discarding what was passed into the function. In my experience, both of these options usually work fine.

What's the point? Is there ever a case when this parameter is needed?

I think to vaguely remember that this is somehow relevant when a form is rebuilt, so this would be the old form.. but I would not really know what to do with it.

Its an interesting question as there are now two ways of altering forms.

Using HOOK_form_alter ie book_form_node_form_alter with $form by ref and by inheritance returning $form as done in ie \Drupal\forum\Form\Overview::buildForm

class Overview extends OverviewTerms {
  ...
  public function buildForm(array $form, FormStateInterface $form_state) {
    ...
    $form = parent::buildForm($form, $form_state, $vocabulary);
    ...
    return $form;
  }
  ...
}

where \Drupal\taxonomy\Form\OverviewTerms::buildForm gets called using $form = parent::buildForm($form, $form_state, $vocabulary); thus in fact zapping $form.

Most code seems to return parent::buildForm($form, $form_state, ...); which we could call 'method' 3.

I guess hook_form_alter will disappear in the next version (10.x?) in favour of event listeners


Bakery: Why do I get the "Logging out the user with the bad cookie"? I am attempting a Single Sign On solution using the Bakery module.

My problem is each attempt to login results in the following error:

  Logging out the user with the bad cookie.

Those failing login attempts are to the master site which also means I can't login to the sub-sites.

All the necessary configurations are in place.

The master site is http://www.example.com/
The master site checkbox is enabled
http://sub.example.com/ is input as the slave site
Cookie age is set to 3600
Private key is examplesite
Cookie domain is .examplesite.com
Username and email are my enabled profile fields

I don't get why it's not responding with successful logins.
Please help if you can.

As an alternative to Bakery, if your sites are all co-hosted and you're using MySQL, you can get your sites to share user tables as described by Lullabot.

The important parts are the Master site setup:

$db_url = 'mysql://user:pass@localhost/master_database';
$db_prefix = '';

The shared cookie domain (which you already have):

$cookie_domain = '.example.com';

And the slave site setup:

$db_url = 'mysql://user:pass@localhost/slave_database';
$db_prefix = array(
   'default'   => 'name_of_slave_database.',
   'users'     => 'name_of_master_database.',
   'sessions'  => 'name_of_master_database.',
   'role'      => 'name_of_master_database.',
   'authmap'   => 'name_of_master_database.',
);

I have succeeded with this method in the past, though I think I used the normal database array instead of $db_url.


D7: Change Drupal "Link" field to store node url instead of alias for internal links I am using the "Link" field in Drupal 7 to store links. Sometimes these links are internal and sometimes they are external. In the case of internal links, I would like to be able to store the system URL ("node/371") instead of an alias ("about/mission-statement") so that the link field will auto-correct itself when someone changes the URL alias.

Entity Reference is great for keeping track of internal nodes, but I would like the same field instance to handle both internal and external links.

Advanced Link doesn't seem to do this processing either.

Is there another module I should use, or a hook I can use to intercept the link field processing pre-storage?

EDIT

I was able to hack the module to get the behavior I wanted by adding two lines of code to _link_process :

$systemPath = drupal_lookup_path('source',$item['url']);
$item['url'] = ($systemPath) ? $systemPath : $item['url'];

… although it would be nice to be able to do this in a way that preserves an upgrade path.

I use pathauto. it should automatically keep up with your node name changes and point to the right internal ref, right?

Then there's Node redirect?

Extended path alias might be promising, too. Extended path aliases


Some user images switched after upgrade I'm working on an upgrade process, and I've noticed something strange when I upgrade my D6 site to 7. I've noticed some behavior that's kinda odd, and was wondering if anyone one else had experienced something similar in their upgrades.

1: Some users have the their avatars in the "file_managed" table, uri field set to:
sites/default/files/user-pictures/...

These are the correct pictures, but they won't work with image styles unless I switch the value of uri to be the correct uri format. Any ideas why some of the images wouldn't get switched to the proper uri formate durring a 6-7 upgrade?

2: Some users have the completely wrong avatar. The avatars aren't even necessarily other user's avatars, though some of them are, but some are just images from site pages. For example, user 55 in D6 had an avatar at picture-55. After upgrading, I find no record of an image with the file name of picture-55 in file_managed, the user table says his user image is set to a file with an fid of 20, which is in attached images.

I've got a lot of users, so making sure the avatars mach up correctly is important. I would appreciate any help in figuring what's causing this/how to fix it.

Drupal 6 did not have {file_managed} at all. Also, user profiles wasn't really fieldable. And both styles and fields changed between 6 and 7. 3 big changes affecting one value - that's bound to create problems.

To get around it, you can use Views Data Export to expose users from old site, and then import your users back using for example Feeds

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.

with Feeds Image Grabber

  an addon for Feeds module, which grabs image for each feed-item from their respective webpages and maps it to an image field


How to reverse engineer a section of a Drupal Page Sorry if this is a beginner or inappropriate question, but I'm trying to work on modifying a complex Drupal site and I have no idea how to find out how it's built.

At the top of the home page there's a bunch of content (specifically an image that moves and zooms like a google map) but I can't find anything about how to edit or control this area.

Where should I look? Views, Blocks, or in the Theme files? I've tried looking through all of these as best as I know but I'm hitting dead ends.

Thanks!

Your question could use more specifics, but I think I understand what you are experiencing.

I've been there. If you cannot find it anywhere, a good bet is that it is part of the theme tpl pages. If you want to confirm this, you should go to the sites/all/themes/whatever-theme-you-are-using and search for files ending in .tpl.php, which are the files that control the theme you are currently using.

Frequently, any special effect or non-drupal configurable behaviour is likely inserted directly into these files. If your intention is to re-use whatever you are seeing at the top of the page, look for js (javascript) files: it is likely that dynamic pages are using some library, and that by googling the js filenames you can find a reference that might be useful.

At least, it has worked for me.


restrict login access by IP Is it possible to restrict the login or role  access by IP in drupal 7.Is there any module available in drupal 7  to provide similar  functionality  Restrict Login
Any one guide me do this.
Thanks

Check out the Restrict IP module.

This module allows administrators to restrict access to the site to an administrator defined set of IP addresses. Anyone trying to access the site from an IP address not in the list of allowed IP addresses will be redirected to an access denied page with the message "Your address is not in the list of allowed IP addresses". No blocks will be rendered, and no JavaScript will be added to the page. This will happen for any and all pages these users try to access. The module also has various configuration options to whitelist or blacklist pages, bypass IP checking by role, and alter the output when the user is blocked.


inheriting fields from a base content type I need to create 10 content types which, apart from their specific fields, will have 4 common fields (e.g name, surname, email, age).

Since I'm using Features I could create the first and copy paste the definitions to the other 9 content types. The problem though is that if the specifications ever change and I need to add or change any of those common fields I'll still need to do repetitive work.

How should I solve this? Is there a module which allows the construction of a "base content type" from which other content types can inherit fields? Or should I just reuse fields?

The following modules don't seem to be active for D7:

http://drupal.org/project/field_inherit
http://drupal.org/project/bundle_inherit
http://drupal.org/project/inherit

Short answer: I would simple go with sharing these four fields across the content types that you have. This is boring and repetitive work, but I'm not aware of a well-established way to do it otherwise, so this is the safest bet in my opinion. This gained a bad reputation in D6 as it caused performance problems, but in D7 there is no difference.

Longer answer: I did try copy/pasting of features code at one point, it works, but is quite messy and carries a large risk of "getting it wrong" as it's not documented nor entirely obvious what code needs to be updated.

As Joe Beuckman suggests, creating a custom entity is one way of solving this as well. If you add your shared data columns as entity "properties" instead of fields, they will be shared across all bundles of that entity type. A core example of this is the "title" property on nodes. A lot of modules today work in a entity agnostic fashion, but it's important however to note that the entity API was far from finished in D7. There is no general way for example to handle "entity access" which may or may not be a problem.

Also, on the last approach, you may also want to take a look at the Entity Construction Kit (ECK) module. I haven't used it myself yet, but I believe it could be helpful in creating new entities.


How to dynamically populate the condition method argument in a Dynamic Query I am writing a query that will retrieve nodes that match a set of criteria. Though the number of cirteria is unknown. I was hopping i could pass to the condition() method an array of criteria with a key as the 'column name' and that value as the 'value to match' for that colum. For instance :

$criteria = array ('nid' => 1, 'etid' => '1')

$query = db_select('table', 't');

$query
  ->condition( $criteria)
  ->fields('t', some_field);

I have almost 10 criteria and no way to know which will be selected so writing a query for each wont be possible.

Is there a way to achieve that ?

EDIT:

i thought about using that :

if (empty($criteria1)){
    $criteria = array (":criteria1"= '*');
}else {
 $criteria = array (":criteria1"=$criteria1);
}
$query = db_query('SELECT nid FROM { parce_index } WHERE criteria1 = :criteria1 AND criteria2= criteria2...',$criteria));

Would that make sense ?

If anyone ever need that i got an answer there.

http://drupal.org/node/12843

This is useful as well :

https://stackoverflow.com/questions/7476611/how-to-write-a-query-with-a-dynamic-where-clause


How can I embed the content of a field into the content of another field? If I have a news site where I can select a source e.g. a press agency (given by a Taxonomy field) when creating a new article, how can I put this source at the beginning of the article text when viewing it? Like this:

(SOURCE) Beginning of article blabla............................

I already found a solution by using three different custom templates for getting rid of all the html wrappers and then floating the article text around (SOURCE), but there must a better solution like manipulating the node array or sth?

You can combine two fields in hook_ENTITY_TYPE_view()

function mymodule_node_view(&$build, $entity, $display, $view_mode) {

  if (isset($build['field_source'][0]['#markup']) && isset($build['body']['0']['#text'])) {

    $build['body']['0']['#text'] =
      '<strong>(' . $build['field_source'][0]['#markup'] . ')</strong> ' .
      $build['body']['0']['#text'];

    unset($build['field_source']);

  }
}

and unset the added field to avoid double content.

You can also add html tags if they are allowed in the text format.

This is an example. You have to look into the build array after you've configured the display mode in ui and adjust the array keys.


What are the best practices to manage site mirrors with Drupal? I have gone through the reading of this Backing up and migrating a site from which i know basically there are two parts to backup - keeping the Drupal folder and the dump of MySql.

I am not really planning to migrate a site, but want to create a development environment separate and then push it to the live site.

Apart from the link above, are there any best practices that are worth doing? What are the problems or pit falls that should i avoid? What tools works best?

Looking at the practical experiences people have been through which is not obvious.

PS: I am planning to host it in a Linux based environment.

It always a big deal with Drupal to have a Staging and Production environment. Because you can't just make a simple mirror.

Because you are going to do Site Building in your Staging area, you can't export the database and import it in production, because of user content generation. The inverse its also a problem, as you have done some Site Building.

Of corse you have some tools like Selinium IDE that helps you to save your configuration and that you can use after in production.

The others solution its to move everything, configuration I mean, into files. You've couples of modules that can helps you. First of all, Features that allow you export configurations as feature and you can enable it easily once on production.

For variable and blocks, you've Strongarm and Boxes. Finally the hook_update_N will help you to archive the last goals.

For the code part of your project, I guess nothing is better than versioning, like Subversion or Git (goes for Git as it's use by drupal.org). And for the workflow model I can just advice this one that works pretty well in our organization.


How to add a custom url to user menu? I've create a theme for user login page with different style and everything is good.
When a user log in to my site in his profile he can see a user menu and add content link.
I don't want to show /user page when user click on user menu , I want to show /user/% ?
Any advice ?

You cannot add wildcards to menu item paths. I do not know why you want to do this as it is not neccessarry - when a logged in user clicks on "/user" he gets to his account page.