Using Control Adapter to Set Default Values for Publishing Pages

February 24 2010 91 comments

Developers, who use customized page layouts bound with custom content type, have probably realized that if your custom content type is not the default content type of Pages library, you will not get default values populated when you create a new page. One way to work around this is to create feature, which sets your customized content type to be the default (1st content type) in Pages library. However, it does not work for the rest of the page layouts in that same library.

Here is another workaround to consider. Create a control adapter, which will populate default values to any of the publishing page in Pages library.

public class BaseFieldControlAdapter : ControlAdapter
{
 protected override void OnLoad(EventArgs e)
 {
  var bfc = Control as BaseFieldControl;
  var context = SPContext.Current;
           
  if (bfc != null && context != null)
  {
  var item = context.ListItem;

  if (item != null)
  {
   if (bfc.Field != null && !Page.IsPostBack)
    {
     var defaultValue = bfc.Field.DefaultValueTyped;

     if (defaultValue != null)
     {
      if (bfc.ItemFieldValue == null)
       bfc.ItemFieldValue = defaultValue;
      if (bfc.Value == null)
       bfc.Value = defaultValue;                                    
     }
    }
   }
  }
  base.OnLoad(e);
 }
}

When using adapter you need to create .browser file for the web application’s App_Browsers directory

<?xml version="1.0" encoding="utf-8" ?>
<browsers>
 <browser refID="Default">
  <controlAdapters>
   <adapter controlType="Microsoft.SharePoint.WebControls.BaseFieldControl"
   adapterType="..BaseFieldControlAdapter, ..., Ver..., Cul..., Pub..." />
   </controlAdapters>
  </browser>
</browsers>

As a bonus, if you override Render method, you can use it to mark Required field on the page in edit mode by changeing the css class of that control and then customize it as you wish.

protected override void Render(HtmlTextWriter writer)
{
 var bfc = Control as BaseFieldControl;

 if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit ||
     bfc == null || bfc.Field == null || !bfc.Field.Required)
 {
  base.Render(writer);
  return;
 }

 using (var sw = new StringWriter())
  {
   using (var tw = new HtmlTextWriter(sw))
   {
    base.Render(tw);
   }

   sw.GetStringBuilder()
   .Replace("ms-formfieldcontainer", "ms-formfieldcontainer req");
   writer.Write(sw.ToString());
  }
}

Snippets above demonstrate just how to use control adapter to do this. You still need to check if current page is in edit mode and that it’s a new page (otherwise it will always display the default values, not the saved ones).

***********************************************
Jerry Seinfeld: Why not? We’re neighbors. What’s mine is yours.
Cosmo Kramer: [leaning against the door-frame and looking around in wonder] Really?
***********************************************

Popularity: 10% [?]

91 comments to “Using Control Adapter to Set Default Values for Publishing Pages”

  1. [...] While ago I posted something very similar to this. Here [...]

  2. Alhis says:

    Dude, you have a bug in the adapter. The condition should be
    if (SPContext.Current.FormContext.FormMode != SPControlMode.Edit ||
    bfc == null || bfc.Field == null || !bfc.Field.Required)

  3. Tomi says:

    Alhis, you got that right.
    I will update the code.
    Thanks for collaboration.

  4. I’ve been exploring for a little bit for any high quality articles or weblog posts on this sort of area . Exploring in Yahoo I ultimately stumbled upon this site. Studying this info So i’m happy to
    convey that I have an incredibly excellent uncanny feeling I
    found out just what I needed. I most for sure will make certain to
    don?t disregard this web site and give it a look on a constant basis.

    Feel free to surf to my website; turbo jam exercise video

  5. Porter says:

    This is the right blog for everyone who wishes to understand this
    topic. You understand a whole lot its almost tough to argue
    with you (not that I really will need to…HaHa).
    You certainly put a brand new spin on a topic that has
    been discussed for many years. Great stuff,
    just excellent!

  6. Hi to every one, it’s in fact a nice for me to go to see this web site, it includes helpful Information.

  7. Why visitors still use to read news papers
    when in this technological world the whole
    thing is presented on web?

  8. I am really loving the theme/design of your weblog.
    Do you ever run into any web browser compatibility problems?
    A small number of my blog readers have complained about
    my website not operating correctly in Explorer but looks great
    in Safari. Do you have any tips to help fix this problem?

  9. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your weblog?

    My website is in the very same niche as yours and my visitors would certainly benefit from some of the information you provide here.
    Please let me know if this alright with you.
    Thanks!

  10. Thanks for sharing your thoughts. I truly appreciate your efforts and I will be waiting for your further post
    thank you once again.

  11. Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having
    difficulty finding one? Thanks a lot!

  12. Hello, I think your site might be having browser compatibility issues.

    When I look at your blog site in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, superb blog!

  13. You need to also give a attempt to our Boom Beach hack and cheat tool
    for unlimited game sources!

  14. I believe what you published was actually very reasonable.
    However, what about this? what if you added a little content?

    I am not saying your content is not good, however suppose you added something to possibly get people’s attention? I mean Using Control Adapter to Set
    Default Values for Publishing Pages | SharePoint Blues is
    a little vanilla. You could glance at Yahoo’s home page and note how
    they write news headlines to grab viewers to open the links.
    You might try adding a video or a related pic or two
    to grab readers interested about what you’ve written. Just my opinion, it
    could bring your posts a little bit more interesting.

  15. They are going to find that one of the best was to find these cute love quotes is to utilise the Net.

    mom and that will be doing a lot of wiping on those cute bottoms
    all day. “If only one could tell true love from false love as one can tell mushrooms from toadstools. i20 is pretty fuel efficient with a fuel economy of 18. The game centers around the collection of different colored cards, each with a very cute chameleon on it.

    my homepage cute and easy hairstyles for kids

  16. Hey! Do you know if they make any plugins to
    help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good results. If you know of any please share.
    Many thanks!

  17. I do not even know how I ended up here, but I thought this post was good.

    I don’t know who you are but definitely you are
    going to a famous blogger if you aren’t already ;) Cheers!

  18. Pasos que vosotros mismos haréis en clase con todos los
    materiales que os proporcionamos a fin de que trabajéis.

  19. Leonardo says:

    Are you searching for a way to keep your carpet looking newer and lasting longer.
    You must now be capable of decide what the differences
    are between letting it sit there and never letting it.
    Bissell has several scented product if you prefer different scents
    on your cleaned carpeting.

  20. Thanks for this website, can happily declare we now have a steam shower of our own and we love it

    Take a look at my webpage; Steam Shower kit

  21. you are really a good webmaster. The web site loading velocity
    is amazing. It sort of feels that you’re doing any distinctive
    trick. Also, The contents are masterpiece. you’ve performed a excellent activity
    on this matter!

  22. Wow, this piece of writing is fastidious, mу sister is analyzing thesе things, thus I aam ɡoing to
    convey her.

  23. State and Federal laws prohibit certain ways of spying on a cheating mate.
    The Guardian revealed that the NSA extracts data including
    location, contact networks and credit card details from the text messages that it collects.
    Our i – Phone Spy App has already been helping people with name Copy9.

  24. Learning about the music that they can come tomorrow?
    In the first game in the event. Hence, Farm heroes saga cheats (https://www.multipassid.com/Activity-Feed/My-Profile/UserId/655) if implemented properly.

    The video gaming is really a basic idea of video and audio engineers.

    Do you think that’s suitable, how did the experiments in a world typically reserved for the hands
    of evildoers though I don’t see that idea through
    to play the instrument itself. Establish a system of rating games for other systems.
    Walt Disney was told he would never be more skilled.

  25. I was wondering if you ever thought of changing the structure of
    your site? Its very well written; I love what
    youve got to say. But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or
    two pictures. Maybe you could space it out better?

  26. As well as, social media marketing is NOT broadcast media.

  27. You ought to take part in a contest for one of the best websites on the
    net. I am going to highly recommend this web site!

  28. seks sohebt says:

    Haluaa mennä syvemmälle omissa fantasioissaan, taai
    kokeilla jotain täysin uutta villiä. Flirttaile siis villisti ϳa sovi heti tärskyt unekmiesi kumppanin kanssa.
    Aloita mukavat hetket livechat toiminnolla muiden kanssa jutellen.

    Мy website … seks sohebt

  29. My brother recommended I might like this web site.
    He was once totally right. This publish truly made my day.
    You can not imagine just how so much time I had spent for this information! Thanks!

  30. Rinse the garment under running water for three to five minutes, thoroughly flushing the dye out of the fabric.
    Lastly, there are Thin-to-Thick, Damage-Control and Dandruff
    products. It is advisable to consult with hair experts as they can give you the best
    advice for choosing the colour that brings out best in you according to
    Jacqueline Fernandez, Dimple Kapadia. If the bride to be has naturally curly hair,
    this can be enhanced with mousse, a finger diffuser and a
    curling iron to create ringlets or spirals.

    Modern solutions will enable you have the look that you require.

  31. Another advantage games have over reality is the safety issue.
    Online play is welcoming yet very challenging and the career mode will probably infuriate and cause enjoyment.
    The practice mode allows you to race you’d
    like it is possible to minus the pressure from the other opponents.
    The XBox 360 Wireless Racing Wheel is made employing a comfortable grip along with a sleek design helping to make
    your gambling racing experience seem very real.
    When selecting a car, don’t just look in the maximum speed.
    Umbrella weapons: Nothing frustrates more than bumping into blocks during gameplay, especially in racing games.
    Just Shut Up & Drive – the name says all this
    within this hectic driving game. ‘It’s sort of running the gamut for customization,’ said Hong.
    He won the Epsom Derby and Irish Derby, both races being approximately a mile plus a
    half. They often license real cars or racing leagues, and can sometimes
    use fantasy cars created to resemble real ones or even able to acquire the state license
    for them. Whether you or your child as a stock car race or are curious about
    more games in Indy car racing, there is something for everyone.
    The difference between racing games and fighting games, and
    why the first kind is often a better option, is always that kart games is often a lot easier for the complete novice to grab.
    They mostly provide free flash games with smaller sizes
    so you are able to download them after which have them and never having to worry that they’ll occupy the space within your memory space.

    But the challenges are distinct during these video gaming racing boats:
    you will discover no lousy or trying to shoot cops rather in the wind is unpredictable, which
    includes struggled to accomplish regulate from your
    boat. Read the full length writeup on Need for
    Speed Prostreet, for more thorough information. Wireless steering wheels are
    available also for many consoles, so you are able to sit and play online car racing games, devoid of the hassles of getting wires all tangled up.

    This racing game will amaze you through graphics, sounds and all sorts of the opposite how-to’s you will see here.
    Project CARS can also be works with upcoming virtual reality
    tech. The wheel is quite responsive so perhaps the slightest turn could
    make the kart steer within the intended direction. Variety could be the spice
    of life, and also this sit does not disappoint.

    Although the game initially had its fair share of problems, after nearly 24 months of modding community slaving, Grand Prix 4 did start to show
    great gains. Moto Racer – The graphics of Moto Racer is probably not
    up to the mark for several hard-core gamers since there are a number of other video games with better graphics.

    Use in-game currency to get and install upgrades for the ride whether
    these are performance enhancing or perhaps aesthetic.
    ” The next person should come up with a word for B, by way of example, “B for Bananas,” whilst the next might say, “C for cantaloupe.
    The racing games supply you with variety like no other game.

  32. This will be more likely to help you in the business, this will be the easiest way
    clash of lords 2 cheats to encourage activities, the Strogg were dealt a deadly
    mistake. The game’s publisher, however, Atari can not sit
    still at school by going to a great moment of pride
    when you use them. This is comparable to these types of
    video games or computer. Practical Ways to Limit Your Child’s Physical FitnessWhen selecting a Wii or Kinect, be sure to keep in mind, hopefully, open a file folder.

    My web-site clash of lords 2 cheat mac

  33. Admiring the hard work you put into your website and detailed information you present.

    It’s good to come across a blog every once in a while
    that isn’t the same outdated rehashed material. Great read!
    I’ve saved your site and I’m including your RSS feeds to my Google account.

  34. Superb post from expert. Thank you very much for writing this useful info for all of us.

  35. Asking questions are really nice thing if you are not understanding
    something fully, except this piece of writing gives good understanding even.

  36. “Dungeons & Dragons” has a number of worlds unique to its brand,
    while the old TSR game “Star Frontiers” imagined a part of the galaxy with
    several alien species and planets that were in an alliance with humans.
    This is done and conducted in a successful, fast and easy manner.
    , the US generic drugs market hhas witnessed a significant surge during the
    past few years. Complete range of products is distributed to meet the
    demands of public by restoring the disorders caused in them.
    However, the generic drugs lkok diffrrent from their brand names.
    hardrives go from 120 GB to 320 GB of RAM is 2 GB annd 4 GB.

    Feel free to surf to myy web site: water ionizer

  37. porn says:

    I have read several just right stuff here. Certainly worth bookmarking for revisiting.
    I surprise how much attempt you place to create one of these great
    informative web site.

  38. juresta says:

    Wij zijn 3 jaar klant geweest bij Juresta Nederland
    bv. Wij hebben veel klachten over Juresta, ze werpen veel hindernissen op als ze
    moeten incasseren. Juresta kwam meestal bij ons zeuren dat het een niet haalbare incasso was en dat wij Juresta moesten betalen. Als we
    dan toch wilden doorzetten lieten ze de incasso zaak versloffen. Een ander probleem was dat Juresta wil
    dat voordat ze iets aan hun klant uitkeren dat die klant
    allemaal fax formulieren verstuurt. En ze lieten het ons niet weten als
    er geld op de rekening bij Juresta binnenkwam. Wij adviseren iedereen een ander incassobureau te zoeken, wij zijn nu bij
    een ander bureau zeer tevreden.

  39. Nice post. I was checking constantly this blog and I’m impressed!

    Very helpful information specifically thee last part :
    ) I care for such info a lot. I was seeking this certain information for a very
    long time. Thank yyou and good luck.

    Feel free to visit my wweb blog: Taekwondo best steroids

  40. Good article! We are linking to this great content on our
    website. Keep up the great writing.

  41. This article offers clear idea designed for the new users
    of blogging, that really how to do blogging and site-building.

  42. hotel murah says:

    I do not even know the way I ended up right here, but I assumed this submit
    used to be great. I do not realize who you might be however certainly you are going to a famous blogger in case
    you aren’t already. Cheers!

  43. By character, I mean the height, size, texture, pallettes, etc.
    It can provide your garden a soft ambiance as effectively
    as give added illumination to get more secure paths and stairways.
    If the one thing that you can visualize that will be a
    bother include the mosquitoes, consider blanketing your yard with citronella candles.

    Large weeds have deeper roots and therefore are more difficult to remove.
    Another method to invite wildlife for your backyard is actually by installing a garden pond or pond and waterfall.

  44. Evangeline says:

    Sulfur is an important vitamin used for several procedures in your body.

    It can help preserve bones, hair, skin and fingernails plus enhanced mutual freedom, reduces reduces and stiffness swelling and Pain. Under you’ll see the different tinctures from Surthrival and Arts.

    The distinction it the price point.

  45. Get this Conflict Of Lords Crack for totally free nowadays!

  46. Liebe.,Abercrombie MilanoIch zu den Sy erklären, halb im Scherz, zu erklären, ihr in den Raum veröffentlicht, darüber zu sprechen “, ich weiß,http://wwwtruereligion-salescom, aber immer noch sehr verwirrt”, ist nicht impliziert, dass akzeptiert mein Geständnis zu ihr, aber nicht wissen, wie es zu tun. Ich denke schon! Ich weiß, ich habe nicht genug Kapazitäten, sie zu lieben, sie zu verletzen, aber ich werde hart arbeiten, ich,Ed Hardy Shop, um einen Punkt auf zwei Tage machen wollen, um Wubi lernen,Ray-Ban Sunglasses RB3332 006/9A 64mm Frame Black, um nicht später als 12.00 Uhr zu schlafen jeden Tag,ralph lauren Mujer El dinero o no, la reunión de Año Nuevo Chino, jeden Tag sieben aufstehen, nicht mehr Vermieter nicht mehr spielen Mahjong, wird nie das Richtige zu verzögern! In diesem Jahr, um ein großes Ziel gesetzt, ein Ziel, jeden Monat,Ed Hardy Outlet Die Liebe ist eine Lampe, ist die, jede Woche, jeden Tag, Tanken

  47. I ことができませんでした |コメントご遠慮レジスト。 非常によく書かれました!
    メール便送料無料 2015年秋冬新作 http://www.toomuch.fr/tide-24966-173.html

  48. 紛れもなく あなたがすることを考えています。お気に入りの正当化 | ウェブインターネット 最も簡単を意識する事で、であるように思われたがようでした。人々は考えるながら| イライライライラする | いないについて知っている、彼らはただはっきりことを心配取得|私は確かに間違いなく、あなたに言います。 信号を取る人々は、あなたがトップ時に釘を打つことをどうにかとせずに全部外に定義副作用副作用が。 おそらくになります多くを得るために戻って。感謝
    輸入元価格より35%off 即日出荷 http://www.twhost.com.br/tide-24630-193.html

  49. 実際には非常に興味深い、これがある|非常に熟練したブロガーあなたがしているあなたにしています。 私が持っている と素晴らしいのより求めることを楽しみにしてあなたに参加したポストを。また、私がしました私のソーシャルネットワークでサイトあなたを共有しました!
    即日出荷 本物保証 激安販売 http://jodla.pl/tide-25315-174.html

  50. 印象的な|巨大|この偉大を共有している人このの |素晴らしい|素晴らしい} 記事 {ここで、|この場所で。
    メール便送料無料 高品質5☆大好評 http://www.yasinborekoglu.com/tide-25041-163.html

Leave a Reply