Custom symfony2 form - symfony-forms

I have three entities, fos_user, command and preference. The user can send himself an email containing a specific field from each entity, these fields can't be empty. So when the user decides to send the mail, he should update/fill these fields through a form before sending the email. The new values will only be sent through the email and won't be saved into the database.
How do I build this form with needed validators?
Thanks in advance,

Found the anwser :), I'm working on something like this:
$o = new \stdClass();
$o->name = null;
$o->command_name = null;
$o->like_it = null;
$form = $this->createFormBuilder....
We can even use a table instead of stdClass object.

Related

Apereo CAS 6.0.x Pass the login form field to the resolved attributes

I need to add a field to the CAS 6.0.X login screen (language selector) that is not used to authenticate users but I need it after logging in.
How can I do to pass this field added to the form to the data that is passed to the client application in the "principal" object.
In the end I have achieved what I needed. We have overwritten the jdbc support module to add checks and there I have put the following code that helps me to retrieve parameters of the request.
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes()).getRequest();
String[] fields = fieldsToPrincipal.split(",");
for(String field : fields2Principal)
{
dbFields.put( field.trim() , request.getParameter( field.trim() ) );
}
fieldsToPrincipal It is a string of form field names that I want to send the applications through the "principal" map attributes.
Now in the properties files I have 2 properties in which I report the names of the fields. The default property that tells you which fields will be retrieved for the principal and my custom property where I indicate which fields will come from the form
cas.authn.jdbc.query[0].principalAttributeList:USERID, USERNAME, LANGUAGE_SELECTED
cas.custom.properties.jdbc.loginfields.to.principal=LANGUAGE_SELECTED

How to simulate a Zend\Form submit without to display the form in Zend Framework 2/3?

I have a complex nested (order) Zend\Form, that can be edited multiple times. Now I want to get the data and pass it later to a new form. (This way I want to implement a simple cloning mechanism.)
What already works is transforming the request data to JSON
if ($request->isPost()) {
...
if(isset($request->getPost()->toArray()['store'])) {
$this->storeFormJson(json_encode($request->getPost()));
}
...
}
...
and passing it to an empty form:
if ($this->params()->fromQuery('populate')) {
$formDataJson = $this->getFormDataJson();
$formDataArray = json_decode($formDataJson, true);
$parameters = new Parameters($formDataArray);
$request->setPost($parameters);
$request->setMethod(Request::METHOD_POST);
}
Alright. But it requires, that the user needs to call the edit form first, edit it (if needed), and send the data to the server (by submitting the form). Since the goal is to create clones on the fly, I need a way to simulate these steps.
How to get the data, that usually comes passed via form submitting, without a real submitting?
One thought is to create a new form F2 in which the fields are all hidden, populate F2 with values from your populated form F1, deliver the rendered F2 form to the client, and add client-side javascript that auto-submits the now-populated F2 form on page load. Just thinking out loud...

PetaPoco complex types posting to controller

As per a question that I asked yesterday I was trying to find a way to dynamically create more text boxes and have those map to my view's model so upon post to the server it will grab all the dynamically(js) generated text boxes and post that to an object such as a List.
To give an example of this confusing question:
I have a textbox that is labeled "Primary Contact" and the ticket creator can enter the contacts name and phone number into this box. What I want to do essentially is, switch this to three text boxes. One for Name, Email and PhoneNumber instead of one box. Then I will create some javascript that will dynamically create three more boxes to add another contact to this List collection. Then when the user submits the form to modify or create the ticket it passes this collection inside the model to the controller. However with petapoco it is a little confusing. Let me show you the controller:
[HttpPost]
public ActionResult ModifyTicket(Ticket model)
{
string userString = User.Identity.Name.Replace("ONHOLD\\", "");
if (ModelState.IsValid)
{
model.CreatedDate = DateTime.Now;
model.LastUpdateBy = Util.GetEmployeeIdByName(userString);
model.LastUpdate = DateTime.Now;
model.IsComplete = false;
model.ClientString = Util.GetClientNameById(model.ClientId);
model.LocationString = Util.GetLocationNameById(model.LocationId);
model.Update();
SuccessMessage = "You have successfully updated ticket number: " + model.TicketId + " for the following client: " + model.ClientString + ".";
return RedirectToAction("Index");
}
ErrorMessage = "Woops! Something went wrong, please check back in a few moments, if the problem persists please contact development.";
return RedirectToAction("Index");
}
The simple answer to this would be that my database model would contain a List object for this exact reason. However, I am using PetaPoco and I'm not entirely sure how it would be done. I could manually add in a collection to my Database model but when I regenerate my model based on any database schema changes I will lose any changes I've made to the file.
I am also using a partial class that my view uses for validation using DataAnnotations. However this class is identical to the database model it just contains DataAnnotations to provide client-side validation.
If anyone understands what I'm trying to accomplish I would be more than happyto provide more information to clarify any missing pieces. I just need a resolution to this as I can't find a solid way to go about resolving this issue!
Not entirely sure what you mean but it's easy to model bind from/to a list with MVC as you may already know. As for saving a deep object like this I'd use the [Ignore] attribute on the Ticket.List so it isn't persisted and handle it separately. I'd load the Contacts in separately from the Ticket object then manually add them to the Ticket object, alternatively use a join query and try the one-to-many approach to load it all in one go.
I think you're expecting Petapoco to update all in one? This won't happen you'll need to break it up. Hard to say from what you've written so far. There won't be a long list of contacts (from the sounds of it) so just insert or update them one by one.
Well that might help, or might not.

How to clear the post data for a textbox in an ASP.NET MVC application?

By default, a textbox rendered using <%= Html.TextBox("somefield")%> uses the value from the post data, e.g. if you have validation errors on your page, the value is retrieved from the posted data and used for the value attribute.
Now, in a few cases I want to be able to clear that value, in other words I want the textbox to be blank, I don't want MVC to get the value from the posted data and uses it for the value attribute, how can I do? How can I clear the post data?
Thanks
ModelState.Remove("key");
Remove the value from the model state, like this:
ViewData.ModelState.Remove("somefield");
I found I had to both remove the ModelState and change the model, as if MVC tries ModelState first, then the model:
ModelState.Remove("key");
model.key = "";
And if you don't want to lose your Error state for the model, you can just change the value like this:
ModelState.SetModelValue("Captcha", new ValueProviderResult(null, string.Empty, System.Globalization.CultureInfo.InvariantCulture));
model.key = "";

asp.net mvc - obtain values from a bunch of inputs selectively

I have a bunch of text inputs on my page (HTML.TEXTBOX, generated through for loop), and I want to read their values and commit to database only when user has modified something in those textboxes.
What would be a proper way to do that? (Do you think it may make more sense to commit the entire thing to database if number of textboxes is less than 100?)
Also, in general, how would I read values from a bunch on textboxes and commit to the database? I would need something that uses a key-value pair, where key would be the id and value would be that input in the textbox.
Unless you use for example JavaScript and hidden fields to keep track of user changes, there is no way for you to know which fields have been modified without querying the database, since the web in general, and ASP.NET MVC in particular, is stateless. However, if you loop out the fields with their values filled in with data stored in an object, you can probably save that object in a session variable to compare against on the next request.
Pseudo-example:
public ActionResult GetFormView()
{
var values = (select relevant information from db and store in a
IQueryable<Dictionary<string, string>> or something similar
where you have a relation between input field id/name and value);
Session["TheInputListValues"] = values;
return View(values); // Your view renders your list of input fields
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveChanges(FormCollection form)
{
var oldValues = (Dictionary<string, string>)Session["TheInputListValues"];
var changedValues = new Dictionary<string, string>();
foreach(string key in form.AllKeys)
{
if(oldValues.ContainsKey(key))
{
if (oldValues[key] != form[key])
{
changedValues(key, form[key]);
}
}
}
SaveToDB(changedValues);
return Redirect("SomeWhereElse"); // PRG is king!
}
I haven't tested this implementation, but it's worth a try =)
I have done something similar using jQuery and it works pretty well. Attach a behavior to the textboxes where if the data changes then submit it's value to an action that saves the data.
$(function(){
$("input[type='text']").change(function(){
$.post("/SaveChanges",{id: $(this).attr("id"),value : $(this).attr("text")});
});
});
This would be assuming you had ID's that were some sort of unique key to you record on each input.
<input id="4576" name="4576"/>
you could also have a callback that would say add a class to this field letting them know that the information was saved by changing it to green or something.
Check this out for more details:
http://docs.jquery.com/Ajax/jQuery.post

Resources