Pergunta

I would like a user in my web application to make a post. The post will contain his username to indicate he posted it. How would I do this?

UPDATE!

This my working code

Please see my code below:

        def createlisting = isAuthenticated { username => implicit request =>
          Ok(html.createlisting(listingsForm))
        }

        def postlisting = withUser {user => implicit request => {
          listingsForm.bindFromRequest.fold(
            formWithErrors => BadRequest(html.createlisting(formWithErrors)),
            listing => {
              val username = val username = User.getUserName(user)
              Listings.create(listing.categorytype, listing.title, listing.description, username)
              Redirect(routes.Application.active).flashing("success" -> "Listing %s has been posted".format(listing.title))
              }
            )
            }
          }

        val listingsForm = Form(
          mapping(
            "_id" ->  ignored(new ObjectId()),
            "categorytype" -> mapping(
              "category" -> nonEmptyText,
              "subcategory" -> nonEmptyText)(Type.apply)(Type.unapply),
            "title" -> nonEmptyText,
            "description" -> nonEmptyText,
            "username" -> igrnored(String)
          )(Listings.apply)(Listings.unapply)
        )

scala.html

                @(createForm: Form[Listings])

                @import helper._

                @implicitFieldConstructor = @{ FieldConstructor(twitterBootstrapInput.f) } 

                    <h1>Add a Listing</h1>

                    @form(routes.Application.postlisting()) {

                        <fieldset>
                            @inputText(createForm("categorytype.category"), '_label -> "Main Category")
                            @inputText(createForm("categorytype.subcategory"), '_label -> "Sub Category")
                            @inputText(createForm("title"), '_label -> "Title")
                            @inputText(createForm("description"), '_label -> "Description")

                        </fieldset>

                        <div class="actions">
                            <input type="submit" value="Post Add" class="btn primary" href="/"> or 
                            <a href="/" class="btn primary">Cancel</a> 
                        </div>

                    }

What can I do to have the username automatically passed to the postlistings function and save in my database?

Foi útil?

Solução

If the username is in the session (as would appear from the use of withUser in the other function), you have nothing to do, it will be passed automatically with each request.

What you do need to do is recover it, though. It would appear that you can just wrap your Action in another call to withUser and that would just work.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top