Making CCK fields read-only in Drupal 6

Posted on May 14, 2012

Generally, using form alter on any form field and setting #disabled => TRUE works great. However, form alter is too early of a hook to use on CCK's fields. Moreover, if you disable a field, the browser won't even post the value. This can result in annoying validation issues. So why this post? I found that the most popular post on this topic did not work for me. This post applies to Drupal 6. But relax, there's a Drupal 7 technique.

The correct and safe way to do lock changes to a widget is to mark its HTML elements as read only, not as disabled. To do this, we use the readonly attribute. This ensures that the browser posts the value, unlike disabled. But we can't just stop here. We need to make sure the value isn't changed by a crafty user modifying his post request.

Learning Drupal? Subscribe to my Drupal articles, tips and tutorials.

First, let's hook in to the node form so we can add our #after_build callback. Keep in mind that in this example, we're adding our callback to all node forms. You might want to further limit this to a specific content type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php

/**                                                                           
 * Implements hook_form_alter().                                              
 */                                                                           
function example_form_alter(&$form, &$form_state, $form_id) {                 
  if (isset($form['#node']) && $form_id == $form['#node']->type .'_node_form') {
    $form['#after_build'][] = 'example_after_build';                          
  }                                                                           
}

Let's keep things simple and modify a text widget. For simple widgets, CCK generally uses the key value.

1
2
3
4
5
6
7
8
<?php

function example_after_build($form, &$form_state) {                           
  $field = 'field_example_cck_field';                                         
  $form[$field][0]['value']['#attributes']['readonly'] = 'readonly';          
  $form_state['values'][$field][0]['value'] = $form[$field]['#default_value']['value'];
  return $form;                                                               
}

And that's it! You can now count on your field being readonly. Yet it will still be posted by the browser. And even if a user tries to post a changed value - or uses Firebug to edit the contents of the fields - our build function restores the original value.

Below is the complete code for reference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php

/**                                                                           
 * Implements hook_form_alter().                                              
 */                                                                           
function example_form_alter(&$form, &$form_state, $form_id) {                 
  if (isset($form['#node']) && $form_id == $form['#node']->type .'_node_form') {
    $form['#after_build'][] = 'example_after_build';                          
  }                                                                           
}

function example_after_build($form, &$form_state) {                           
  $field = 'field_example_cck_field';                                         
  $form[$field][0]['value']['#attributes']['readonly'] = 'readonly';          
  $form_state['values'][$field][0]['value'] = $form[$field]['#default_value']['value'];
  return $form;                                                               
}

Comments

AtaAug. 16, 2012, 12:03 p.m.

liked and effective. Its working. Thanks

Reply
OperationsOct. 5, 2012, 6:41 p.m.

Nice & Tricky -- I liked restoring the value !

Reply
IgorJune 12, 2013, 5:33 p.m.

Thanks a lot - google'd it for a while, couldn't find anything. This solved the issue.

Reply
Nick LewisJuly 1, 2013, 11:25 a.m.

This works beautifully for text fields! How about a single Checkbox though? I am guessing that the key "value" doesn't apply to checkboxes?

Reply
silviogutierrezJuly 3, 2013, 1:52 a.m.

Did you try it? it should work. If I recall correctly, individual checkboxes are also stored with a 'value' key.

Reply
HélèneOct. 19, 2013, 7:19 p.m.

I need the field to be open for input at the create node stage but readonly whenever it is open for edit at a later time. Can the form_alter hook be used for when the node is in edit mode?

Reply
silviogutierrezNov. 4, 2013, 4:49 p.m.

It sure can. Just check that $form['#node'] has an nid. If it does, that means you're editing instead of creating. Hope that helps.

Reply
NeilJuly 31, 2014, 7:21 a.m.

I think a easy way.

$form['field_sw_part']['#pre_render'] = array('field_sw_part_readonly');

function field_sw_part_readonly($element) { $element[0]['value']['#attributes'] = array('readonly' => 'readonly', 'class' => 'readonly'); return $element; }

Reply
silviogutierrezJuly 31, 2014, 4:15 p.m.

Neil,

This will not prevent a user from manually editing the POST data and changing the value. It will only make the field readonly in the browser. So data integrity is not guaranteed.

- Silvio

Reply
dfyMay 14, 2019, 10:56 a.m.

nice post. Thanks

Reply
Beatrice R. WashingtonApril 18, 2019, 4:24 a.m.

With the progression of time and lavish way of life, the innovation of web likewise changes like the development of Wi-Fi switch which associates your WIFI versatile with best essays customer service and you can appreciate the web on your portable through switch WIFI framework, right off the bat WIFI switch requires a few settings then you can make the most of your switch arranges on your portable.

Reply
LilMay 17, 2019, 1:57 p.m.

I’m so happy that you found something in Saratov that works for you and thank you so much for sharing your story here with us.

Reply
fggfggfMay 18, 2019, 2:16 p.m.

Le personnel des ventes doit être au courant du processus de vente, c’est-à-dire que, dans le processus de traitement des clients, vous n’enseignez pas un savoir ou que vous n’enseignez pas à vos clients, vous fournissez des services et de l’aide. tag heuer replique C'est aussi résoudre des problèmes et des difficultés pour eux. Ce n'est que lorsque vos clients réalisent que vous le servez, plutôt que d'économiser de l'argent de sa poche, qu'il diminuera sa défense psychologique et vous acceptera beaucoup. Parce que quand vous aidez sincèrement les autres, presque personne ne rejettera votre sincérité.

Reply
DavidJune 9, 2019, 8:28 a.m.

This is a nice and informative post thanks for the information! https://saludpulso.com

Reply
Mark JonesJune 3, 2019, 8:02 a.m.

Using Drupal 6 did not prove useful for solving my problem. Therefore, read spinpalace NZ review for details as I was worried whether Drupal 7 will help me or not but to my lucky nature Drupal 7 has made my CCK fields available only in the read only mode.

Reply
Sumitsingh72June 6, 2019, 7:17 a.m.

Contract the Best Packers and Movers in Hyderabad through Shiftinindia
More info :- packers and movers in Hyderabad packers and movers Hyderabad charges packers and movers Pune to Mumbai

Reply
Sumitsingh72June 6, 2019, 7:17 a.m.

Presently Find Trusted Packers and Movers in Pune through Shiftinindia More info :- packers and movers in Pune packers and movers charges packers and movers Pune Charges

Reply
erickJune 28, 2019, 8:36 p.m.

I think we need just one tool for that as I have found the best solution at the following website https://fr.altomerge.com/faq. It is so much more easier for me as it happens quickly.

Reply
kevinJuly 2, 2019, 8:33 p.m.

Just admiring your work and wondering how you managed this blog so well. It’s so remarkable that I can't afford to not go through this valuable information whenever I surf the internet! http://www.fidelitydating.com/text-chemistry-reviews

Reply
Cheap Jewelry GiftsJuly 4, 2019, 2:29 p.m.

We ensure that each product is strictly inspected, qualified environmental protection, fashionable design, high quality materials, you can have a low price, our products include rings, necklaces, earrings, bracelets. Cheap Jewelry Gifts

Reply
jamesJuly 7, 2019, 7:11 a.m.

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information Agen Bola Terpercaya

Reply
kevinJuly 10, 2019, 2:22 p.m.

That gives off an impression of being brilliant anyway i am still not very beyond any doubt that I like it. At any rate will look significantly more into it and choose by and by! cheap essay

Reply
digitincJuly 14, 2019, 3:55 a.m.

Great Message sharing. I am very happy to read this article. I truly like what you have acquired here, really like what you’re saying and the way in which you say it. You make it enjoyable and you still take care of to keep it sensible. Thanks for sharing. counselling for teenagers in Basingstoke

Reply
Erick NorthmanJuly 15, 2019, 11:32 a.m.

The goal of our online writing company is to provide the best possible academic writing services to students. We always help the learners who come to us for assistance. Our writers understand how to write a unique essay that will be worth every penny that you spend on it. Our essays are famous for getting only A+ grades! However, we understand that, in today's uncertain economic climate, money can be an issue. That is why we have designed a special discount program that shows our appreciation to those customers who return to us to order more papers. We do not want our customers to experience financial difficulties when they do business with us. Therefore, we do everything possible to set reasonable prices.

Reply
Erick NorthmanJuly 15, 2019, 11:36 a.m.

The goal of our online writing company is to provide the best possible academic writing services to students. We always help the learners who come to us for assistance. Our writers understand how to write a unique essay that will be worth every penny that you spend on it. Our essays are famous for getting only A+ grades! However, we understand that, in today's uncertain economic climate, money can be an issue. That is why we have designed a special discount program that shows our appreciation to those customers who return to us to order more papers. We do not want our customers to experience financial difficulties when they do business with us. Therefore, we do everything possible to set reasonable prices. essay for me discount code

Reply
kevinJuly 17, 2019, 11:04 a.m.

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. Brochure designing services Kolkata

Reply
Allergic Reaction To CosmeticsJuly 17, 2019, 2:52 p.m.

Very useful post. I am happy to find this Allergic Reaction To Cosmetics Very useful for me, as it contains a lot of information. I always prefer to read The quality and glad I found this thing in your post. I found so many interesting stuff in your blog especially its discussion. Really its great article.

Reply
sarahJuly 18, 2019, 4:44 p.m.

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks شركة نقل اثاث

Reply
sunset beach rentalsJuly 19, 2019, 4:29 a.m.

This is certainly also a very good post that any of us completely beloved looking at. I must say and thanks for the information. I think this is an educational post and it is very beneficial and knowledgeable. Thank you for sharing. sunset beach rentals

Reply
paulJuly 20, 2019, 11:28 a.m.

This is a fantastic website and I can not recommend you guys enough. I really appreciate your post. It is very helpful for all the people on the web. i will seo lyrics

Reply
Bigg Boss 13July 21, 2019, 1:59 p.m.

Very valuable post. I am happy to find this post Very Bigg Boss 13 for me, as it contains a lot of information. I always prefer to read The state and glad I found this thing in your post. Really its great article.

Reply
kevinJuly 22, 2019, 10:07 a.m.

Thanks so much with this fantastic new web site. I’m very fired up to show it to anyone. It makes me so satisfied your vast understanding and wisdom have a new channel for trying into the world. Cheap Jewelry Gifts

Reply
kevinJuly 22, 2019, 5:02 p.m.

Just admiring your work and wondering how you managed this blog so well. It’s so remarkable that I can't afford to not go through this valuable information whenever I surf the internet! บาคาร่า

Reply
Underwater hull cleaning SydneyJuly 24, 2019, 3:38 a.m.

Articles that are very good and interesting. You will find a lot of propositions after visiting your post. Underwater hull cleaning Sydney I propose very appreciatively that I read this. It is very helpful and very informative and I really learned a lot from it.

Reply
Jason RoyJuly 26, 2019, 12:49 p.m.

To required Custom Cigarette Packaging by quickboxespackaging.com is the best option after the best quality boxes for your products. I am in love to have such a great amazing informative article. Good Luck!

Reply
johnJuly 27, 2019, 2:15 p.m.

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks Download Latest Mp3 Song

Reply
how to list your house on mlsJuly 28, 2019, 1:24 p.m.

I think this is an informative post and it is very how to list your house on mls profitable and knowledgeable. The information here will surely be of some help to me. I just jumped upon your blog and wanted to say that I have really enjoyed reading your blog stations. Thanks for sharing.

Reply
johnJuly 29, 2019, 4:54 p.m.

This is a fantastic website and I can not recommend you guys enough. I really appreciate your post. It is very helpful for all the people on the web. poker indonesia

Reply
Watch Divya Drishti OnlineJuly 29, 2019, 10:43 p.m.

Aw, this was a very nice post. Taking the time and actual effort to produce a superb article… but what can I say… I procrastinate a whole lot and never manage to get anything done. Watch Divya Drishti Online

Reply
kevinAug. 1, 2019, 1:47 p.m.

That's what makes you the best. You should keep publishing more articles and you will Such Become One of the best writers ever Dentist Newcastle

Reply
johnAug. 2, 2019, 12:39 p.m.

That's what makes you the best. You should keep publishing more articles and you will Such Become One of the best writers ever Model Paper 2020

Reply
Yoga vacationsAug. 3, 2019, 8:32 a.m.

Thanks for sharing valuable knowledge with all of us, I feel completely Yoga vacations that love and read more on this topic. Looking to reading your next post.

Reply
liamAug. 5, 2019, 11:18 a.m.

I enjoy every single posts, I actually appreciated, I would personally adore extra information and facts because of this, mainly because its fairly pleasing., Have fun here ideal for allowing. 먹튀

Reply
paulAug. 5, 2019, 2:03 p.m.

A high speed broadband internet service at home is a must for today’s requirement, where the cheapest and unlimited data offers that you can hook up your Smart TV or game console to one, but there are so many different ISP’s out there and not to mention the myriad of plans they have on offer, we’ve gone through all of them and presenting the most popular BSNL Broadband Plans sorted that you should consider to opt.

Reply
g1thin clientAug. 5, 2019, 11:54 p.m.

it's a great article.Thank you . find Quality and High Performance G1 thin clients & Mini pcs for Low Price g1thinclient

Reply
Anna BoykoAug. 9, 2019, 12:10 p.m.

https://www.romexsoft.com/aws-managed-services/ https://www.romexsoft.com/aws-cloud-migration/

Reply
frankAug. 6, 2019, 3:09 p.m.

To say the truth I am very impressed by what you told. You share tons of interesting info, neat and excellent design you’ve got here. It’s certainly one of the most informative stuff on this topic I’ve ever read. dedicated development team

Reply
liamAug. 6, 2019, 6:46 p.m.

FindOrg is a chrome extension that empowers Recruiters, Sales professionals and BD teams to find email address and phone numbers for FREE. No strings attached! And its free for life. find email

Reply
meerabAug. 7, 2019, 10:26 a.m.

That gives off an impression of being brilliant anyway i am still not very beyond any doubt that I like it. At any rate will look significantly more into it and choose by and by! russia.marketingtochina

Reply
jamesAug. 7, 2019, 10:52 a.m.

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. marketingtochina

Reply
Nikki HopeAug. 7, 2019, 8:04 p.m.

Hey, Your blog is very informative. It is nice to read such high-quality content. Attractive information on your blog, thank you for taking the time and share with us. This article delivers high-quality content related to Custom Candle Boxes

Reply
Anna BoykoAug. 9, 2019, 12:09 p.m.

Nice to be visiting your blog. I hope you are also interested in cloud technology. For example, with services such as : [url]https://www.romexsoft.com/aws-cloud-migration/[/url], [url]https://www.romexsoft.com/aws-managed-services/[/url]

Reply
William BryantAug. 11, 2019, 1:25 p.m.

I like to watch football on television with friends in our little bar. It's fun, it's a way to break the ice, to go out in clubs, or go to a restaurant. And that's why we have our team. That's why it was important to talk about the club." waalwijk venlo

Reply
Anna BoykoAug. 12, 2019, 8:06 a.m.

To say the truth I am very impressed by what you told. You share tons of interesting info, neat and excellent design you’ve got here. dedicated development team /a>

Reply
Kevin AdamsAug. 13, 2019, 2:35 p.m.

Do anyone know where I can find help with a dissertation hypothesis online? I'm looking for academic freelance writer, who can help me to get perfect results for my assignment.

Reply
Ariella CezartAug. 14, 2019, 11:32 a.m.

From my perspective, it’s certainly one of the most informative stuff on this topic I’ve ever read. Thanks for your post! offshore software development services

Reply
andreAug. 15, 2019, 8:16 a.m.

is very helpful for all the people on the web thanks about this posting, good script work to meidn poker & jasabola

Reply
Mike RooneyAug. 17, 2019, 10:26 a.m.

with a fluent speaker websites and flash walls are often wrong. If you wanted something a little larger you could each have a pair of hands holding each other, to symbolise your. Movies Jackets

Reply
AanhangerAug. 20, 2019, 6:20 a.m.

Een aanhangwagen of aanhanger is een wagen die achter een voertuig kan worden gekoppeld aan de trekhaak. Voor kleine aanhangers van minder dan 750 kg inclusief laadvermogen heeft de bestuurder van de auto geen apart rijbewijs nodig. Voor ieder soort vervoer is er een speciale aanhanger beschikbaar. ( Bron wikipedia ) Steigercentrum levert steigeraanhangers voor het vervoer van steigers. Aanhanger

Reply
David MillarAug. 22, 2019, 5:24 a.m.

Place you can do that is After you ping make sure to bookmark the final page you get which. your blog. Then, when you write a new post visit that link and it will repost your. Quantum Realm Jacket

Reply
jakdownAug. 22, 2019, 6:05 p.m.

Thanks so much with this fantastic new web site. I’m very fired up to show it to anyone. It makes me so satisfied your vast understanding and wisdom have a new channel for trying into the world. leaflet distribution

Reply

Post New Comment