A User Generated Rsc in Zotonic
For the purpose of this example, I have gone crazy and decided to allow people to anonymously post articles to my blog.
Well, not really!
I have written Zotonic modules already which have used their own database schema, but for a lot of things I am planning to do it would be better to be able to create and modify actual Zotonic resources. For example, on a site where users generate content themselves, or can change their own profile details I would prefer not to show them the standard Zotonic admin.
For this example, I have modified mod_hello from my last post . Here is the event function, which goes in mod_hello.erl
%% @doc Handle the submit event of hello
event({submit, {newarticle, _}, _TriggerId, _TargetId}, Context) ->
Title = z_context:get_q_validated("title", Context),
Summary = z_context:get_q_validated("summary", Context),
Body = z_context:get_q_validated("body", Context),
CategoryId = m_category:name_to_id_check(article, Context),
Props = [
{body, Body},
{category_id, CategoryId},
{title, Title},
{summary, Summary},
{is_published, true}],
AdminContext = z_acl:sudo(Context),
{ok, RscId} = m_rsc:insert(Props, AdminContext),
Context1 = z_render:update("hello-text", "Created article " ++
integer_to_list(RscId) ++ " entitled ~ " ++ Title, Context),
Context1.
And a new template that can be saved in the file _hello.tpl.
<h2>{_ Hello 2 _}</h2>
<div id="hello-text">Hello World</div>
{% wire id="hello-form" type="submit" postback={newarticle id=id}
delegate="mod_hello" %}
<form id="hello-form" method="post" action="postback">
<div>
<div class="form-item">
<label for="title">Title</label>
<input type="text" name="title" id="title" />
{% validate id="title" type={presence} %}
</div>
<div class="form-item">
<label for="summary">Summary</label>
<input type="text" name="summary" id="summary" />
{% validate id="summary" type={presence} %} </div>
<div class="form-item">
<label for="body">{_ Body _}</label>
<textarea name="body" id="body" cols="60" rows="8"></textarea>
{% validate id="body" type={presence} %}
</div>
<div class="form-item button-wrapper">
<button type="submit">{_ Post _}</button>
</div>
</div>
</form>
So in the code above allows a user to post an article, which under normal circumstances would have failed because the user did not have permission. But thanks to sudo:
AdminContext = z_acl:sudo(Context),
{ok, RscId} = m_rsc:insert(Props, AdminContext),
which will be a familiar concept to Linux users, we have posted the article regardless.
Comments