Laravel eloquent has_many_and_belongs_to sync() without writing to database - forms

In short, does Laravel's eloquent have something like it's sync() functionality that doesn't save the relationships to the database right away?
I have two models
Place (id, name, address);
and
Feature (id, name);
These two models has a has_many_and_belongs_to relationship with each other, using the pivot table
feature_place(place_id, feature_id). This works as expected. Now I'm trying trying to build a form for creating a new Place. The form contains a checkbox for each existant Feature. For error handling I want to be able to create a Place object when the form is submitted. I'd like to be able to create my HABTM relationship, so I can easily rebuild and fill the form if submission fails (validation error or similar). sync() would usually handle the relationships, but since the submission has failed I don't want to insert the Place in the database yet.
Is there an easy way, like sync(), to create the relationship between my Place and it's Features that I can use to repopulate my form on rebuild, without having to write to the database before form submission succeeds?

It sounds like you need to flash the input to the session and then load the old values when the form is rendered.
// Somewhere in your post route
if ( $oh_noes_teh_validator_failed )
{
Input::flash();
Redirect::to_route( 'my-edit-form' );
}
// Somewhere in your edit route or view
$title = Input::old( 'title', $title );

Related

Multi page form data validation in Play Framework?

I am a beginner in java play framework. I an building an app which will take form data spread in multiple pages say 4 to 5 pages. But all the data is mapped to same model. How can I get the data uploaded by user per page, validate against my model's constraints, and at the end save whole data in my model.
For ex:- If page 1 has name field which is required, and page 2 has hobbies field which is required. Then how can i specifically validate data filled in that particular page, navigate till last page, and save all the data in model, in last page.
Model would have 60-70 fields.
I am using Hibernate ORM.
Thanks !
You could prefill the next form with the values of the last form, save them in the database, go to the next form, load the entered values from the values and pre-fill the next form and so on. For this, use a method in your controller:
public static Result fillOutForm1(){
Hobby form1 = new Hobby("sitting still", "diabetes");
Form<Hobby > preFilledForm = newHobbyForm.fill(form1);
return ok(views.html.YOURVIEWCLASS.render(preFilledForm);
}
With this you "send" some values to the first view class with a form. In there, the user answers some more fields and hits Submit.
So you need a route back to your controller, to handle the new input in routes.conf:
GET /Form1 controllers.Application.fillOutForm1()
POST /Form1 controllers.Application.sendForm1()
This is in your controller class:
public static Result sendForm1(){
Form<Hobby> boundHobby = newHobbyForm.bindFromRequest();
Hobby newHobby = boundHobby.get();
//In your hobby class you need a finder implementation, so that you can interact with the database. With save() you put it into the database. This may be different for the database you use!
newHobby.save();
return redirect(routes.Application.index());
}
You can then not redirect to the index, but to the next view class with the next form and there get your last answers from the db, prefill them again and put them into the form. Do this as often as you need.

How can I create a Symfony form base class for fields used on every entity?

I'm trying to come up with a way to create a 'base form' that contains fields used on every entity, i.e. id, created_at, updated_at, etc.
I want to either extend the base form when I create a new form or easily include it in each new form I make. I can't find much documentation on it, is this a common thing to do?

Foreign entity in form into different kind of input

I have two entities: product and category (Symfony 2.3).
I want to create a form in which an user can choose a product by first selecting the category. A user selects the category by clicking on image, then I want to set the image's value into a hidden input, but I don't see how can I change a foreign entity choice list to a hidden input (http://symfony.com/doc/current/reference/forms/types/entity.html).
How can I accomplish this? (how to change form input to hidden)
If I set cascade validation to true, will it for example check if a category really exist. (To prevent putting products with non-existing category from malicious users) ?
Part 1
To do this you need to use a data transformer to do two things:
transform an entity into an identifier that is either a string or integer so a form can render it as a hidden field.
transform the string or integer identifier into the entity when the form is submitted so that the parent entity can be saved with the correct relationship
The symfony docs I linked to above (here too) actually walk though an entire example of using a data transformer with a form.
As a shameless plug (because I believe it is helpful) I have written a little tutorial on using a data transformer for a hidden field with an entity id: http://lrotherfield.com/blog/symfony2-forms-entity-as-hidden-field/
Part 2
If you are using the data transformer then you don't need to worry about malicious users. The data transformer will fail because it will not be able to reverse transform the category from the fake id. In my tutorial the transformer will throw a Symfony\Component\Form\Exception\TransformationFailedException exception.
You can also write a validator (potentially using a call back) if you wanted that checks that the submitted category is real if you want an error to show in the form. Doctrine wont allow you to persist a fake category relationship as the foreign key constraint will fail.

One view, multiple nested forms, multiple tables

Background
I was given the task of writing a Small Business online database. This database is to include a lot of info as well as info on their directors and branches. Since any business can have an unlimited amount of directors and branches, I need to create a database that is not limited to just one director and/or branch.
What do I have
Currently I have 3 tables.
smmes [id, company_name, trading_name, business_address, registration_number, tax_reference, vat_number, bbbee_status, employees, awards, created, modified]
ownerships [id, smme_id, name, surname, gender, age, race, disability, qualification, created, modified]
branches [id, smme_id, location, contact_number, contact_person, created, modified]
Note: smme_id is the id of the company in smmes that the branch or director belongs to.
And I have a view for the SMME's.
What is my question
I'm VERY new to cakePHP (in fact, this is my first app I'm creating with cakePHP). I want to know how I can make one form where a user can enter all this detail and then add the details for all directors and branches from one view. I would prefer that they do not have various views to go through to create all the details. Add to that, this one view should then save all the data to the correct tables with the correct smme_id.
Is this possible or should I rather leave cakePHP and write it manually.
You can load model on demand in your controller and then pass model specific data(received from posted form) to loaded model's save method.
public function detail(){
if($this->request->is('post')): // update only when form is posted
$this->loadModel('ownerships');
$owner_name= $this->request->data['Ownername'];
$ownerships_data = array('Ownership' = > array(
'name' = > $owner_name
//add other keys from posted form
)
);
$this->Ownership->saveAll($ownerships_data);
// load other models for saving posted data in related tables
endif;
}
Similarly load other models and pass fields from posted form as array to it's save method.
Suppose URL format is http://example.com/director/detail.So you would like to put above method(termed as action in MVC terminology) in app/controllers/directors_controller.php
Generally if URL format is http://somesite.com/abc/xyz it will look for xyz action in
app/controllers/abcs_controller.php
You can read more about cake conventions here

Entity Framework SET IDENTITY_INSERT

Is there a way to force the ID value for a new entity in EF when we have an auto-incrementing ID column, i.e. use SET IDENTITY_INSERT behaviour through EF?
Our requirement is that our create form must always show a new, unique ID for the object we're creating on the empty form before it is filled in or saved. The idea is that this ID can be out read to someone over the phone and then the user can complete and save the form after the call is complete. We could reserve an ID by inserting an empty row into the database there and then, but we have unique columns and FKs; instead I've made a 'next ID' table that we increment with locks for safety, and I test this against the top ID in the object table too to be careful. The idea was to then force the use of this new ID when we write back the entity - but I can't see how to get EF to do it.
Is that possible - is it just something I've missed? I don't think the ID even makes it down to the insert so I don't think manually calling SET IDENTITY_INSERT around the SaveChanges would help.
Or do I have to do something else? I can see alternatives:
Change our ID column to not be an identity and take manual control of it all: there's a table ID inheritance here so this is potentially tricky too.
Separate DB ID and user-visible ID into a separate column, and record our unique ID there.
Empty row to reserve the ID, as above; might need some nullability changes, and amending our data read code to ignore these records.
Thanks! This is EF4 (using an EDMX and generated classes not POCOs), and against SQL Server 2008 in case that matters.
Why not use a Guid as primary key. Nothing to do with auto-increment, no concurrency pitfalls etc. You just create the Guid at the moment you create the form. Hand it over to a caller and fill in the form afterwards. When the form is cancelled, no problem. When the form is finished create the entity with the created Guid set the other values of the entity object, apply it to the (a) context and SaveChanges()...
Alternatives that wont alter your schema
Use EF Transaction
You can call context.SaveChanges() and get the autoincremented primary key. Once the process is completed you can commit the transaction. If the transaction is cancelled or there is an error/exception, you can always rollback so you wont have holes/dirty-data in your rows. I suggest you use the singleton pattern and pass the same transaction/context to whatever methods or screens to complete the process.
Just add an additional status: Draft
Save empty form as draft with saved ID, then proceed to edit the form with the information. Once complete save the form as final/ready. If you wont proceed to save the form, you can always recycle the draft.